mir-group / flare

An open-source Python package for creating fast and accurate interatomic potentials.
https://mir-group.github.io/flare
MIT License
291 stars 71 forks source link

Magnetization command in DFT script not working #297

Closed owaisahmad18 closed 2 years ago

owaisahmad18 commented 2 years ago

I am trying to work with iron and copper, i need to start magnetization for iron specifically, but it says OrderedDict mutated during operation. do i need to write starting_magnetization command differently? Below is the DFT sccript part i am using

#################################### import os from ase.calculators.espresso import Espresso

---------------- set up executable ---------------- label = 'Fe-Cu' input_file = label+'.pwi' output_file = label+'.pwo' no_cpus = 4 npool = 4 pw_loc = '/home/owais/Downloads/q-e-qe-6.8/PW/src/pw.x'

serial os.environ['ASE_ESPRESSO_COMMAND'] = f'{pw_loc} < {input_file} > {output_file}' parallel qe using mpirun os.environ['ASE_ESPRESSO_COMMAND'] = f'mpirun -np {no_cpus} {pw_loc} -npool {npool} < {input_file} > {output_file}'

parallel qe using srun (for slurm system) os.environ['ASE_ESPRESSO_COMMAND'] = 'srun -n {no_cpus} --mpi=pmi2 {pw_loc} -npool {npool} < {input_file} > {output_file}' -------------- set up input parameters -------------- input_data = {'control': {'prefix': label, 'pseudo_dir': './', 'outdir': './out', 'calculation': 'scf'}, 'system': {'ibrav': 0 , 'ecutwfc': 40, 'ecutrho': 200, 'starting_magnetization(2)': 1, 'nspin': 2, 'occupations': 'smearing', 'degauss': 0.01}, 'electrons': { 'electron_maxstep': 100, 'mixing_beta': 0.25}}

---------------- pseudo-potentials ----------------- ion_pseudo = {'Cu': 'Cu.pbe-dn-kjpaw_psl.1.0.0.UPF','Fe': 'Fe.pbe-nd-rrkjus.UPF'}

-------------- create ASE calculator ---------------- dft_calc = Espresso(pseudopotentials=ion_pseudo, label=label, tstress=True, tprnfor=True, nosym=True, input_data=input_data, kpts=(5, 5, 5))

image

YuuuXie commented 2 years ago

Hi @owaisahmad18 , could you please share a complete script and the error message?

owaisahmad18 commented 2 years ago

Thanks for responding , here is the code i am using

from ase import Atoms import numpy as np from ase import units from ase.spacegroup import crystal from ase.build import bulk from ase.visualize import view

np.random.seed(12345) a = 2.865 super_cell = bulk('Fe','bcc',a=a,cubic=True) super_cell.symbols[0] = "Cu" jitter_factor = 0.1 for atom_pos in super_cell.positions: for coord in range(3): atom_pos[coord] += (2 np.random.rand() - 1) jitter_factor list(super_cell.symbols)

from flare.gp import GaussianProcess from flare.utils.parameter_helper import ParameterHelper

set up GP hyperparameters

kernels = ['twobody', 'threebody'] # use 2+3 body kernel parameters = {'cutoff_twobody': 7, 'cutoff_threebody': 5} pm = ParameterHelper( kernels = kernels, random = True, parameters=parameters )

hm = pm.as_dict() hyps = hm['hyps'] cut = hm['cutoffs'] print('hyps', hyps)

gp_model = GaussianProcess( kernels = kernels, component = 'mc', # If you are using ASE, please set to "mc" no matter for single-component or multi-component hyps = hyps, cutoffs = cut, hyp_labels = ['sig2','ls2','sig3','ls3','noise'], opt_algorithm = 'L-BFGS-B', n_cpus = 1 )

from flare.ase.calculator import FLARE_Calculator

flare_calculator = FLARE_Calculator(gp_model, par = True, mgp_model = None, use_mapping = False)

super_cell.set_calculator(flare_calculator)

import os from ase.calculators.espresso import Espresso

---------------- set up executable ----------------

label = 'Fe-Cu' input_file = label+'.pwi' output_file = label+'.pwo' no_cpus = 4 npool = 4 pw_loc = '/home/owais/Downloads/q-e-qe-6.8/PW/src/pw.x'

serial

os.environ['ASE_ESPRESSO_COMMAND'] = f'{pw_loc} < {input_file} > {output_file}'

parallel qe using mpirun

os.environ['ASE_ESPRESSO_COMMAND'] = f'mpirun -np {no_cpus} {pw_loc} -npool {npool} < {input_file} > {output_file}'

parallel qe using srun (for slurm system)

os.environ['ASE_ESPRESSO_COMMAND'] = 'srun -n {no_cpus} --mpi=pmi2 {pw_loc} -npool {npool} < {input_file} > {output_file}'

-------------- set up input parameters --------------

input_data = {'control': {'prefix': label, 'pseudo_dir': './', 'outdir': './out', 'calculation': 'scf'}, 'system': {'ibrav': 0, 'ecutwfc': 40, 'ecutrho': 200, 'nspin': 2, 'occupations': 'smearing', 'starting_magnetization(2)' : 2 , 'degauss': 0.01}, 'electrons': { 'electron_maxstep': 100, 'mixing_beta': 0.25}}

---------------- pseudo-potentials -----------------

ion_pseudo = {'Cu': 'Cu.pbe-dn-kjpaw_psl.1.0.0.UPF','Fe': 'Fe.pbe-nd-rrkjus.UPF'}

-------------- create ASE calculator ----------------

dft_calc = Espresso(pseudopotentials=ion_pseudo, label=label, tstress=True, tprnfor=True, nosym=True, input_data=input_data, kpts=(5, 5, 5))

from ase import units from ase.md.velocitydistribution import (MaxwellBoltzmannDistribution, Stationary, ZeroRotation)

temperature = 200 MaxwellBoltzmannDistribution(super_cell, temperature * units.kB) Stationary(super_cell) # zero linear momentum ZeroRotation(super_cell) # zero angular momentum

md_engine = 'VelocityVerlet' md_kwargs = {}

from flare.ase.otf import ASE_OTF

otf_params = {'init_atoms': [0, 1], 'output_name': 'Fe-Cu_otf', 'std_tolerance_factor': -0.01, 'max_atoms_added' : 4, 'freeze_hyps': 10, 'min_steps_with_model' : 10, 'update_style' : "threshold", 'update_threshold' : 0.005, 'write_model': 1} # If you will probably resume the training, please set to 3

test_otf = ASE_OTF(super_cell, timestep = 1 * units.fs, number_of_steps = 100, dft_calc = dft_calc, md_engine = md_engine, md_kwargs = md_kwargs, **otf_params,force_only=True)

test_otf.run()

################################################## ###################################################### ######################################################

I GET FOLLOWING ERROR:::

RuntimeError Traceback (most recent call last) /tmp/ipykernel_1230882/1452360906.py in 19 **otf_params,force_only=True) 20 ---> 21 test_otf.run()

/usr/local/lib/python3.8/dist-packages/flare/otf.py in run(self) 248 # When DFT is called, ASE energy, forces, and stresses should 249 # get updated. --> 250 self.initialize_train() 251 252 # after step 1, try predicting with GP model

/usr/local/lib/python3.8/dist-packages/flare/ase/otf.py in initialize_train(self) 162 163 def initialize_train(self): --> 164 super().initialize_train() 165 166 # TODO: Turn this into a "reset" method.

/usr/local/lib/python3.8/dist-packages/flare/otf.py in initialize_train(self) 335 def initialize_train(self): 336 # call dft and update positions --> 337 self.run_dft() 338 dft_frcs = deepcopy(self.structure.forces) 339 dft_stress = deepcopy(self.structure.stress)

/usr/local/lib/python3.8/dist-packages/flare/otf.py in run_dft(self) 378 # calculate DFT forces 379 # TODO: Return stress and energy --> 380 forces = self.dft_module.run_dft_par( 381 self.dft_input, 382 self.structure,

/usr/local/lib/python3.8/dist-packages/flare/ase/dft.py in run_dft_par(atoms, structure, dft_calc, **dft_kwargs) 34 # https://wiki.fysik.dtu.dk/ase/_modules/ase/io/espresso.html#read_espresso_out 35 # Note that ASE and QE stresses differ by a minus sign. ---> 36 forces = atoms.get_forces() 37 stress = atoms.get_stress() 38 energy = atoms.get_potential_energy()

~/.local/lib/python3.8/site-packages/ase/atoms.py in get_forces(self, apply_constraint, md) 786 if self._calc is None: 787 raise RuntimeError('Atoms object has no calculator.') --> 788 forces = self._calc.get_forces(self) 789 790 if apply_constraint:

~/.local/lib/python3.8/site-packages/ase/calculators/abc.py in get_forces(self, atoms) 21 22 def get_forces(self, atoms=None): ---> 23 return self.get_property('forces', atoms) 24 25 def get_stress(self, atoms=None):

~/.local/lib/python3.8/site-packages/ase/calculators/calculator.py in get_property(self, name, atoms, allow_calculation) 735 if not allow_calculation: 736 return None --> 737 self.calculate(atoms, [name], system_changes) 738 739 if name not in self.results:

~/.local/lib/python3.8/site-packages/ase/calculators/calculator.py in calculate(self, atoms, properties, system_changes) 909 system_changes=all_changes): 910 Calculator.calculate(self, atoms, properties, system_changes) --> 911 self.write_input(self.atoms, properties, system_changes) 912 if self.command is None: 913 raise CalculatorSetupError(

~/.local/lib/python3.8/site-packages/ase/calculators/espresso.py in write_input(self, atoms, properties, system_changes) 110 def write_input(self, atoms, properties=None, system_changes=None): 111 FileIOCalculator.write_input(self, atoms, properties, system_changes) --> 112 io.write(self.label + '.pwi', atoms, **self.parameters) 113 114 def read_results(self):

~/.local/lib/python3.8/site-packages/ase/io/formats.py in write(filename, images, format, parallel, append, kwargs) 626 io = get_ioformat(format) 627 --> 628 return _write(filename, fd, format, io, images, 629 parallel=parallel, append=append, kwargs) 630

~/.local/lib/python3.8/site-packages/ase/parallel.py in new_func(*args, *kwargs) 242 not kwargs.pop('parallel', True)): 243 # Disable: --> 244 return func(args, **kwargs) 245 246 ex = None

~/.local/lib/python3.8/site-packages/ase/io/formats.py in _write(filename, fd, format, io, images, parallel, append, kwargs) 662 # XXX remember to re-enable compressed open 663 # fd = io.open(filename, mode) --> 664 return io.write(fd, images, kwargs) 665 finally: 666 if open_new and fd is not None:

~/.local/lib/python3.8/site-packages/ase/io/formats.py in _write_wrapper(self, *args, *kwargs) 189 if function is None: 190 raise ValueError(f'Cannot write to {self.name}-format') --> 191 return function(args, **kwargs) 192 193 @property

~/.local/lib/python3.8/site-packages/ase/io/espresso.py in write_espresso_in(fd, atoms, input_data, pseudopotentials, kspacing, kpts, koffset, crystal_coordinates, kwargs) 1621 # Note that the name input_data is chosen to prevent clash with 1622 # parameters in Calculator objects -> 1623 input_parameters = construct_namelist(input_data, kwargs) 1624 1625 # Convert ase constraints to QE constraints

~/.local/lib/python3.8/site-packages/ase/io/espresso.py in construct_namelist(parameters, warn, **kwargs) 1329 1330 # Check if there is a key(i) version (no extra parsing) -> 1331 for arg_key in parameters.get(section, {}): 1332 if arg_key.split('(')[0].strip().lower() == key.lower(): 1333 sec_list[arg_key] = parameters[section].pop(arg_key)

RuntimeError: OrderedDict mutated during iteration ​

owaisahmad18 commented 2 years ago

Hi @YuuuXie : please help me the issue

YuuuXie commented 2 years ago

Hi @owaisahmad18,

Sorry for the late response. I looked into your code, and it seems that the problem is not with flare, but with your DFT interface settings with ASE.

In ASE QE calculator, the key word 'starting_magnetization(xxx)' should not be used directly in the parameter dictionary. To set up the initial magnetic moment of the configuration, you need to assign magnetic moment to each atom of the super_cell instead. Check the ASE website: https://wiki.fysik.dtu.dk/ase/ase/atoms.html#ase.Atoms.set_initial_magnetic_moments

For example,

# assign each atom an initial magnetic moment of 1
magmom = np.ones(len(super_cell))
super_cell.set_initial_magnetic_moments(magmom)

and then remove the key 'starting_magnetization(xxx)' from your parameter dictionary. In this way the quantum espresso should work.

Let me know if it works, and happy new year! Yu

owaisahmad18 commented 2 years ago

Hi, Thanks for responding, Happy new year to you too. I made the suggested change in script but i am not sure that this will magnetise iron atoms only. please take a look.

from ase import Atoms import numpy as np from ase import units from ase.spacegroup import crystal from ase.build import bulk from ase.visualize import view

np.random.seed(12345)

a = 2.865 super_cell = bulk('Fe','bcc',a=a,cubic=True)

assign each atom an initial magnetic moment of 1

magmom = np.ones(len(super_cell)) super_cell.set_initial_magnetic_moments(magmom)

super_cell.symbols[0] = "Cu"

jitter_factor = 0.1 for atom_pos in super_cell.positions: for coord in range(3): atom_pos[coord] += (2 np.random.rand() - 1) jitter_factor list(super_cell.symbols)

view(atoms, viewer="x3d")

YuuuXie commented 2 years ago

Hi @owaisahmad18 , if you need to set magnetic moment for Cu atoms, please change the values in magmom array corresponding to Cu atoms, such as magmom[0]=0

You shouldn't just copy my toy example, instead, you need to understand what the code does and adapt it to fit your own need. And you can write some minimal scripts to validate if your code works as expected.

If you are not familiar with ASE, I would suggest you to take a look at ASE tutorials and try some toy examples.

Since this issue is not with flare, I will close it for now. You can still comment below it if you have questions. Thanks.

owaisahmad18 commented 2 years ago

Thanks , I appreciate your suggestion will work on it.

YuuuXie commented 2 years ago

Hi,

Have you solved it or did you deleted your comment? I can not see this question in the issue page: https://github.com/mir-group/flare/issues/297#issuecomment-1016257438 https://github.com/mir-group/flare/issues/297#issuecomment-1016257438

On Jan 19, 2022, at 4:43 AM, Owais Ahmad @.***> wrote:

Hi, @YuuuXie https://github.com/YuuuXie I figured out setting magnetic moments through ASE tutorials but now i am getting a python error. can you please take a look https://user-images.githubusercontent.com/38828004/150104871-f3bb14b8-21b1-48ca-a1cc-aac20a4aeb5e.png — Reply to this email directly, view it on GitHub https://github.com/mir-group/flare/issues/297#issuecomment-1016257438, or unsubscribe https://github.com/notifications/unsubscribe-auth/AFYVQC4KBGVRGHJWTJHHXNLUW2BUJANCNFSM5KRVXVYQ. Triage notifications on the go with GitHub Mobile for iOS https://apps.apple.com/app/apple-store/id1477376905?ct=notification-email&mt=8&pt=524675 or Android https://play.google.com/store/apps/details?id=com.github.android&referrer=utm_campaign%3Dnotification-email%26utm_medium%3Demail%26utm_source%3Dgithub. You are receiving this because you were mentioned.

owaisahmad18 commented 2 years ago

Sorry for the late reply, Yes i have solved and deleted the comment.