当前位置: 首页>>代码示例>>Python>>正文


Python calculator.Calculator类代码示例

本文整理汇总了Python中ase.calculators.calculator.Calculator的典型用法代码示例。如果您正苦于以下问题:Python Calculator类的具体用法?Python Calculator怎么用?Python Calculator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了Calculator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: __init__

 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
开发者ID:rchiechi,项目名称:QuantumParse,代码行数:7,代码来源:checkpoint.py

示例2: __init__

 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
开发者ID:rchiechi,项目名称:QuantumParse,代码行数:35,代码来源:ff.py

示例3: __init__

 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()
开发者ID:PHOTOX,项目名称:fuase,代码行数:27,代码来源:singlepoint.py

示例4: calculate

    def calculate(self, atoms, properties, system_changes):
        # call parent method:
        Calculator.calculate(self, atoms, properties, system_changes)

        if not(system_changes is None):
            self.update_atoms()

        if 'energy' in properties:
            energy = self.ff.Energy()
            # energy units are kcal/mole according to http://forums.openbabel.org/Energy-units-td1574278.html
            # and in Avogadro they are reported as kJ/mole ...
            self.results['energy'] = energy * units.kJ / units.mol

        if 'forces' in properties:
            d = 0.001
            F_ai = np.zeros( (self.natoms, 3) )
            for iatom in xrange( self.natoms ):
                for iaxis in xrange( 3 ):
                    obatom = self.mol.GetAtom( 1 + iatom )
                    vec = obatom.GetVector()

                    obatom.SetVector( self._shift_OBvec(vec, iaxis, d) )
                    self.ff.Setup( self.mol )
                    eplus = self.ff.Energy() * units.kJ/units.mol

                    obatom.SetVector( self._shift_OBvec(vec, iaxis, -2*d) )
                    self.ff.Setup( self.mol )
                    eminus = self.ff.Energy() * units.kJ/units.mol

                    obatom.SetVector( self._shift_OBvec(vec, iaxis, d) ) # put it back
                    F_ai[iatom, iaxis] = (eminus - eplus) / (2 * d)
            self.results['forces'] = F_ai
开发者ID:lavakyan,项目名称:ase-bimetall,代码行数:32,代码来源:obcalc.py

示例5: calculate

    def calculate(self, atoms, properties, system_changes):
        Calculator.calculate(self, atoms, properties, system_changes)
        
        if self.qmatoms is None:
            self.initialize_qm(atoms)
            
        self.qmatoms.positions = atoms.positions[self.selection]
        if self.vacuum:
            self.qmatoms.positions += (self.center -
                                       self.qmatoms.positions.mean(axis=0))
            
        energy = self.mmcalc2.get_potential_energy(atoms)
        forces = self.mmcalc2.get_forces(atoms)
        
        energy += self.qmcalc.get_potential_energy(self.qmatoms)
        qmforces = self.qmcalc.get_forces(self.qmatoms)
        if self.vacuum:
            qmforces -= qmforces.mean(axis=0)
        forces[self.selection] += qmforces
        
        energy -= self.mmcalc1.get_potential_energy(self.qmatoms)
        forces[self.selection] -= self.mmcalc1.get_forces(self.qmatoms)

        self.results['energy'] = energy
        self.results['forces'] = forces
开发者ID:rosswhitfield,项目名称:ase,代码行数:25,代码来源:qmmm.py

示例6: __init__

    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
开发者ID:ZhouHUB,项目名称:pyIID,代码行数:25,代码来源:spring_calc.py

示例7: calculate

    def calculate(self, atoms, properties, system_changes):
        Calculator.calculate(self, atoms, properties, system_changes)
        if system_changes: # if anything at all changed (could be made more fine-grained)
            self.logger.pr('calculation triggered with properties={0}, system_changes={1}'.format(properties,
                                                                                                  system_changes))
            self.server.put(atoms, 0, self.label)
            if self.label != 1:
                # send atoms over socket, unless first time
                self.logger.pr('socket calculator sending Atoms label={0}'.format(self.label))
                self.server.handle_request()
            # wait for results to be ready
            self.logger.pr('socket calculator waiting for results label={0}'.format(self.label))
            self.server.handle_request()

            self.label += 1
            [results] = self.server.get_results()

            # we always compute energy, forces and stresses, regardless of what was requested
            stress = -(results.info['virial']/results.get_volume())
            self.results = {'energy': results.info['energy'],
                            'forces': results.arrays['force'],
                            'stress': full_3x3_to_Voigt_6_stress(stress)}
        else:
            self.logger.pr('calculation avoided with properties={0}, system_changes={1}'.format(properties,
                                                                                                system_changes))
开发者ID:libAtoms,项目名称:matscipy,代码行数:25,代码来源:socketcalc.py

示例8: __init__

    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()}
开发者ID:libAtoms,项目名称:matscipy,代码行数:7,代码来源:calculator.py

示例9: calculate

    def calculate(self, atoms=None, properties=['energy'],
                  system_changes=all_changes):
        """EAM Calculator

        atoms: Atoms object
            Contains positions, unit-cell, ...
        properties: list of str
            List of what needs to be calculated.  Can be any combination
            of 'energy', 'forces'
        system_changes: list of str
            List of what has changed since last calculation.  Can be
            any combination of these five: 'positions', 'numbers', 'cell',
            'pbc', 'initial_charges' and 'initial_magmoms'.
            """

        Calculator.calculate(self, atoms, properties, system_changes)

        # we shouldn't really recalc if charges or magmos change
        if len(system_changes) > 0:  # something wrong with this way
            self.update(self.atoms)
            self.calculate_energy(self.atoms)

            if 'forces' in properties:
                self.calculate_forces(self.atoms)

        # check we have all the properties requested
        for property in properties:
            if property not in self.results:
                if property is 'energy':
                    self.calculate_energy(self.atoms)

                if property is 'forces':
                    self.calculate_forces(self.atoms)
开发者ID:rchiechi,项目名称:QuantumParse,代码行数:33,代码来源:eam.py

示例10: run_calculation

 def run_calculation(self, atoms=None, properties=None,
                         system_changes=all_changes):
     '''
     Internal calculation executor. We cannot use FileIOCalculator
     directly since we need to support remote execution.
     
     This calculator is different from others. 
     It prepares the directory, launches the remote process and
     raises the exception to signal that we need to come back for results
     when the job is finished.
     '''
     if properties is None:
         properties = ['energy']
     Calculator.calculate(self, atoms, properties, system_changes)
     self.write_input(self.atoms, properties, system_changes)
     if self.command is None:
         raise RuntimeError('Please configure RemoteQE calculator!')
     olddir = os.getcwd()
     errorcode=0
     try:
         os.chdir(self.directory)
         output = subprocess.check_output(self.command, shell=True)
         self.jobid=output.split()[0]
         self.submited=True
         #print "Job %s submitted. Waiting for it." % (self.jobid)
         # Waiting loop. To be removed.
     except subprocess.CalledProcessError as e:
         errorcode=e.returncode
     finally:
         os.chdir(olddir)
     
     if errorcode:
         raise RuntimeError('%s returned an error: %d' %
                            (self.name, errorcode))
     self.read_results()
开发者ID:jochym,项目名称:qe-util,代码行数:35,代码来源:__init__.py

示例11: calculate

    def calculate(self, atoms=None, properties=['energy'],
                  system_changes=all_changes):
        """GEBF Calculator
        """

        Calculator.calculate(self, atoms, properties, system_changes)

        if len(system_changes) > 0:  # something wrong with this way
            self.update(self.atoms)
            if 'energy' in properties:
                self.calculate_energy(self.atoms)

            if 'forces' in properties:
                self.calculate_forces(self.atoms)

            if 'charges' in properties:
                self.calculate_charges(self.atoms)

        # check we have all the properties requested
        for property in properties:
            if property not in self.results:
                if property is 'energy':
                    self.calculate_energy(self.atoms)

                if property is 'forces':
                    self.calculate_forces(self.atoms)

                if property is 'charges':
                    self.calculate_charges(self.atoms)

#FUMPORTANT|
        atoms.set_initial_charges(self.results['charges'])
开发者ID:PHOTOX,项目名称:fuase,代码行数:32,代码来源:gebf.py

示例12: calculate

    def calculate(self, atoms=None, properties=['energy'],
                  system_changes=all_changes):
        # We don't call FileIOCalculator.calculate here, because that method
        # calls subprocess.call(..., shell=True), which we don't want to do.
        # So, we reproduce some content from that method here.
        Calculator.calculate(self, atoms, properties, system_changes)

        # If a parameter file exists in the working directory, delete it
        # first. If we need that file, we'll recreate it later.
        localparfile = os.path.join(self.directory, '.dftd3par.local')
        if os.path.isfile(localparfile):
            os.remove(localparfile)

        # Write XYZ or POSCAR file and .dftd3par.local file if we are using
        # custom damping parameters.
        self.write_input(self.atoms, properties, system_changes)
        command = self._generate_command()

        # Finally, call dftd3 and parse results.
        with open(self.label + '.out', 'w') as f:
            errorcode = subprocess.call(command, cwd=self.directory, stdout=f)

        if errorcode:
            raise RuntimeError('%s returned an error: %d' %
                               (self.name, errorcode))
        self.read_results()
开发者ID:rchiechi,项目名称:QuantumParse,代码行数:26,代码来源:dftd3.py

示例13: __init__

    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
开发者ID:jochym,项目名称:Elastic,代码行数:25,代码来源:parcalc.py

示例14: calculate

    def calculate(self, atoms, properties, system_changes):
        """
        Calculation of the energy of system and forces of all atoms.
        """
        # The inherited method below just sets the atoms object,
        # if specified, to self.atoms.
        Calculator.calculate(self, atoms, properties, system_changes)

        log = self.log
        log('Calculation requested.')

        images = hash_images([self.atoms])
        key = images.keys()[0]

        if properties == ['energy']:
            log('Calculating potential energy...', tic='pot-energy')
            self.descriptor.calculate_fingerprints(images=images,
                                                   log=log,
                                                   calculate_derivatives=False)
            energy = self.model.get_energy(self.descriptor.fingerprints[key])
            self.results['energy'] = energy
            log('...potential energy calculated.', toc='pot-energy')

        if properties == ['forces']:
            log('Calculating forces...', tic='forces')
            self.descriptor.calculate_fingerprints(images=images,
                                                   log=log,
                                                   calculate_derivatives=True)
            forces = \
                self.model.get_forces(self.descriptor.fingerprints[key],
                                      self.descriptor.fingerprintprimes[key])
            self.results['forces'] = forces
            log('...forces calculated.', toc='forces')
开发者ID:AkshayTharval,项目名称:Atomistic-Machine-Learning-Potentials,代码行数:33,代码来源:__init__.py

示例15: calculate

 def calculate(self, atoms, properties, system_changes):
     Calculator.calculate(self, atoms, properties, system_changes)
     try:
         results = self.checkpoint.load(atoms)
         prev_atoms, results = results[0], results[1:]
         try:
             assert atoms_almost_equal(atoms, prev_atoms)
         except AssertionError:
             raise AssertionError('mismatch between current atoms and those read from checkpoint file')
         self.logger.pr('retrieved results for {0} from checkpoint'.format(properties))
         # save results in calculator for next time
         if isinstance(self.calculator, Calculator):
             if not hasattr(self.calculator, 'results'):
                 self.calculator.results = {}
             self.calculator.results.update(dict(zip(properties, results)))
     except NoCheckpoint:
         if isinstance(self.calculator, Calculator):
             self.logger.pr('doing calculation of {0} with new-style calculator interface'.format(properties))
             self.calculator.calculate(atoms, properties, system_changes)
             results = [self.calculator.results[prop] for prop in properties]
         else:
             self.logger.pr('doing calculation of {0} with old-style calculator interface'.format(properties))
             results = []
             for prop in properties:
                 method_name = CheckpointCalculator.property_to_method_name[prop]
                 method = getattr(self.calculator, method_name)
                 results.append(method(atoms))
         _calculator = atoms.get_calculator
         try:
             atoms.set_calculator(self.calculator)
             self.checkpoint.save(atoms, *results)
         finally:
             atoms.set_calculator(_calculator)
         
     self.results = dict(zip(properties, results))
开发者ID:maldegunde,项目名称:matscipy,代码行数:35,代码来源:checkpoint.py


注:本文中的ase.calculators.calculator.Calculator类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。