code
stringlengths 17
6.64M
|
---|
def get_device(device=None):
if (device is None):
if torch.cuda.is_available():
device = 'cuda'
torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
device = 'cpu'
elif (device == 'cuda'):
if torch.cuda.is_available():
device = 'cuda'
torch.set_default_tensor_type('torch.cuda.FloatTensor')
else:
device = 'cpu'
else:
device = 'cpu'
if (device == 'cuda'):
logger.info("CUDA device set to '{}'.".format(torch.cuda.get_device_name(0)))
return device
|
class MyDataset(Dataset):
def __init__(self, X, y):
self.data = X
self.target = y
def __getitem__(self, index):
x = self.data[index]
y = self.target[index]
return (x, y)
def __len__(self):
return len(self.data)
|
def lossFunctionKLD(mu, logvar):
'Compute KL divergence loss. \n Parameters\n ----------\n mu: Tensor\n Latent space mean of encoder distribution.\n logvar: Tensor\n Latent space log variance of encoder distribution.\n '
kl_error = ((- 0.5) * torch.sum((((1 + logvar) - mu.pow(2)) - logvar.exp())))
return kl_error
|
def recoLossGaussian(predicted_s, x, gaussian_noise_std, data_std):
'\n Compute reconstruction loss for a Gaussian noise model. \n This is essentially the MSE loss with a factor depending on the standard deviation.\n Parameters\n ----------\n predicted_s: Tensor\n Predicted signal by DivNoising decoder.\n x: Tensor\n Noisy observation image.\n gaussian_noise_std: float\n Standard deviation of Gaussian noise.\n data_std: float\n Standard deviation of training and validation data combined (used for normailzation).\n '
reconstruction_error = (torch.mean(((predicted_s - x) ** 2)) / (2.0 * ((gaussian_noise_std / data_std) ** 2)))
return reconstruction_error
|
def recoLoss(predicted_s, x, data_mean, data_std, noiseModel):
'Compute reconstruction loss for an arbitrary noise model. \n Parameters\n ----------\n predicted_s: Tensor\n Predicted signal by DivNoising decoder.\n x: Tensor\n Noisy observation image.\n data_mean: float\n Mean of training and validation data combined (used for normailzation).\n data_std: float\n Standard deviation of training and validation data combined (used for normailzation).\n device: GPU device\n torch cuda device\n '
predicted_s_denormalized = ((predicted_s * data_std) + data_mean)
x_denormalized = ((x * data_std) + data_mean)
predicted_s_cloned = predicted_s_denormalized
predicted_s_reduced = predicted_s_cloned.permute(1, 0, 2, 3)
x_cloned = x_denormalized
x_cloned = x_cloned.permute(1, 0, 2, 3)
x_reduced = x_cloned[(0, ...)]
likelihoods = noiseModel.likelihood(x_reduced, predicted_s_reduced)
log_likelihoods = torch.log(likelihoods)
reconstruction_error = (- torch.mean(log_likelihoods))
return reconstruction_error
|
def loss_fn(predicted_s, x, mu, logvar, gaussian_noise_std, data_mean, data_std, noiseModel):
'Compute DivNoising loss. \n Parameters\n ----------\n predicted_s: Tensor\n Predicted signal by DivNoising decoder.\n x: Tensor\n Noisy observation image.\n mu: Tensor\n Latent space mean of encoder distribution.\n logvar: Tensor\n Latent space logvar of encoder distribution.\n gaussian_noise_std: float\n Standard deviation of Gaussian noise (required when using Gaussian reconstruction loss).\n data_mean: float\n Mean of training and validation data combined (used for normailzation).\n data_std: float\n Standard deviation of training and validation data combined (used for normailzation).\n device: GPU device\n torch cuda device\n noiseModel: NoiseModel object\n Distribution of noisy pixel values corresponding to clean signal (required when using general reconstruction loss).\n '
kl_loss = lossFunctionKLD(mu, logvar)
if (noiseModel is not None):
reconstruction_loss = recoLoss(predicted_s, x, data_mean, data_std, noiseModel)
else:
reconstruction_loss = recoLossGaussian(predicted_s, x, gaussian_noise_std, data_std)
return (reconstruction_loss, (kl_loss / float(x.numel())))
|
def create_dataloaders(x_train_tensor, x_val_tensor, batch_size):
train_dataset = dataLoader.MyDataset(x_train_tensor, x_train_tensor)
val_dataset = dataLoader.MyDataset(x_val_tensor, x_val_tensor)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size, shuffle=True)
return (train_loader, val_loader)
|
def create_model_and_train(basedir, data_mean, data_std, gaussian_noise_std, noise_model, n_depth, max_epochs, logger, checkpoint_callback, train_loader, val_loader, kl_annealing, weights_summary):
for filename in glob.glob((basedir + '/*')):
os.remove(filename)
vae = lightningmodel.VAELightning(data_mean=data_mean, data_std=data_std, gaussian_noise_std=gaussian_noise_std, noise_model=noise_model, n_depth=n_depth, kl_annealing=kl_annealing)
if torch.cuda.is_available():
trainer = pl.Trainer(gpus=1, max_epochs=max_epochs, logger=logger, callbacks=[EarlyStopping(monitor='val_loss', min_delta=1e-06, patience=100, verbose=True, mode='min'), checkpoint_callback], weights_summary=weights_summary)
else:
trainer = pl.Trainer(max_epochs=max_epochs, logger=logger, callbacks=[EarlyStopping(monitor='val_loss', min_delta=1e-06, patience=100, verbose=True, mode='min'), checkpoint_callback], weights_summary=weights_summary)
trainer.fit(vae, train_loader, val_loader)
collapse_flag = vae.collapse
return collapse_flag
|
def train_network(x_train_tensor, x_val_tensor, batch_size, data_mean, data_std, gaussian_noise_std, noise_model, n_depth, max_epochs, model_name, basedir, log_info=False):
(train_loader, val_loader) = create_dataloaders(x_train_tensor, x_val_tensor, batch_size)
collapse_flag = True
if (not os.path.exists(basedir)):
os.makedirs(basedir)
checkpoint_callback = ModelCheckpoint(monitor='val_loss', dirpath=basedir, filename=(model_name + '_best'), save_last=True, save_top_k=1, mode='min')
checkpoint_callback.CHECKPOINT_NAME_LAST = (model_name + '_last')
logger = TensorBoardLogger(basedir, name='', version='', default_hp_metric=False)
weights_summary = ('top' if log_info else None)
if (not log_info):
pl.utilities.distributed.log.setLevel(logging.ERROR)
posterior_collapse_count = 0
while (collapse_flag and (posterior_collapse_count < 20)):
collapse_flag = create_model_and_train(basedir, data_mean, data_std, gaussian_noise_std, noise_model, n_depth, max_epochs, logger, checkpoint_callback, train_loader, val_loader, kl_annealing=False, weights_summary=weights_summary)
if collapse_flag:
posterior_collapse_count = (posterior_collapse_count + 1)
if collapse_flag:
print('Posterior collapse limit reached, attempting training with KL annealing turned on!')
while collapse_flag:
collapse_flag = create_model_and_train(basedir, data_mean, data_std, gaussian_noise_std, noise_model, n_depth, max_epochs, logger, checkpoint_callback, train_loader, val_loader, kl_annealing=True, weights_summary=weights_summary)
|
def PickleMapName(name):
'\n\tIf you change the name of a function or module, then pickle, you can fix it with this.\n\t'
if (name in renametable):
return renametable[name]
return name
|
def mapped_load_global(self):
module = PickleMapName(self.readline()[:(- 1)])
name = PickleMapName(self.readline()[:(- 1)])
print('Finding ', module, name)
klass = self.find_class(module, name)
self.append(klass)
|
class MyUnpickler(pickle.Unpickler):
def find_class(self, module, name):
return pickle.Unpickler.find_class(self, PickleMapName(module), PickleMapName(name))
|
def UnPickleTM(file):
"\n\tEventually we need to figure out how the mechanics of dispatch tables changed.\n\tSince we only use this as a hack anyways, I'll just comment out what changed\n\tbetween python2.7x and python3x.\n\t"
tmp = None
if (sys.version_info[0] < 3):
f = open(file, 'rb')
unpickler = pickle.Unpickler(f)
unpickler.dispatch[pickle.GLOBAL] = mapped_load_global
tmp = unpickler.load()
f.close()
else:
f = open(file, 'rb')
unpickler = MyUnpickler(f, encoding='latin1')
tmp = unpickler.load()
f.close()
tmp.pop('evaluate', None)
tmp.pop('MolInstance_fc_sqdiff_BP', None)
tmp.pop('Eval_BPForceSingle', None)
tmp.pop('TFMolManage', None)
tmp.pop('TFManage', None)
tmp.pop('Prepare', None)
tmp.pop('load', None)
tmp.pop('Load', None)
tmp.pop('TensorMol.TFMolManage.path', None)
tmp.pop('TensorMol.TFMolManage.Load', None)
tmp.pop('TensorMol.TFMolManage.Prepare', None)
tmp.pop('TensorMol.TFInstance', None)
tmp.pop('TensorMol.TFInstance.train_dir', None)
tmp.pop('TensorMol.TFMolInstance.train_dir', None)
tmp.pop('TensorMol.TFInstance.chk_file', None)
tmp.pop('TensorMol.TFMolInstance.chk_file', None)
tmp.pop('save', None)
tmp.pop('Save', None)
tmp.pop('Trainable', None)
tmp.pop('TFMolManage.Trainable', None)
tmp.pop('__init__', None)
return tmp
|
class MorseModel(ForceHolder):
def __init__(self, natom_=3):
'\n\t\tsimple morse model for three atoms for a training example.\n\t\t'
ForceHolder.__init__(self, natom_)
self.lat_pl = None
self.Prepare()
def PorterKarplus(self, x_pl):
x1 = (x_pl[0] - x_pl[1])
x2 = (x_pl[2] - x_pl[1])
x12 = (x_pl[0] - x_pl[2])
r1 = tf.norm(x1)
r2 = tf.norm(x2)
r12 = tf.norm(x12)
v1 = (0.7 * tf.pow((1.0 - tf.exp((- (r1 - 0.7)))), 2.0))
v2 = (0.7 * tf.pow((1.0 - tf.exp((- (r2 - 0.7)))), 2.0))
v3 = (0.7 * tf.pow((1.0 - tf.exp((- (r12 - 0.7)))), 2.0))
return ((v1 + v2) + v3)
def Prepare(self):
self.x_pl = tf.placeholder(tf.float64, shape=tuple([self.natom, 3]))
self.Energy = self.PorterKarplus(self.x_pl)
self.Force = tf.gradients(((- 1.0) * self.PorterKarplus(self.x_pl)), self.x_pl)
init = tf.global_variables_initializer()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.sess.run(init)
def __call__(self, x_):
'\n\t\tArgs:\n\t\t\tx_: the coordinates on which to evaluate the force.\n\t\t\tlat_: the lattice boundary vectors.\n\t\tReturns:\n\t\t\tthe Energy and Force (Eh and Eh/ang.) associated with the quadratic walls.\n\t\t'
(e, f) = self.sess.run([self.Energy, self.Force], feed_dict={self.x_pl: x_})
return (e, f[0])
|
class QuantumElectrostatic(ForceHolder):
def __init__(self, natom_=3):
'\n\t\tThis is a huckle-like model, something like BeH2\n\t\tfour valence charges are exchanged between the atoms\n\t\twhich experience a screened coulomb interaction\n\t\t'
ForceHolder.__init__(self, natom_)
self.Prepare()
def HuckelBeH2(self, x_pl):
r = tf.reduce_sum((x_pl * x_pl), 1)
r = tf.reshape(r, [(- 1), 1])
D = tf.sqrt((((r - (2 * tf.matmul(x_pl, tf.transpose(x_pl)))) + tf.transpose(r)) + tf.cast(1e-26, tf.float64)))
emat = tf.diag(self.en0s)
J = tf.matrix_band_part(((- 1.0) / tf.pow((D + ((0.5 * 0.5) * 0.5)), (1.0 / 3.0))), 0, (- 1))
emat += (J + tf.transpose(J))
(e, v) = tf.self_adjoint_eig(emat)
popd = tf.nn.top_k(((- 1.0) * e), 2, sorted=True).indices
Energy = (e[popd[0]] + e[popd[1]])
q1 = (((- 1.0) + (v[(popd[0], 0)] * v[(popd[0], 0)])) + (v[(popd[1], 0)] * v[(popd[1], 0)]))
q2 = (((- 0.5) + (v[(popd[0], 1)] * v[(popd[0], 1)])) + (v[(popd[1], 1)] * v[(popd[1], 1)]))
q3 = (((- 0.5) + (v[(popd[0], 2)] * v[(popd[0], 2)])) + (v[(popd[1], 2)] * v[(popd[1], 2)]))
Dipole = ((((q1 * x_pl[0]) + (q2 * x_pl[1])) + (q3 * x_pl[2])) / 3.0)
return (Energy, Dipole, [q1, q2, q3])
def Prepare(self):
self.en0s = tf.constant([(- 1.1), (- 0.5), (- 0.5)], dtype=tf.float64)
self.x_pl = tf.placeholder(tf.float64, shape=tuple([self.natom, 3]))
(self.Energy, self.Dipole, self.Charges) = self.HuckelBeH2(self.x_pl)
self.Force = tf.gradients(((- 1.0) * self.Energy), self.x_pl)
init = tf.global_variables_initializer()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.sess.run(init)
def __call__(self, x_):
'\n\t\tArgs:\n\t\t\tx_: the coordinates on which to evaluate the force.\n\t\tReturns:\n\t\t\tthe Energy and Force (Eh and Eh/ang.) associated with the quadratic walls.\n\t\t'
(e, f, d, q) = self.sess.run([self.Energy, self.Force, self.Dipole, self.Charges], feed_dict={self.x_pl: x_})
return (e, f[0], d, q)
|
class ExtendedHuckel(ForceHolder):
def __init__(self):
'\n\n\t\t'
ForceHolder.__init__(self, natom_)
self.Prepare()
def HuckelBeH2(self, x_pl):
r = tf.reduce_sum((x_pl * x_pl), 1)
r = tf.reshape(r, [(- 1), 1])
D = tf.sqrt((((r - (2 * tf.matmul(x_pl, tf.transpose(x_pl)))) + tf.transpose(r)) + tf.cast(1e-26, tf.float64)))
emat = tf.diag(self.en0s)
J = tf.matrix_band_part(((- 1.0) / tf.pow((D + ((0.5 * 0.5) * 0.5)), (1.0 / 3.0))), 0, (- 1))
emat += (J + tf.transpose(J))
(e, v) = tf.self_adjoint_eig(emat)
popd = tf.nn.top_k(((- 1.0) * e), 2, sorted=True).indices
Energy = (e[popd[0]] + e[popd[1]])
q1 = (((- 1.0) + (v[(popd[0], 0)] * v[(popd[0], 0)])) + (v[(popd[1], 0)] * v[(popd[1], 0)]))
q2 = (((- 0.5) + (v[(popd[0], 1)] * v[(popd[0], 1)])) + (v[(popd[1], 1)] * v[(popd[1], 1)]))
q3 = (((- 0.5) + (v[(popd[0], 2)] * v[(popd[0], 2)])) + (v[(popd[1], 2)] * v[(popd[1], 2)]))
Dipole = ((((q1 * x_pl[0]) + (q2 * x_pl[1])) + (q3 * x_pl[2])) / 3.0)
return (Energy, Dipole, [q1, q2, q3])
def Prepare(self):
self.en0s = tf.constant([(- 1.1), (- 0.5), (- 0.5)], dtype=tf.float64)
self.x_pl = tf.placeholder(tf.float64, shape=tuple([self.natom, 3]))
(self.Energy, self.Dipole, self.Charges) = self.HuckelBeH2(self.x_pl)
self.Force = tf.gradients(((- 1.0) * self.Energy), self.x_pl)
init = tf.global_variables_initializer()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.sess.run(init)
def __call__(self, x_):
'\n\t\tArgs:\n\t\t\tx_: the coordinates on which to evaluate the force.\n\t\tReturns:\n\t\t\tthe Energy and Force (Eh and Eh/ang.) associated with the quadratic walls.\n\t\t'
(e, f, d, q) = self.sess.run([self.Energy, self.Force, self.Dipole, self.Charges], feed_dict={self.x_pl: x_})
return (e, f[0], d, q)
|
class TMIPIManger():
def __init__(self, EnergyForceField=None, TCP_IP='localhost', TCP_PORT=31415):
self.EnergyForceField = EnergyForceField
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.hasdata = False
try:
self.s.connect((TCP_IP, TCP_PORT))
print('Connect to server with address:', ((TCP_IP + ' ') + str(TCP_PORT)))
except:
print('Fail connect to server with address: ', ((TCP_IP + ' ') + str(TCP_PORT)))
def md_run(self):
while True:
data = self.s.recv(HDRLEN)
if (data.strip() == 'STATUS'):
if self.hasdata:
print('client has data.')
self.s.sendall('HAVEDATA ')
else:
print('client is ready to get position from server')
self.s.sendall('READY ')
elif (data.strip() == 'POSDATA'):
print('server is sending positon.')
buf_ = self.s.recv((9 * 8))
cellh = (np.fromstring(buf_, np.float64) / BOHRPERA)
buf_ = self.s.recv((9 * 8))
cellih = (np.fromstring(buf_, np.float64) * BOHRPERA)
buf_ = self.s.recv(4)
natom = np.fromstring(buf_, np.int32)[0]
buf_ = self.s.recv(((3 * natom) * 8))
position = (np.fromstring(buf_, np.float64) / BOHRPERA).reshape(((- 1), 3))
print('cellh:', cellh, ' cellih:', cellih, ' natom:', natom)
print('position:', position)
print('now is running the client to calculate force...')
(energy, force) = self.EnergyForceField(position)
force = ((force / JOULEPERHARTREE) / BOHRPERA)
vir = np.zeros((3, 3))
self.hasdata = True
elif (data.strip() == 'GETFORCE'):
print('server is ready to get force from client')
self.s.sendall('FORCEREADY ')
self.s.sendall(np.float64(energy))
self.s.sendall(np.int32(natom))
self.s.sendall(force)
self.s.sendall(vir)
self.s.sendall(np.int32(7))
self.s.sendall('nothing')
self.hasdata = False
else:
raise Exception('wrong message from server')
|
class NN_MBE():
def __init__(self, tfm_=None):
self.nn_mbe = dict()
if (tfm_ != None):
for order in tfm_:
print(tfm_[order])
self.nn_mbe[order] = TFMolManage(tfm_[order], None, False)
return
def NN_Energy(self, mol):
mol.Generate_All_MBE_term(atom_group=3, cutoff=6, center_atom=0)
nn_energy = 0.0
for i in range(1, (mol.mbe_order + 1)):
nn_energy += self.nn_mbe[i].Eval_Mol(mol)
mol.Set_MBE_Force()
mol.nn_energy = nn_energy
print('coords of mol:', mol.coords)
print('force of mol:', mol.properties['mbe_deri'])
print('energy of mol:', nn_energy)
return
|
class NN_MBE_Linear():
def __init__(self, tfm_=None):
self.mbe_order = PARAMS['MBE_ORDER']
self.nn_mbe = tfm_
self.max_num_frags = None
self.nnz_frags = None
return
def EnergyForceDipole(self, N_MB):
eval_set = MSet('TmpMBESet')
MBE_C = []
MBE_Index = []
NAtom = []
self.max_num_frags = ((N_MB.nf + ((N_MB.nf * (N_MB.nf - 1)) / 2)) + (((N_MB.nf * (N_MB.nf - 1)) * (N_MB.nf - 2)) / 6))
if (self.mbe_order >= 1):
for i in range(N_MB.nf):
natom = np.count_nonzero(N_MB.singz[i])
NAtom.append(natom)
eval_set.mols.append(Mol(N_MB.singz[i][:natom], N_MB.sings[i][:natom]))
MBE_C.append(N_MB.singC[i])
MBE_Index.append(N_MB.singI[i])
if (self.mbe_order >= 2):
for i in range(N_MB.npair):
natom = np.count_nonzero(N_MB.pairz[i])
NAtom.append(natom)
eval_set.mols.append(Mol(N_MB.pairz[i][:natom], N_MB.pairs[i][:natom]))
MBE_C.append(N_MB.pairC[i])
MBE_Index.append(N_MB.pairI[i])
if (self.mbe_order >= 3):
for i in range(N_MB.ntrip):
natom = np.count_nonzero(N_MB.tripz[i])
NAtom.append(natom)
eval_set.mols.append(Mol(N_MB.tripz[i][:natom], N_MB.trips[i][:natom]))
MBE_C.append(N_MB.tripC[i])
MBE_Index.append(N_MB.tripI[i])
if (self.mbe_order >= 4):
raise Exception('Linear MBE only implemented up to order 3')
MBE_C = np.asarray(MBE_C)
self.nnz_frags = MBE_C.shape[0]
for dummy_index in range(self.nnz_frags, self.max_num_frags):
eval_set.mols.append(Mol(np.zeros(1, dtype=np.uint8), np.zeros((1, 3), dtype=float)))
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = self.nn_mbe.EvalBPDirectEESet(eval_set, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
print(('Etotal:', Etotal, ' self.nnz_frags:', self.nnz_frags))
E_mbe = np.sum((Etotal[:self.nnz_frags] * MBE_C))
gradient_mbe = np.zeros((N_MB.nt, 3))
atom_charge_mbe = np.zeros(N_MB.nt)
for (i, index) in enumerate(MBE_Index):
gradient_mbe[index] += (gradient[i][:NAtom[i]] * MBE_C[i])
atom_charge_mbe[index] += (atom_charge[i][:NAtom[i]] * MBE_C[i])
return (E_mbe, gradient_mbe, atom_charge_mbe)
|
class NN_MBE_BF():
def __init__(self, tfm_=None, dipole_tfm_=None):
self.mbe_order = PARAMS['MBE_ORDER']
self.nn_mbe = tfm_
self.nn_dipole_mbe = dipole_tfm_
return
def NN_Energy(self, mol, embed_=False):
s = MSet()
for order in range(1, (self.mbe_order + 1)):
s.mols += mol.mbe_frags[order]
energies = np.asarray(self.nn_mbe.Eval_BPEnergy(s))
pointer = 0
for order in range(1, (self.mbe_order + 1)):
mol.frag_energy_sum[order] = np.sum(energies[pointer:(pointer + len(mol.mbe_frags[order]))])
if ((order == 1) or (order == 2)):
for (i, mol_frag) in enumerate(mol.mbe_frags[order]):
mol_frag.properties['nn_energy'] = energies[(pointer + i)]
pointer += len(mol.mbe_frags[order])
if embed_:
mol.MBE_Energy_Embed()
else:
mol.MBE_Energy()
return
def NN_Dipole(self, mol):
s = MSet()
for order in range(1, (self.mbe_order + 1)):
s.mols += mol.mbe_frags[order]
(dipoles, charges) = self.nn_dipole_mbe.Eval_BPDipole_2(s)
pointer = 0
for order in range(1, (self.mbe_order + 1)):
mol.frag_dipole_sum[order] = np.sum(dipoles[pointer:(pointer + len(mol.mbe_frags[order]))], axis=0)
pointer += len(mol.mbe_frags[order])
mol.MBE_Dipole()
print('mbe dipole: ', mol.nn_dipole)
return
def NN_Energy_Force(self, mol, embed_=False):
s = MSet()
for order in range(1, (self.mbe_order + 1)):
s.mols += mol.mbe_frags[order]
t = time.time()
(energies, forces) = self.nn_mbe.Eval_BPForceSet(s)
print('actual evaluation cost:', (time.time() - t))
energies = np.asarray(energies)
pointer = 0
for order in range(1, (self.mbe_order + 1)):
mol.frag_force_sum[order] = np.zeros((mol.NAtoms(), 3))
for (i, mol_frag) in enumerate(mol.mbe_frags[order]):
mol.frag_force_sum[order][mol_frag.properties['mbe_atom_index']] += forces[(pointer + i)]
mol.frag_energy_sum[order] = np.sum(energies[pointer:(pointer + len(mol.mbe_frags[order]))])
if ((order == 1) or (order == 2)):
for (i, mol_frag) in enumerate(mol.mbe_frags[order]):
mol_frag.properties['nn_energy'] = energies[(pointer + i)]
mol_frag.properties['nn_energy_grads'] = forces[(pointer + i)]
pointer += len(mol.mbe_frags[order])
if embed_:
t = time.time()
mol.MBE_Energy_Embed()
print('MBE_Energy_Embed cost:', (t - time.time()))
t = time.time()
mol.MBE_Force_Embed()
print('MBE_Force_Embed cost:', (t - time.time()))
else:
t = time.time()
mol.MBE_Energy()
print('MBE_Energy_Embed cost:', (t - time.time()))
t = time.time()
mol.MBE_Force()
print('MBE_Force_Embed cost:', (t - time.time()))
return (mol.nn_energy, mol.nn_force)
def NN_Charge(self, mol, grads_=False):
s = MSet()
for order in range(1, (self.mbe_order + 1)):
s.mols += mol.mbe_frags[order]
if (not grads_):
(dipoles, charges) = self.nn_dipole_mbe.Eval_BPDipole_2(s)
else:
(dipoles, charges, gradient) = self.nn_dipole_mbe.Eval_BPDipoleGrad_2(s)
pointer = 0
for order in range(1, (self.mbe_order + 1)):
mol.frag_charge_sum[order] = np.zeros(mol.NAtoms())
charge_charge_sum = 0.0
for (i, mol_frag) in enumerate(mol.mbe_frags[order]):
mol.frag_charge_sum[order][mol_frag.properties['mbe_atom_index']] += charges[(pointer + i)]
if (order == 2):
mol_frag.properties['atom_charges'] = charges[(pointer + i)]
if grads_:
mol_frag.properties['atom_charges_grads'] = gradient[(pointer + i)]
pointer += len(mol.mbe_frags[order])
t = time.time()
mol.MBE_Charge()
print('MBE_Charge cost:', (time.time() - t))
return mol.nn_charge
|
class SteepestDescent():
def __init__(self, ForceAndEnergy_, x0_):
'\n\t\tThe desired interface for a solver in tensormol.\n\n\t\tArgs:\n\t\t\tForceAndEnergy_: a routine which returns energy, force.\n\t\t\tx0_: a initial vector\n\t\t'
self.step = 0
self.x0 = x0_.copy()
if (len(self.x0.shape) == 2):
self.natom = self.x0.shape[0]
else:
self.natom = (self.x0.shape[0] * self.x0.shape[1])
self.EForce = ForceAndEnergy_
return
def __call__(self, new_vec_):
'\n\t\tIterate\n\n\t\tArgs:\n\t\t\tnew_vec_: Point at which to minimize gradients\n\t\tReturns:\n\t\t\tNext point, energy, and gradient.\n\t\t'
(e, g) = self.EForce(new_vec_)
self.step += 1
return ((new_vec_ + (PARAMS['SDStep'] * g)), e, g)
|
class VerletOptimizer():
def __init__(self, ForceAndEnergy_, x0_):
"\n\t\tBased on Hankelman's momentum optimizer.\n\n\t\tArgs:\n\t\t\tForceAndEnergy_: a routine which returns energy, force.\n\t\t\tx0_: a initial vector\n\t\t"
self.step = 0
self.x0 = x0_.copy()
self.v = np.zeros(x0_.shape)
self.a = np.zeros(x0_.shape)
self.dt = 0.1
if (len(self.x0.shape) == 2):
self.natom = self.x0.shape[0]
else:
self.natom = (self.x0.shape[0] * self.x0.shape[1])
self.EForce = ForceAndEnergy_
return
def __call__(self, x_):
'\n\t\tIterate\n\n\t\tArgs:\n\t\t\tnew_vec_: Point at which to minimize gradients\n\t\tReturns:\n\t\t\tNext point, energy, and gradient.\n\t\t'
x = ((x_ + (self.v * self.dt)) + ((((1.0 / 2.0) * self.a) * self.dt) * self.dt))
(e, f_x_) = self.EForce(x)
self.v += (((1.0 / 2.0) * (self.a + f_x_)) * self.dt)
if (np.sum((self.v * f_x_)) < 0):
self.v *= 0.0
self.a *= 0.0
self.step += 1
return (x, e, f_x_)
|
class BFGS(SteepestDescent):
def __init__(self, ForceAndEnergy_, x0_):
'\n\t\tSimplest Possible minimizing BFGS\n\n\t\tArgs:\n\t\t\tForceAndEnergy_: a routine which returns energy, force.\n\t\t\tx0_: a initial vector\n\t\t'
self.m_max = PARAMS['MaxBFGS']
self.step = 0
self.x0 = x0_.copy()
if (len(self.x0.shape) == 2):
self.natom = self.x0.shape[0]
else:
self.natom = (self.x0.shape[0] * self.x0.shape[1])
self.EForce = ForceAndEnergy_
self.R_Hist = np.zeros(([self.m_max] + list(self.x0.shape)))
self.F_Hist = np.zeros(([self.m_max] + list(self.x0.shape)))
return
def BFGSstep(self, new_vec_, new_residual_):
if (self.step < self.m_max):
self.R_Hist[self.step] = new_vec_.copy()
self.F_Hist[self.step] = new_residual_.copy()
else:
self.R_Hist = np.roll(self.R_Hist, (- 1), axis=0)
self.F_Hist = np.roll(self.F_Hist, (- 1), axis=0)
self.R_Hist[(- 1)] = new_vec_.copy()
self.F_Hist[(- 1)] = new_residual_.copy()
q = new_residual_.copy()
a = np.zeros(min(self.m_max, self.step))
for i in range((min(self.m_max, self.step) - 1), 0, (- 1)):
s = (self.R_Hist[i] - self.R_Hist[(i - 1)])
y = (self.F_Hist[i] - self.F_Hist[(i - 1)])
rho = (1.0 / np.sum((y * s)))
a[i] = (rho * np.sum((s * q)))
q -= (a[i] * y)
if (self.step < 1):
H = 1.0
else:
num = min((self.m_max - 1), self.step)
v1 = (self.R_Hist[num] - self.R_Hist[(num - 1)])
v2 = (self.F_Hist[num] - self.F_Hist[(num - 1)])
H = (np.sum((v1 * v2)) / np.sum((v2 * v2)))
if (abs(H) < 0.001):
self.step += 1
return ((- 0.001) * new_residual_)
z = (H * q)
for i in range(1, min(self.m_max, self.step)):
s = (self.R_Hist[i] - self.R_Hist[(i - 1)])
y = (self.F_Hist[i] - self.F_Hist[(i - 1)])
rho = (1.0 / np.sum((y * s)))
beta = (rho * np.sum((y * z)))
z += (s * (a[i] - beta))
self.step += 1
return ((- 1.0) * z)
def __call__(self, new_vec_):
'\n\t\tIterate BFGS\n\n\t\tArgs:\n\t\t\tnew_vec_: Point at which to minimize gradients\n\t\tReturns:\n\t\t\tNext point, energy, and gradient.\n\t\t'
(e, g) = self.EForce(new_vec_)
z = self.BFGSstep(new_vec_, g)
return ((new_vec_ + (0.005 * z)), e, g)
|
class BFGS_WithLinesearch(BFGS):
def __init__(self, ForceAndEnergy_, x0_):
'\n\t\tSimplest Possible BFGS\n\n\t\tArgs:\n\t\t\tForceAndEnergy_: a routine which returns energy, force.\n\t\t\tx0_: a initial vector\n\t\t'
BFGS.__init__(self, ForceAndEnergy_, x0_)
self.alpha = PARAMS['GSSearchAlpha']
self.Energy = (lambda x: self.EForce(x, False))
return
def LineSearch(self, x0_, p_, thresh=0.0001):
'\n\t\tgolden section search to find the minimum of f on [a,b]\n\n\t\tArgs:\n\t\t\tf_: a function which returns energy.\n\t\t\tx0_: Origin of the search.\n\t\t\tp_: search direction.\n\n\t\tReturns:\n\t\t\tx: coordinates which minimize along this search direction.\n\t\t'
k = 0
rmsdist = 10.0
a = x0_
b = (x0_ + (self.alpha * p_))
c = (b - ((b - a) / GOLDENRATIO))
d = (a + ((b - a) / GOLDENRATIO))
fa = self.Energy(a)
fb = self.Energy(b)
fc = self.Energy(c)
fd = self.Energy(d)
while (rmsdist > thresh):
if ((fa < fc) and (fa < fd) and (fa < fb)):
print('Line Search: Overstep')
if (self.alpha > 0.0001):
self.alpha /= 1.71
else:
print('Keeping step')
return a
a = x0_
b = (x0_ + (self.alpha * p_))
c = (b - ((b - a) / GOLDENRATIO))
d = (a + ((b - a) / GOLDENRATIO))
fa = self.Energy(a)
fb = self.Energy(b)
fc = self.Energy(c)
fd = self.Energy(d)
elif ((fb < fc) and (fb < fd) and (fb < fa)):
print('Line Search: Understep')
if (self.alpha < 100.0):
self.alpha *= 1.7
a = x0_
b = (x0_ + (self.alpha * p_))
c = (b - ((b - a) / GOLDENRATIO))
d = (a + ((b - a) / GOLDENRATIO))
fa = self.Energy(a)
fb = self.Energy(b)
fc = self.Energy(c)
fd = self.Energy(d)
elif (fc < fd):
b = d
c = (b - ((b - a) / GOLDENRATIO))
d = (a + ((b - a) / GOLDENRATIO))
fb = fd
fc = self.Energy(c)
fd = self.Energy(d)
else:
a = c
c = (b - ((b - a) / GOLDENRATIO))
d = (a + ((b - a) / GOLDENRATIO))
fa = fc
fc = self.Energy(c)
fd = self.Energy(d)
rmsdist = (np.sum(np.linalg.norm((a - b), axis=1)) / self.natom)
k += 1
return ((b + a) / 2)
def __call__(self, new_vec_):
'\n\t\tIterate BFGS\n\n\t\tArgs:\n\t\t\tnew_vec_: Point at which to minimize gradients\n\t\tReturns:\n\t\t\tNext point, energy, and gradient.\n\t\t'
(e, g) = self.EForce(new_vec_)
z = self.BFGSstep(new_vec_, g)
new_vec = self.LineSearch(new_vec_, z)
return (new_vec, e, g)
|
class Basis():
def __init__(self, Name_=None):
self.path = './basis/'
self.name = Name_
self.params = None
def Load(self, filename=None):
print('Unpickling Basis Set')
if (filename == None):
filename = self.name
f = open(((self.path + filename) + '.tmb'), 'rb')
tmp = pickle.load(f)
self.__dict__.update(tmp)
f.close()
return
def Save(self):
if (filename == None):
filename = self.name
f = open(((((self.path + self.name) + '_') + self.dig.name) + '.tmb'), 'wb')
pickle.dump(self.__dict__, f, protocol=pickle.HIGHEST_PROTOCOL)
f.close()
return
|
class Basis_GauSH(Basis):
def __init__(self, Name_=None):
Basis.__init__(self, Name_)
self.type = 'GauSH'
self.RBFS = np.tile(np.array([[0.1, 0.156787], [0.3, 0.3], [0.5, 0.5], [0.7, 0.7], [1.3, 1.3], [2.2, 2.4], [4.4, 2.4], [6.6, 2.4], [8.8, 2.4], [11.0, 2.4], [13.2, 2.4], [15.4, 2.4]]), (10, 1, 1))
return
def Orthogonalize(self):
from TensorMol.LinearOperations import MatrixPower
S_Rad = MolEmb.Overlap_RBFS(PARAMS, self.RBFS)
self.SRBF = np.zeros((self.RBFS.shape[0], PARAMS['SH_NRAD'], PARAMS['SH_NRAD']))
for i in range(S_Rad.shape[0]):
self.SRBF[i] = MatrixPower(S_Rad[i], ((- 1.0) / 2))
|
class EmbeddingOptimizer():
'\n\tProvides an objective function to optimize an embedding, maximizing the reversibility of the embedding, and the distance the embedding predicts between molecules which are not equivalent in their geometry or stoiciometry.\n\t'
def __init__(self, method_, set_, dig_, OptParam_, OType_=None, Elements_=None):
print('Will produce an objective function to optimize basis parameters, and then optimize it')
self.method = method_
self.set = set_
self.dig = dig_
self.OptParam = OptParam_
LOGGER.info('Optimizing %s part of %s based off of %s', self.OptParam, self.dig.name, self.method)
if (self.method == 'Ipecac'):
self.ip = Ipecac.Ipecac(self.set, self.dig, eles_=[1, 6, 7, 8])
self.Mols = []
self.DistortMols = []
self.DesiredEmbs = []
for mol in self.set.mols:
self.Mols.append(copy.deepcopy(mol))
self.Mols[(- 1)].BuildDistanceMatrix()
for mol in self.Mols:
self.DistortMols.append(copy.deepcopy(mol))
self.DistortMols[(- 1)].Distort(0.15)
self.DistortMols[(- 1)].BuildDistanceMatrix()
LOGGER.info('Using %d unique geometries', len(self.Mols))
elif (self.method == 'KRR'):
self.OType = OType_
if (self.OType == None):
raise Exception('KRR optimization requires setting OType_ for the EmbeddingOptimizer.')
self.elements = Elements_
if (self.elements == None):
raise Exception('KRR optimization requires setting Elements_ for the EmbeddingOptimizer.')
self.TreatedAtoms = self.set.AtomTypes()
print('Optimizing based off ', self.OType, ' using elements')
return
def SetBasisParams(self, basisParams_):
if (self.dig.name == 'GauSH'):
if (self.OptParam == 'radial'):
PARAMS['RBFS'] = basisParams_[:(PARAMS['SH_NRAD'] * 2)].reshape(PARAMS['SH_NRAD'], 2).copy()
elif (self.OptParam == 'atomic'):
PARAMS['ANES'][[0, 5, 6, 7]] = basisParams_[[0, 1, 2, 3]].copy()
elif (self.digname == 'ANI1_Sym'):
raise Exception('Not yet implemented for ANI1')
S_Rad = MolEmb.Overlap_RBF(PARAMS)
PARAMS['SRBF'] = MatrixPower(S_Rad, ((- 1.0) / 2))
print('Eigenvalue Overlap Error: ', ((1 / np.amin(np.linalg.eigvals(S_Rad))) / 1000000.0))
return np.abs(((1 / np.amin(np.linalg.eigvals(S_Rad))) / 1000000.0))
def Ipecac_Objective(self, basisParams_):
'\n\t\tResets the parameters. Builds the overlap if neccesary. Resets the desired embeddings. Reverses the distorted set and computes an error.\n\t\t'
berror = self.SetBasisParams(basisParams_)
self.SetEmbeddings()
resultmols = []
for i in range(len(self.DistortMols)):
m = copy.deepcopy(self.DistortMols[i])
emb = self.DesiredEmbs[i]
resultmols.append(self.ip.ReverseAtomwiseEmbedding(emb, m.atoms, guess_=m.coords, GdDistMatrix=self.Mols[i].DistMatrix))
SelfDistances = 0.0
OtherDistances = 0.0
for i in range(len(self.DistortMols)):
SelfDistances += self.Mols[i].rms_inv(resultmols[i])
print(SelfDistances)
for j in range(len(self.DistortMols)):
if ((i != j) and (len(self.Mols[i].atoms) == len(self.Mols[j].atoms))):
OtherDistances += np.exp(((- 1.0) * self.Mols[i].rms_inv(resultmols[j])))
LOGGER.info('Using params_: %s', basisParams_)
LOGGER.info('Got Error: %.6f', ((berror + SelfDistances) + OtherDistances))
return ((berror + SelfDistances) + OtherDistances)
def KRR_Objective(self, basisParams_):
'\n\t\tResets the parameters. Builds the overlap if neccesary. Resets the desired embeddings. Reverses the distorted set and computes an error.\n\t\t'
berror = self.SetBasisParams(basisParams_)
sqerr = 0.0
tset = TensorData(self.set, self.dig)
tset.BuildTrainMolwise((self.set.name + '_BasisOpt'))
for ele in self.elements:
ele_inst = Instance_KRR(tset, ele, None)
sqerr += (ele_inst.basis_opt_run() ** 2)
LOGGER.info('Basis Params: %s', basisParams_)
LOGGER.info('SqError: %f', (sqerr + berror))
return (sqerr + berror)
def PerformOptimization(self):
prm0 = PARAMS['RBFS'][:PARAMS['SH_NRAD']].flatten()
print(prm0)
print('Optimizing RBFS.')
if (self.method == 'Ipecac'):
obj = (lambda x: self.Ipecac_Objective(x))
elif (self.method == 'KRR'):
obj = (lambda x: self.KRR_Objective(x))
res = optimize.minimize(obj, prm0, method='COBYLA', tol=1e-08, options={'disp': True, 'rhobeg': 0.1})
LOGGER.info('Opt complete: %s', res.message)
LOGGER.info('Optimal Basis Parameters: %s', res.x)
return
def BasinHopping(self):
prm0 = PARAMS['RBFS'][:PARAMS['SH_NRAD']].flatten()
print(prm0)
print('Optimizing RBFS.')
if (self.method == 'Ipecac'):
obj = (lambda x: self.Ipecac_Objective(x))
elif (self.method == 'KRR'):
obj = (lambda x: self.KRR_Objective(x))
min_kwargs = {'method': 'COBYLA', 'options': "{'rhobeg':0.1}"}
ret = optimize.basinhopping(obj, prm0, minimizer_kwargs=min_kwargs, niter=100)
LOGGER.info('Optimal Basis Parameters: %s', res.x)
return
def SetEmbeddings(self):
self.DesiredEmbs = []
for mol in self.Mols:
self.DesiredEmbs.append(self.dig.Emb(mol, MakeOutputs=False))
|
class Ipecac():
def __init__(self, set_, dig_, eles_):
'\n\t\tArgs:\n\t\t\tset_ : an MSet of molecules\n\t\t\tdig_: embedding type for reversal\n\t\t\teles_: list of possible elements for reversal\n\t\t'
self.set = set_
self.dig = dig_
self.eles = eles_
def ReverseAtomwiseEmbedding(self, emb_, atoms_, guess_, GdDistMatrix):
'\n\t\tArgs:\n\t\t\tatoms_: a list of element types for which this routine provides coords.\n\t\t\tdig_: a digester\n\t\t\temb_: the embedding which we will try to construct a mol to match. Because this is atomwise this will actually be a (natoms X embedding shape) tensor.\n\t\tReturns:\n\t\t\tA best-fit version of a molecule which produces an embedding as close to emb_ as possible.\n\t\t'
natoms = emb_.shape[0]
if (atoms_ == None):
atoms = np.full(natoms, 6)
else:
atoms = atoms_
coords = guess_
objective = (lambda crds: self.EmbAtomwiseErr(Mol(atoms, crds.reshape(natoms, 3)), emb_))
if 1:
def callbk(x_):
mn = Mol(atoms, x_.reshape(natoms, 3))
mn.BuildDistanceMatrix()
print('Distance error : ', np.sqrt(np.sum(((GdDistMatrix - mn.DistMatrix) * (GdDistMatrix - mn.DistMatrix)))))
import scipy.optimize
step = 0
res = optimize.minimize(objective, coords.reshape((natoms * 3)), method='L-BFGS-B', tol=1e-12, options={'maxiter': 5000000, 'maxfun': 10000000}, callback=callbk)
mfit = Mol(atoms, res.x.reshape(natoms, 3))
self.DistanceErr(GdDistMatrix, mfit)
return mfit
def BruteForceAtoms(self, mol_, emb_):
print('Searching for best atom fit')
bestmol = copy.deepcopy(mol_)
besterr = 100.0
for stoich in itertools.product([1, 6, 7, 8], repeat=len(mol_.atoms)):
tmpmol = Mol(np.array(stoich), mol_.coords)
tmperr = self.EmbAtomwiseErr(tmpmol, emb_)
if (tmperr < besterr):
bestmol = copy.deepcopy(tmpmol)
besterr = tmperr
print(besterr)
print(bestmol.atoms)
return bestmol.atoms
def EmbAtomwiseErr(self, mol_, emb_):
ins = self.dig.Emb(mol_, MakeOutputs=False)
err = np.sqrt(np.sum(((ins - emb_) * (ins - emb_))))
return err
def DistanceErr(self, GdDistMatrix_, mol_):
mol_.BuildDistanceMatrix()
print('Final Distance error : ', np.sqrt(np.sum(((GdDistMatrix_ - mol_.DistMatrix) * (GdDistMatrix_ - mol_.DistMatrix)))))
|
class OnlineEstimator():
'\n\tSimple storage-less Knuth estimator which\n\taccumulates mean and variance.\n\t'
def __init__(self, x_):
self.n = 1
self.mean = (x_ * 0.0)
self.m2 = (x_ * 0.0)
delta = (x_ - self.mean)
self.mean += (delta / self.n)
delta2 = (x_ - self.mean)
self.m2 += (delta * delta2)
def __call__(self, x_):
self.n += 1
delta = (x_ - self.mean)
self.mean += (delta / self.n)
delta2 = (x_ - self.mean)
self.m2 += (delta * delta2)
return (self.mean, (self.m2 / (self.n - 1)))
|
class NudgedElasticBand():
def __init__(self, f_, g0_, g1_, name_='Neb', thresh_=None, nbeads_=None):
'\n\t\tNudged Elastic band. JCP 113 9978\n\n\t\tArgs:\n\t\t\tf_: an energy, force routine (energy Hartree, Force Kcal/ang.)\n\t\t\tg0_: initial molecule.\n\t\t\tg1_: final molecule.\n\n\t\tReturns:\n\t\t\tA reaction path.\n\t\t'
self.name = name_
self.thresh = PARAMS['OptThresh']
if (thresh_ != None):
self.thresh = thresh_
self.max_opt_step = PARAMS['OptMaxCycles']
self.nbeads = PARAMS['NebNumBeads']
if (nbeads_ != None):
self.nbeads = nbeads_
self.k = PARAMS['NebK']
self.f = f_
self.atoms = g0_.atoms.copy()
self.natoms = len(self.atoms)
self.beads = np.array([(((1.0 - l) * g0_.coords) + (l * g1_.coords)) for l in np.linspace(0.0, 1.0, self.nbeads)])
self.Fs = np.zeros(self.beads.shape)
self.Ss = np.zeros(self.beads.shape)
self.Ts = np.zeros(self.beads.shape)
self.Es = np.zeros(self.nbeads)
self.Esi = np.zeros(self.nbeads)
self.Rs = np.zeros(self.nbeads)
self.Solver = None
self.step = 0
if (PARAMS['NebSolver'] == 'SD'):
self.Solver = SteepestDescent(self.WrappedEForce, self.beads)
if (PARAMS['NebSolver'] == 'Verlet'):
self.Solver = VerletOptimizer(self.WrappedEForce, self.beads)
elif (PARAMS['NebSolver'] == 'BFGS'):
self.Solver = BFGS_WithLinesearch(self.WrappedEForce, self.beads)
elif (PARAMS['NebSolver'] == 'DIIS'):
self.Solver = DIIS(self.WrappedEForce, self.beads)
elif (PARAMS['NebSolver'] == 'CG'):
self.Solver = ConjGradient(self.WrappedEForce, self.beads)
else:
raise Exception('Missing Neb Solver')
for (i, bead) in enumerate(self.beads):
m = Mol(self.atoms, bead)
m.WriteXYZfile('./results/', 'NebTraj0')
return
def Tangent(self, beads_, i):
if ((i == 0) or (i == (self.nbeads - 1))):
return np.zeros(self.beads[0].shape)
tm1 = (beads_[i] - beads_[(i - 1)])
tp1 = (beads_[(i + 1)] - beads_[i])
t = (tm1 + tp1)
t = (t / np.sqrt(np.einsum('ia,ia', t, t)))
return t
def SpringEnergy(self, beads_):
tmp = 0.0
for i in range((self.nbeads - 1)):
tmp2 = (beads_[(i + 1)] - beads_[i])
tmp += (((0.5 * self.k) * self.nbeads) * np.sum((tmp2 * tmp2)))
return tmp
def SpringDeriv(self, beads_, i):
if ((i == 0) or (i == (self.nbeads - 1))):
return np.zeros(self.beads[0].shape)
tmp = ((self.k * self.nbeads) * (((2.0 * beads_[i]) - beads_[(i + 1)]) - beads_[(i - 1)]))
return tmp
def Parallel(self, v_, t_):
return (t_ * np.einsum('ia,ia', v_, t_))
def Perpendicular(self, v_, t_):
return (v_ - (t_ * np.einsum('ia,ia', v_, t_)))
def BeadAngleCosine(self, beads_, i):
v1 = (beads_[(i + 1)] - beads_[i])
v2 = (beads_[(i - 1)] - beads_[i])
return (np.einsum('ia,ia', v1, v2) / (np.linalg.norm(v1) * np.linalg.norm(v2)))
def NebForce(self, beads_, i, DoForce=True):
'\n\t\tThis uses the mixing of Perpendicular spring force\n\t\tto reduce kinks\n\t\t'
if ((i == 0) or (i == (self.nbeads - 1))):
self.Fs[i] = np.zeros(self.beads[0].shape)
self.Es[i] = self.f(beads_[i], False)
elif DoForce:
(self.Es[i], self.Fs[i]) = self.f(beads_[i], DoForce)
else:
self.Es[i] = self.f(beads_[i], DoForce)
if (not DoForce):
return self.Es[i]
t = self.Tangent(beads_, i)
self.Ts[i] = t
S = ((- 1.0) * self.SpringDeriv(beads_, i))
Spara = self.Parallel(S, t)
self.Ss[i] = Spara
F = self.Fs[i].copy()
F = self.Perpendicular(F, t)
if 0:
if (np.linalg.norm(F) != 0.0):
Fn = (F / np.linalg.norm(F))
else:
Fn = F
Sperp = self.Perpendicular(self.Perpendicular(S, t), Fn)
Fneb = (Spara + F)
if (PARAMS['NebClimbingImage'] and (self.step > 10) and (i == self.TSI)):
print('Climbing image i', i)
Fneb = (self.Fs[i] + (((- 2.0) * np.sum((self.Fs[i] * self.Ts[i]))) * self.Ts[i]))
return (self.Es[i], Fneb)
def WrappedEForce(self, beads_, DoForce=True):
F = np.zeros(beads_.shape)
if DoForce:
for (i, bead) in enumerate(beads_):
(self.Es[i], F[i]) = self.NebForce(beads_, i, DoForce)
F[i] = RemoveInvariantForce(bead, F[i], self.atoms)
F[i] /= JOULEPERHARTREE
TE = (np.sum(self.Es) + self.SpringEnergy(beads_))
return (TE, F)
else:
for (i, bead) in enumerate(beads_):
self.Es[i] = self.NebForce(beads_, i, DoForce)
TE = (np.sum(self.Es) + self.SpringEnergy(beads_))
return TE
def IntegrateEnergy(self):
'\n\t\tUse the fundamental theorem of line integrals to calculate an energy.\n\t\tAn interpolated path could improve this a lot.\n\t\t'
self.Esi[0] = self.Es[0]
for i in range(1, self.nbeads):
dR = (self.beads[i] - self.beads[(i - 1)])
dV = (((- 1) * (self.Fs[i] + self.Fs[(i - 1)])) / 2.0)
self.Esi[i] = (self.Esi[(i - 1)] + np.einsum('ia,ia', dR, dV))
def HighQualityPES(self, npts_=100):
'\n\t\tDo a high-quality integration of the path and forces.\n\t\t'
from scipy.interpolate import CubicSpline
ls = np.linspace(0.0, 1.0, self.nbeads)
Rint = CubicSpline(self.beads)
Fint = CubicSpline(self.Fs)
Es = np.zeros(npts_)
Es[0] = 0
ls = np.linspace(0.0, 1.0, npts_)
for (i, l) in enumerate(ls):
if (i == 0):
continue
else:
Es[i] = (Es[(i - 1)] + np.einsum('ia,ia', (Rint(l) - Rint(ls[(i - 1)])), ((- 1.0) * Fint(l))))
m = Mol(self.atoms, Rint(l))
m.properties['Energy'] = Es[i]
m.properties['Force'] = Fint(l)
m.WriteXYZfile('./results/', 'NebHQTraj')
def WriteTrajectory(self, nm_):
for (i, bead) in enumerate(self.beads):
m = Mol(self.atoms, bead)
m.WriteXYZfile('./results/', ('Bead' + str(i)))
for (i, bead) in enumerate(self.beads):
m = Mol(self.atoms, bead)
m.properties['bead'] = i
m.properties['Energy'] = self.Es[i]
m.properties['NormNebForce'] = np.linalg.norm(self.Fs[i])
m.WriteXYZfile('./results/', (nm_ + 'Traj'))
return
def Opt(self, filename='Neb', Debug=False):
'\n\t\tOptimize the nudged elastic band using the solver that has been selected.\n\t\t'
self.step = 0
self.Fs = np.ones(self.beads.shape)
PES = np.zeros((self.max_opt_step, self.nbeads))
while ((self.step < self.max_opt_step) and (np.sqrt(np.mean((self.Fs * self.Fs))) > self.thresh)):
(self.beads, energy, self.Fs) = self.Solver(self.beads)
PES[self.step] = self.Es.copy()
self.IntegrateEnergy()
print('Rexn Profile: ', self.Es, self.Esi)
self.TSI = np.argmax(self.Es)
beadFs = [np.linalg.norm(x) for x in self.Fs[1:(- 1)]]
beadFperp = [np.linalg.norm(self.Perpendicular(self.Fs[i], self.Ts[i])) for i in range(1, (self.nbeads - 1))]
beadRs = [np.linalg.norm((self.beads[(x + 1)] - self.beads[x])) for x in range((self.nbeads - 1))]
beadCosines = [self.BeadAngleCosine(self.beads, i) for i in range(1, (self.nbeads - 1))]
print('Frce Profile: ', beadFs)
print('F_|_ Profile: ', beadFperp)
print('Dist Profile: ', beadRs)
print('BCos Profile: ', beadCosines)
minforce = np.min(beadFs)
if ((self.step % 10) == 0):
self.WriteTrajectory(filename)
LOGGER.info((self.name + 'Step: %i Objective: %.5f RMS Gradient: %.5f Max Gradient: %.5f |F_perp| : %.5f |F_spring|: %.5f '), self.step, np.sum(PES[self.step]), np.sqrt(np.mean((self.Fs * self.Fs))), np.max(self.Fs), np.mean(beadFperp), np.linalg.norm(self.Ss))
self.step += 1
print('Activation Energy:', (np.max(self.Es) - np.min(self.Es)))
np.savetxt((('./results/NEB_' + filename) + '_Energy.txt'), PES)
return self.beads
|
def PeriodicVelocityVerletStep(pf_, a_, x_, v_, m_, dt_):
"\n\tA Periodic Velocity Verlet Step (just modulo's the vectors.)\n\n\tArgs:\n\t\tpf_: The PERIODIC force class (returns Joules/Angstrom)\n\t\ta_: The acceleration at current step. (A^2/fs^2)\n\t\tx_: Current coordinates (A)\n\t\tv_: Velocities (A/fs)\n\t\tm_: the mass vector. (kg)\n\tReturns:\n\t\tx: updated positions\n\t\tv: updated Velocities\n\t\ta: updated accelerations\n\t\te: Energy at midpoint per unit cell.\n\t"
x = ((x_ + (v_ * dt_)) + ((((1.0 / 2.0) * a_) * dt_) * dt_))
x = pf_.lattice.ModuloLattice(x)
(e, f_x_) = pf_(x)
a = (pow(10.0, (- 10.0)) * np.einsum('ax,a->ax', f_x_, (1.0 / m_)))
v = (v_ + (((1.0 / 2.0) * (a_ + a)) * dt_))
return (x, v, a, e)
|
class PeriodicNoseThermostat(NoseThermostat):
def __init__(self, m_, v_):
NoseThermostat.__init__(self, m_, v_)
return
def step(self, pf_, a_, x_, v_, m_, dt_):
'\n\t\tA periodic Nose thermostat velocity verlet step\n\t\thttp://www2.ph.ed.ac.uk/~dmarendu/MVP/MVP03.pdf\n\n\t\tArgs:\n\t\t\tpf_: a Periodic force class.\n\t\t\ta_: acceleration\n\t\t\tx_: coordinates\n\t\t\tv_: velocities\n\t\t\tm_: masses\n\t\t\tdt_: timestep.\n\t\t'
self.kT = ((IDEALGASR * pow(10.0, (- 10.0))) * self.T)
self.tau = ((20.0 * PARAMS['MDdt']) * self.N)
self.Q = ((self.kT * self.tau) * self.tau)
x = ((x_ + (v_ * dt_)) + ((((1.0 / 2.0) * (a_ - (self.eta * v_))) * dt_) * dt_))
x = pf_.lattice.ModuloLattice(x)
vdto2 = (v_ + (((1.0 / 2.0) * (a_ - (self.eta * v_))) * dt_))
(e, f_x_) = pf_(x)
a = (pow(10.0, (- 10.0)) * np.einsum('ax,a->ax', f_x_, (1.0 / m_)))
ke = ((1.0 / 2.0) * np.dot(np.einsum('ia,ia->i', v_, v_), m_))
etadto2 = (self.eta + ((dt_ / (2.0 * self.Q)) * (ke - ((((3.0 * self.N) + 1) / 2.0) * self.kT))))
kedto2 = ((1.0 / 2.0) * np.dot(np.einsum('ia,ia->i', vdto2, vdto2), m_))
self.eta = (etadto2 + ((dt_ / (2.0 * self.Q)) * (kedto2 - ((((3.0 * self.N) + 1) / 2.0) * self.kT))))
v = ((vdto2 + ((dt_ / 2.0) * a)) / (1 + ((dt_ / 2.0) * self.eta)))
return (x, v, a, e)
|
class PeriodicVelocityVerlet(VelocityVerlet):
def __init__(self, Force_, name_='PdicMD', v0_=None):
'\n\t\tMolecular dynamics\n\n\t\tArgs:\n\t\t\tForce_: A PERIODIC energy, force CLASS.\n\t\t\tPMol_: initial molecule.\n\t\t\tPARAMS["MDMaxStep"]: Number of steps to take.\n\t\t\tPARAMS["MDTemp"]: Temperature to initialize or Thermostat to.\n\t\t\tPARAMS["MDdt"]: Timestep.\n\t\t\tPARAMS["MDV0"]: Sort of velocity initialization (None, or "Random")\n\t\t\tPARAMS["MDLogTrajectory"]: Write MD Trajectory.\n\t\tReturns:\n\t\t\tNothing.\n\t\t'
self.PForce = Force_
VelocityVerlet.__init__(self, None, self.PForce.mol0, name_, self.PForce.__call__)
if (v0_ is not None):
self.v = v0_
if (PARAMS['MDThermostat'] == 'Nose'):
self.Tstat = PeriodicNoseThermostat(self.m, self.v)
else:
print('Unthermostated Periodic Velocity Verlet.')
return
def Density(self):
'\n\t\tReturns the density in g/cm**3 of the bulk.\n\t\t'
return self.PForce.Density()
def WriteTrajectory(self):
m = Mol(self.atoms, self.x)
m.properties['Lattice'] = self.PForce.lattice.lattice.copy()
m.properties['Time'] = self.t
m.properties['KineticEnergy'] = self.KE
m.properties['PotEnergy'] = self.EPot
m.WriteXYZfile('./results/', ('MDTrajectory' + self.name), 'a', True)
return
def Prop(self):
'\n\t\tPropagate VelocityVerlet\n\t\t'
print('begin Periodic VelocityVerlet')
step = 0
self.md_log = np.zeros((self.maxstep, 7))
while (step < self.maxstep):
t = time.time()
self.t = (step * self.dt)
self.KE = KineticEnergy(self.v, self.m)
Teff = (((2.0 / 3.0) * self.KE) / IDEALGASR)
if (PARAMS['MDThermostat'] == None):
(self.x, self.v, self.a, self.EPot) = PeriodicVelocityVerletStep(self.PForce, self.a, self.x, self.v, self.m, self.dt)
else:
(self.x, self.v, self.a, self.EPot) = self.Tstat.step(self.PForce, self.a, self.x, self.v, self.m, self.dt)
self.md_log[(step, 0)] = self.t
self.md_log[(step, 4)] = self.KE
self.md_log[(step, 5)] = self.EPot
self.md_log[(step, 6)] = (self.KE + ((self.EPot - self.EPot0) * JOULEPERHARTREE))
if PARAMS['PrintTMTimer']:
PrintTMTIMER()
if (((step % 1) == 0) and PARAMS['MDLogTrajectory']):
self.WriteTrajectory()
if ((step % 500) == 0):
np.savetxt(((('./results/' + 'MDLog') + self.name) + '.txt'), self.md_log)
step += 1
LOGGER.info('Step: %i time: %.1f(fs) <KE>(kJ/mol): %.5f <|a|>(m/s2): %.5f <EPot>(Eh): %.5f <Etot>(kJ/mol): %.5f Rho(g/cm**3): %.5f Teff(K): %.5f', step, self.t, (self.KE / 1000.0), np.linalg.norm(self.a), self.EPot, ((self.KE / 1000.0) + (self.EPot * KJPERHARTREE)), self.Density(), Teff)
print(('per step cost:', (time.time() - t)))
return
|
class PeriodicBoxingDynamics(PeriodicVelocityVerlet):
def __init__(self, Force_, BoxingLatp_=np.eye(3), name_='PdicBoxMD', BoxingT_=400):
'\n\t\tPeriodically Crushes a molecule by shrinking it\'s lattice to obtain a desired density.\n\n\t\tArgs:\n\t\t\tForce_: A PeriodicForce object\n\t\t\tBoxingLatp_ : Final Lattice.\n\t\t\tBoxingT_: amount of time for the boxing dynamics in fs.\n\t\t\tPARAMS["MDMaxStep"]: Number of steps to take.\n\t\t\tPARAMS["MDTemp"]: Temperature to initialize or Thermostat to.\n\t\t\tPARAMS["MDdt"]: Timestep.\n\t\t\tPARAMS["MDV0"]: Sort of velocity initialization (None, or "Random")\n\t\t\tPARAMS["MDLogTrajectory"]: Write MD Trajectory.\n\t\tReturns:\n\t\t\tNothing.\n\t\t'
self.PForce = Force_
self.BoxingLat0 = Force_.lattice.lattice.copy()
self.BoxingLatp = BoxingLatp_.copy()
self.BoxingT = BoxingT_
VelocityVerlet.__init__(self, None, self.PForce.mol0, name_, self.PForce.__call__)
if (PARAMS['MDThermostat'] == 'Nose'):
self.Tstat = PeriodicNoseThermostat(self.m, self.v)
else:
print('Unthermostated Periodic Velocity Verlet.')
return
def Prop(self):
'\n\t\tPropagate VelocityVerlet\n\t\t'
step = 0
self.md_log = np.zeros((self.maxstep, 7))
while (step < self.maxstep):
t = time.time()
self.t = (step * self.dt)
self.KE = KineticEnergy(self.v, self.m)
if (self.t > self.BoxingT):
print('Exceeded Boxtime\n', self.BoxingLatp)
else:
newlattice = ((((self.BoxingT - self.t) / self.BoxingT) * self.BoxingLat0) + ((1.0 - ((self.BoxingT - self.t) / self.BoxingT)) * self.BoxingLatp))
self.x = self.PForce.AdjustLattice(self.x, self.PForce.lattice.lattice, newlattice)
self.v = self.PForce.AdjustLattice(self.v, self.PForce.lattice.lattice, newlattice)
self.a = self.PForce.AdjustLattice(self.a, self.PForce.lattice.lattice, newlattice)
self.PForce.ReLattice(newlattice)
print('Density:', self.Density())
Teff = (((2.0 / 3.0) * self.KE) / IDEALGASR)
if (PARAMS['MDThermostat'] == None):
(self.x, self.v, self.a, self.EPot) = PeriodicVelocityVerletStep(self.PForce, self.a, self.x, self.v, self.m, self.dt)
else:
(self.x, self.v, self.a, self.EPot) = self.Tstat.step(self.PForce, self.a, self.x, self.v, self.m, self.dt)
self.md_log[(step, 0)] = self.t
self.md_log[(step, 4)] = self.KE
self.md_log[(step, 5)] = self.EPot
self.md_log[(step, 6)] = (self.KE + ((self.EPot - self.EPot0) * JOULEPERHARTREE))
if (((step % 3) == 0) and PARAMS['MDLogTrajectory']):
self.WriteTrajectory()
if ((step % 500) == 0):
np.savetxt(((('./results/' + 'MDLog') + self.name) + '.txt'), self.md_log)
step += 1
LOGGER.info('Step: %i time: %.1f(fs) <KE>(kJ/mol): %.5f <|a|>(m/s2): %.5f <EPot>(Eh): %.5f <Etot>(kJ/mol): %.5f Teff(K): %.5f', step, self.t, (self.KE / 1000.0), np.linalg.norm(self.a), self.EPot, ((self.KE / 1000.0) + (self.EPot * KJPERHARTREE)), Teff)
print(('per step cost:', (time.time() - t)))
return
|
class PeriodicAnnealer(PeriodicVelocityVerlet):
def __init__(self, Force_, name_='PdicAnneal', AnnealThresh_=9e-06):
'\n\t\tAnneals a periodic molecule.\n\n\t\tArgs:\n\t\t\tForce_: A PeriodicForce object\n\t\t\tPARAMS["MDMaxStep"]: Number of steps to take.\n\t\t\tPARAMS["MDTemp"]: Temperature to initialize or Thermostat to.\n\t\t\tPARAMS["MDdt"]: Timestep.\n\t\t\tPARAMS["MDV0"]: Sort of velocity initialization (None, or "Random")\n\t\t\tPARAMS["MDLogTrajectory"]: Write MD Trajectory.\n\t\tReturns:\n\t\t\tNothing.\n\t\t'
PeriodicVelocityVerlet.__init__(self, Force_, name_)
self.dt = 0.1
self.v *= 0.0
self.AnnealT0 = PARAMS['MDAnnealT0']
self.AnnealSteps = PARAMS['MDAnnealSteps']
self.MinS = 0
self.MinE = 99999999.0
self.Minx = None
self.AnnealThresh = AnnealThresh_
self.Tstat = PeriodicNoseThermostat(self.m, self.v)
return
def Prop(self):
'\n\t\tPropagate VelocityVerlet\n\t\t'
step = 0
self.md_log = np.zeros((self.maxstep, 7))
while (step < self.AnnealSteps):
t = time.time()
self.t = (step * self.dt)
self.KE = KineticEnergy(self.v, self.m)
Teff = (((2.0 / 3.0) * self.KE) / IDEALGASR)
AnnealFrac = (float((self.AnnealSteps - step)) / self.AnnealSteps)
self.Tstat.T = (((self.AnnealT0 * AnnealFrac) + (PARAMS['MDAnnealTF'] * (1.0 - AnnealFrac))) + pow(10.0, (- 10.0)))
(self.x, self.v, self.a, self.EPot) = self.Tstat.step(self.PForce, self.a, self.x, self.v, self.m, self.dt)
if ((self.EPot < self.MinE) and (abs((self.EPot - self.MinE)) > self.AnnealThresh) and (step > 1)):
self.MinE = self.EPot
self.Minx = self.x.copy()
self.MinS = step
LOGGER.info(' -- cycling annealer -- ')
if (PARAMS['MDAnnealT0'] > PARAMS['MDAnnealTF']):
self.AnnealT0 = (self.Tstat.T + PARAMS['MDAnnealKickBack'])
print(self.x)
step = 0
self.md_log[(step, 0)] = self.t
self.md_log[(step, 4)] = self.KE
self.md_log[(step, 5)] = self.EPot
self.md_log[(step, 6)] = (self.KE + ((self.EPot - self.EPot0) * JOULEPERHARTREE))
if (((step % 3) == 0) and PARAMS['MDLogTrajectory']):
self.WriteTrajectory()
if ((step % 500) == 0):
np.savetxt(((('./results/' + 'MDLog') + self.name) + '.txt'), self.md_log)
step += 1
LOGGER.info('Step: %i time: %.1f(fs) <KE>(kJ/mol): %.5f <|a|>(m/s2): %.5f <EPot>(Eh): %.5f <Etot>(kJ/mol): %.5f Rho(g/cm3) %.5f Teff(K): %.5f T_target(K): %.5f', step, self.t, (self.KE / 1000.0), np.linalg.norm(self.a), self.EPot, ((self.KE / 1000.0) + (self.EPot * KJPERHARTREE)), self.Density(), Teff, self.Tstat.T)
print(('per step cost:', (time.time() - t)))
Mol(self.atoms, self.Minx).WriteXYZfile('./results', 'PAnnealMin', wprop=True)
return
|
class LocalReactions():
def __init__(self, f_, g0_, Nstat_=20):
'\n\t\tIn this case the bumps are pretty severe\n\t\tand the metadynamics is designed to sample reactions rapidly.\n\n\t\tArgs:\n\t\t\tf_: an energy, force routine (energy Hartree, Force Kcal/ang.)\n\t\t\tg0_: initial molecule.\n\t\t'
self.NStat = Nstat_
LOGGER.info('Finding reactions between %i local minima... ', self.NStat)
MOpt = MetaOptimizer(f_, g0_, StopAfter_=self.NStat)
mins = MOpt.MetaOpt()
LOGGER.info('---------------------------------')
LOGGER.info('--------- Nudged Bands ----------')
LOGGER.info('---------------------------------')
nbead = 15
self.path = np.zeros(shape=(((self.NStat - 1) * nbead), g0_.NAtoms(), 3))
for i in range((self.NStat - 1)):
g0 = Mol(g0_.atoms, mins[i])
g1 = Mol(g0_.atoms, mins[(i + 1)])
neb = NudgedElasticBand(f_, g0, g1, name_=('Neb' + str(i)), thresh_=0.004, nbeads_=nbead)
self.path[(i * nbead):((i + 1) * nbead)] = neb.Opt()
for i in range(self.path.shape[0]):
m = Mol(g0_.atoms, self.path[i])
m.WriteXYZfile('./results/', 'WebPath')
return
|
def FillWithGas(l=10.0):
'\n\tFills a box of length l with H2, CH4, N2, H2O, CO\n\t'
return
|
class PairProvider():
def __init__(self, nmol_, natom_):
'\n\t\tReturns pairs within a cutoff.\n\n\t\tArgs:\n\t\t\tnatom: number of atoms in a molecule.\n\t\t\tnmol: number of molecules in the batch.\n\t\t'
self.nmol = nmol_
self.natom = natom_
self.sess = None
self.xyzs_pl = None
self.nnz_pl = None
self.rng_pl = None
self.Prepare()
return
def PairsWithinCutoff(self, xyzs_pl, rng_pl, nnz_pl):
"\n\t\tIt's up to whatever routine calls this to chop out\n\t\tall the indices which are larger than the number of atoms in this molecule.\n\t\t"
nrawpairs = ((self.nmol * self.natom) * self.natom)
Ds = TFDistances(xyzs_pl)
Ds = tf.matrix_band_part(Ds, 0, (- 1))
Ds = tf.where(tf.equal(Ds, 0.0), (10000.0 * tf.ones_like(Ds)), Ds)
inds = tf.reshape(AllDoublesSet(tf.tile(tf.reshape(tf.range(self.natom), [1, self.natom]), [self.nmol, 1])), [((self.nmol * self.natom) * self.natom), 3])
nnzs = tf.reshape(tf.tile(tf.reshape(nnz_pl, [self.nmol, 1, 1]), [1, self.natom, self.natom]), [((self.nmol * self.natom) * self.natom), 1])
a1 = tf.slice(inds, [0, 1], [(- 1), 1])
a2 = tf.slice(inds, [0, 2], [(- 1), 1])
prs = tf.reshape(tf.less(Ds, rng_pl), [((self.nmol * self.natom) * self.natom), 1])
msk0 = tf.reshape(tf.logical_and(tf.logical_and(tf.less(a1, nnzs), tf.less(a2, nnzs)), prs), [nrawpairs])
inds = tf.boolean_mask(inds, msk0)
a1 = tf.slice(inds, [0, 1], [(- 1), 1])
a2 = tf.slice(inds, [0, 2], [(- 1), 1])
nodiag = tf.not_equal(a1, a2)
msk = tf.reshape(nodiag, [tf.shape(inds)[0]])
return tf.boolean_mask(inds, msk)
def Prepare(self):
with tf.Graph().as_default():
self.xyzs_pl = tf.placeholder(tf.float64, shape=tuple([None, self.natom, 3]))
self.rng_pl = tf.placeholder(tf.float64, shape=())
self.nnz_pl = tf.placeholder(tf.int32, shape=None)
init = tf.global_variables_initializer()
self.GetPairs = self.PairsWithinCutoff(self.xyzs_pl, self.rng_pl, self.nnz_pl)
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.sess.run(init)
return
def __call__(self, xpl, rngpl, nnz):
'\n\t\tReturns the nonzero pairs.\n\t\t'
tmp = self.sess.run([self.GetPairs], feed_dict={self.xyzs_pl: xpl, self.rng_pl: rngpl, self.nnz_pl: nnz})
return tmp[0]
|
class MolInstance_BP_Dipole(MolInstance_fc_sqdiff_BP):
'\n\t\tCalculate the Dipole of Molecules\n\t'
def __init__(self, TData_, Name_=None, Trainable_=True):
'\n\t\tRaise a Behler-Parinello TensorFlow instance.\n\n\t\tArgs:\n\t\t\tTData_: A TensorMolData instance.\n\t\t\tName_: A name for this instance.\n\t\t'
self.NetType = 'fc_sqdiff_BP'
MolInstance.__init__(self, TData_, Name_, Trainable_)
self.name = ((((((('Mol_' + self.TData.name) + '_') + self.TData.dig.name) + '_') + str(self.TData.order)) + '_') + self.NetType)
LOGGER.debug(('Raised Instance: ' + self.name))
self.train_dir = (PARAMS['networks_directory'] + self.name)
self.learning_rate = 0.0001
self.momentum = 0.95
if self.Trainable:
self.TData.LoadDataToScratch(self.tformer)
self.inshape = np.prod(self.TData.dig.eshape)
print('MolInstance_BP_Dipole.inshape: ', self.inshape)
self.eles = self.TData.eles
self.n_eles = len(self.eles)
self.MeanStoich = self.TData.MeanStoich
self.MeanNumAtoms = np.sum(self.MeanStoich)
self.AtomBranchNames = []
self.netcharge_output = None
self.dipole_output = None
self.inp_pl = None
self.mats_pl = None
self.coords = None
self.label_pl = None
self.batch_size = 10000
self.batch_size_output = 0
self.hidden1 = 100
self.hidden2 = 100
self.hidden3 = 100
self.summary_op = None
self.summary_writer = None
def Clean(self):
MolInstance_fc_sqdiff_BP.Clean(self)
self.coords_pl = None
self.netcharge_output = None
self.dipole_output = None
return
def TrainPrepare(self, continue_training=False):
'\n\t\tGet placeholders, graph and losses in order to begin training.\n\t\tAlso assigns the desired padding.\n\n\t\tArgs:\n\t\t\tcontinue_training: should read the graph variables from a saved checkpoint.\n\t\t'
self.MeanNumAtoms = self.TData.MeanNumAtoms
print('self.MeanNumAtoms: ', self.MeanNumAtoms)
self.batch_size_output = int(((1.5 * self.batch_size) / self.MeanNumAtoms))
print('Assigned batch input size: ', self.batch_size)
print('Assigned batch output size in BP_Dipole:', self.batch_size_output)
with tf.Graph().as_default():
self.inp_pl = []
self.mats_pl = []
self.coords_pl = []
for e in range(len(self.eles)):
self.inp_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.inshape])))
self.mats_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.batch_size_output])))
self.coords_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, 3])))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 4]))
(self.netcharge_output, self.dipole_output, self.atom_outputs) = self.inference(self.inp_pl, self.mats_pl, self.coords_pl)
self.check = tf.add_check_numerics_ops()
(self.total_loss, self.loss) = self.loss_op(self.netcharge_output, self.dipole_output, self.label_pl)
self.train_op = self.training(self.total_loss, self.learning_rate, self.momentum)
self.summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver = tf.train.Saver()
try:
metafiles = [x for x in os.listdir(self.train_dir) if (x.count('meta') > 0)]
if (len(metafiles) > 0):
most_recent_meta_file = metafiles[0]
LOGGER.info(('Restoring training from Metafile: ' + most_recent_meta_file))
config = tf.ConfigProto(allow_soft_placement=True)
self.sess = tf.Session(config=config)
self.saver = tf.train.import_meta_graph(((self.train_dir + '/') + most_recent_meta_file))
self.saver.restore(self.sess, tf.train.latest_checkpoint(self.train_dir))
except Exception as Ex:
print('Restore Failed', Ex)
pass
self.summary_writer = tf.summary.FileWriter(self.train_dir, self.sess.graph)
self.sess.run(init)
return
def loss_op(self, netcharge_output, dipole_output, labels):
'\n\t\ttotal_loss = scaler*l2(netcharge) + l2(dipole)\n\t\t'
charge_labels = tf.slice(labels, [0, 0], [self.batch_size_output, 1])
dipole_labels = tf.slice(labels, [0, 1], [self.batch_size_output, 3])
charge_diff = tf.subtract(netcharge_output, charge_labels)
dipole_diff = tf.subtract(dipole_output, dipole_labels)
charge_loss = tf.nn.l2_loss(charge_diff)
dipole_loss = tf.nn.l2_loss(dipole_diff)
loss = tf.add(charge_loss, dipole_loss)
tf.add_to_collection('losses', loss)
return (tf.add_n(tf.get_collection('losses'), name='total_loss'), loss)
def inference(self, inp_pl, mats_pl, coords_pl):
"\n\t\tBuilds a Behler-Parinello graph which also matches monopole,3-dipole, and 9-quadropole elements.\n\n\t\t- It has the shape of two energy networks in parallel.\n\t\t- One network produces the energy, the other produces the charge on an atom.\n\t\t- The charges are constrained to reproduce the molecular multipoles.\n\t\t- The energy and charge are together constrained to produce the molecular energy.\n\t\t- The same atomic linear transformation is used to produce the charges as the energy.\n\t\t- All multipoles have the form of a dot product with atomic charges. That's pre-computed externally\n\t\tThe attenuated coulomb energy has the form of a per-molecule vector-matrix-vector product.\n\t\tAnd it is generated as well by this routine.\n\n\t\tArgs:\n\t\t\t\tinp_pl: a list of (num_of atom type X flattened input shape) matrix of input cases.\n\t\t\t\tmats_pl: a list of (num_of atom type X batchsize) matrices which linearly combines the elements to give molecular outputs.\n\t\t\t\tmul_pl: Multipole inputs (see Mol::GenerateMultipoleInputs)\n\t\tReturns:\n\t\t\tAtom BP Energy, Atom Charges\n\t\t\tI'm thinking about doing the contractions for the multipoles and electrostatic energy loss in loss_op... haven't settled on it yet.\n\n\t\t"
branches = []
atom_outputs = []
hidden1_units = self.hidden1
hidden2_units = self.hidden2
hidden3_units = self.hidden3
netcharge_output = tf.zeros([self.batch_size_output, 1], dtype=self.tf_prec)
dipole_output = tf.zeros([self.batch_size_output, 3], dtype=self.tf_prec)
nrm1 = (1.0 / (10 + math.sqrt(float(self.inshape))))
nrm2 = (1.0 / (10 + math.sqrt(float(hidden1_units))))
nrm3 = (1.0 / (10 + math.sqrt(float(hidden2_units))))
nrm4 = (1.0 / (10 + math.sqrt(float(hidden3_units))))
LOGGER.info('Norms: %f,%f,%f', nrm1, nrm2, nrm3)
for e in range(len(self.eles)):
branches.append([])
inputs = inp_pl[e]
mats = mats_pl[e]
coords = coords_pl[e]
shp_in = tf.shape(inputs)
shp_coords = tf.shape(coords)
if (PARAMS['CheckLevel'] > 2):
tf.Print(tf.to_float(shp_in), [tf.to_float(shp_in)], message=(('Element ' + str(e)) + 'input shape '), first_n=10000000, summarize=100000000)
mats_shape = tf.shape(mats)
tf.Print(tf.to_float(mats_shape), [tf.to_float(mats_shape)], message=(('Element ' + str(e)) + 'mats shape '), first_n=10000000, summarize=100000000)
tf.Print(tf.to_float(shp_coords), [tf.to_float(shp_coords)], message=(('Element ' + str(e)) + 'coords shape '), first_n=10000000, summarize=100000000)
if (PARAMS['CheckLevel'] > 3):
tf.Print(tf.to_float(inputs), [tf.to_float(inputs)], message='This is input shape ', first_n=10000000, summarize=100000000)
with tf.name_scope((str(self.eles[e]) + '_hidden_1')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[self.inshape, hidden1_units], var_stddev=nrm1, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden1_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(tf.nn.relu((tf.matmul(inputs, weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_hidden_2')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden1_units, hidden2_units], var_stddev=nrm2, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden2_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(tf.nn.relu((tf.matmul(branches[(- 1)][(- 1)], weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_hidden_3')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden2_units, hidden3_units], var_stddev=nrm3, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden3_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(tf.nn.relu((tf.matmul(branches[(- 1)][(- 1)], weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_regression_linear')):
shp = tf.shape(inputs)
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden3_units, 1], var_stddev=nrm4, var_wd=None)
biases = tf.Variable(tf.zeros([1], dtype=self.tf_prec), name='biases')
branches[(- 1)].append((tf.matmul(branches[(- 1)][(- 1)], weights) + biases))
shp_out = tf.shape(branches[(- 1)][(- 1)])
cut = tf.slice(branches[(- 1)][(- 1)], [0, 0], [shp_out[0], 1])
rshp = tf.reshape(cut, [1, shp_out[0]])
atom_outputs.append(rshp)
coords_rshp = tf.transpose(coords)
coords_rshp_shape = tf.shape(coords_rshp)
dipole_tmp = tf.multiply(rshp, coords_rshp)
dipole_tmp = tf.reshape(dipole_tmp, [3, shp_out[0]])
netcharge = tf.matmul(rshp, mats)
dipole = tf.matmul(dipole_tmp, mats)
netcharge = tf.transpose(netcharge)
dipole = tf.transpose(dipole)
netcharge_output = tf.add(netcharge_output, netcharge)
dipole_output = tf.add(dipole_output, dipole)
tf.verify_tensor_all_finite(netcharge_output, 'Nan in output!!!')
tf.verify_tensor_all_finite(dipole_output, 'Nan in output!!!')
return (netcharge_output, dipole_output, atom_outputs)
def fill_feed_dict(self, batch_data):
'\n\t\tFill the tensorflow feed dictionary.\n\n\t\tArgs:\n\t\t\tbatch_data: a list of numpy arrays containing inputs, bounds, matrices and desired energies in that order.\n\t\t\tand placeholders to be assigned. (it can be longer than that c.f. TensorMolData_BP)\n\n\t\tReturns:\n\t\t\tFilled feed dictionary.\n\t\t'
for e in range(len(self.eles)):
if (not np.all(np.isfinite(batch_data[0][e]), axis=(0, 1))):
print('I was fed shit1')
raise Exception('DontEatShit')
if (not np.all(np.isfinite(batch_data[1][e]), axis=(0, 1))):
print('I was fed shit3')
raise Exception('DontEatShit')
if (not np.all(np.isfinite(batch_data[2][e]), axis=(0, 1))):
print('I was fed shit3')
raise Exception('DontEatShit')
if (not np.all(np.isfinite(batch_data[3]), axis=(0, 1))):
print('I was fed shit4')
raise Exception('DontEatShit')
feed_dict = {i: d for (i, d) in zip((((self.inp_pl + self.mats_pl) + self.coords_pl) + [self.label_pl]), (((batch_data[0] + batch_data[1]) + batch_data[2]) + [batch_data[3]]))}
return feed_dict
def train_step(self, step):
'\n\t\tPerform a single training step (complete processing of all input), using minibatches of size self.batch_size\n\n\t\tArgs:\n\t\t\tstep: the index of this step.\n\t\t'
Ncase_train = self.TData.NTrain
start_time = time.time()
train_loss = 0.0
num_of_mols = 0
for ministep in range(0, int((Ncase_train / self.batch_size))):
batch_data = self.TData.GetTrainBatch(self.batch_size, self.batch_size_output)
actual_mols = np.count_nonzero(np.any(batch_data[3][1:], axis=1))
(dump_, dump_2, total_loss_value, loss_value, netcharge_output, dipole_output) = self.sess.run([self.check, self.train_op, self.total_loss, self.loss, self.netcharge_output, self.dipole_output], feed_dict=self.fill_feed_dict(batch_data))
train_loss = (train_loss + loss_value)
duration = (time.time() - start_time)
num_of_mols += actual_mols
self.print_training(step, train_loss, num_of_mols, duration)
return
def test(self, step):
'\n\t\tPerform a single test step (complete processing of all input), using minibatches of size self.batch_size\n\n\t\tArgs:\n\t\t\tstep: the index of this step.\n\t\t'
test_loss = 0.0
start_time = time.time()
Ncase_test = self.TData.NTest
num_of_mols = 0
for ministep in range(0, int((Ncase_test / self.batch_size))):
batch_data = self.TData.GetTestBatch(self.batch_size, self.batch_size_output)
feed_dict = self.fill_feed_dict(batch_data)
actual_mols = np.count_nonzero(np.any(batch_data[3][1:], axis=1))
(total_loss_value, loss_value, netcharge_output, dipole_output, atom_outputs) = self.sess.run([self.total_loss, self.loss, self.netcharge_output, self.dipole_output, self.atom_outputs], feed_dict=feed_dict)
test_loss += loss_value
num_of_mols += actual_mols
print('testing result:')
print('acurrate charge, dipole:', batch_data[3][:20])
print('predict dipole', dipole_output[:20])
duration = (time.time() - start_time)
self.print_training(step, test_loss, num_of_mols, duration)
return (test_loss, feed_dict)
def print_training(self, step, loss, Ncase, duration, Train=True):
if Train:
print('step: ', ('%7d' % step), ' duration: ', ('%.5f' % duration), ' train loss: ', ('%.10f' % (float(loss) / Ncase)))
else:
print('step: ', ('%7d' % step), ' duration: ', ('%.5f' % duration), ' test loss: ', ('%.10f' % (float(loss) / NCase)))
return
def evaluate(self, batch_data):
nmol = batch_data[3].shape[0]
LOGGER.debug('nmol: %i', batch_data[3].shape[0])
self.batch_size_output = nmol
if (not self.sess):
LOGGER.info('loading the session..')
self.EvalPrepare()
feed_dict = self.fill_feed_dict(batch_data)
(netcharge, dipole, total_loss_value, loss_value, atom_outputs) = self.sess.run([self.netcharge_output, self.dipole_output, self.total_loss, self.loss, self.atom_outputs], feed_dict=feed_dict)
return (netcharge, (dipole / AUPERDEBYE), atom_outputs)
def EvalPrepare(self):
if isinstance(self.inshape, tuple):
if (len(self.inshape) > 1):
raise Exception('My input should be flat')
else:
self.inshape = self.inshape[0]
with tf.Graph().as_default(), tf.device('/job:localhost/replica:0/task:0/gpu:1'):
self.inp_pl = []
self.mats_pl = []
self.coords_pl = []
for e in range(len(self.eles)):
self.inp_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.inshape])))
self.mats_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.batch_size_output])))
self.coords_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, 3])))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 4]))
(self.netcharge_output, self.dipole_output, self.atom_outputs) = self.inference(self.inp_pl, self.mats_pl, self.coords_pl)
self.check = tf.add_check_numerics_ops()
(self.total_loss, self.loss) = self.loss_op(self.netcharge_output, self.dipole_output, self.label_pl)
self.train_op = self.training(self.total_loss, self.learning_rate, self.momentum)
self.summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
self.saver = tf.train.Saver()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver.restore(self.sess, self.chk_file)
return
def Prepare(self):
self.MeanNumAtoms = self.TData.MeanNumAtoms
self.batch_size_output = int(((1.5 * self.batch_size) / self.MeanNumAtoms))
with tf.Graph().as_default(), tf.device('/job:localhost/replica:0/task:0/gpu:1'):
self.inp_pl = []
self.mats_pl = []
self.coords = []
for e in range(len(self.eles)):
self.inp_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.inshape])))
self.mats_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.batch_size_output])))
self.coords_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, 3])))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 4]))
(self.netcharge_output, self.dipole_output, self.atom_outputs) = self.inference(self.inp_pl, self.mats_pl, self.coords_pl)
self.check = tf.add_check_numerics_ops()
(self.total_loss, self.loss) = self.loss_op(self.netcharge_output, self.dipole_out, self.label_pl)
self.train_op = self.training(self.total_loss, self.learning_rate, self.momentum)
self.summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
self.saver = tf.train.Saver()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver.restore(self.sess, self.chk_file)
return
|
class MolInstance_BP_Dipole_2(MolInstance_BP_Dipole):
'\n\t\tCalculate the Dipole of Molecules\n\t'
def __init__(self, TData_, Name_=None, Trainable_=True):
'\n\t\tRaise a Behler-Parinello TensorFlow instance.\n\n\t\tArgs:\n\t\t\tTData_: A TensorMolData instance.\n\t\t\tName_: A name for this instance.\n\t\t'
self.NetType = 'fc_sqdiff_BP'
MolInstance.__init__(self, TData_, Name_, Trainable_)
self.name = ((((((('Mol_' + self.TData.name) + '_') + self.TData.dig.name) + '_') + str(self.TData.order)) + '_') + self.NetType)
LOGGER.debug(('Raised Instance: ' + self.name))
self.train_dir = (PARAMS['networks_directory'] + self.name)
self.momentum = 0.95
if self.Trainable:
self.TData.LoadDataToScratch(self.tformer)
self.inshape = np.prod(self.TData.dig.eshape)
print('MolInstance_BP_Dipole.inshape: ', self.inshape)
self.eles = self.TData.eles
self.n_eles = len(self.eles)
self.MeanStoich = self.TData.MeanStoich
self.MeanNumAtoms = np.sum(self.MeanStoich)
self.AtomBranchNames = []
self.netcharge_output = None
self.dipole_output = None
self.inp_pl = None
self.mats_pl = None
self.coords = None
self.label_pl = None
self.natom_pl = None
self.charge_gradient = None
self.output_list = None
self.unscaled_atom_outputs = None
self.batch_size = 10000
self.batch_size_output = 0
self.summary_op = None
self.summary_writer = None
def Clean(self):
MolInstance_BP_Dipole.Clean(self)
self.natom_pl = None
self.net_charge = None
self.charge_gradient = None
self.unscaled_atom_outputs = None
self.output_list = None
return
def TrainPrepare(self, continue_training=False):
'\n\t\tGet placeholders, graph and losses in order to begin training.\n\t\tAlso assigns the desired padding.\n\n\t\tArgs:\n\t\t\tcontinue_training: should read the graph variables from a saved checkpoint.\n\t\t'
self.MeanNumAtoms = self.TData.MeanNumAtoms
print('self.MeanNumAtoms: ', self.MeanNumAtoms)
self.batch_size_output = int(((1.5 * self.batch_size) / self.MeanNumAtoms))
print('Assigned batch input size: ', self.batch_size)
print('Assigned batch output size in BP_Dipole:', self.batch_size_output)
with tf.Graph().as_default():
self.inp_pl = []
self.mats_pl = []
self.coords_pl = []
for e in range(len(self.eles)):
self.inp_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.inshape])))
self.mats_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.batch_size_output])))
self.coords_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, 3])))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 3]))
self.natom_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 1]))
(self.dipole_output, self.atom_outputs, self.unscaled_atom_outputs, self.net_charge) = self.inference(self.inp_pl, self.mats_pl, self.coords_pl, self.natom_pl)
self.check = tf.add_check_numerics_ops()
(self.total_loss, self.loss) = self.loss_op(self.dipole_output, self.label_pl)
self.train_op = self.training(self.total_loss, self.learning_rate, self.momentum)
self.summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver = tf.train.Saver()
self.summary_writer = tf.summary.FileWriter(self.train_dir, self.sess.graph)
self.sess.run(init)
return
def loss_op(self, dipole_output, labels):
'\n\t\ttotal_loss = l2(dipole)\n\t\t'
dipole_diff = tf.subtract(dipole_output, labels)
loss = tf.nn.l2_loss(dipole_diff)
tf.add_to_collection('losses', loss)
return (tf.add_n(tf.get_collection('losses'), name='total_loss'), loss)
def inference(self, inp_pl, mats_pl, coords_pl, natom_pl):
"\n\t\tBuilds a Behler-Parinello graph which also matches monopole,3-dipole, and 9-quadropole elements.\n\n\t\t- It has the shape of two energy networks in parallel.\n\t\t- One network produces the energy, the other produces the charge on an atom.\n\t\t- The charges are constrained to reproduce the molecular multipoles.\n\t\t- The energy and charge are together constrained to produce the molecular energy.\n\t\t- The same atomic linear transformation is used to produce the charges as the energy.\n\t\t- All multipoles have the form of a dot product with atomic charges. That's pre-computed externally\n\t\tThe attenuated coulomb energy has the form of a per-molecule vector-matrix-vector product.\n\t\tAnd it is generated as well by this routine.\n\n\t\tArgs:\n\t\t\t\tinp_pl: a list of (num_of atom type X flattened input shape) matrix of input cases.\n\t\t\t\tmats_pl: a list of (num_of atom type X batchsize) matrices which linearly combines the elements to give molecular outputs.\n\t\t\t\tmul_pl: Multipole inputs (see Mol::GenerateMultipoleInputs)\n\t\tReturns:\n\t\t\tAtom BP Energy, Atom Charges\n\t\t\tI'm thinking about doing the contractions for the multipoles and electrostatic energy loss in loss_op... haven't settled on it yet.\n\n\t\t"
branches = []
atom_outputs = []
hidden1_units = self.hidden1
hidden2_units = self.hidden2
hidden3_units = self.hidden3
netcharge_output = tf.zeros([self.batch_size_output, 1], dtype=self.tf_prec)
scaled_netcharge_output = tf.zeros([1, self.batch_size_output], dtype=self.tf_prec)
dipole_output = tf.zeros([self.batch_size_output, 3], dtype=self.tf_prec)
nrm1 = (1.0 / (10 + math.sqrt(float(self.inshape))))
nrm2 = (1.0 / (10 + math.sqrt(float(hidden1_units))))
nrm3 = (1.0 / (10 + math.sqrt(float(hidden2_units))))
nrm4 = (1.0 / (10 + math.sqrt(float(hidden3_units))))
LOGGER.info('Norms: %f,%f,%f', nrm1, nrm2, nrm3)
for e in range(len(self.eles)):
branches.append([])
inputs = inp_pl[e]
mats = mats_pl[e]
coords = coords_pl[e]
shp_in = tf.shape(inputs)
shp_coords = tf.shape(coords)
if (PARAMS['CheckLevel'] > 2):
tf.Print(tf.to_float(shp_in), [tf.to_float(shp_in)], message=(('Element ' + str(e)) + 'input shape '), first_n=10000000, summarize=100000000)
mats_shape = tf.shape(mats)
tf.Print(tf.to_float(mats_shape), [tf.to_float(mats_shape)], message=(('Element ' + str(e)) + 'mats shape '), first_n=10000000, summarize=100000000)
tf.Print(tf.to_float(shp_coords), [tf.to_float(shp_coords)], message=(('Element ' + str(e)) + 'coords shape '), first_n=10000000, summarize=100000000)
if (PARAMS['CheckLevel'] > 3):
tf.Print(tf.to_float(inputs), [tf.to_float(inputs)], message='This is input shape ', first_n=10000000, summarize=100000000)
with tf.name_scope((str(self.eles[e]) + '_hidden_1')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[self.inshape, hidden1_units], var_stddev=nrm1, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden1_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(tf.nn.relu((tf.matmul(inputs, weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_hidden_2')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden1_units, hidden2_units], var_stddev=nrm2, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden2_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(tf.nn.relu((tf.matmul(branches[(- 1)][(- 1)], weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_hidden_3')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden2_units, hidden3_units], var_stddev=nrm3, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden3_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(tf.nn.relu((tf.matmul(branches[(- 1)][(- 1)], weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_regression_linear')):
shp = tf.shape(inputs)
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden3_units, 1], var_stddev=nrm4, var_wd=None)
biases = tf.Variable(tf.zeros([1], dtype=self.tf_prec), name='biases')
branches[(- 1)].append((tf.matmul(branches[(- 1)][(- 1)], weights) + biases))
shp_out = tf.shape(branches[(- 1)][(- 1)])
cut = tf.slice(branches[(- 1)][(- 1)], [0, 0], [shp_out[0], 1])
rshp = tf.reshape(cut, [1, shp_out[0]])
atom_outputs.append(rshp)
netcharge = tf.matmul(rshp, mats)
netcharge = tf.transpose(netcharge)
netcharge_output = tf.add(netcharge_output, netcharge)
delta_charge = tf.multiply(netcharge_output, natom_pl)
delta_charge = tf.transpose(delta_charge)
scaled_charge_list = []
for e in range(len(self.eles)):
mats = mats_pl[e]
shp_out = tf.shape(atom_outputs[e])
coords = coords_pl[e]
trans_mats = tf.transpose(mats)
ele_delta_charge = tf.matmul(delta_charge, trans_mats)
scaled_charge = tf.subtract(atom_outputs[e], ele_delta_charge)
scaled_charge_list.append(scaled_charge)
scaled_netcharge = tf.matmul(scaled_charge, mats)
scaled_netcharge_output = tf.add(scaled_netcharge_output, scaled_netcharge)
coords_rshp = tf.transpose(coords)
dipole_tmp = tf.multiply(scaled_charge, coords_rshp)
dipole_tmp = tf.reshape(dipole_tmp, [3, shp_out[1]])
dipole = tf.matmul(dipole_tmp, mats)
dipole = tf.transpose(dipole)
dipole_output = tf.add(dipole_output, dipole)
tf.verify_tensor_all_finite(netcharge_output, 'Nan in output!!!')
tf.verify_tensor_all_finite(dipole_output, 'Nan in output!!!')
return (dipole_output, scaled_charge_list, atom_outputs, scaled_netcharge_output)
def fill_feed_dict(self, batch_data):
'\n\t\tFill the tensorflow feed dictionary.\n\n\t\tArgs:\n\t\t\tbatch_data: a list of numpy arrays containing inputs, bounds, matrices and desired energies in that order.\n\t\t\tand placeholders to be assigned. (it can be longer than that c.f. TensorMolData_BP)\n\n\t\tReturns:\n\t\t\tFilled feed dictionary.\n\t\t'
for e in range(len(self.eles)):
if (not np.all(np.isfinite(batch_data[0][e]), axis=(0, 1))):
print('I was fed shit1')
raise Exception('DontEatShit')
if (not np.all(np.isfinite(batch_data[1][e]), axis=(0, 1))):
print('I was fed shit3')
raise Exception('DontEatShit')
if (not np.all(np.isfinite(batch_data[2][e]), axis=(0, 1))):
print('I was fed shit3')
raise Exception('DontEatShit')
if (not np.all(np.isfinite(batch_data[4]), axis=(0, 1))):
print('I was fed shit5')
raise Exception('DontEatShit')
feed_dict = {i: d for (i, d) in zip(((((self.inp_pl + self.mats_pl) + self.coords_pl) + [self.natom_pl]) + [self.label_pl]), ((((batch_data[0] + batch_data[1]) + batch_data[2]) + [batch_data[3]]) + [batch_data[4]]))}
return feed_dict
def train_step(self, step):
'\n\t\tPerform a single training step (complete processing of all input), using minibatches of size self.batch_size\n\n\t\tArgs:\n\t\t\tstep: the index of this step.\n\t\t'
Ncase_train = self.TData.NTrain
start_time = time.time()
train_loss = 0.0
num_of_mols = 0
for ministep in range(0, int((Ncase_train / self.batch_size))):
batch_data = self.TData.GetTrainBatch(self.batch_size, self.batch_size_output)
actual_mols = np.count_nonzero(np.any(batch_data[3][1:], axis=1))
(dump_, dump_2, total_loss_value, loss_value, dipole_output, atom_outputs, net_charge) = self.sess.run([self.check, self.train_op, self.total_loss, self.loss, self.dipole_output, self.atom_outputs, self.net_charge], feed_dict=self.fill_feed_dict(batch_data))
train_loss = (train_loss + loss_value)
duration = (time.time() - start_time)
num_of_mols += actual_mols
self.print_training(step, train_loss, num_of_mols, duration)
return
def test(self, step):
'\n\t\tPerform a single test step (complete processing of all input), using minibatches of size self.batch_size\n\n\t\tArgs:\n\t\t\tstep: the index of this step.\n\t\t'
test_loss = 0.0
start_time = time.time()
Ncase_test = self.TData.NTest
num_of_mols = 0
for ministep in range(0, int((Ncase_test / self.batch_size))):
batch_data = self.TData.GetTestBatch(self.batch_size, self.batch_size_output)
feed_dict = self.fill_feed_dict(batch_data)
actual_mols = np.count_nonzero(np.any(batch_data[3][1:], axis=1))
(total_loss_value, loss_value, dipole_output, atom_outputs, net_charge) = self.sess.run([self.total_loss, self.loss, self.dipole_output, self.atom_outputs, self.net_charge], feed_dict=feed_dict)
test_loss += loss_value
num_of_mols += actual_mols
print('acurrate charge, dipole:', batch_data[4][:20], ' dipole shape:', batch_data[4].shape)
print('predict dipole', dipole_output[:20])
duration = (time.time() - start_time)
self.print_training(step, test_loss, num_of_mols, duration)
return (test_loss, feed_dict)
def print_training(self, step, loss, Ncase, duration, Train=True):
if Train:
print('step: ', ('%7d' % step), ' duration: ', ('%.5f' % duration), ' train loss: ', ('%.10f' % (float(loss) / Ncase)))
else:
print('step: ', ('%7d' % step), ' duration: ', ('%.5f' % duration), ' test loss: ', ('%.10f' % (float(loss) / NCase)))
return
def evaluate(self, batch_data, IfChargeGrad=False):
nmol = batch_data[4].shape[0]
LOGGER.debug('nmol: %i', batch_data[4].shape[0])
self.batch_size_output = nmol
if (not self.sess):
LOGGER.info('loading the session..')
self.EvalPrepare()
feed_dict = self.fill_feed_dict(batch_data)
if (not IfChargeGrad):
output_list = self.sess.run([self.output_list], feed_dict=feed_dict)
return ((output_list[0][0] / AUPERDEBYE), output_list[0][1])
else:
(output_list, charge_gradient) = self.sess.run([self.output_list, self.charge_gradient], feed_dict=feed_dict)
return ((output_list[0] / AUPERDEBYE), output_list[1], charge_gradient)
def EvalPrepare(self):
if isinstance(self.inshape, tuple):
if (len(self.inshape) > 1):
raise Exception('My input should be flat')
else:
self.inshape = self.inshape[0]
with tf.Graph().as_default(), tf.device('/job:localhost/replica:0/task:0/gpu:1'):
self.inp_pl = []
self.mats_pl = []
self.coords_pl = []
for e in range(len(self.eles)):
self.inp_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.inshape])))
self.mats_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.batch_size_output])))
self.coords_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, 3])))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 3]))
self.natom_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 1]))
self.output_list = self.inference(self.inp_pl, self.mats_pl, self.coords_pl, self.natom_pl)
self.charge_gradient = tf.gradients(self.output_list[2], self.inp_pl)
self.check = tf.add_check_numerics_ops()
self.summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
self.saver = tf.train.Saver()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver.restore(self.sess, self.chk_file)
return
def Prepare(self):
self.MeanNumAtoms = self.TData.MeanNumAtoms
self.batch_size_output = int(((1.5 * self.batch_size) / self.MeanNumAtoms))
with tf.Graph().as_default(), tf.device('/job:localhost/replica:0/task:0/gpu:1'):
self.inp_pl = []
self.mats_pl = []
self.coords = []
for e in range(len(self.eles)):
self.inp_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.inshape])))
self.mats_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, self.batch_size_output])))
self.coords_pl.append(tf.placeholder(self.tf_prec, shape=tuple([None, 3])))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 3]))
self.natom_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size_output, 1]))
(self.dipole_output, self.atom_outputs, self.unscaled_atom_outputs, self.net_charge) = self.inference(self.inp_pl, self.mats_pl, self.coords_pl, self.natom_pl)
(self.total_loss, self.loss) = self.loss_op(self.dipole_out, self.label_pl)
self.train_op = self.training(self.total_loss, self.learning_rate, self.momentum)
self.summary_op = tf.summary.merge_all()
init = tf.global_variables_initializer()
self.saver = tf.train.Saver()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver.restore(self.sess, self.chk_file)
return
|
class MolInstance_BP_Dipole_2_Direct(MolInstance_DirectBP_NoGrad):
'\n\t\tCalculate the Dipole of Molecules\n\t'
def __init__(self, TData_, Name_=None, Trainable_=True, ForceType_='LJ'):
'\n\t\tArgs:\n\t\t TData_: A TensorMolData instance.\n\t\t Name_: A name for this instance.\n\t\t'
self.NetType = 'RawBP_Dipole'
MolInstance.__init__(self, TData_, Name_, Trainable_)
self.SFPa = None
self.SFPr = None
self.Ra_cut = None
self.Rr_cut = None
self.MaxNAtoms = self.TData.MaxNAtoms
self.eles = self.TData.eles
self.n_eles = len(self.eles)
self.eles_np = np.asarray(self.eles).reshape((self.n_eles, 1))
self.eles_pairs = []
for i in range(len(self.eles)):
for j in range(i, len(self.eles)):
self.eles_pairs.append([self.eles[i], self.eles[j]])
self.eles_pairs_np = np.asarray(self.eles_pairs)
self.SetANI1Param()
self.batch_size = PARAMS['batch_size']
self.NetType = 'RawBP_Dipole'
self.name = ((((('Mol_' + self.TData.name) + '_') + self.TData.dig.name) + '_') + self.NetType)
LOGGER.debug(('Raised Instance: ' + self.name))
self.train_dir = (PARAMS['networks_directory'] + self.name)
if self.Trainable:
self.TData.LoadDataToScratch(self.tformer)
self.xyzs_pl = None
self.Zs_pl = None
self.label_pl = None
self.sess = None
self.total_loss = None
self.loss = None
self.train_op = None
self.summary_op = None
self.saver = None
self.summary_writer = None
self.netcharge_output = None
self.dipole_output = None
self.natom_pl = None
self.charge_gradient = None
self.output_list = None
self.unscaled_atom_outputs = None
def Clean(self):
MolInstance_DirectBP_NoGrad.Clean(self)
self.unscaled_atom_outputs = None
self.netcharge_output = None
self.dipole_output = None
self.natom_pl = None
self.output_list = None
return
def TrainPrepare(self, continue_training=False):
'\n\t\tGet placeholders, graph and losses in order to begin training.\n\t\tAlso assigns the desired padding.\n\n\t\tArgs:\n\t\t\tcontinue_training: should read the graph variables from a saved checkpoint.\n\t\t'
with tf.Graph().as_default():
self.xyzs_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size, self.MaxNAtoms, 3]))
self.Zs_pl = tf.placeholder(tf.int64, shape=tuple([self.batch_size, self.MaxNAtoms]))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size, 3]))
self.natom_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size]))
Ele = tf.Variable(self.eles_np, trainable=False, dtype=tf.int64)
Elep = tf.Variable(self.eles_pairs_np, trainable=False, dtype=tf.int64)
SFPa = tf.Variable(self.SFPa, trainable=False, dtype=self.tf_prec)
SFPr = tf.Variable(self.SFPr, trainable=False, dtype=self.tf_prec)
SFPa2 = tf.Variable(self.SFPa2, trainable=False, dtype=self.tf_prec)
SFPr2 = tf.Variable(self.SFPr2, trainable=False, dtype=self.tf_prec)
Rr_cut = tf.Variable(self.Rr_cut, trainable=False, dtype=self.tf_prec)
Ra_cut = tf.Variable(self.Ra_cut, trainable=False, dtype=self.tf_prec)
zeta = tf.Variable(self.zeta, trainable=False, dtype=self.tf_prec)
eta = tf.Variable(self.eta, trainable=False, dtype=self.tf_prec)
(self.Scatter_Sym, self.Sym_Index) = TFSymSet_Scattered_Update_Scatter(self.xyzs_pl, self.Zs_pl, Ele, SFPr2, Rr_cut, Elep, SFPa2, zeta, eta, Ra_cut)
(self.dipole_output, self.atom_outputs, self.unscaled_atom_outputs) = self.inference(self.Scatter_Sym, self.Sym_Index, self.xyzs_pl, self.natom_pl)
self.check = tf.add_check_numerics_ops()
(self.total_loss, self.loss) = self.loss_op(self.dipole_output, self.label_pl)
self.train_op = self.training(self.total_loss, self.learning_rate, self.momentum)
init = tf.global_variables_initializer()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver = tf.train.Saver()
self.summary_writer = tf.summary.FileWriter(self.train_dir, self.sess.graph)
self.sess.run(init)
return
def loss_op(self, dipole_output, labels):
'\n\t\ttotal_loss = l2(dipole)\n\t\t'
dipole_diff = tf.subtract(dipole_output, labels)
loss = tf.nn.l2_loss(dipole_diff)
tf.add_to_collection('losses', loss)
return (tf.add_n(tf.get_collection('losses'), name='total_loss'), loss)
def inference(self, inp, indexs, xyzs, natom):
'\n\t\tBuilds a Behler-Parinello graph\n\n\t\tArgs:\n\t\t\tinp: a list of (num_of atom type X flattened input shape) matrix of input cases.\n\t\t\tindex: a list of (num_of atom type X batchsize) array which linearly combines the elements\n\t\tReturns:\n\t\t\tThe BP graph output\n\t\t'
branches = []
atom_outputs = []
hidden1_units = self.hidden1
hidden2_units = self.hidden2
hidden3_units = self.hidden3
output = tf.zeros([self.batch_size, self.MaxNAtoms], dtype=self.tf_prec)
nrm1 = (1.0 / (10 + math.sqrt(float(self.inshape))))
nrm2 = (1.0 / (10 + math.sqrt(float(hidden1_units))))
nrm3 = (1.0 / (10 + math.sqrt(float(hidden2_units))))
nrm4 = (1.0 / (10 + math.sqrt(float(hidden3_units))))
print('Norms:', nrm1, nrm2, nrm3)
LOGGER.info('Layer initial Norms: %f %f %f', nrm1, nrm2, nrm3)
for e in range(len(self.eles)):
branches.append([])
inputs = inp[e]
shp_in = tf.shape(inputs)
index = tf.cast(indexs[e], tf.int64)
if (PARAMS['CheckLevel'] > 2):
tf.Print(tf.to_float(shp_in), [tf.to_float(shp_in)], message=(('Element ' + str(e)) + 'input shape '), first_n=10000000, summarize=100000000)
index_shape = tf.shape(index)
tf.Print(tf.to_float(index_shape), [tf.to_float(index_shape)], message=(('Element ' + str(e)) + 'index shape '), first_n=10000000, summarize=100000000)
if (PARAMS['CheckLevel'] > 3):
tf.Print(tf.to_float(inputs), [tf.to_float(inputs)], message='This is input shape ', first_n=10000000, summarize=100000000)
with tf.name_scope((str(self.eles[e]) + '_hidden_1')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[self.inshape, hidden1_units], var_stddev=nrm1, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden1_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(self.activation_function((tf.matmul(inputs, weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_hidden_2')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden1_units, hidden2_units], var_stddev=nrm2, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden2_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(self.activation_function((tf.matmul(branches[(- 1)][(- 1)], weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_hidden_3')):
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden2_units, hidden3_units], var_stddev=nrm3, var_wd=0.001)
biases = tf.Variable(tf.zeros([hidden3_units], dtype=self.tf_prec), name='biases')
branches[(- 1)].append(self.activation_function((tf.matmul(branches[(- 1)][(- 1)], weights) + biases)))
with tf.name_scope((str(self.eles[e]) + '_regression_linear')):
shp = tf.shape(inputs)
weights = self._variable_with_weight_decay(var_name='weights', var_shape=[hidden3_units, 1], var_stddev=nrm4, var_wd=None)
biases = tf.Variable(tf.zeros([1], dtype=self.tf_prec), name='biases')
branches[(- 1)].append((tf.matmul(branches[(- 1)][(- 1)], weights) + biases))
shp_out = tf.shape(branches[(- 1)][(- 1)])
cut = tf.slice(branches[(- 1)][(- 1)], [0, 0], [shp_out[0], 1])
rshp = tf.reshape(cut, [1, shp_out[0]])
atom_outputs.append(rshp)
rshpflat = tf.reshape(cut, [shp_out[0]])
atom_indice = tf.slice(index, [0, 1], [shp_out[0], 1])
ToAdd = tf.reshape(tf.scatter_nd(atom_indice, rshpflat, [(self.batch_size * self.MaxNAtoms)]), [self.batch_size, self.MaxNAtoms])
output = tf.add(output, ToAdd)
tf.verify_tensor_all_finite(output, 'Nan in output!!!')
netcharge = tf.reshape(tf.reduce_sum(output, axis=1), [self.batch_size])
delta_charge = tf.multiply(netcharge, natom)
delta_charge_tile = tf.tile(tf.reshape(delta_charge, [self.batch_size, 1]), [1, self.MaxNAtoms])
scaled_charge = tf.subtract(output, delta_charge_tile)
flat_dipole = tf.multiply(tf.reshape(xyzs, [(self.batch_size * self.MaxNAtoms), 3]), tf.reshape(scaled_charge, [(self.batch_size * self.MaxNAtoms), 1]))
dipole = tf.reduce_sum(tf.reshape(flat_dipole, [self.batch_size, self.MaxNAtoms, 3]), axis=1)
return (dipole, scaled_charge, output)
def fill_feed_dict(self, batch_data):
'\n\t\tFill the tensorflow feed dictionary.\n\n\t\tArgs:\n\t\t\tbatch_data: a list of numpy arrays containing inputs, bounds, matrices and desired energies in that order.\n\t\t\tand placeholders to be assigned. (it can be longer than that c.f. TensorMolData_BP)\n\n\t\tReturns:\n\t\t\tFilled feed dictionary.\n\t\t'
if (not np.all(np.isfinite(np.sum(batch_data[2], axis=1)), axis=0)):
print('I was fed shit')
raise Exception('DontEatShit')
feed_dict = {i: d for (i, d) in zip(((([self.xyzs_pl] + [self.Zs_pl]) + [self.label_pl]) + [self.natom_pl]), ((([batch_data[0]] + [batch_data[1]]) + [batch_data[2]]) + [batch_data[3]]))}
return feed_dict
def train_step(self, step):
'\n\t\tPerform a single training step (complete processing of all input), using minibatches of size self.batch_size\n\n\t\tArgs:\n\t\t step: the index of this step.\n\t\t'
Ncase_train = self.TData.NTrain
start_time = time.time()
train_loss = 0.0
train_energy_loss = 0.0
train_grads_loss = 0.0
num_of_mols = 0
pre_output = np.zeros(self.batch_size, dtype=np.float64)
for ministep in range(0, int((Ncase_train / self.batch_size))):
batch_data = self.TData.GetTrainBatch(self.batch_size)
actual_mols = self.batch_size
t = time.time()
(dump_, dump_2, total_loss_value, loss_value, dipole_output, atom_outputs) = self.sess.run([self.check, self.train_op, self.total_loss, self.loss, self.dipole_output, self.atom_outputs], feed_dict=self.fill_feed_dict(batch_data))
train_loss = (train_loss + loss_value)
duration = (time.time() - start_time)
num_of_mols += actual_mols
self.print_training(step, train_loss, num_of_mols, duration)
return
def test(self, step):
'\n\t\tPerform a single test step (complete processing of all input), using minibatches of size self.batch_size\n\n\t\tArgs:\n\t\t\tstep: the index of this step.\n\t\t'
test_loss = 0.0
start_time = time.time()
Ncase_test = self.TData.NTest
num_of_mols = 0
for ministep in range(0, int((Ncase_test / self.batch_size))):
batch_data = self.TData.GetTestBatch(self.batch_size)
feed_dict = self.fill_feed_dict(batch_data)
actual_mols = self.batch_size
(total_loss_value, loss_value, dipole_output, atom_outputs) = self.sess.run([self.total_loss, self.loss, self.dipole_output, self.atom_outputs], feed_dict=feed_dict)
test_loss += loss_value
num_of_mols += actual_mols
duration = (time.time() - start_time)
print('testing...')
self.print_training(step, test_loss, num_of_mols, duration)
return (test_loss, feed_dict)
def evaluate(self, batch_data, IfGrad=True):
'\n\t\tEvaluate the energy, atom energies, and IfGrad = True the gradients\n\t\tof this Direct Behler-Parinello graph.\n\t\t'
nmol = batch_data[2].shape[0]
self.MaxNAtoms = batch_data[0].shape[1]
LOGGER.debug('nmol: %i', batch_data[2].shape[0])
self.batch_size = nmol
if (not self.sess):
print('loading the session..')
self.EvalPrepare()
feed_dict = self.fill_feed_dict(batch_data)
(dipole_output, atom_outputs) = self.sess.run([self.dipole_output, self.atom_outputs], feed_dict=feed_dict)
return (dipole_output, atom_outputs)
def Prepare(self):
self.TrainPrepare()
return
def EvalPrepare(self):
"\n\t\tDoesn't generate the training operations or losses.\n\t\t"
with tf.Graph().as_default():
self.xyzs_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size, self.MaxNAtoms, 3]))
self.Zs_pl = tf.placeholder(tf.int64, shape=tuple([self.batch_size, self.MaxNAtoms]))
self.label_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size, 3]))
self.natom_pl = tf.placeholder(self.tf_prec, shape=tuple([self.batch_size]))
Ele = tf.Variable(self.eles_np, trainable=False, dtype=tf.int64)
Elep = tf.Variable(self.eles_pairs_np, trainable=False, dtype=tf.int64)
SFPa = tf.Variable(self.SFPa, trainable=False, dtype=self.tf_prec)
SFPr = tf.Variable(self.SFPr, trainable=False, dtype=self.tf_prec)
SFPa2 = tf.Variable(self.SFPa2, trainable=False, dtype=self.tf_prec)
SFPr2 = tf.Variable(self.SFPr2, trainable=False, dtype=self.tf_prec)
Rr_cut = tf.Variable(self.Rr_cut, trainable=False, dtype=self.tf_prec)
Ra_cut = tf.Variable(self.Ra_cut, trainable=False, dtype=self.tf_prec)
zeta = tf.Variable(self.zeta, trainable=False, dtype=self.tf_prec)
eta = tf.Variable(self.eta, trainable=False, dtype=self.tf_prec)
(self.Scatter_Sym, self.Sym_Index) = TFSymSet_Scattered_Update_Scatter(self.xyzs_pl, self.Zs_pl, Ele, SFPr2, Rr_cut, Elep, SFPa2, zeta, eta, Ra_cut)
(self.dipole_output, self.atom_outputs, self.unscaled_atom_outputs) = self.inference(self.Scatter_Sym, self.Sym_Index, self.xyzs_pl, self.natom_pl)
self.check = tf.add_check_numerics_ops()
self.sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
self.saver = tf.train.Saver()
self.saver.restore(self.sess, self.chk_file)
self.summary_writer = tf.summary.FileWriter(self.train_dir, self.sess.graph)
print('Prepared for Evaluation...')
return
|
class TMParams(dict):
def __init__(self, *args, **kwargs):
myparam = kwargs.pop('myparam', '')
dict.__init__(self, *args, **kwargs)
self['GIT_REVISION'] = os.popen('git rev-parse --short HEAD').read()
self['CheckLevel'] = 1
self['PrintTMTimer'] = False
self['MAX_ATOMIC_NUMBER'] = 10
self['RBFS'] = np.array([[0.35, 0.35], [0.7, 0.35], [1.05, 0.35], [1.4, 0.35], [1.75, 0.35], [2.1, 0.35], [2.45, 0.35], [2.8, 0.35], [3.15, 0.35], [3.5, 0.35], [3.85, 0.35], [4.2, 0.35], [4.55, 0.35], [4.9, 0.35]])
self['ANES'] = np.array([2.2, 1.0, 1.0, 1.0, 1.0, 2.55, 3.04, 3.44])
self['SRBF'] = np.zeros((self['RBFS'].shape[0], self['RBFS'].shape[0]))
self['SH_LMAX'] = 4
self['SH_NRAD'] = 14
self['SH_ORTH'] = 1
self['SH_rot_invar'] = False
self['SH_MAXNR'] = self['RBFS'].shape[0]
self['AN1_r_Rc'] = 4.6
self['AN1_a_Rc'] = 3.1
self['AN1_eta'] = 4.0
self['AN1_zeta'] = 8.0
self['AN1_num_r_Rs'] = 32
self['AN1_num_a_Rs'] = 8
self['AN1_num_a_As'] = 8
self['AN1_r_Rs'] = np.array([((self['AN1_r_Rc'] * i) / self['AN1_num_r_Rs']) for i in range(0, self['AN1_num_r_Rs'])])
self['AN1_a_Rs'] = np.array([((self['AN1_a_Rc'] * i) / self['AN1_num_a_Rs']) for i in range(0, self['AN1_num_a_Rs'])])
self['AN1_a_As'] = np.array([(((2.0 * Pi) * i) / self['AN1_num_a_As']) for i in range(0, self['AN1_num_a_As'])])
self['GradScalar'] = 1.0
self['DipoleScalar'] = 1.0
self['RotateSet'] = 0
self['TransformSet'] = 1
self['NModePts'] = 10
self['NDistorts'] = 5
self['GoK'] = 0.05
self['dig_ngrid'] = 20
self['dig_SamplingType'] = 'Smooth'
self['BlurRadius'] = 0.05
self['Classify'] = False
self['Embedded_Charge_Order'] = 2
self['MBE_ORDER'] = 3
self['MonitorSet'] = None
self['NetNameSuffix'] = ''
self['NeuronType'] = 'relu'
self['tf_prec'] = 'tf.float64'
self['learning_rate'] = 0.001
self['learning_rate_dipole'] = 0.0001
self['learning_rate_energy'] = 1e-05
self['momentum'] = 0.9
self['max_steps'] = 1001
self['batch_size'] = 1000
self['test_freq'] = 10
self['HiddenLayers'] = [200, 200, 200]
self['hidden1'] = 512
self['hidden2'] = 512
self['hidden3'] = 512
self['GradWeight'] = 0.01
self['TestRatio'] = 0.2
self['Profiling'] = False
self['max_checkpoints'] = 1
self['KeepProb'] = 0.7
self['weight_decay'] = 0.001
self['ConvFilter'] = [32, 64]
self['ConvKernelSize'] = [[8, 1], [4, 1]]
self['ConvStrides'] = [[8, 1], [4, 1]]
self['sigmoid_alpha'] = 100.0
self['EnergyScalar'] = 1.0
self['GradScalar'] = (1.0 / 20.0)
self['DipoleScaler'] = 1.0
self['InNormRoutine'] = None
self['OutNormRoutine'] = None
self['RandomizeData'] = True
self['MxTimePerElement'] = 36000
self['MxMemPerElement'] = 16000
self['ChopTo'] = None
self['RotAvOutputs'] = 1
self['OctahedralAveraging'] = 0
self['train_gradients'] = True
self['train_dipole'] = True
self['train_quadrupole'] = False
self['train_rotation'] = True
self['OptMaxCycles'] = 50
self['OptThresh'] = 0.0001
self['OptMaxStep'] = 0.1
self['OptStepSize'] = 0.1
self['OptMomentum'] = 0.5
self['OptMomentumDecay'] = 0.8
self['OptPrintLvl'] = 1
self['OptLatticeStep'] = 0.05
self['GSSearchAlpha'] = 0.05
self['SDStep'] = 0.05
self['MaxBFGS'] = 7
self['NebSolver'] = 'Verlet'
self['NebNumBeads'] = 18
self['NebK'] = 0.07
self['NebKMax'] = 1.0
self['NebClimbingImage'] = True
self['DiisSize'] = 20
self['RemoveInvariant'] = True
self['MDMaxStep'] = 20000
self['MDdt'] = 0.2
self['MDTemp'] = 300.0
self['MDV0'] = 'Random'
self['MDThermostat'] = None
self['MDLogTrajectory'] = True
self['MDUpdateCharges'] = True
self['MDIrForceMin'] = False
self['MDAnnealT0'] = 20.0
self['MDAnnealTF'] = 300.0
self['MDAnnealKickBack'] = 1.0
self['MDAnnealSteps'] = 1000
self['MDFieldVec'] = np.array([1.0, 0.0, 0.0])
self['MDFieldAmp'] = 0.0
self['MDFieldFreq'] = (1.0 / 1.2)
self['MDFieldTau'] = 1.2
self['MDFieldT0'] = 3.0
self['MetaBumpTime'] = 15.0
self['MetaBowlK'] = 0.0
self['MetaMaxBumps'] = 500
self['MetaMDBumpHeight'] = 0.05
self['MetaMDBumpWidth'] = 0.1
self['AddEcc'] = True
self['OPR12'] = 'Poly'
self['Poly_Width'] = 4.6
self['Elu_Width'] = 4.6
self['EEOn'] = True
self['EESwitchFunc'] = 'CosLR'
self['EEVdw'] = True
self['EEOrder'] = 2
self['EEdr'] = 1.0
self['EECutoff'] = 5.0
self['EECutoffOn'] = 4.4
self['EECutoffOff'] = 15.0
self['Erf_Width'] = 0.2
self['DSFAlpha'] = 0.18
self['tm_root'] = '.'
self['sets_dir'] = (self['tm_root'] + '/datasets/')
self['networks_directory'] = (self['tm_root'] + '/networks/')
self['output_root'] = '.'
self['results_dir'] = (self['output_root'] + '/results/')
self['dens_dir'] = (self['output_root'] + '/densities/')
self['log_dir'] = (self['output_root'] + '/logs/')
self['Qchem_RIMP2_Block'] = '$rem\n jobtype sp\n method rimp2\n MAX_SCF_CYCLES 200\n basis cc-pvtz\n aux_basis rimp2-cc-pvtz\n symmetry false\n INCFOCK 0\n thresh 12\n SCF_CONVERGENCE 12\n$end\n'
np.set_printoptions(formatter={'float': '{: .8f}'.format})
def __str__(self):
tore = ''
for k in self.keys():
tore = ((((tore + k) + ':') + str(self[k])) + '\n')
return tore
|
def TMBanner():
print('--------------------------')
try:
if (sys.version_info[0] < 3):
print((((((((((((' ' + unichr(4944)) + unichr(8455)) + unichr(8469)) + unichr(1029)) + unichr(10686)) + unichr(11364)) + '-') + unichr(5711)) + unichr(10686)) + unichr(8466)) + ' 0.1'))
else:
print((((((((((((' ' + chr(4944)) + chr(8455)) + chr(8469)) + chr(1029)) + chr(10686)) + chr(11364)) + '-') + chr(5711)) + chr(10686)) + chr(8466)) + ' 0.1'))
except:
pass
print('--------------------------')
print('By using this software you accept the terms of the GNU public license in ')
print('COPYING, and agree to attribute the use of this software in publications as: \n')
print('K.Yao, J. E. Herr, D. Toth, R. McIntyre, J. Garside, J. Parckhill. TensorMol 0.2 (2018)')
print('--------------------------')
|
def TMLogger(path_):
logger = logging.getLogger()
logger.handlers = []
tore = logging.getLogger('TensorMol')
tore.setLevel(logging.DEBUG)
if (not os.path.exists(path_)):
os.makedirs(path_)
fh = logging.FileHandler(filename=((path_ + time.strftime('%a_%b_%d_%H.%M.%S_%Y')) + '.log'))
fh.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
fformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
pformatter = logging.Formatter('%(message)s')
fh.setFormatter(fformatter)
ch.setFormatter(pformatter)
tore.addHandler(fh)
tore.addHandler(ch)
return tore
|
def MakeDirIfAbsent(path):
if ((sys.version_info[0] + (sys.version_info[1] * 0.1)) < 3.2):
try:
os.makedirs(path)
except OSError:
if (not os.path.isdir(path)):
raise
else:
os.makedirs(path, exist_ok=True)
|
def PrintTMTIMER():
LOGGER.info('======= Accumulated Time Information =======')
LOGGER.info('Category ||| Time Per Call ||| Total Elapsed ')
for key in TMTIMER.keys():
if (TMTIMER[key][1] > 0):
LOGGER.info((key + ' ||| %0.5f ||| %0.5f '), (TMTIMER[key][0] / TMTIMER[key][1]), TMTIMER[key][0])
|
def TMTiming(nm_='Obs'):
if (not (nm_ in TMTIMER.keys())):
TMTIMER[nm_] = [0.0, 0]
def wrap(f):
def wf(*args, **kwargs):
t0 = time.time()
output = f(*args, **kwargs)
TMTIMER[nm_][0] += (time.time() - t0)
TMTIMER[nm_][1] += 1
return output
LOGGER.debug((('TMTimed ' + nm_) + str(TMTIMER[nm_])))
return wf
return wrap
|
@atexit.register
def exitTensorMol():
PrintTMTIMER()
LOGGER.info('Total Time : %0.5f s', (time.time() - TMSTARTTIME))
LOGGER.info('~ Adios Homeshake ~')
|
def complement(a, b):
return [i for i in a if (b.count(i) == 0)]
|
def scitodeci(sci):
tmp = re.search('(\\d+\\.?\\d+)\\*\\^(-?\\d+)', sci)
return (float(tmp.group(1)) * pow(10, float(tmp.group(2))))
|
def AtomicNumber(Symb):
try:
return atoi[Symb]
except Exception as Ex:
raise Exception('Unknown Atom')
return 0
|
def AtomicSymbol(number):
try:
return atoi.keys()[atoi.values().index(number)]
except Exception as Ex:
raise Exception('Unknown Atom')
return 0
|
def LtoS(l):
s = ''
for i in l:
s += (str(i) + ' ')
return s
|
def nCr(n, r):
f = math.factorial
return int(((f(n) / f(r)) / f((n - r))))
|
def DSF(R, R_c, alpha):
if (R > R_c):
return 0.0
else:
twooversqrtpi = 1.1283791671
XX = (alpha * R_c)
ZZ = (scipy.special.erfc(XX) / R_c)
YY = (((twooversqrtpi * alpha) * math.exp(((- XX) * XX))) / R_c)
LR = (((scipy.special.erfc((alpha * R)) / R) - ZZ) + ((R - R_c) * ((ZZ / R_c) + YY)))
return LR
|
def DSF_Gradient(R, R_c, alpha):
if (R > R_c):
return 0.0
else:
twooversqrtpi = 1.1283791671
XX = (alpha * R_c)
ZZ = (scipy.special.erfc(XX) / R_c)
YY = (((twooversqrtpi * alpha) * math.exp(((- XX) * XX))) / R_c)
grads = (- ((((scipy.special.erfc((alpha * R)) / R) / R) + (((twooversqrtpi * alpha) * math.exp(((((- alpha) * R) * alpha) * R))) / R)) - ((ZZ / R_c) + YY)))
return grads
|
def EluAjust(x, a, x0, shift):
if (x > x0):
return ((a * (x - x0)) + shift)
else:
return ((a * (math.exp((x - x0)) - 1.0)) + shift)
|
def sigmoid_with_param(x, prec=tf.float64):
return (tf.log((1.0 + tf.exp(tf.multiply(tf.cast(PARAMS['sigmoid_alpha'], dtype=prec), x)))) / tf.cast(PARAMS['sigmoid_alpha'], dtype=prec))
|
def guassian_act(x, prec=tf.float64):
return tf.exp(((- x) * x))
|
def guassian_rev_tozero(x, prec=tf.float64):
return tf.where(tf.greater(x, 0.0), (1.0 - tf.exp(((- x) * x))), tf.zeros_like(x))
|
def guassian_rev_tozero_tolinear(x, prec=tf.float64):
a = 0.5
b = (- 0.06469509698101589)
x0 = 0.2687204431537632
step1 = tf.where(tf.greater(x, 0.0), (1.0 - tf.exp(((- x) * x))), tf.zeros_like(x))
return tf.where(tf.greater(x, x0), ((a * x) + b), step1)
|
def square_tozero_tolinear(x, prec=tf.float64):
a = 1.0
b = (- 0.0025)
x0 = 0.005
step1 = tf.where(tf.greater(x, 0.0), ((100.0 * x) * x), tf.zeros_like(x))
return tf.where(tf.greater(x, x0), ((a * x) + b), step1)
|
@app.route('/')
def main():
c = db.incr('counter')
return render_template('main.html', counter=c)
|
@socketio.on('connect', namespace='/tms')
def ws_conn():
c = db.incr('user_count')
socketio.emit('msg', {'count': c}, namespace='/tms')
|
@socketio.on('disconnect', namespace='/tms')
def ws_disconn():
c = db.decr('user_count')
socketio.emit('msg', {'count': c}, namespace='/tms')
|
def WriteXYZfile(atoms, coords, nm_='out.xyz'):
natom = len(atoms)
f = open(nm_, 'w')
f.write(((str(natom) + '\n') + '\n'))
for i in range(natom):
f.write((((((((atoms[i] + ' ') + str(coords[i][0])) + ' ') + str(coords[i][1])) + ' ') + str(coords[i][2])) + '\n'))
|
def vlog(level):
os.environ['TF_CPP_MIN_VLOG_LEVEL'] = str(level)
|
class TemporaryFileHelper():
'Provides a way to fetch contents of temporary file.'
def __init__(self, temporary_file):
self.temporary_file = temporary_file
def getvalue(self):
return open(self.temporary_file.name).read()
|
class capture_stderr():
'Utility to capture output, use as follows\n with util.capture_stderr() as stderr:\n sess = tf.Session()\n\n print("Captured:", stderr.getvalue()).\n '
def __init__(self, fd=STDERR):
self.fd = fd
self.prevfd = None
def __enter__(self):
t = tempfile.NamedTemporaryFile()
self.prevfd = os.dup(self.fd)
os.dup2(t.fileno(), self.fd)
return TemporaryFileHelper(t)
def __exit__(self, exc_type, exc_value, traceback):
os.dup2(self.prevfd, self.fd)
|
def _parse_logline(l):
if ('MemoryLogTensorOutput' in l):
m = tensor_output_regex.search(l)
if (not m):
m = tensor_output_regex_no_bytes.search(l)
assert m, l
d = m.groupdict()
d['type'] = 'MemoryLogTensorOutput'
elif ('MemoryLogTensorAllocation' in l):
m = tensor_allocation_regex.search(l)
if (not m):
return {'type': 'MemoryLogTensorAllocation', 'line': l, 'allocation_id': '-1'}
assert m, l
d = m.groupdict()
d['type'] = 'MemoryLogTensorAllocation'
if debug_messages:
print(('Got allocation for %s, %s' % (d['allocation_id'], d['kernel_name'])))
elif ('MemoryLogTensorDeallocation' in l):
m = tensor_deallocation_regex.search(l)
assert m, l
d = m.groupdict()
d['type'] = 'MemoryLogTensorDeallocation'
if debug_messages:
print(('Got deallocation for %s' % d['allocation_id']))
elif ('MemoryLogStep' in l):
m = tensor_logstep_regex.search(l)
assert m, l
d = m.groupdict()
d['type'] = 'MemoryLogStep'
elif ('MemoryLogRawAllocation' in l):
m = raw_allocation_regex.search(l)
assert m, l
d = m.groupdict()
d['type'] = 'MemoryLogRawAllocation'
elif ('MemoryLogRawDeallocation' in l):
m = raw_deallocation_regex.search(l)
assert m, l
d = m.groupdict()
d['type'] = 'MemoryLogRawDeallocation'
else:
assert False, ('Unknown log line: ' + l)
if (not ('allocation_id' in d)):
d['allocation_id'] = '-1'
d['line'] = l
return d
|
def memory_timeline(log):
if hasattr(log, 'getvalue'):
log = log.getvalue()
def unique_alloc_id(line):
if (line['allocation_id'] == '-1'):
return '-1'
return ((line['allocation_id'] + '-') + line['allocator_name'])
def get_alloc_names(line):
alloc_id = unique_alloc_id(line)
for entry in reversed(allocation_map.get(alloc_id, [])):
kernel_name = entry.get('kernel_name', 'unknown')
if (not ('unknown' in kernel_name)):
return (((kernel_name + '(') + unique_alloc_id(line)) + ')')
return (('(' + alloc_id) + ')')
def get_alloc_bytes(line):
for entry in allocation_map.get(unique_alloc_id(line), []):
if ('allocated_bytes' in entry):
return entry['allocated_bytes']
return '0'
def get_alloc_type(line):
for entry in allocation_map.get(unique_alloc_id(line), []):
if ('allocator_name' in entry):
return entry['allocator_name']
return '0'
parsed_lines = []
for l in log.split('\n'):
if ('LOG_MEMORY' in l):
parsed_lines.append(_parse_logline(l))
allocation_map = {}
for line in parsed_lines:
if ((line['type'] == 'MemoryLogTensorAllocation') or (line['type'] == 'MemoryLogRawAllocation') or (line['type'] == 'MemoryLogTensorOutput')):
allocation_map.setdefault(unique_alloc_id(line), []).append(line)
if debug_messages:
print(allocation_map)
result = []
for (i, line) in enumerate(parsed_lines):
if (int(line['allocation_id']) == (- 1)):
continue
alloc_names = get_alloc_names(line)
if (int(line.get('allocated_bytes', (- 1))) < 0):
alloc_bytes = get_alloc_bytes(line)
else:
alloc_bytes = line.get('allocated_bytes', (- 1))
alloc_type = get_alloc_type(line)
if (line['type'] == 'MemoryLogTensorOutput'):
continue
if ((line['type'] == 'MemoryLogTensorDeallocation') or (line['type'] == 'MemoryLogRawDeallocation')):
alloc_bytes = ('-' + alloc_bytes)
result.append((i, alloc_names, alloc_bytes, alloc_type))
return result
|
def peak_memory(log, gpu_only=False):
'Peak memory used across all devices.'
peak_memory = (- 123456789)
total_memory = 0
for record in memory_timeline(log):
(i, kernel_name, allocated_bytes, allocator_type) = record
allocated_bytes = int(allocated_bytes)
if gpu_only:
if (not allocator_type.startswith('gpu')):
continue
total_memory += allocated_bytes
peak_memory = max(total_memory, peak_memory)
return peak_memory
|
def print_memory_timeline(log, gpu_only=False, ignore_less_than_bytes=0):
total_memory = 0
for record in memory_timeline(log):
(i, kernel_name, allocated_bytes, allocator_type) = record
allocated_bytes = int(allocated_bytes)
if gpu_only:
if (not allocator_type.startswith('gpu')):
continue
if (abs(allocated_bytes) < ignore_less_than_bytes):
continue
total_memory += allocated_bytes
print(('%9d %42s %11d %11d %s' % (i, kernel_name, allocated_bytes, total_memory, allocator_type)))
|
def plot_memory_timeline(log, gpu_only=False, ignore_less_than_bytes=1000):
total_memory = 0
timestamps = []
data = []
current_time = 0
for record in memory_timeline(log):
(timestamp, kernel_name, allocated_bytes, allocator_type) = record
allocated_bytes = int(allocated_bytes)
if (abs(allocated_bytes) < ignore_less_than_bytes):
continue
if gpu_only:
if (not record[3].startswith('gpu')):
continue
timestamps.append((current_time - 1e-08))
data.append(total_memory)
total_memory += int(record[2])
timestamps.append(current_time)
data.append(total_memory)
current_time += 1
plt.plot(timestamps, data)
|
def smart_initialize(variables=None, sess=None):
"Initializes all uninitialized variables in correct order. Initializers\n are only run for uninitialized variables, so it's safe to run this multiple\n times.\n\n Args:\n sess: session to use. Use default session if None.\n "
from tensorflow.contrib import graph_editor as ge
def make_initializer(var):
def f():
return tf.assign(var, var.initial_value).op
return f
def make_noop():
return tf.no_op()
def make_safe_initializer(var):
'Returns initializer op that only runs for uninitialized ops.'
return tf.cond(tf.is_variable_initialized(var), make_noop, make_initializer(var), name=('safe_init_' + var.op.name)).op
if (not sess):
sess = tf.get_default_session()
g = tf.get_default_graph()
if (not variables):
variables = tf.get_collection(tf.GraphKeys.GLOBAL_VARIABLES)
safe_initializers = {}
for v in variables:
safe_initializers[v.op.name] = make_safe_initializer(v)
for v in variables:
var_name = v.op.name
var_cache = g.get_operation_by_name((var_name + '/read'))
ge.reroute.add_control_inputs(var_cache, [safe_initializers[var_name]])
sess.run(tf.group(*safe_initializers.values()))
for v in variables:
var_name = v.op.name
var_cache = g.get_operation_by_name((var_name + '/read'))
ge.reroute.remove_control_inputs(var_cache, [safe_initializers[var_name]])
|
def QchemDft(m_, basis_='6-31g*', xc_='b3lyp'):
istring = '$molecule\n0 1 \n'
crds = m_.coords.copy()
crds[(abs(crds) < 0.0)] *= 0.0
for j in range(len(m_.atoms)):
istring = ((((((((istring + itoa[m_.atoms[j]]) + ' ') + str(crds[(j, 0)])) + ' ') + str(crds[(j, 1)])) + ' ') + str(crds[(j, 2)])) + '\n')
istring = (((((istring + '$end\n\n$rem\njobtype sp\nbasis ') + basis_) + '\nexchange ') + xc_) + '\n thresh 11\n symmetry false\n sym_ignore true\n$end\n')
f = open('./qchem/tmp.in', 'w')
f.write(istring)
f.close()
subprocess.call('qchem ./qchem/tmp.in ./qchem/tmp.out'.split(), shell=False)
f = open('./qchem/tmp.out', 'r')
lines = f.readlines()
f.close()
for line in lines:
if (line.count(' met') > 0):
return np.array([float(line.split()[1])])[0]
return np.array([0.0])[0]
|
def david_AnnealHarmonic(set_='david_test', Anneal=True, WriteNM_=False):
'\n\tOptionally anneals a molecule and then runs it through a finite difference normal mode analysis\n\n\tArgs:\n\t\tset_: dataset from which a molecule comes\n\t\tAnneal: whether or not to perform an annealing routine before the analysis\n\t\tWriteNM_: whether or not to write normal modes to a readable file\n\tReturns:\n\t\tFrequencies (wavenumbers)\n\t\tNormal modes (cartesian)\n\t'
a = MSet(set_)
a.ReadXYZ(set_)
manager = TFMolManage('Mol_uneq_chemspider_ANI1_Sym_fc_sqdiff_BP_1', None, False, RandomTData_=False, Trainable_=False)
x_ = a.mols[6]
qmanager = TFMolManage('Mol_chemspider9_multipole_ANI1_Sym_Dipole_BP_1', None, False, RandomTData_=False, Trainable_=False)
EnergyField = (lambda x: manager.Eval_BPForceSingle(Mol(x_.atoms, x), True)[0])
ForceField = (lambda x: manager.Eval_BPForceSingle(Mol(x_.atoms, x), True))
ChargeField = (lambda x: qmanager.Eval_BPDipole(Mol(x_.atoms, x), False)[2][0])
masses = np.array(map((lambda x: ATOMICMASSESAMU[(x - 1)]), x_.atoms))
m_ = masses
eps_ = 0.04
if (Anneal == True):
PARAMS['OptMomentum'] = 0.0
PARAMS['OptMomentumDecay'] = 0.9
PARAMS['OptStepSize'] = 0.02
PARAMS['OptMaxCycles'] = 200
PARAMS['MDdt'] = 0.2
PARAMS['RemoveInvariant'] = True
PARAMS['MDMaxStep'] = 100
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDV0'] = None
PARAMS['MDTemp'] = 1.0
annealx_ = Annealer(ForceField, ChargeField, x_, 'Anneal')
annealx_.Prop()
x_.coords = annealx_.Minx.copy()
x_.WriteXYZfile('./results/', 'davidIR_opt')
HarmonicSpectra(EnergyField, x_.coords, masses, x_.atoms, WriteNM_=True)
|
def WriteXYZfile(atoms, coords, nm_='out.xyz'):
natom = len(atoms)
f = open(nm_, 'w')
f.write(((str(natom) + '\n') + '\n'))
for i in range(natom):
f.write((((((((atoms[i] + ' ') + str(coords[i][0])) + ' ') + str(coords[i][1])) + ' ') + str(coords[i][2])) + '\n'))
|
def GetEnergyAndForceFromManager(MName_, a):
'\n\tMName: name of the manager. (specifies sampling method)\n\tset_: An MSet() dataset which has been loaded.\n\t'
TreatedAtoms = a.AtomTypes()
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='AtomizationEnergy')
tset = TensorMolData_BP_Direct_Linear(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScalar'] = 1
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
manager = TFMolManage(MName_, tset, False, RandomTData_=False, Trainable_=False)
nmols = len(a.mols)
EErr = np.zeros(nmols)
FErr = np.zeros(nmols)
for (i, mol) in enumerate(a.mols):
mol.properties['atomization'] = mol.properties['energy']
mol.properties['gradients'] = mol.properties['forces']
for j in range(0, mol.NAtoms()):
mol.properties['atomization'] -= ele_E_david[mol.atoms[j]]
q_en = mol.properties['atomization']
q_f = mol.properties['gradients']
(en, grad) = manager.Eval_BPEnergy_Direct_Grad_Linear(Mol(mol.atoms, mol.coords))
new_grad = (grad / (- JOULEPERHARTREE))
EErr[i] = (en - q_en)
F_diff = (new_grad - q_f)
FErr[i] = np.sqrt((np.sum((F_diff * F_diff)) / mol.NAtoms()))
final_E_err = (np.sqrt((np.sum((EErr * EErr)) / nmols)) * KCALPERHARTREE)
final_F_err = ((np.sum(FErr) / nmols) * KCALPERHARTREE)
print(np.sum(FErr, axis=0), nmols)
print('RMS energy error: ', (np.sqrt((np.sum((EErr * EErr)) / nmols)) * KCALPERHARTREE))
print('<|F_err|> error: ', ((np.sum(FErr) / nmols) * KCALPERHARTREE))
return (final_E_err, final_F_err)
|
def CompareAllData():
'\n\tCompares all errors from every network tested against every dataset.\n\tResults are stored in a dictionary; the keys for the dictionary are\n\tthe managers.\n\t'
f = open('/media/sdb1/dtoth/TensorMol/results/SamplingData.txt', 'w')
managers = ['Mol_DavidMD_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_Grad_Linear_1', 'Mol_DavidMetaMD_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_Grad_Linear_1', 'Mol_DavidNM_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_Grad_Linear_1', 'Mol_DavidRandom_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_Grad_Linear_1', 'Mol_Hybrid_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_Grad_Linear_1', 'Mol_GoldStd_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_Grad_Linear_1']
SetNames = ['DavidMD', 'DavidMetaMD', 'DavidNM', 'DavidRandom', 'Hybrid', 'GoldStd']
MSets = [MSet(name) for name in SetNames]
for aset in MSets:
aset.Load()
results = {}
print('Loaded Sets... ')
for i in managers:
for j in range(len(MSets)):
(en, f) = GetEnergyAndForceFromManager(i, MSets[j])
results[(i, SetNames[j])] = (en, f)
print(results)
try:
f.write(results)
except:
f.write(str(results))
|
def TestOptimization(MName_):
'\n\tDistorts a set of molecules from their equilibrium geometries,\n\tthen optimizes the distorted geometries using a trained network.\n\n\tArgs:\n\n\t\tMName_: Trained network\n\n\tReturns:\n\n\t\tnp.mean(rms_list): Average value of all of the RMS errors for all molecules\n\t'
a = MSet('david_test')
a.ReadXYZ()
mol = a.mols[(- 2)]
PARAMS['hidden1'] = 200
PARAMS['hidden2'] = 200
PARAMS['hidden3'] = 200
PARAMS['Hidden layers'] = [200, 200, 200]
TreatedAtoms = a.AtomTypes()
print('TreatedAtoms:', TreatedAtoms)
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='AtomizationEnergy')
tset = TensorMolData_BP_Direct_Linear(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage(MName_, tset, False, RandomTData_=False, Trainable_=False)
rms_list = []
EnergyForceField = (lambda x: manager.Eval_BPEnergy_Direct_Grad_Linear(Mol(mol.atoms, x)))
mol.Distort(0.2)
PARAMS['OptMaxCycles'] = 2000
molp = GeomOptimizer(EnergyForceField).Opt(mol)
tmp_rms = mol.rms_inv(molp)
rms_list.append(tmp_rms)
print('RMS:', tmp_rms)
return np.mean(rms_list)
|
def GetEnergyVariance(MName_):
'\n\tUseful routine to get the data for\n\ta plot of the energy variance within a dataset (MSet).\n\n\tArgs:\n\t\tMName_: Name of dataset as a string\n\t'
a = MSet(MName_)
a.Load()
for mol in a.mols:
mol.properties['energy'] = mol.properties['atomization']
ens = np.array([mol.properties['energy'] for m in a.mols])
ensmav = (ens - np.average(ens))
np.savetxt(MName_, ensmav)
|
def Prepare():
if 1:
a = MSet('watercube', center_=False)
a.ReadXYZ('watercube')
repeat = 5
space = 3.0
mol_cout = np.zeros((repeat ** 3), dtype=int)
tm_coords = []
tm_atoms = []
portion = (np.array([1.0, 1.0, 1.0, 1, 0, 9.0]) / np.sum(np.array([1, 1, 1, 1, 9])))
print('portion:', portion)
for i in range(0, repeat):
for j in range(0, repeat):
for k in range(0, repeat):
s = random.random()
print('s:', s)
if (s < np.sum(portion[:1])):
index = 0
elif (s < np.sum(portion[:2])):
index = 1
elif (s < np.sum(portion[:3])):
index = 2
elif (s < np.sum(portion[:4])):
index = 3
else:
index = 4
print('index:', index)
m = a.mols[index]
tm_coords += list((m.coords + np.asarray([(i * space), (j * space), (k * space)])))
tm_atoms += list(m.atoms)
tm_coords = np.asarray(tm_coords)
tm_atoms = np.asarray(tm_atoms, dtype=int)
tm = Mol(tm_atoms, tm_coords)
tm.WriteXYZfile(fpath='./datasets', fname='reactor')
if 0:
a = MSet('watercube', center_=False)
a.ReadXYZ('watercube')
m = a.mols[0]
m.coords = (m.coords + 1)
repeat = 4
space = 4.0
tm_coords = np.zeros((((repeat ** 3) * m.NAtoms()), 3))
tm_atoms = np.zeros(((repeat ** 3) * m.NAtoms()), dtype=int)
p = 0
for i in range(0, repeat):
for j in range(0, repeat):
for k in range(0, repeat):
tm_coords[(p * m.NAtoms()):((p + 1) * m.NAtoms())] = (m.coords + np.asarray([(i * space), (j * space), (k * space)]))
tm_atoms[(p * m.NAtoms()):((p + 1) * m.NAtoms())] = m.atoms
p += 1
tm = Mol(tm_atoms, tm_coords)
tm.WriteXYZfile(fpath='./datasets', fname='watercube')
|
def Eval():
if 1:
a = MSet('reactor', center_=True)
a.ReadXYZ('reactor')
TreatedAtoms = np.array([1, 6, 7, 8], dtype=np.uint8)
PARAMS['NetNameSuffix'] = 'act_sigmoid100'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 21
PARAMS['batch_size'] = 50
PARAMS['test_freq'] = 1
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['EnergyScalar'] = 1.0
PARAMS['GradScalar'] = (1.0 / 20.0)
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'sigmoid_with_param'
PARAMS['sigmoid_alpha'] = 100.0
PARAMS['HiddenLayers'] = [2000, 2000, 2000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 0
PARAMS['Elu_Width'] = 4.6
PARAMS['EECutoffOff'] = 15.0
PARAMS['DSFAlpha'] = (0.18 * BOHRPERA)
PARAMS['AddEcc'] = True
PARAMS['KeepProb'] = [1.0, 1.0, 1.0, 0.7]
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 2
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE_WithEle(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_chemspider12_clean_maxatom35_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout_act_sigmoid100', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout', False, False)
m = a.mols[0]
print('m.coords:', np.max(m.coords, axis=0), np.min(m.coords, axis=0))
m.coords = (m.coords - np.min(m.coords, axis=0))
print('m.coords:', np.max(m.coords, axis=0), np.min(m.coords, axis=0))
def EnAndForce(x_, DoForce=True):
m.coords = x_
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
def GetEnergyForceForMol(m):
def EnAndForce(x_, DoForce=True):
tmpm = Mol(m.atoms, x_)
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
return EnAndForce
def EnForceCharge(x_):
m.coords = x_
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
return (energy, force, atom_charge[0])
def ChargeField(x_):
m.coords = x_
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
return atom_charge[0]
def EnergyField(x_):
return EnAndForce(x_, True)[0]
def DipoleField(x_):
q = np.asarray(ChargeField(x_))
dipole = np.zeros(3)
for i in range(0, q.shape[0]):
dipole += (q[i] * x_[i])
return dipole
def DFTForceField(x_, DoForce=True):
if DoForce:
return QchemDFT(Mol(m.atoms, x_), basis_='6-31g*', xc_='b3lyp', jobtype_='force', threads=24)
else:
return np.asarray([QchemDFT(Mol(m.atoms, x_), basis_='6-31g*', xc_='b3lyp', jobtype_='sp', threads=24)])[0]
DFTDipoleField = (lambda x: QchemDFT(Mol(m.atoms, x), basis_='6-31g', xc_='b3lyp', jobtype_='dipole', threads=12))
EnergyForceField = (lambda x: EnAndForce(x))
PARAMS['MDdt'] = 0.2
PARAMS['RemoveInvariant'] = True
PARAMS['MDMaxStep'] = 10000
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDTemp'] = 300.0
meta = BoxedMetaDynamics(EnergyForceField, m, name_='BoxMetaReactor', Box_=np.array((18.0 * np.eye(3))))
meta.Prop()
return
if 0:
a = MSet('watercube', center_=False)
a.ReadXYZ('watercube')
TreatedAtoms = np.array([1, 6, 7, 8], dtype=np.uint8)
PARAMS['NetNameSuffix'] = 'act_sigmoid100'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 21
PARAMS['batch_size'] = 50
PARAMS['test_freq'] = 1
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['EnergyScalar'] = 1.0
PARAMS['GradScalar'] = (1.0 / 20.0)
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'sigmoid_with_param'
PARAMS['sigmoid_alpha'] = 100.0
PARAMS['HiddenLayers'] = [2000, 2000, 2000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 0
PARAMS['Elu_Width'] = 4.6
PARAMS['EECutoffOff'] = 15.0
PARAMS['DSFAlpha'] = (0.18 * BOHRPERA)
PARAMS['AddEcc'] = True
PARAMS['KeepProb'] = [1.0, 1.0, 1.0, 0.7]
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 2
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE_WithEle(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_chemspider12_clean_maxatom35_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout_act_sigmoid100', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout', False, False)
m = a.mols[1]
print('m.coords:', np.max(m.coords, axis=0), np.min(m.coords, axis=0))
m.coords += np.asarray([0, 1, 0])
def EnAndForce(x_, DoForce=True):
m.coords = x_
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
def GetEnergyForceForMol(m):
def EnAndForce(x_, DoForce=True):
tmpm = Mol(m.atoms, x_)
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
return EnAndForce
def EnForceCharge(x_):
m.coords = x_
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
return (energy, force, atom_charge[0])
def ChargeField(x_):
m.coords = x_
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
return atom_charge[0]
def EnergyField(x_):
return EnAndForce(x_, True)[0]
def DipoleField(x_):
q = np.asarray(ChargeField(x_))
dipole = np.zeros(3)
for i in range(0, q.shape[0]):
dipole += (q[i] * x_[i])
return dipole
def DFTForceField(x_, DoForce=True):
if DoForce:
return QchemDFT(Mol(m.atoms, x_), basis_='6-31g*', xc_='b3lyp', jobtype_='force', threads=24)
else:
return np.asarray([QchemDFT(Mol(m.atoms, x_), basis_='6-31g*', xc_='b3lyp', jobtype_='sp', threads=24)])[0]
DFTDipoleField = (lambda x: QchemDFT(Mol(m.atoms, x), basis_='6-31g', xc_='b3lyp', jobtype_='dipole', threads=12))
EnergyForceField = (lambda x: EnAndForce(x))
PARAMS['MDdt'] = 0.2
PARAMS['RemoveInvariant'] = True
PARAMS['MDMaxStep'] = 10000
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDTemp'] = 300.0
meta = BoxedMetaDynamics(EnergyForceField, m, name_='BoxMetaTest', Box_=np.array((16.0 * np.eye(3))))
meta.Prop()
return
|
def GenerateData(model_='Huckel'):
'\n\tGenerate random configurations in a reasonable range.\n\tand calculate their energies and forces.\n\t'
nsamp = 10000
crds = np.random.uniform(4.0, size=(nsamp, 3, 3))
st = MSet()
MDL = None
natom = 4
ANS = np.array([3, 1, 1])
if (model_ == 'Morse'):
MDL = MorseModel()
else:
MDL = QuantumElectrostatic()
for s in range(nsamp):
if (model_ == 'Morse'):
st.mols.append(Mol(np.array([1.0, 1.0, 1.0]), crds[s]))
(en, f) = MDL(crds[s])
st.mols[(- 1)].properties['dipole'] = np.array([0.0, 0.0, 0.0])
else:
st.mols.append(Mol(np.array([3.0, 1.0, 1.0]), crds[s]))
(en, f, d, q) = MDL(crds[s])
st.mols[(- 1)].properties['dipole'] = d
st.mols[(- 1)].properties['charges'] = q
st.mols[(- 1)].properties['energy'] = en
st.mols[(- 1)].properties['force'] = f
st.mols[(- 1)].properties['gradients'] = ((- 1.0) * f)
st.mols[(- 1)].CalculateAtomization()
return st
|
def TestTraining_John():
PARAMS['train_dipole'] = True
tset = GenerateData()
net = BehlerParinelloDirectGauSH(tset)
net.train()
return
|
def TestTraining():
a = GenerateData()
TreatedAtoms = a.AtomTypes()
PARAMS['NetNameSuffix'] = 'training_sample'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 15
PARAMS['batch_size'] = 100
PARAMS['test_freq'] = 5
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['EnergyScalar'] = 1.0
PARAMS['GradScalar'] = (1.0 / 20.0)
PARAMS['NeuronType'] = 'sigmoid_with_param'
PARAMS['sigmoid_alpha'] = 100.0
PARAMS['KeepProb'] = [1.0, 1.0, 1.0, 1.0]
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='AtomizationEnergy')
tset = TensorMolData_BP_Direct_EandG_Release(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EandG_SymFunction')
PARAMS['Profiling'] = 0
manager.Train(1)
|
def TestOpt():
return
|
def TestMD():
return
|
def TrainPrepare():
if 0:
a = MSet('chemspider9_force')
dic_list = pickle.load(open('./datasets/chemspider9_force.dat', 'rb'))
for dic in dic_list:
atoms = []
for atom in dic['atoms']:
atoms.append(AtomicNumber(atom))
atoms = np.asarray(atoms, dtype=np.uint8)
mol = Mol(atoms, dic['xyz'])
mol.properties['charges'] = dic['charges']
mol.properties['dipole'] = dic['dipole']
mol.properties['quadropole'] = dic['quad']
mol.properties['energy'] = dic['scf_energy']
mol.properties['gradients'] = dic['gradients']
mol.CalculateAtomization()
a.mols.append(mol)
a.Save()
if 1:
B3LYP631GstarAtom = {}
B3LYP631GstarAtom[1] = (- 0.5002727827)
B3LYP631GstarAtom[6] = (- 37.8462793509)
B3LYP631GstarAtom[7] = (- 54.5844908554)
B3LYP631GstarAtom[8] = (- 75.0606111011)
a = MSet('chemspider9_metady_force')
dic_list = pickle.load(open('./datasets/chemspider9_metady_force.dat', 'rb'))
for dic in dic_list:
atoms = []
for atom in dic['atoms']:
atoms.append(AtomicNumber(atom))
atoms = np.asarray(atoms, dtype=np.uint8)
mol = Mol(atoms, dic['xyz'])
mol.properties['charges'] = dic['charges']
mol.properties['dipole'] = np.asarray(dic['dipole'])
mol.properties['quadropole'] = dic['quad']
mol.properties['energy'] = dic['scf_energy']
mol.properties['gradients'] = dic['gradients']
mol.properties['atomization'] = dic['scf_energy']
for i in range(0, mol.NAtoms()):
mol.properties['atomization'] -= B3LYP631GstarAtom[mol.atoms[i]]
a.mols.append(mol)
a.mols[100].WriteXYZfile(fname='metady_test')
print(a.mols[100].properties)
a.Save()
if 0:
RIMP2Atom = {}
RIMP2Atom[1] = (- 0.4998098112)
RIMP2Atom[8] = (- 74.9659650581)
a = MSet('H2O_augmented_more_cutoff5_rimp2_force_dipole')
dic_list = pickle.load(open('./datasets/H2O_augmented_more_cutoff5_rimp2_force_dipole.dat', 'rb'))
for dic in dic_list:
atoms = []
for atom in dic['atoms']:
atoms.append(AtomicNumber(atom))
atoms = np.asarray(atoms, dtype=np.uint8)
mol = Mol(atoms, dic['xyz'])
mol.properties['mul_charges'] = dic['mul_charges']
mol.properties['dipole'] = dic['dipole']
mol.properties['scf_dipole'] = dic['scf_dipole']
mol.properties['energy'] = dic['energy']
mol.properties['scf_energy'] = dic['scf_energy']
mol.properties['gradients'] = dic['gradients']
mol.properties['atomization'] = dic['energy']
for i in range(0, mol.NAtoms()):
mol.properties['atomization'] -= RIMP2Atom[mol.atoms[i]]
a.mols.append(mol)
a.Save()
if 1:
RIMP2Atom = {}
RIMP2Atom[1] = (- 0.4998098112)
RIMP2Atom[8] = (- 74.9659650581)
a = MSet('H2O_augmented_more_bowl02_rimp2_force_dipole')
dic_list_1 = pickle.load(open('./datasets/H2O_augmented_more_cutoff5_rimp2_force_dipole.dat', 'rb'))
dic_list_2 = pickle.load(open('./datasets/H2O_long_dist_pair.dat', 'rb'))
dic_list_3 = pickle.load(open('./datasets/H2O_metady_bowl02.dat', 'rb'))
dic_list = ((dic_list_1 + dic_list_2) + dic_list_3)
random.shuffle(dic_list)
for dic in dic_list:
atoms = []
for atom in dic['atoms']:
atoms.append(AtomicNumber(atom))
atoms = np.asarray(atoms, dtype=np.uint8)
mol = Mol(atoms, dic['xyz'])
mol.properties['mul_charges'] = dic['mul_charges']
mol.properties['dipole'] = dic['dipole']
mol.properties['scf_dipole'] = dic['scf_dipole']
mol.properties['energy'] = dic['energy']
mol.properties['scf_energy'] = dic['scf_energy']
mol.properties['gradients'] = dic['gradients']
mol.properties['atomization'] = dic['energy']
for i in range(0, mol.NAtoms()):
mol.properties['atomization'] -= RIMP2Atom[mol.atoms[i]]
a.mols.append(mol)
b = MSet('H2O_bowl02_rimp2_force_dipole')
for dic in dic_list_3:
atoms = []
for atom in dic['atoms']:
atoms.append(AtomicNumber(atom))
atoms = np.asarray(atoms, dtype=np.uint8)
mol = Mol(atoms, dic['xyz'])
mol.properties['mul_charges'] = dic['mul_charges']
mol.properties['dipole'] = dic['dipole']
mol.properties['scf_dipole'] = dic['scf_dipole']
mol.properties['energy'] = dic['energy']
mol.properties['scf_energy'] = dic['scf_energy']
mol.properties['gradients'] = dic['gradients']
mol.properties['atomization'] = dic['energy']
for i in range(0, mol.NAtoms()):
mol.properties['atomization'] -= RIMP2Atom[mol.atoms[i]]
b.mols.append(mol)
print('number of a mols:', len(a.mols))
print('number of b mols:', len(b.mols))
a.Save()
b.Save()
if 0:
a = MSet('chemspider9_force')
a.Load()
rmsgrad = np.zeros(len(a.mols))
for (i, mol) in enumerate(a.mols):
rmsgrad[i] = (np.sum(np.square(mol.properties['gradients'])) ** 0.5)
meangrad = np.mean(rmsgrad)
print('mean:', meangrad, 'std:', np.std(rmsgrad))
np.savetxt('chemspider9_force_dist.dat', rmsgrad)
for (i, mol) in enumerate(a.mols):
rmsgrad = (np.sum(np.square(mol.properties['gradients'])) ** 0.5)
if (2 > rmsgrad > 1.5):
mol.WriteXYZfile(fname='large_force')
print(rmsgrad)
if 0:
a = MSet('chemspider9_force')
a.Load()
b = MSet('chemspider9_force_cleaned')
for (i, mol) in enumerate(a.mols):
rmsgrad = (np.sum(np.square(mol.properties['gradients'])) ** 0.5)
if (rmsgrad <= 1.5):
b.mols.append(mol)
b.Save()
c = MSet('chemspider9_force_cleaned_debug')
c.mols = b.mols[:1000]
c.Save()
if 0:
a = MSet('chemspider9_force')
a.Load()
print(a.mols[0].properties)
a.mols[0].WriteXYZfile(fname='test')
|
def TrainForceField():
if 0:
a = MSet('chemspider9_force_cleaned')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['hidden1'] = 1000
PARAMS['hidden2'] = 1000
PARAMS['hidden3'] = 1000
PARAMS['learning_rate'] = 0.001
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 101
PARAMS['batch_size'] = 28
PARAMS['test_freq'] = 2
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 0.05
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Train(maxstep=101)
if 0:
a = MSet('H2O_augmented_more_cutoff5_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 1101
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 4.0
PARAMS['Erf_Width'] = 0.2
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Train()
if 0:
a = MSet('H2O_augmented_more_cutoff5_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 0.0001
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 2
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 1
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 4.4
PARAMS['EECutoffOff'] = 15.0
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_H2O_augmented_more_cutoff5_rimp2_force_dipole_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_1', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Continue_Training(target='All')
if 0:
a = MSet('H2O_augmented_more_cutoff5_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 901
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 8.0
PARAMS['AN1_num_r_Rs'] = 64
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Train()
if 1:
a = MSet('H2O_augmented_more_cutoff5_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 901
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 5.0
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Train()
if 0:
a = MSet('H2O_augmented_more_cutoff5_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 901
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 8.0
PARAMS['AN1_num_r_Rs'] = 64
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode')
manager.Train()
if 0:
a = MSet('H2O_augmented_more_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 901
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [512, 512, 512]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 8.0
PARAMS['AN1_num_r_Rs'] = 64
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Train()
if 1:
a = MSet('H2O_bowl02_rimp2_force_dipole')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 901
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 8.0
PARAMS['AN1_num_r_Rs'] = 64
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE')
manager.Train()
if 0:
a = MSet('chemspider9_metady_force')
a.Load()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 101
PARAMS['batch_size'] = 35
PARAMS['test_freq'] = 2
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [1000, 1000, 1000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 10
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode')
manager.Train()
|
def EvalForceField():
if 0:
a = MSet('H2O_force_test', center_=False)
a.ReadXYZ('H2O_force_test')
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 300
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 5.0
PARAMS['AN1_num_r_Rs'] = 32
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_H2O_augmented_more_cutoff5_rimp2_force_dipole_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_1', tset, False, 'fc_sqdiff_BP_Direct_EE', False, False)
m = a.mols[4]
def EnAndForce(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return (energy, force)
def EnForceCharge(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return (energy, force, atom_charge)
def ChargeField(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return atom_charge[0]
ForceField = (lambda x: EnAndForce(x)[(- 1)])
EnergyField = (lambda x: EnAndForce(x)[0])
EnergyForceField = (lambda x: EnAndForce(x))
PARAMS['MDdt'] = 0.2
PARAMS['RemoveInvariant'] = True
PARAMS['MDMaxStep'] = 10000
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDV0'] = None
PARAMS['MDAnnealTF'] = 300.0
PARAMS['MDAnnealT0'] = 0.0
PARAMS['MDAnnealSteps'] = 10000
anneal = Annealer(EnergyForceField, None, m, 'Anneal')
anneal.Prop()
m.coords = anneal.Minx.copy()
m.WriteXYZfile('./results/', 'Anneal_opt')
PARAMS['MDThermostat'] = None
PARAMS['MDTemp'] = 0
PARAMS['MDdt'] = 0.1
PARAMS['MDV0'] = None
PARAMS['MDMaxStep'] = 100000
md = IRTrajectory(EnAndForce, ChargeField, m, 'IR')
md.Prop()
WriteDerDipoleCorrelationFunction(md.mu_his)
if 0:
a = MSet('NeigborMB_test', center_=False)
a.ReadXYZ('NeigborMB_test')
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 300
PARAMS['batch_size'] = 1000
PARAMS['test_freq'] = 10
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [200, 200, 200]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['AN1_r_Rc'] = 5.0
PARAMS['AN1_num_r_Rs'] = 32
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 100
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_H2O_augmented_more_cutoff5_rimp2_force_dipole_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_1', tset, False, 'fc_sqdiff_BP_Direct_EE', False, False)
m = a.mols[5]
mono_index = []
for i in range(0, 10):
mono_index.append([(i * 3), ((i * 3) + 1), ((i * 3) + 2)])
MBEterms = MBNeighbors(m.coords, m.atoms, mono_index)
mbe = NN_MBE_Linear(manager)
def EnAndForce(x_):
m.coords = x_
MBEterms.Update(m.coords, 10, 10)
(Etotal, gradient, charge) = mbe.EnergyForceDipole(MBEterms)
energy = Etotal
force = gradient
return (energy, force)
EnergyForceField = (lambda x: EnAndForce(x))
print(EnergyForceField(m.coords))
def ChargeField(x_):
m.coords = x_
MBEterms.Update(m.coords, 20.0, 20.0)
(Etotal, gradient, charge) = mbe.EnergyForceDipole(MBEterms)
return charge
ForceField = (lambda x: EnAndForce(x)[(- 1)])
EnergyField = (lambda x: EnAndForce(x)[0])
EnergyForceField = (lambda x: EnAndForce(x))
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDTemp'] = 30
PARAMS['MDdt'] = 0.1
PARAMS['RemoveInvariant'] = True
PARAMS['MDV0'] = None
PARAMS['MDMaxStep'] = 10000
warm = VelocityVerlet(ForceField, m, 'warm', EnergyForceField)
warm.Prop()
m.coords = warm.x.copy()
PARAMS['MDThermostat'] = None
PARAMS['MDTemp'] = 0
PARAMS['MDdt'] = 0.1
PARAMS['MDV0'] = None
PARAMS['MDMaxStep'] = 40000
md = IRTrajectory(EnAndForce, ChargeField, m, 'IR', warm.v)
md.Prop()
WriteDerDipoleCorrelationFunction(md.mu_his)
if 1:
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
a = MSet('chemspider9_metady_force')
a.Load()
b = MSet('IRSmallmols')
b.ReadXYZ()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 101
PARAMS['batch_size'] = 35
PARAMS['test_freq'] = 2
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [1000, 1000, 1000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 10
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_chemspider9_metady_force_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_ChargeEncode_1', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode', False, False)
m = b.mols[8]
def EnAndForce(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return (energy, force)
def EnForceCharge(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return (energy, force, atom_charge)
def ChargeField(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return atom_charge[0]
ForceField = (lambda x: EnAndForce(x)[(- 1)])
EnergyField = (lambda x: EnAndForce(x)[0])
EnergyForceField = (lambda x: EnAndForce(x))
PARAMS['OptMaxCycles'] = 200
Opt = GeomOptimizer(EnergyForceField)
m = Opt.Opt(m)
PARAMS['MDdt'] = 0.2
PARAMS['RemoveInvariant'] = True
PARAMS['MDMaxStep'] = 10000
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDV0'] = None
PARAMS['MDAnnealTF'] = 300.0
PARAMS['MDAnnealT0'] = 0.1
PARAMS['MDAnnealSteps'] = 10000
anneal = Annealer(EnergyForceField, None, m, 'Anneal')
anneal.Prop()
m.coords = anneal.Minx.copy()
m.WriteXYZfile('./results/', 'Anneal_opt')
PARAMS['MDThermostat'] = None
PARAMS['MDTemp'] = 0
PARAMS['MDdt'] = 0.1
PARAMS['MDV0'] = None
PARAMS['MDMaxStep'] = 40000
md = IRTrajectory(EnAndForce, ChargeField, m, 'IR', anneal.v)
md.Prop()
WriteDerDipoleCorrelationFunction(md.mu_his)
if 0:
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
a = MSet('chemspider9_metady_force')
a.Load()
b = MSet('chemspider12_metady_test')
b.ReadXYZ()
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 101
PARAMS['batch_size'] = 35
PARAMS['test_freq'] = 2
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScaler'] = 1.0
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [1000, 1000, 1000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 7.0
PARAMS['Erf_Width'] = 0.4
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 10
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_chemspider9_metady_force_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_ChargeEncode_1', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode', False, False)
m = b.mols[1]
def EnAndForce(x_):
m.coords = x_
(Etotal, Ebp, Ecc, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEESingle(m, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'])
energy = Etotal[0]
force = gradient[0]
return (energy, force)
ForceField = (lambda x: QchemDFT(Mol(m.atoms, x), basis_='6-31g*', xc_='b3lyp', jobtype_='force', filename_='chemspider12_meta_test', path_='./qchem/', threads=24))
EnergyField = (lambda x: EnAndForce(x)[0])
EnergyForceField = (lambda x: EnAndForce(x))
PARAMS['MDdt'] = 0.5
PARAMS['RemoveInvariant'] = True
PARAMS['MDMaxStep'] = 10000
PARAMS['MDThermostat'] = 'Nose'
PARAMS['MDTemp'] = 500.0
PARAMS['MetaBowlK'] = 0.0
meta = MetaDynamics(ForceField, m)
meta.Prop()
|
def TestIPI():
if 1:
a = MSet('water_tiny', center_=False)
a.ReadXYZ('water_tiny')
m = a.mols[(- 1)]
m.coords = ((m.coords - np.min(m.coords)) + 1e-05)
TreatedAtoms = a.AtomTypes()
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 101
PARAMS['batch_size'] = 150
PARAMS['test_freq'] = 1
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['GradScalar'] = (1.0 / 20.0)
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'relu'
PARAMS['HiddenLayers'] = [500, 500, 500]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 0
PARAMS['Poly_Width'] = 4.6
PARAMS['EECutoffOff'] = 15.0
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 15
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE_WithEle(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_H2O_wb97xd_1to21_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_1', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw', False, False)
cellsize = 9.3215
lat = (cellsize * np.eye(3))
PF = TFPeriodicVoxelForce(15.0, lat)
zp = np.zeros((m.NAtoms() * PF.tess.shape[0]), dtype=np.int32)
xp = np.zeros(((m.NAtoms() * PF.tess.shape[0]), 3))
for i in range(0, PF.tess.shape[0]):
zp[(i * m.NAtoms()):((i + 1) * m.NAtoms())] = m.atoms
xp[(i * m.NAtoms()):((i + 1) * m.NAtoms())] = (m.coords + (cellsize * PF.tess[i]))
m_periodic = Mol(zp, xp)
def EnAndForce(x_):
x_ = np.mod(x_, cellsize)
xp = np.zeros(((m.NAtoms() * PF.tess.shape[0]), 3))
for i in range(0, PF.tess.shape[0]):
xp[(i * m.NAtoms()):((i + 1) * m.NAtoms())] = (x_ + (cellsize * PF.tess[i]))
m_periodic.coords = xp
m_periodic.coords[:m.NAtoms()] = x_
(Etotal, gradient) = manager.EvalBPDirectEEUpdateSinglePeriodic(m_periodic, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], m.NAtoms())
energy = Etotal[0]
force = gradient[0]
print('energy:', energy)
return (energy, force)
ForceField = (lambda x: EnAndForce(x)[(- 1)])
EnergyField = (lambda x: EnAndForce(x)[0])
EnergyForceField = (lambda x: EnAndForce(x))
interface = TMIPIManger(EnergyForceField, TCP_IP='localhost', TCP_PORT=31415)
interface.md_run()
return
|
def GetChemSpiderNetwork(a, Solvation_=False):
TreatedAtoms = np.array([1, 6, 7, 8], dtype=np.uint8)
PARAMS['tm_root'] = '/home/animal/Packages/TensorMol'
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['NeuronType'] = 'sigmoid_with_param'
PARAMS['sigmoid_alpha'] = 100.0
PARAMS['HiddenLayers'] = [2000, 2000, 2000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 0
PARAMS['Elu_Width'] = 4.6
PARAMS['EECutoffOff'] = 15.0
PARAMS['AddEcc'] = True
PARAMS['KeepProb'] = [1.0, 1.0, 1.0, 0.7]
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE_WithEle(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
PARAMS['DSFAlpha'] = (0.18 * BOHRPERA)
manager = TFMolManage('chemspider12_nosolvation', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout', False, False)
return manager
|
def EnAndForce(x_, DoForce=True):
mtmp = Mol(m.atoms, x_)
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(mtmp, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
|
def GetChemSpider12(a):
TreatedAtoms = np.array([1, 6, 7, 8], dtype=np.uint8)
PARAMS['NetNameSuffix'] = 'act_sigmoid100'
PARAMS['learning_rate'] = 1e-05
PARAMS['momentum'] = 0.95
PARAMS['max_steps'] = 21
PARAMS['batch_size'] = 50
PARAMS['test_freq'] = 1
PARAMS['tf_prec'] = 'tf.float64'
PARAMS['EnergyScalar'] = 1.0
PARAMS['GradScalar'] = (1.0 / 20.0)
PARAMS['DipoleScaler'] = 1.0
PARAMS['NeuronType'] = 'sigmoid_with_param'
PARAMS['sigmoid_alpha'] = 100.0
PARAMS['HiddenLayers'] = [2000, 2000, 2000]
PARAMS['EECutoff'] = 15.0
PARAMS['EECutoffOn'] = 0
PARAMS['Elu_Width'] = 4.6
PARAMS['EECutoffOff'] = 15.0
PARAMS['DSFAlpha'] = 0.18
PARAMS['AddEcc'] = True
PARAMS['KeepProb'] = [1.0, 1.0, 1.0, 0.7]
PARAMS['learning_rate_dipole'] = 0.0001
PARAMS['learning_rate_energy'] = 1e-05
PARAMS['SwitchEpoch'] = 2
d = MolDigester(TreatedAtoms, name_='ANI1_Sym_Direct', OType_='EnergyAndDipole')
tset = TensorMolData_BP_Direct_EE_WithEle(a, d, order_=1, num_indis_=1, type_='mol', WithGrad_=True)
manager = TFMolManage('Mol_chemspider12_maxatom35_H2O_with_CH4_ANI1_Sym_Direct_fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout_act_sigmoid100_rightalpha', tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode_Update_vdw_DSF_elu_Normalize_Dropout', False, False)
return manager
|
def Eval():
a = MSet('EndiandricC', center_=False)
a.ReadXYZ()
manager = GetChemSpider12(a)
def GetEnergyForceForMol(m):
def EnAndForce(x_, DoForce=True):
tmpm = Mol(m.atoms, x_)
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(tmpm, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
return EnAndForce
if 0:
PARAMS['OptMaxCycles'] = 20
print('Optimizing ', len(a.mols), ' mols')
for i in range(6):
F = GetEnergyForceForMol(a.mols[i])
Opt = GeomOptimizer(F)
a.mols[i] = Opt.Opt(a.mols[i])
a.mols[i].WriteXYZfile('./results/', ('OptMol' + str(i)))
PARAMS['OptMaxCycles'] = 500
PARAMS['NebSolver'] = 'Verlet'
PARAMS['SDStep'] = 0.05
PARAMS['NebNumBeads'] = 22
PARAMS['MaxBFGS'] = 12
(a.mols[0], a.mols[1]) = a.mols[0].AlignAtoms(a.mols[1])
a.mols[0].WriteXYZfile('./results/', ('Aligned' + str(0)))
a.mols[0].WriteXYZfile('./results/', ('Aligned' + str(1)))
F = GetEnergyForceForMol(a.mols[0])
neb = NudgedElasticBand(F, a.mols[0], a.mols[1])
Beads = neb.Opt('NebStep1')
|
def TestBetaHairpin():
a = MSet('2evq', center_=False)
a.ReadXYZ()
a.OnlyAtoms([1, 6, 7, 8])
manager = GetChemSpider12(a)
def F(z_, x_, nreal_, DoForce=True):
'\n\t\tThis is the primitive form of force routine required by PeriodicForce.\n\t\t'
mtmp = Mol(z_, x_)
if DoForce:
(en, f) = manager.EvalBPDirectEEUpdateSinglePeriodic(mtmp, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], nreal_, True)
return (en[0], f[0])
else:
en = manager.EvalBPDirectEEUpdateSinglePeriodic(mtmp, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], nreal_, True, DoForce)
return en[0]
m = a.mols[0]
xmn = np.amin(m.coords, axis=0)
m.coords -= xmn
xmx = np.amax(m.coords, axis=0)
print('Xmn,Xmx', xmn, xmx)
m.properties['lattice'] = np.array([[xmx[0], 0.0, 0.0], [0.0, xmx[1], 0.0], [0.0, 0.0, xmx[2]]])
PF = PeriodicForce(m, m.properties['lattice'])
PF.BindForce(F, 15.0)
if 0:
for i in range(4):
print('En0:', PF(m.coords)[0])
m.coords += ((np.random.random((1, 3)) - 0.5) * 3.0)
m.coords = PF.lattice.ModuloLattice(m.coords)
print(('En:' + str(i)), PF(m.coords)[0])
PARAMS['OptMaxCycles'] = 100
POpt = PeriodicGeomOptimizer(PF)
PF.mol0 = POpt.Opt(m, 'ProOpt')
PARAMS['MDTemp'] = 300.0
PARAMS['MDdt'] = 0.2
PARAMS['MDMaxStep'] = 2000
traj = PeriodicVelocityVerlet(PF, 'Protein0')
traj.Prop()
|
def TestUrey():
a = MSet('2mzx_open')
a.ReadXYZ()
m = a.mols[0]
m.coords -= np.min(m.coords)
manager = GetChemSpider12(a)
def GetEnergyForceForMol(m):
def EnAndForce(x_, DoForce=True):
tmpm = Mol(m.atoms, x_)
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(tmpm, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
return EnAndForce
F = GetEnergyForceForMol(m)
PARAMS['OptMaxCycles'] = 500
Opt = MetaOptimizer(F, m, Box_=False)
Opt.Opt(m)
|
def MetadynamicsStatistics():
'\n\tGather statistics about the metadynamics exploration process varying bump depth, and width.\n\t'
sugarXYZ = '23\n\n \tC 0.469801362563 -0.186971976654 -0.917684108862\n\tO -0.859493679862 0.107094904765 -0.545217785597\n\tC -1.33087192983 -0.507316368828 0.650893179939\n\tC -0.438298062157 -0.0755659372548 1.80797104148\n\tO -0.778094885449 -0.696482563857 3.03079166065\n\tC 1.00192237607 -0.469457749055 1.52906960905\n\tC 1.477875031 0.077136161307 0.194458937693\n\tO 1.68692471022 1.45839447946 0.287157941131\n\tO 1.85082739088 0.082940968659 2.50886417356\n\tC -2.78317030311 -0.10545520088 0.824144527485\n\tO 0.616447904421 -1.51600440404 -1.31396642612\n\tH -1.26896203668 -1.59866670272 0.550821100756\n\tH -0.480848486767 1.0203835586 1.89601850937\n\tH 1.05389278947 -1.56571961461 1.52835050017\n\tH 2.41481082624 -0.436974077322 -0.0657764020213\n\tH 0.69100263804 0.494721792561 -1.74781805697\n\tH -0.193905967702 -1.76927170884 -1.75808894835\n\tH 2.04490869072 1.58866981496 1.17215002368\n\tH 1.58881143012 -0.273592522211 3.36016004218\n\tH -1.59032043389 -0.31753857396 3.3666667337\n\tH -2.86651153898 0.952637274148 1.08604018776\n\tH -3.31879024248 -0.265179614329 -0.112506279571\n\tH -3.27220758287 -0.69654193988 1.59910983889\n\t'
m = Mol()
m.FromXYZString(sugarXYZ)
def GetEnergyForceForMol(m):
s = MSet()
s.mols.append(m)
manager = GetChemSpider12(s)
def EnAndForce(x_, DoForce=True):
tmpm = Mol(m.atoms, x_)
(Etotal, Ebp, Ebp_atom, Ecc, Evdw, mol_dipole, atom_charge, gradient) = manager.EvalBPDirectEEUpdateSingle(tmpm, PARAMS['AN1_r_Rc'], PARAMS['AN1_a_Rc'], PARAMS['EECutoffOff'], True)
energy = Etotal[0]
force = gradient[0]
if DoForce:
return (energy, force)
else:
return energy
return EnAndForce
F = GetEnergyForceForMol(m)
Opt = GeomOptimizer(F)
m = Opt.Opt(m)
PARAMS['MDdt'] = 0.5
PARAMS['MDMaxStep'] = 8000
PARAMS['MetaBumpTime'] = 10.0
PARAMS['MetaMaxBumps'] = 500
PARAMS['MetaBowlK'] = 0.0
PARAMS['MDThermostat'] = 'Andersen'
PARAMS['MDTemp'] = 300.0
PARAMS['MDV0'] = None
if 0:
PARAMS['MetaMDBumpHeight'] = 0.0
PARAMS['MetaMDBumpWidth'] = 0.5
traj = MetaDynamics(None, m, 'MetaMD_000_05', F)
traj.Prop()
PARAMS['MetaMDBumpHeight'] = 0.5
PARAMS['MetaMDBumpWidth'] = 0.5
traj = MetaDynamics(None, m, 'MetaMD_050_05', F)
traj.Prop()
PARAMS['MetaMDBumpHeight'] = 0.5
PARAMS['MetaMDBumpWidth'] = 1.0
traj = MetaDynamics(None, m, 'MetaMD_050_10', F)
traj.Prop()
PARAMS['MetaMDBumpHeight'] = 0.5
PARAMS['MetaMDBumpWidth'] = 2.0
traj = MetaDynamics(None, m, 'MetaMD_050_20', F)
traj.Prop()
PARAMS['MetaMDBumpHeight'] = 1.0
PARAMS['MetaMDBumpWidth'] = 1.0
traj = MetaDynamics(None, m, 'MetaMD_100_10', F)
traj.Prop()
PARAMS['MetaMDBumpHeight'] = 1.0
PARAMS['MetaMDBumpWidth'] = 2.0
traj = MetaDynamics(None, m, 'MetaMD_100_20', F)
traj.Prop()
PARAMS['MetaBumpTime'] = 10.0
PARAMS['MetaMDBumpHeight'] = 2.0
PARAMS['MetaMDBumpWidth'] = 1.0
PARAMS['MetaBowlK'] = 0.1
traj = MetaDynamics(None, m, 'MetaMD_100_10_X', F)
traj.Prop()
|