def hess(x_): tmpm = Mol(m.atoms, x_) Energy, Force, Hessian = manager.EvalBPDirectEEHessSingle( tmpm, PARAMS["AN1_r_Rc"], PARAMS["AN1_a_Rc"], PARAMS["EECutoffOff"]) return Energy[0], Force[0], Hessian[0].reshape( (3 * m.NAtoms(), 3 * m.NAtoms()))
def main(): a = MSet() m = Mol() m.FromXYZString("""4 C 1. 0. 0. H 0. 1. 0. N 0. 0. 1. O 1. 1. 0.""") a.mols.append(m) TreatedAtoms = np.array([1, 6, 7, 8], dtype=np.uint8) # PARAMS["networks_directory"] = # "/home/animal/Packages/TensorMol/networks/" 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 # when elu is used EECutoffOn should always equal to 0 PARAMS["Elu_Width"] = 4.6 PARAMS["EECutoffOff"] = 15.0 PARAMS["AddEcc"] = True PARAMS["KeepProb"] = [1.0, 1.0, 1.0, 0.7] # Initialize a digester that apply descriptor for the fragme d = MolDigester(TreatedAtoms, name_="ANI1_Sym_Direct", OType_="EnergyAndDipole") tset = TensorMolData_BP_Direct_EE_WithEle_Release(a, d, order_=1, num_indis_=1, type_="mol") # WithGrad=True) PARAMS["DSFAlpha"] = 0.18 manager = TFMolManage( "chemspider12_solvation", tset, False, 'fc_sqdiff_BP_Direct_EE_ChargeEncode' + '_Update_vdw_DSF_elu_Normalize_Dropout', False, False) return manager
def energy_force_function(x_, do_force=True): """Calculate energy and force.""" mtmp = Mol(molecule.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 do_force: return energy, force else: return energy
PARAMS["NebSolver"] = "Verlet" PARAMS["SDStep"] = 0.05 PARAMS["NebNumBeads"] = 22 PARAMS["MaxBFGS"] = 12 neb = NudgedElasticBand(energy_force_function, molecule, final_molecule) Beads = neb.Opt("NebStep1") print(Beads) if __name__ == "__main__": import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from networks import tensormol01 from TensorMol import Mol molecule = Mol() molecule.FromXYZString("""4 C 1. 0. 0. H 0. 1. 0. N 0. 0. 1. O 1. 1. 0.""") secondary_molecule = Mol() secondary_molecule.FromXYZString("""4 C 1. 0. 0. H 0. 1. 0. N 0. 0. 1. O 0. 1. 0.""") print(main(tensormol01.main(), molecule, secondary_molecule, steps=3))
return energy # Perform geometry optimization PARAMS["OptMaxCycles"] = 100 + (len(molecule.atoms) / 100) * 300 PARAMS["OptThresh"] = 0.001 Opt = GeomOptimizer(energy_force_function) molecule = Opt.Opt(molecule, callback=emit_callback) return molecule if __name__ == "__main__": import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from networks import tensormol01, tensormol02, ani1 molecule = Mol() molecule.FromXYZString("""12 benzene C 0.00000 1.40272 0 H 0.00000 2.49029 0 C -1.21479 0.70136 0 H -2.15666 1.24515 0 C -1.21479 -0.70136 0 H -2.15666 -1.24515 0 C 0.00000 -1.40272 0 H 0.00000 -2.49029 0 C 1.21479 -0.70136 0 H 2.15666 -1.24515 0 C 1.21479 0.70136 0 H 2.15666 1.24515 0""") print(main(tensormol01.main(), molecule))
else: return energy # Perform geometry optimization PARAMS["OptMaxCycles"] = 2000 PARAMS["OptThresh"] = 0.001 Opt = ConfSearch(energy_force_function, molecule, StopAfter_=n_conf) return Opt.Search(molecule, callback=on_conformer_found) if __name__ == "__main__": import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from networks import tensormol01, tensormol02 molecule = Mol() molecule.FromXYZString("""17 C -7.079716 0.739119 0.004923 C -8.238053 1.731919 0.077636 C -7.724415 3.170105 0.092342 H -8.833846 1.547485 0.980576 H -8.903682 1.588910 -0.783054 C -8.864043 4.177735 0.119896 H -7.097400 3.358841 -0.788140 H -7.075050 3.330803 0.962085 O -8.312426 5.486788 0.162899 H -9.492618 4.035746 1.004615 H -9.484897 4.090243 -0.777434 H -9.058605 6.110699 0.167557 N -7.585679 -0.628274 -0.011876
def on_run_calculation(options): """Run when a calculation is submitted.""" print('Tensormol received ' + options.get('calculation').get('_id')) global calculation_running if calculation_running: return calculation_running = True calculation = options.get('calculation') calculation_id = calculation.get('_id') calculation_type = calculation.get('type') geometries = calculation.get('geometries') # charge = calculation.get('charge') # multiplicity = calculation.get('multiplicity') network_name = calculation.get('network') print('Calculation Received: ', calculation_id) # print(calculation) def ping_calculation_running(calculation): global ping_timer def socket_callback(error='', result=''): if error: print(error) raise Exception('Socket Error!') # print(result) socket_io.emit('pingCalculationRunning', {'calculationId': calculation_id}, socket_callback) print('Running Calculation: ', calculation_id) ping_timer = threading.Timer(3, ping_calculation_running, [calculation]) ping_timer.start() def stop_pinging(): global ping_timer if ping_timer: ping_timer.cancel() try: socket_result = {} def socket_callback(error='', result=''): nonlocal socket_result if error: print(error) raise Exception('Socket Error!') socket_result = result socket_io.emit('setCalculationRunning', {'calculationId': calculation_id}, socket_callback) socket_io.wait_for_callbacks() if not socket_result.get('updated'): # calculation not started, exit calculation_running = False return print('Calculation Started: ', calculation_id) ping_calculation_running(calculation) molecule = Mol() molecule.FromXYZString( str(len(geometries[0].split('\n'))) + '\n\n' + geometries[0]) secondary_molecule = Mol() if len(geometries) > 1: secondary_molecule.FromXYZString( str(len(geometries[1].split('\n'))) + '\n\n' + geometries[1]) # add switch based on network name if network_name == 'tensormol01': network = tensormol01_network elif network_name == 'ani1': network = ani1_network else: network = tensormol02_network # TODO: Attempt to run saveCalculationResult a few times on # error in callback if calculation_type == 'groundState': energy, force = energy_and_force.main( network, molecule) socket_io.emit( 'saveCalculationResult', { 'calculationId': calculation_id, 'properties': { 'energy': energy, 'force': force.tolist() } }) elif calculation_type == 'geometryOptimization': firstm = None def on_optimization_step_completed(mol_hist): nonlocal firstm print("Emitting Callback") firstm = mol_hist[0] energies = [firstm.properties['energy']] geometries = [ '\n'.join(str(firstm).split('\n')[2:]) ] if len(mol_hist) > 1: for m in mol_hist[-9:]: energies.append(m.properties['energy']) geometries.append('\n'.join( str(m).split('\n')[2:])) socket_io.emit( 'saveIntermediateCalculationResult', { 'calculationId': calculation_id, 'properties': { 'geometries': geometries, 'energies': energies } }) finalm = geometry_optimization.main( network, molecule, on_optimization_step_completed) first_xyz = '\n'.join(str(firstm).split('\n')[2:]) final_xyz = '\n'.join(str(finalm).split('\n')[2:]) socket_io.emit( 'saveCalculationResult', { 'calculationId': calculation_id, 'properties': { 'geometries': [first_xyz, final_xyz], 'energies': [ firstm.properties['energy'], finalm.properties['energy'] ] } }) elif calculation_type == 'harmonicSpectra': finalm, w, v, td = harmonic_spectra.main( network, molecule) xyz = '\n'.join(str(finalm).split('\n')[2:]) socket_io.emit( 'saveCalculationResult', { 'calculationId': calculation_id, 'properties': { 'optimizedGeometry': xyz, 'frequencies': w.tolist(), 'intensities': v.tolist(), 'freeEnergy': { '300K1ATM': td['Grot'] + td['Gtrans'] + td['Gvib'] } } }) elif calculation_type == 'nudgedElasticBand': # run neb # values = nudged_elastic_band.main( # network, [mol1, mol2]) pass elif calculation_type == 'conformerSearch': # TODO: add parameters. (window etc.) nConf = calculation.get('numberOfConformers') if nConf is None: print("Bad Conformer number: ", nConf) nConf = 20 def on_conformer_found(mol_hist): socket_io.emit( 'saveIntermediateCalculationResult', { 'calculationId': calculation_id, 'properties': { 'geometries': [ '\n'.join(str(m).split('\n')[2:]) for m in mol_hist ], 'energies': [ m.properties['energy'] for m in mol_hist ] } }) mol_hist = conformer_search.main( network, molecule, on_conformer_found, n_conf=nConf) socket_io.emit( 'saveCalculationResult', { 'calculationId': calculation_id, 'properties': { 'geometries': [ '\n'.join(str(m).split('\n')[2:]) for m in mol_hist ], 'energies': [m.properties['energy'] for m in mol_hist] } }) elif calculation_type == 'relaxedScan': # TODO: add parameters. (window etc.) atoms = calculation.get('atoms') final_distance = calculation.get('finalDistance') steps = calculation.get('steps') if steps is None: print("Bad steps number: ", steps) steps = 20 def on_step(mol_hist): socket_io.emit( 'saveIntermediateCalculationResult', { 'calculationId': calculation_id, 'properties': { 'geometries': [ '\n'.join(str(m).split('\n')[2:]) for m in mol_hist ], 'energies': [ m.properties['energy'] for m in mol_hist ], 'distances': [ m.properties['rs_r'] for m in mol_hist ] } }) mol_hist = relaxed_scan.main( network, molecule, on_step, steps=steps, final_distance=final_distance, atom_one=atoms[0], atom_two=atoms[1]) socket_io.emit( 'saveCalculationResult', { 'calculationId': calculation_id, 'properties': { 'geometries': [ '\n'.join(str(m).split('\n')[2:]) for m in mol_hist ], 'energies': [m.properties['energy'] for m in mol_hist], 'distances': [m.properties['rs_r'] for m in mol_hist] } }) else: print('Unknown CalculationType!', calculation_type) except Exception as e: print("Unexpected error:", e) socket_io.emit( 'saveCalculationResult', { 'calculationId': calculation_id, 'properties': {}, 'error': { 'message': str(e), 'createdAt': int(round(time.time() * 1000)), }, }) stop_pinging() calculation_running = False raise stop_pinging() calculation_running = False print('Calculation Finished: ', calculation_id)
for i in range(0, q.shape[0]): dipole += q[i] * x_[i] return dipole PARAMS["OptMaxCycles"] = 50 + (len(molecule.atoms) / 100) * 300 PARAMS["OptThresh"] = 0.0002 Opt = GeomOptimizer(energy_force_function) molecule = Opt.Opt(molecule) # Gotta optimize before running spectra w, v, i, TD = HarmonicSpectra(energy_force_function, molecule.coords, molecule.atoms, WriteNM_=True, Mu_=DipoleField, h_=lambda x: EFH(x)[2]) return molecule, w, i, TD if __name__ == "__main__": import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), '..')) from networks import tensormol01 molecule = Mol() molecule.FromXYZString("""3 water H 0 0 0 H 0 0 2 O 0 0.8 0.5""") print(main(tensormol01.main(), molecule))