def __init__(self, f, cutoff=None): Calculator.__init__(self) self.f = f self.dict = {x: obj.get_cutoff() for x, obj in f.items()} self.df = {x: obj.derivative(1) for x, obj in f.items()} self.df2 = {x: obj.derivative(2) for x, obj in f.items()}
def __init__(self, calculator, db='checkpoints.db', logfile=None): Calculator.__init__(self) self.calculator = calculator if logfile is None: logfile = DevNull() self.checkpoint = Checkpoint(db, logfile) self.logfile = logfile
def __init__(self, restart=None, ignore_bad_restart_file=False, label=None, atoms=None, k=10, rt=1.5, sp_type='rep', **kwargs): Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) # Common parameters to all springs self.sp_type = sp_type self.k = k self.rt = rt # Depending on the spring type use different kernels self.nrg_func = spring_nrg self.f_func = spring_force self.v_nrg = voxel_spring_nrg self.atomwise_nrg = atomwise_spring_nrg if sp_type == 'com': self.nrg_func = com_spring_nrg self.f_func = com_spring_force self.v_nrg = voxel_com_spring_nrg self.atomwise_nrg = atomwise_com_spring_nrg if sp_type == 'att': self.nrg_func = att_spring_nrg self.f_func = att_spring_force self.v_nrg = voxel_att_spring_nrg self.atomwise_nrg = atomwise_att_spring_nrg
def __init__(self, hirshfeld=None, vdwradii=None, calculator=None, Rmax = 10, # maximal radius for periodic calculations vdWDB_alphaC6 = vdWDB_alphaC6, txt=None, ): """Constructor Parameters ========== hirshfeld: the Hirshfeld partitioning object calculator: the calculator to get the PBE energy """ self.hirshfeld = hirshfeld if calculator is None: self.calculator = self.hirshfeld.get_calculator() else: self.calculator = calculator if txt is None: self.txt = self.calculator.txt else: self.txt = get_txt(txt, rank) self.vdwradii = vdwradii self.vdWDB_alphaC6 = vdWDB_alphaC6 self.Rmax = Rmax self.atoms = None self.sR = 0.94 self.d = 20 Calculator.__init__(self)
def __init__(self, restart=None, ignore_bad_restart_file=False, label=None, atoms=None, calc=None, block=False, **kwargs): '''Basic calculator implementation. restart: str Prefix for restart file. May contain a directory. Default is None: don't restart. ignore_bad_restart_file: bool Ignore broken or missing restart file. By default, it is an error if the restart file is missing or broken. label: str Name used for all files. May contain a directory. atoms: Atoms object Optional Atoms object to which the calculator will be attached. When restarting, atoms will get its positions and unit-cell updated from file. Create a remote execution calculator based on actual ASE calculator calc. ''' logging.debug("Calc: %s Label: %s" % (calc, label)) Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) logging.debug("Dir: %s Ext: %s" % (self.directory, self.ext)) self.calc=calc self.jobid=None self.block=block
def __init__(self, *args, **results): """Save energy, forces, stress, ... for the current configuration.""" if args and isinstance(args[0], float): # Old interface: assert not results for key, value in zip(['energy', 'forces', 'stress', 'magmoms'], args): if value is not None: results[key] = value atoms = args[-1] else: if args: atoms = args[0] else: atoms = results.pop('atoms') Calculator.__init__(self) self.results = {} for property, value in results.items(): assert property in all_properties if value is None: continue if property in ['energy', 'magmom']: self.results[property] = value else: self.results[property] = np.array(value, float) self.atoms = atoms.copy()
def __init__(self, morses=None, bonds=None, angles=None, dihedrals=None, vdws=None, coulombs=None, **kwargs): Calculator.__init__(self, **kwargs) if (morses is None and bonds is None and angles is None and dihedrals is None and vdws is None and coulombs is None): raise ImportError("At least one of morses, bonds, angles, dihedrals," "vdws or coulombs lists must be defined!") if morses is None: self.morses = [] else: self.morses = morses if bonds is None: self.bonds = [] else: self.bonds = bonds if angles is None: self.angles = [] else: self.angles = angles if dihedrals is None: self.dihedrals = [] else: self.dihedrals = dihedrals if vdws is None: self.vdws = [] else: self.vdws = vdws if coulombs is None: self.coulombs = [] else: self.coulombs = coulombs
def __init__(self, restart=None, ignore_bad_restart_file=False, label='cp2k', atoms=None, command=None, debug=False, **kwargs): """Construct CP2K-calculator object.""" self._debug = debug self._force_env_id = None self._child = None self._shell_version = None self.label = None self.parameters = None self.results = None self.atoms = None # Several places are check to determine self.command if command is not None: self.command = command elif CP2K.command is not None: self.command = CP2K.command elif 'ASE_CP2K_COMMAND' in os.environ: self.command = os.environ['ASE_CP2K_COMMAND'] else: self.command = 'cp2k_shell' # default assert 'cp2k_shell' in self.command Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) # launch cp2k_shell child process if self._debug: print(self.command) self._child = Popen(self.command, shell=True, universal_newlines=True, stdin=PIPE, stdout=PIPE, bufsize=1) assert self._recv() == '* READY' # check version of shell self._send('VERSION') shell_version = self._recv().rsplit(":", 1) assert self._recv() == '* READY' assert shell_version[0] == "CP2K Shell Version" self._shell_version = float(shell_version[1]) assert self._shell_version >= 1.0 # enable harsh mode, stops on any error self._send('HARSH') assert self._recv() == '* READY' if restart is not None: try: self.read(restart) except: if ignore_bad_restart_file: self.reset() else: raise
def __init__(self, restart=None, ignore_bad_restart_file=False, label=None, atoms=None, **kwargs): """Accepted Keypairs calculation: str - only scf[default] supported at the moment ecutwfc: plane wave cuttoff [eV] notice not in Ry! nbands: number of bands for calculation (see pw.x -> nbnd) usesymm: whether or not to use symmetry in calculation (True/False) maxiter: maximum number of iterations in an scf step convergence: {'energy', <value>} - only one implemented kpts: (1, 1, 1) - gamma point (n1, n2, n3) - Morstead Packing [[k1, k2, k3] ... ] - List of kpoints prefix: (self.label is meaningless at moment) str - string to append to output files pseudo: {'atom symbol': 'name of pseudo potential', ...} - dictionary of pseudo per atom outdir: str - relative or absolute path to output directory. Will create it if it does not exist. pseudo_dir: str - relative or absolute path to pseudo directory. occupations: str - 'smearing', 'tetrahedra', 'fixed', 'from_input' input_dft: str - functional to use fft_mesh: [nr1, nr2, nr3] - fft mesh to use for calculation keypairs: way to initialize via the base class PWBase. (DO NOT SET CELL OR ATOM POSITIONS via PWBase this is done automagically via ASE Atoms) debug: if True will print input and output QE files AUTOMATICALLY SET KEYPAIRS: Set so we can always extract stress and forces: control.tstress=True control.tprnfor=True From atoms object: CARD 'CELL PARAMETERS (angstroms)' from atoms.cell CARD 'ATOMIC POSITIONS (angstroms)' from atoms[i] system.nat from number of unique atoms in atoms[i] system.ntyp from len(atoms) Thus DO NOT SET: A, B, C, cosAB, cosBC, cosAC, celldm(1-6) or any of these previously mentioned. Be smart """ Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) self._pw = None
def __init__(self, atoms=None, label=None, top=None, crd=None, mm_options=None, qm_options=None, permutation=None, **kwargs): if not have_sander: raise RuntimeError("sander Python module could not be imported!") Calculator.__init__(self, label, atoms) self.permutation = permutation if qm_options is not None: sander.setup(top, crd.coordinates, crd.box, mm_options, qm_options) else: sander.setup(top, crd.coordinates, crd.box, mm_options)
def __init__(self, calculator, jsonfile=None, dumpjson=False): Calculator.__init__(self) self.calculator = calculator self.fmax = {} self.walltime = {} self.energy_evals = {} self.energy_count = {} self.set_label('(none)') if jsonfile is not None: self.read_json(jsonfile) self.dumpjson = dumpjson
def __init__(self, rc=5.0, width=1.0): """TIP3P potential. rc: float Cutoff radius for Coulomb part. width: float Width for cutoff function for Coulomb part. """ self.rc = rc self.width = width Calculator.__init__(self)
def __init__(self, client, ip=None, atoms=None, port=0, logger=screen, bgq=False): Calculator.__init__(self) self.client = client if ip is None: ip = '127.0.0.1' # default to localhost self.logger = logger self.bgq=bgq self.server = AtomsServerSync((ip, port), AtomsRequestHandler, [self.client], logger=self.logger, bgq=self.bgq) self.label = 1 self.atoms = atoms
def __init__(self, atoms, **results): """Save energy, forces, stress, ... for the current configuration.""" Calculator.__init__(self) self.results = {} for property, value in results.items(): assert property in all_properties if value is None: continue if property in ['energy', 'magmom', 'free_energy']: self.results[property] = value else: self.results[property] = np.array(value, float) self.atoms = atoms.copy()
def __init__(self, selection, qmcalc, mmcalc, interaction, vacuum=None, embedding=None, output=None): """EIQMMM object. The energy is calculated as:: _ _ _ _ E = E (R ) + E (R ) + E (R , R ) QM QM MM MM I QM MM parameters: selection: list of int, slice object or list of bool Selection out of all the atoms that belong to the QM part. qmcalc: Calculator object QM-calculator. mmcalc: Calculator object MM-calculator. interaction: Interaction object Interaction between QM and MM regions. vacuum: float or None Amount of vacuum to add around QM atoms. Use None if QM calculator doesn't need a box. embedding: Embedding object or None Specialized embedding object. Use None in order to use the default one. output: None, '-', str or file-descriptor. File for logging information - default is no logging (None). """ self.selection = selection self.qmcalc = qmcalc self.mmcalc = mmcalc self.interaction = interaction self.vacuum = vacuum self.embedding = embedding self.qmatoms = None self.mmatoms = None self.mask = None self.center = None # center of QM atoms in QM-box self.name = '{0}+{1}+{2}'.format(qmcalc.name, interaction.name, mmcalc.name) self.output = convert_string_to_fd(output) Calculator.__init__(self)
def __init__(self, descriptor, model, label='amp', dblabel=None, cores=None, atoms=None): Calculator.__init__(self, label=label, atoms=atoms) log = Logger(make_filename(self.label, '-log.txt')) self.log = log self._printheader(log) # Note the following are properties: these are setter functions. self.descriptor = descriptor self.model = model self.cores = cores # Note this calls 'assign_cores'. self.dblabel = label if dblabel is None else dblabel
def __init__(self, restart=None, ignore_bad_restart_file=False, label='pmd', atoms=None, command='pmd > out.pmd', dimension=(True,True,True), specorder=None, **kwargs): """Construct PMD-calculator object. Parameters ========== label: str Prefix to use for filenames (in.label, erg.label, ...). [Default: 'pmd'] command: str Command string to execute pmd. [Default: 'pmd > out.pmd'] force_type: str or tuple/list Force fields to be used, which must be set. [Default: None] specorder: list Order of species. This is probably very important, since the order of species is usually fixed in pmd whereas not in ASE atoms object. [Default: None] Examples ======== Use default values: >>> h = Atoms('H', calculator=PMD(label='pmd',force_type='NN')) >>> e = h.get_potential_energy() """ Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) if label not in ['pmd']: raise RuntimeError('label must be pmd.') if self.parameters['force_type'] is None: raise RuntimeError('force_type must be specified.') if command is None: self.command = self.label+' > out.'+self.label elif '>' in command: self.command = command.split('>')[0] +' > out.'+self.label else: self.command = command +' > out.'+self.label self.specorder= specorder self.dimension = dimension
def __init__(self, restart=None, ignore_bad_restart_file=False, label=os.curdir, atoms=None, **kwargs): if "potential" in kwargs: self.read_potential(kwargs["potential"]) Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) valid_args = ( "potential", "elements", "header", "drho", "dr", "cutoff", "atomic_number", "mass", "a", "lattice", "embedded_energy", "electron_density", "phi", # derivatives "d_embedded_energy", "d_electron_density", "d_phi", "d", "q", "d_d", "d_q", # adp terms "skin", "form", "Z", "nr", "nrho", "mass", ) # set any additional keyword arguments for arg, val in self.parameters.iteritems(): if arg in valid_args: setattr(self, arg, val) else: raise RuntimeError('unknown keyword arg "%s" : not in %s' % (arg, valid_args))
def __init__(self, forcefield='UFF', filename='/tmp/obcalc_atoms.xyz', logfile=None): """ Open Babel Universal Force Filed (UFF) calculator. Parameters: filename: path to a file where cooridnates will be stored to transfer to OB Note: transfer throught file is slow, but required sicne manual formation of atoms system in OB python environment requires explicit notation of bonds.. TODO: get away from file-based transfer. """ import ase.parallel # logging copied from ase.md.logger.MDLogger if ase.parallel.rank > 0: self.logfile = None # Only log on master if logfile == '-': self.logfile = sys.stdout self.ownlogfile = False elif hasattr(logfile, 'write'): self.logfile = logfile self.ownlogfile = False elif not (logfile is None): self.logfile = open(logfile, 'w') self.ownlogfile = True else: self.logfile = None self.filename = filename self.file_format = 'xyz' #TODO: auto-detect format? self.natoms = 0 self.nbonds = 0 #self.nrotat = 0 #self.ndihed = 0 self.mol = None self.ff = 0 openbabel.OBConversion() # this magic function should be called before FF search... self.ff = openbabel.OBForceField.FindForceField( forcefield ) self.name = 'OB_%s' % forcefield if (self.ff == 0): print('Could not find forcefield') self.ff.SetLogLevel(openbabel.OBFF_LOGLVL_HIGH) Calculator.__init__(self)
def __init__(self, label='project001', restart=None, ignore_bad_restart_file=False, atoms=None, debug=False, **kwargs): '''Construct CP2K-calculator object.''' self._debug = debug self._force_env_id = None self._child = None self.label = None self.parameters = None self.results = None self.atoms = None Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) # launch cp2k_shell child process if(self._debug): print(self.command) cmd = self.command.split() self._child = Popen(cmd, stdin=PIPE, stdout=PIPE, bufsize=1) assert(self._recv() == '* READY')
def __init__(self, parameters): """ Calculator for Buckinham potential: E_B = A exp(-r/rho) - C/r^6 with Coulumb interaction: E_C = q_i * q_j e^2/(4pi eps_0 r^2) charges are read from atoms object Parameters: parameters: dict Mapping from pair of atoms to tuple containing A, rho and C for that pair. A in eV, rho in Angstr, C in eV/Angstr^2 Example: calc = Buck({('O', 'O'): (A, rho, C)}) """ Calculator.__init__(self) self.parameters = {} for (symbol1, symbol2), (A, rho, C) in parameters.items(): self.parameters[_tup2str((symbol1, symbol2))] = A, rho, C self.parameters[_tup2str((symbol2, symbol1))] = A, rho, C
def __init__(self, restart=None, ignore_bad_restart_file=False, label='PySCF', atoms=None, scratch=None, **kwargs): """Construct PySCF-calculator object. Parameters ========== label: str Prefix to use for filenames (label.in, label.txt, ...). Default is 'PySCF'. mfclass: PySCF mean-field class molcell: PySCF :Mole: or :Cell: """ Calculator.__init__(self, restart=None, ignore_bad_restart_file=False, label='PySCF', atoms=None, scratch=None, **kwargs) # TODO # This explicitly refers to "cell". How to refer # to both cell and mol together? self.mf=None self.initialize(**kwargs)
def __init__(self, restart=None, ignore_bad_restart_file=False, label='pmd', atoms=None, command='pmd > out.pmd', specorder=None, **kwargs): """Construct PMD-calculator object. Parameters ========== label: str Prefix to use for filenames (in.label, erg.label, ...). Default is 'pmd'. Examples ======== Use default values: >>> h = Atoms('H', calculator=PMD(label='pmd',force_type='NN')) >>> e = h.get_potential_energy() """ Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) if label not in ['pmd']: raise RuntimeError('label must be pmd.') if self.parameters['force_type'] is None: raise RuntimeError('force_type must be specified.') if command is None: self.command = self.label+' > out.'+self.label elif '>' in command: self.command = command.split('>')[0] +' > out.'+self.label else: self.command = command +' > out.'+self.label self.specorder= specorder
def __init__(self, hirshfeld=None, vdwradii=None, calculator=None, Rmax=10, # maximal radius for periodic calculations vdWDB_alphaC6=vdWDB_alphaC6, txt=None, sR=None): """Constructor Parameters ========== hirshfeld: the Hirshfeld partitioning object calculator: the calculator to get the PBE energy """ self.hirshfeld = hirshfeld if calculator is None: self.calculator = self.hirshfeld.get_calculator() else: self.calculator = calculator if txt is None: txt = get_logging_file_descriptor(self.calculator) self.txt = convert_string_to_fd(txt) self.vdwradii = vdwradii self.vdWDB_alphaC6 = vdWDB_alphaC6 self.Rmax = Rmax self.atoms = None if sR is None: try: xc_name = self.calculator.get_xc_functional() self.sR = sR_opt[xc_name] except KeyError: raise ValueError('Tkatchenko-Scheffler dispersion correction not implemented for %s functional' % xc_name) else: self.sR = sR self.d = 20 Calculator.__init__(self)
def __init__(self, restart=None, ignore_bad_restart_file=False, label=os.curdir, atoms=None, **kwargs): if 'potential' in kwargs: self.read_potential(kwargs['potential']) Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) valid_args = ('potential', 'elements', 'header', 'drho', 'dr', 'cutoff', 'atomic_number', 'mass', 'a', 'lattice', 'embedded_energy', 'electron_density', 'phi', # derivatives 'd_embedded_energy', 'd_electron_density', 'd_phi', 'd', 'q', 'd_d', 'd_q', # adp terms 'skin', 'form', 'Z', 'nr', 'nrho', 'mass') # set any additional keyword arguments for arg, val in self.parameters.items(): if arg in valid_args: setattr(self, arg, val) else: raise RuntimeError('unknown keyword arg "%s" : not in %s' % (arg, valid_args))
def __init__(self, restart=None, ignore_bad_restart_file=False, label='cp2k', atoms=None, command=None, debug=False, **kwargs): """Construct CP2K-calculator object.""" self._debug = debug self._force_env_id = None self._shell = None self.label = None self.parameters = None self.results = None self.atoms = None # Several places are check to determine self.command if command is not None: self.command = command elif CP2K.command is not None: self.command = CP2K.command elif 'ASE_CP2K_COMMAND' in os.environ: self.command = os.environ['ASE_CP2K_COMMAND'] else: self.command = 'cp2k_shell' # default Calculator.__init__(self, restart, ignore_bad_restart_file, label, atoms, **kwargs) self._shell = Cp2kShell(self.command, self._debug) if restart is not None: try: self.read(restart) except: if ignore_bad_restart_file: self.reset() else: raise
def __init__(self, selection, qmcalc, mmcalc1, mmcalc2, vacuum=None): """SimpleQMMM object. The energy is calculated as:: _ _ _ E = E (R ) - E (R ) + E (R ) QM QM MM QM MM all parameters: selection: list of int, slice object or list of bool Selection out of all the atoms that belong to the QM part. qmcalc: Calculator object QM-calculator. mmcalc1: Calculator object MM-calculator used for QM region. mmcalc2: Calculator object MM-calculator used for everything. vacuum: float or None Amount of vacuum to add around QM atoms. Use None if QM calculator doesn't need a box. """ self.selection = selection self.qmcalc = qmcalc self.mmcalc1 = mmcalc1 self.mmcalc2 = mmcalc2 self.vacuum = vacuum self.qmatoms = None self.center = None self.name = '{0}-{1}+{1}'.format(qmcalc.name, mmcalc1.name) Calculator.__init__(self)
def __init__(self, np_species = ['Pt', 'Cu'], sp_species = ['C'], np_calc = EMT(), sp_calc = BrennerPotential(), inter_calc=None, vacuum=None, txt='-'): """ Hybrid calculator, mixing two many-body calculators, i.e. EMT and Brenner. The first is good for description of metal nanoparticle, and the second is used for carbon support or matrix dynamics. The energy is calculated as:: _ _ E = E (R ) + E (R ) + ?interaction? EMT nano Brenner Carbon parameters: vacuum: float or None Amount of vacuum to add around QM atoms. Use None if QM calculator doesn't need a box. """ self.np_species = np_species self.sp_species = sp_species self.np_calc = np_calc self.sp_calc = sp_calc self.ia_calc = inter_calc self.vacuum = vacuum self.np_selection = [] self.sp_selection = [] self.np_atoms = None self.sp_atoms = None self.center = None #self.name = '{0}+{1}'.format(np_calc.name, sp_calc.name) self.name = 'hybrid' Calculator.__init__(self)
def __init__(self, calc=None, port=None, unixsocket=None, timeout=None, log=None): """Initialize socket I/O calculator. This calculator launches a server which passes atomic coordinates and unit cells to an external code via a socket, and receives energy, forces, and stress in return. ASE integrates this with the Quantum Espresso, FHI-aims and Siesta calculators. This works with any external code that supports running as a client over the i-PI protocol. Parameters: calc: calculator or None If calc is not None, a client process will be launched using calc.command, and the input file will be generated using ``calc.write_input()``. Otherwise only the server will run, and it is up to the user to launch a compliant client process. port: integer port number for socket. Should normally be between 1025 and 65535. Typical ports for are 31415 (default) or 3141. unixsocket: str or None if not None, ignore host and port, creating instead a unix socket using this name prefixed with ``/tmp/ipi_``. The socket is deleted when the calculator is closed. timeout: float >= 0 or None timeout for connection, by default infinite. See documentation of Python sockets. For longer jobs it is recommended to set a timeout in case of undetected client-side failure. log: file object or None (default) logfile for communication over socket. For debugging or the curious. In order to correctly close the sockets, it is recommended to use this class within a with-block: >>> with SocketIOCalculator(...) as calc: ... atoms.calc = calc ... atoms.get_forces() ... atoms.rattle() ... atoms.get_forces() It is also possible to call calc.close() after use. This is best done in a finally-block.""" Calculator.__init__(self) self.calc = calc self.timeout = timeout self.server = None self.log = log # We only hold these so we can pass them on to the server. # They may both be None as stored here. self._port = port self._unixsocket = unixsocket # First time calculate() is called, system_changes will be # all_changes. After that, only positions and cell may change. self.calculator_initialized = False # If there is a calculator, we will launch in calculate() because # we are responsible for executing the external process, too, and # should do so before blocking. Without a calculator we want to # block immediately: if calc is None: self.launch_server()
def __init__(self, **kwargs): Calculator.__init__(self, **kwargs)
def __init__(self, atoms=None, classical_calculator=None, qm_calculator=None, qm_cluster=None, forced_qm_list=None, change_bonds=True, calculate_errors=False, calculation_always_required=False, buffer_hops=10, verbose=0, enable_check_state=True): """Initialize a generic ASE potential without any calculating power, This is only to have access to the necessary functions, all the evaluations will be performes in self.mm_pot and self.qm_calculator Parameters ---------- atoms : ASE.atoms atoms object classical_calculator : AE.calculator classical calculator qm_calculator : ASE.calculator qm calculator qm_cluster : matscipy.calculators.mcfm.qm_cluster flagging/cluster carving utility forced_qm_list : list add this list to enforce a set of atoms for qm treatment change_bonds : bool call the classical potential to update topology calculate_errors : bool evaluate errors after each step calculation_always_required : bool as name buffer_hops : int number of neighbours hop used to construct the core QM region verbose : int For now verbose levels are: 0 - nothing is printed 1 - More data is added to Atoms object 10 - Calculate steps are listed 100 - Information about specific QM clusters (the default is 0) enable_check_state : bool Save the atoms after each evaluation to enable meth::check_state """ # Set the verbose status self.verbose = verbose self.debug_cluster_carving = False # Set storing atoms - slows down evaluation but enables check_state funtion self.enable_check_state = enable_check_state # Flag for warmup self.warmup = False # Init ASE calculator as a parent class self._calc_args = {} self._default_properties = [] self.calculation_always_required = calculation_always_required Calculator.__init__(self) # If an atoms objct has been specified, attach a copy to the calculator to facilitate # the proper use of meth:check_state() if atoms is not None: self.atoms = atoms.copy() atoms.set_calculator(self) # Set some flags and values self.errors = {} self.calculate_errors = calculate_errors self.change_bonds = change_bonds self.buffer_hops = buffer_hops self.conserve_momentum = False self.long_range_weight = 0.0 self.doParallel = True # Flag for QM debugging self.debug_qm_calculator = False # Set the cluster carving object self.qm_cluster = qm_cluster if forced_qm_list is None: self.forced_qm_list = None else: self.forced_qm_list = [forced_qm_list] self.cluster_list = [] self.cluster_data_list = None # Set qm and mm calculators self.classical_calculator = classical_calculator self.qm_calculator = qm_calculator # Set up writing clusters self.clusterDebug_cluster_atoms = None if (self.verbose >= 100): self.debug_cluster_carving = True self.clusterDebug_cluster_atoms = open("clusterDebug_cluster_atoms.xyz", "w") self.clusterDebug_full_structure = None if (self.verbose >= 100): self.debug_cluster_carving = True self.clusterDebug_full_structure = open("clusterDebug_full_structure.xyz", "w")
def __init__(self, model, label="DP",fparam=0, **kwargs): Calculator.__init__(self, label=label, **kwargs) self.dp = DeepPot(model) self.type_dict = dict(zip(self.dp.get_type_map(), range(self.dp.get_ntypes()))) self.fparam= [fparam]
def __init__(self, *args, **kwargs): Calculator.__init__(self, *args, **kwargs) self.crystal_bonds = 0
def __init__(self, data, feature_matrix=None, similarity_matrix=None, sigma=None, L=1e-5, comp=None, rcut=None, max_similarity=1e-6, bias='avg', **kwargs): """ Arguments: data: A list of ASE atoms objects. feature_matrix: A list of features in the same order as the atoms objects If this is not provided one will be calculated. similarity_matrix: A matrix containing all similarities. If this is not provided one will be calculated. sigma: Width of the kernel used for kernel ridge regression. If not set one will be calculated. L: This is the regularization term. Normally you can just use the default value. comp: Kreg has a default comperator. If you wish to use another set it here. The comperator must have af method named get_features_atoms() to retrive atomic features. rcut: Cut off radius is desired for the default feature. If not set, an optimal cut off radius wil be calculated. max_similarity: The threshold used to determin if two structures are identical. Hint. It can be very time consuming to calculate the feature and similarity matrix. If you use the same system more than once consider saving the feature and the similarity for later use. """ Calculator.__init__(self, **kwargs) self.data_values = np.array([a.get_potential_energy() for a in data]) args = np.argsort(self.data_values) self.data = [data[i] for i in args] self.data_values[args] self.n_data = len(self.data) if comp is None: a = self.data[0] cell = a.get_cell() pbc = list(a.get_pbc()) if rcut is None: if sum(pbc): rcut = pbc[0]*max(cell[0])**2+pbc[1]*max(cell[1])**2+pbc[2]*max(cell[2])**2 pos = a.get_positions() add = (1-pbc[0])*(max(pos.T[0])-min(pos.T[0]))**2+(1-pbc[1])*(max(pos.T[1])-min(pos.T[1]))**2+\ (1-pbc[2])*(max(pos.T[2])-min(pos.T[2]))**2 rcut = np.sqrt(rcut+2.25*add)/2. else: rcut = np.sqrt(cell[0][0]**2+cell[1][1]**2+cell[2][2]) self.comp = FingerprintsComparator(a, n_top=None, cell=cell, dE=1000., cos_dist_max=max_similarity, rcut=rcut, binwidth=0.05, pbc=pbc, maxdims=[cell[0][0],cell[1][1],cell[2][2]], sigma=0.5, nsigma=4) else: self.comp = comp self.feature_matrix = feature_matrix if self.feature_matrix is None: self.feature_matrix = self.get_feature_matrix() self.similarity_matrix = similarity_matrix if self.similarity_matrix is None: self.similarity_matrix = self.get_similarity_matrix() self.kreg = KernelRegression(self.data_values, 5, self.feature_matrix, self.similarity_matrix, self.comp) self.L = L self.bias = bias if sigma is None: self.train() else: self.sigma = sigma self.kreg.sigma= sigma self.max_similarity = max_similarity
def __init__(self, energy=None, forces=None, **kwargs): Calculator.__init__(self, **kwargs) self.energy = energy self.forces = forces
def __init__(self, potential, calculate=partial, **kwargs): Calculator.__init__(self, **kwargs) self.potential = potential self.ext_calculate = calculate