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 = '... |
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)) ... |
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 DivNoi... |
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 ... |
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 ... |
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(va... |
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_... |
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... |
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')
u... |
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])
x... |
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.Prep... |
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.transpo... |
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))
... |
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_Al... |
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_... |
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)):
... |
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(sel... |
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(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... |
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['GSSearchA... |
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) + '... |
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]]),... |
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_... |
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 ReverseAtomwiseEmb... |
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_ - s... |
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... |
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\... |
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\... |
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"]: Temperatu... |
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_ : ... |
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 initiali... |
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'
... |
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_p... |
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 instan... |
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 instanc... |
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'
... |
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_AT... |
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:... |
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'))
... |
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[ke... |
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 ... |
@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 -... |
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)) / ... |
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 =... |
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):
... |
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_... |
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:
... |
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('g... |
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)
... |
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 im... |
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)]))... |
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... |
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_Direc... |
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_sqd... |
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'
... |
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']
en... |
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... |
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
... |
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... |
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'
... |
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(a... |
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
PARA... |
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['tes... |
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... |
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... |
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:
... |
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'... |
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.EvalBPDir... |
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... |
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... |
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.650893... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.