Coverage for ase/calculators/openmx/writer.py: 14.63%
328 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""
2The ASE Calculator for OpenMX <https://www.openmx-square.org>: Python interface
3to the software package for nano-scale material simulations based on density
4functional theories.
5 Copyright (C) 2018 JaeHwan Shim and JaeJun Yu
7 This program is free software: you can redistribute it and/or modify
8 it under the terms of the GNU Lesser General Public License as published by
9 the Free Software Foundation, either version 2.1 of the License, or
10 (at your option) any later version.
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU Lesser General Public License for more details.
17 You should have received a copy of the GNU Lesser General Public License
18 along with ASE. If not, see <https://www.gnu.org/licenses/>.
19"""
21import os
23import numpy as np
25from ase.calculators.calculator import kpts2sizeandoffsets
26from ase.calculators.openmx import parameters as param
27from ase.calculators.openmx.reader import (
28 get_file_name,
29 get_standard_key,
30 read_electron_valency,
31)
32from ase.config import cfg
33from ase.units import Bohr, Ha, Ry, fs, m, s
35keys = [
36 param.tuple_integer_keys,
37 param.tuple_float_keys,
38 param.tuple_bool_keys,
39 param.integer_keys,
40 param.float_keys,
41 param.string_keys,
42 param.bool_keys,
43 param.list_int_keys,
44 param.list_bool_keys,
45 param.list_float_keys,
46 param.matrix_keys,
47]
50def write_openmx(
51 label=None,
52 atoms=None,
53 parameters=None,
54 properties=None,
55 system_changes=None,
56):
57 """
58 From atom image, 'images', write '.dat' file.
59 First, set
60 Write input (dat)-file.
61 See calculator.py for further details.
63 Parameters
64 ----------
65 - atoms : The Atoms object to write.
66 - properties : The properties which should be calculated.
67 - system_changes : List of properties changed since last run.
68 """
69 from ase.calculators.openmx import parameters as param
71 filtered_keywords = parameters_to_keywords(
72 label=label,
73 atoms=atoms,
74 parameters=parameters,
75 properties=properties,
76 system_changes=system_changes,
77 )
78 keys = [
79 'string',
80 'bool',
81 'integer',
82 'float',
83 'tuple_integer',
84 'tuple_float',
85 'tuple_bool',
86 'matrix',
87 'list_int',
88 'list_bool',
89 'list_float',
90 ]
91 # Start writing the file
92 filename = get_file_name('.dat', label)
93 with open(filename, 'w') as fd:
94 # Write 1-line keywords
95 for fltrd_keyword in filtered_keywords.keys():
96 for key in keys:
97 openmx_keywords = getattr(param, key + '_keys')
98 write = globals()['write_' + key]
99 for omx_keyword in openmx_keywords:
100 if fltrd_keyword == get_standard_key(omx_keyword):
101 write(fd, omx_keyword, filtered_keywords[fltrd_keyword])
104def parameters_to_keywords(
105 label=None,
106 atoms=None,
107 parameters=None,
108 properties=None,
109 system_changes=None,
110):
111 """
112 Before writing `label.dat` file, set up the ASE variables to OpenMX
113 keywords. First, It initializes with given openmx keywords and reconstruct
114 dictionary using standard parameters. If standard parameters and openmx
115 keywords are contradict to each other, ignores openmx keyword.
116 It includes,
118 For aesthetical purpose, sequnece of writing input file is specified.
119 """
120 from collections import OrderedDict
122 from ase.calculators.openmx.parameters import matrix_keys, unit_dat_keywords
124 keywords = OrderedDict()
125 sequence = [
126 'system_currentdirectory',
127 'system_name',
128 'data_path',
129 'level_of_fileout',
130 'species_number',
131 'definition_of_atomic_species',
132 'atoms_number',
133 'atoms_speciesandcoordinates_unit',
134 'atoms_speciesandcoordinates',
135 'atoms_unitvectors_unit',
136 'atoms_unitvectors',
137 'band_dispersion',
138 'band_nkpath',
139 'band_kpath',
140 ]
142 _directory, prefix = os.path.split(label)
143 curdir = os.path.join(os.getcwd(), prefix)
144 counterparts = {
145 'system_currentdirectory': curdir,
146 'system_name': prefix,
147 'data_path': cfg.get('OPENMX_DFT_DATA_PATH'),
148 'species_number': len(get_species(atoms.get_chemical_symbols())),
149 'atoms_number': len(atoms),
150 'scf_restart': 'restart',
151 'scf_maxiter': 'maxiter',
152 'scf_xctype': 'xc',
153 'scf_energycutoff': 'energy_cutoff',
154 'scf_criterion': 'convergence',
155 'scf_external_fields': 'external',
156 'scf_mixing_type': 'mixer',
157 'scf_electronic_temperature': 'smearing',
158 'scf_system_charge': 'charge',
159 'scf_eigenvaluesolver': 'eigensolver',
160 }
161 standard_units = {
162 'eV': 1,
163 'Ha': Ha,
164 'Ry': Ry,
165 'Bohr': Bohr,
166 'fs': fs,
167 'K': 1,
168 'GV / m': 1e9 / 1.6e-19 / m,
169 'Ha/Bohr': Ha / Bohr,
170 'm/s': m / s,
171 '_amu': 1,
172 'Tesla': 1,
173 }
174 unit_dict = {get_standard_key(k): v for k, v in unit_dat_keywords.items()}
176 for key in sequence:
177 keywords[key] = None
178 for key in parameters:
179 if 'scf' in key:
180 keywords[key] = None
181 for key in parameters:
182 if 'md' in key:
183 keywords[key] = None
185 # Initializes keywords to to given parameters
186 for key in parameters.keys():
187 keywords[key] = parameters[key]
189 def parameter_overwrites(openmx_keyword):
190 """
191 In a situation conflicting ASE standard parameters and OpenMX keywords,
192 ASE parameters overrides to OpenMX keywords. While doing so, units are
193 converted to OpenMX unit.
194 However, if both parameters and keyword are not given, we fill up that
195 part in suitable manner
196 openmx_keyword : key | Name of key used in OpenMX
197 keyword : value | value corresponds to openmx_keyword
198 ase_parameter : key | Name of parameter used in ASE
199 parameter : value | value corresponds to ase_parameter
200 """
201 ase_parameter = counterparts[openmx_keyword]
202 keyword = parameters.get(openmx_keyword)
203 parameter = parameters.get(ase_parameter)
204 if parameter is not None:
205 # Handles the unit
206 unit = standard_units.get(unit_dict.get(openmx_keyword))
207 if unit is not None:
208 return parameter / unit
209 return parameter
210 elif keyword is not None:
211 return keyword
212 elif 'scf' in openmx_keyword:
213 return None
214 else:
215 return counterparts[openmx_keyword]
217 # Overwrites openmx keyword using standard parameters
218 for openmx_keyword in counterparts:
219 keywords[openmx_keyword] = parameter_overwrites(openmx_keyword)
221 # keywords['scf_stress_tensor'] = 'stress' in properties
222 # This is not working due to the UnitCellFilter method.
223 if 'energies' in properties:
224 keywords['energy_decomposition'] = True
225 if 'stress' in properties:
226 keywords['scf_stress_tensor'] = True
228 keywords['scf_xctype'] = get_xc(keywords['scf_xctype'])
229 keywords['scf_kgrid'] = get_scf_kgrid(atoms, parameters)
230 keywords['scf_spinpolarization'] = get_spinpol(atoms, parameters)
232 if parameters.get('band_kpath') is not None:
233 keywords['band_dispersion'] = True
234 keywords['band_kpath'] = parameters.get('band_kpath')
235 if parameters.get('band_nkpath') is not None:
236 keywords['band_nkpath'] = len(keywords['band_kpath'])
238 # Set up Wannier Environment
239 if parameters.get('wannier_func_calc') is not None:
240 keywords['species_number'] *= 2
242 # Set up some parameters for the later use
243 parameters['_xc'] = keywords['scf_xctype']
244 parameters['_data_path'] = keywords['data_path']
245 parameters['_year'] = get_dft_data_year(parameters)
247 # Set up the matrix-type OpenMX keywords
248 for key in matrix_keys:
249 get_matrix_key = globals()['get_' + get_standard_key(key)]
250 keywords[get_standard_key(key)] = get_matrix_key(atoms, parameters)
251 return OrderedDict(
252 [
253 (k, v)
254 for k, v in keywords.items()
255 if not (v is None or (isinstance(v, list) and v == []))
256 ]
257 )
260def get_species(symbols):
261 species = []
262 [species.append(s) for s in symbols if s not in species]
263 return species
266def get_xc(xc):
267 """
268 Change the name of xc appropriate to OpenMX format
269 """
270 xc = xc.upper()
271 assert xc.upper() in param.OpenMXParameters().allowed_xc
272 if xc in ['PBE', 'GGA', 'GGA-PBE']:
273 return 'GGA-PBE'
274 elif xc in ['LDA']:
275 return 'LDA'
276 elif xc in ['CA', 'PW']:
277 return 'LSDA-' + xc
278 elif xc in ['LSDA', 'LSDA-CA']:
279 return 'LSDA-CA'
280 elif xc in ['LSDA-PW']:
281 return 'LSDA-PW'
282 else:
283 return 'LDA'
286def get_vps(xc):
287 if xc in ['GGA-PBE']:
288 return 'PBE'
289 else:
290 return 'CA'
293def get_scf_kgrid(atoms, parameters):
294 kpts, scf_kgrid = parameters.get('kpts'), parameters.get('scf_kgrid')
295 if (
296 isinstance(kpts, (tuple, list, np.ndarray))
297 and len(kpts) == 3
298 and isinstance(kpts[0], int)
299 ):
300 return kpts
301 elif isinstance(kpts, (float, int)):
302 return tuple(kpts2sizeandoffsets(atoms=atoms, density=kpts)[0])
303 else:
304 return scf_kgrid
307def get_definition_of_atomic_species(atoms, parameters):
308 """
309 Using atoms and parameters, Returns the list `definition_of_atomic_species`
310 where matrix of strings contains the information between keywords.
311 For example,
312 definition_of_atomic_species =
313 [['H','H5.0-s1>1p1>1','H_CA13'],
314 ['C','C5.0-s1>1p1>1','C_CA13']]
315 Goes to,
316 <Definition.of.Atomic.Species
317 H H5.0-s1>1p1>1 H_CA13
318 C C5.0-s1>1p1>1 C_CA13
319 Definition.of.Atomic.Species>
320 Further more, you can specify the wannier information here.
321 A. Define local functions for projectors
322 Since the pseudo-atomic orbitals are used for projectors,
323 the specification of them is the same as for the basis functions.
324 An example setting, for silicon in diamond structure, is as following:
325 Species.Number 2
326 <Definition.of.Atomic.Species
327 Si Si7.0-s2p2d1 Si_CA13
328 proj1 Si5.5-s1p1d1f1 Si_CA13
329 Definition.of.Atomic.Species>
330 """
331 if parameters.get('definition_of_atomic_species') is not None:
332 return parameters['definition_of_atomic_species']
334 definition_of_atomic_species = []
335 xc = parameters.get('_xc')
336 year = parameters.get('_year')
338 chem = atoms.get_chemical_symbols()
339 species = get_species(chem)
340 for element in species:
341 rad_orb = get_cutoff_radius_and_orbital(element=element)
342 suffix = get_pseudo_potential_suffix(element=element, xc=xc, year=year)
343 definition_of_atomic_species.append([element, rad_orb, suffix])
344 # Put the same orbital and radii with chemical symbol.
345 wannier_projectors = parameters.get('definition_of_wannier_projectors', [])
346 for i, projector in enumerate(wannier_projectors):
347 full_projector = definition_of_atomic_species[i]
348 full_projector[0] = projector
349 definition_of_atomic_species.append(full_projector)
350 return definition_of_atomic_species
353def get_dft_data_year(parameters):
354 """
355 It seems there is no version or potential year checker in openmx, thus we
356 implemented one. It parse the pesudo potential path variable such as
357 `~/PATH/TO/OPENMX/openmx3.9/DFT_DATA19/` or `.../openmx3.8/DFT_DATA13/`.
358 By spliting this string, we harness the number of the year that generated
359 such pseudo potential path.
360 """
361 if parameters.get('dft_data_year') is not None:
362 return str(parameters.get('dft_data_year'))
363 data_path = parameters['_data_path']
364 year = data_path.split('DFT_DATA')[1][:2]
365 if year is not None:
366 return year
367 else:
368 raise ValueError(
369 'DFT_DATA year can not be found. Please specify '
370 '`dft_data_year` as year of pseudo potential relesed'
371 )
374def get_cutoff_radius_and_orbital(element=None, orbital=None):
375 """
376 For a given element, retruns the string specifying cutoff radius and
377 orbital using default_settings.py. For example,
378 'Si' -> 'Si.7.0-s2p2d1'
379 If one wannts to change the atomic radius for a special purpose, one should
380 change the default_settings.py directly.
381 """
382 from ase.calculators.openmx import default_settings
384 orbital = element
385 orbital_letters = ['s', 'p', 'd', 'f', 'g', 'h']
386 default_dictionary = default_settings.default_dictionary
387 orbital_numbers = default_dictionary[element]['orbitals used']
388 cutoff_radius = default_dictionary[element]['cutoff radius']
389 orbital += '%.1f' % float(cutoff_radius) + '-'
390 for i, orbital_number in enumerate(orbital_numbers):
391 orbital += orbital_letters[i] + str(orbital_number)
392 return orbital
395def get_pseudo_potential_suffix(element=None, xc=None, year='13'):
396 """
397 For a given element, returns the string specifying pseudo potential suffix.
398 For example,
399 'Si' -> 'Si_CA13'
400 or
401 'Si' -> 'Si_CA19'
402 depending on pseudo potential generation year
403 """
404 from ase.calculators.openmx import default_settings
406 default_dictionary = default_settings.default_dictionary
407 pseudo_potential_suffix = element
408 vps = get_vps(xc)
409 suffix = default_dictionary[element]['pseudo-potential suffix']
410 pseudo_potential_suffix += '_' + vps + year + suffix
411 return pseudo_potential_suffix
414def get_atoms_speciesandcoordinates(atoms, parameters):
415 """
416 The atomic coordinates and the number of spin charge are given by the
417 keyword
418 'Atoms.SpeciesAndCoordinates' as follows:
419 <Atoms.SpeciesAndCoordinates
420 1 Mn 0.00000 0.00000 0.00000 8.0 5.0 45.0 0.0 45.0 0.0 1 on
421 2 O 1.70000 0.00000 0.00000 3.0 3.0 45.0 0.0 45.0 0.0 1 on
422 Atoms.SpeciesAndCoordinates>
423 to know more, link <https://www.openmx-square.org/openmx_man3.7/node85.html>
424 """
425 atoms_speciesandcoordinates = []
426 xc = parameters.get('_xc')
427 year = parameters.get('_year')
428 data_pth = parameters.get('_data_path')
429 # Appending number and elemental symbol
430 elements = atoms.get_chemical_symbols()
431 for i, element in enumerate(elements):
432 atoms_speciesandcoordinates.append([str(i + 1), element])
433 # Appending positions
434 unit = parameters.get('atoms_speciesandcoordinates_unit', 'ang').lower()
435 if unit == 'ang':
436 positions = atoms.get_positions()
437 elif unit == 'frac':
438 positions = atoms.get_scaled_positions(wrap=False)
439 elif unit == 'au':
440 positions = atoms.get_positions() / Bohr
441 for i, position in enumerate(positions):
442 atoms_speciesandcoordinates[i].extend(position)
444 # Even if 'atoms_speciesandcoordinates_unit' exists, `positions` goes first
445 if parameters.get('atoms_speciesandcoordinates') is not None:
446 atoms_spncrd = parameters['atoms_speciesandcoordinates'].copy()
447 for i in range(len(atoms)):
448 atoms_spncrd[i][2] = atoms_speciesandcoordinates[i][2]
449 atoms_spncrd[i][3] = atoms_speciesandcoordinates[i][3]
450 atoms_spncrd[i][4] = atoms_speciesandcoordinates[i][4]
451 return atoms_spncrd
453 # Appending magnetic moment
454 magmoms = atoms.get_initial_magnetic_moments()
455 for i, magmom in enumerate(magmoms):
456 up_down_spin = get_up_down_spin(magmom, elements[i], xc, data_pth, year)
457 atoms_speciesandcoordinates[i].extend(up_down_spin)
458 # Appending magnetic field Spin magnetic moment theta phi
459 spin_directions = get_spin_direction(magmoms)
460 for i, spin_direction in enumerate(spin_directions):
461 atoms_speciesandcoordinates[i].extend(spin_direction)
462 # Appending magnetic field for Orbital magnetic moment theta phi
463 orbital_directions = get_orbital_direction()
464 for i, orbital_direction in enumerate(orbital_directions):
465 atoms_speciesandcoordinates[i].extend(orbital_direction)
466 # Appending Noncolinear schem switch
467 noncollinear_switches = get_noncollinear_switches()
468 for i, noncollinear_switch in enumerate(noncollinear_switches):
469 atoms_speciesandcoordinates[i].extend(noncollinear_switch)
470 # Appending orbital_enhancement_switch
471 lda_u_switches = get_lda_u_switches()
472 for i, lda_u_switch in enumerate(lda_u_switches):
473 atoms_speciesandcoordinates[i].extend(lda_u_switch)
474 return atoms_speciesandcoordinates
477def get_up_down_spin(magmom, element, xc, data_path, year):
478 # for magmom with single number (collinear spin) skip the normalization
479 if isinstance(magmom, (int, float)):
480 # Collinear spin
481 magmom = float(magmom)
482 else:
483 # Non-collinear spin
484 magmom = np.linalg.norm(magmom)
485 suffix = get_pseudo_potential_suffix(element, xc, year)
486 filename = os.path.join(data_path, 'VPS/' + suffix + '.vps')
487 valence_electron = float(read_electron_valency(filename))
488 return [
489 valence_electron / 2 + magmom / 2,
490 valence_electron / 2 - magmom / 2,
491 ]
494def get_spin_direction(magmoms):
495 """
496 From atoms.magmom, returns the spin direction of phi and theta
497 """
498 if (
499 np.array(magmoms).dtype == float
500 or np.array(magmoms).dtype is np.float64
501 ):
502 return []
503 else:
504 magmoms = np.array(magmoms)
505 return magmoms / np.linalg.norm(magmoms, axis=1)
508def get_orbital_direction():
509 orbital_direction = []
510 # print("Not Implemented Yet")
511 return orbital_direction
514def get_noncollinear_switches():
515 noncolinear_switches = []
516 # print("Not Implemented Yet")
517 return noncolinear_switches
520def get_lda_u_switches():
521 lda_u_switches = []
522 # print("Not Implemented Yet")
523 return lda_u_switches
526def get_spinpol(atoms, parameters):
527 """Judgeds the keyword 'scf.SpinPolarization'
528 If the keyword is not None, spinpol gets the keyword by following priority
529 1. standard_spinpol
530 2. scf_spinpolarization
531 3. magnetic moments of atoms
532 """
533 standard_spinpol = parameters.get('spinpol', None)
534 scf_spinpolarization = parameters.get('scf_spinpolarization', None)
535 m = atoms.get_initial_magnetic_moments()
536 syn = {
537 True: 'On',
538 False: None,
539 'on': 'On',
540 'off': None,
541 None: None,
542 'nc': 'NC',
543 }
544 spinpol = np.any(m >= 0.1)
545 if scf_spinpolarization is not None:
546 spinpol = scf_spinpolarization
547 if standard_spinpol is not None:
548 spinpol = standard_spinpol
549 if isinstance(spinpol, str):
550 spinpol = spinpol.lower()
551 return syn[spinpol]
554def get_atoms_unitvectors(atoms, parameters):
555 zero_vec = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
556 if np.all(atoms.get_cell() == zero_vec) is True:
557 default_cell = np.array([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
558 return parameters.get('atoms_unitvectors', default_cell)
559 unit = parameters.get('atoms_unitvectors_unit', 'ang').lower()
560 if unit == 'ang':
561 atoms_unitvectors = atoms.get_cell()
562 elif unit == 'au':
563 atoms_unitvectors = atoms.get_cell() / Bohr
564 return atoms_unitvectors
567def get_hubbard_u_values(atoms, parameters):
568 return parameters.get('hubbard_u_values', [])
571def get_atoms_cont_orbitals(atoms, parameters):
572 return parameters.get('atoms_cont_orbitals', [])
575def get_md_fixed_xyz(atoms, parameters):
576 return parameters.get('md_fixed_xyz', [])
579def get_md_tempcontrol(atoms, parameters):
580 return parameters.get('md_tempcontrol', [])
583def get_md_init_velocity(atoms, parameters):
584 return parameters.get('md_init_velocity', [])
587def get_band_kpath_unitcell(atoms, parameters):
588 return parameters.get('band_kpath_unitcell', [])
591def get_band_kpath(atoms, parameters):
592 kpts = parameters.get('kpts')
593 if isinstance(kpts, list) and len(kpts) > 3:
594 return get_kpath(kpts=kpts)
595 else:
596 return parameters.get('band_kpath', [])
599def get_mo_kpoint(atoms, parameters):
600 return parameters.get('mo_kpoint', [])
603def get_wannier_initial_projectors(atoms, parameters):
604 """
605 B. Specify the orbital, central position and orientation of a projector
606 Wannier.Initial.Projectos will be used to specify the projector name,
607 local orbital function, center of local orbital, and the local z-axis and
608 x-axis for orbital orientation.
610 An example setting is shown here:
611 wannier_initial_projectors=
612 [['proj1-sp3','0.250','0.250','0.25','-1.0','0.0','0.0','0.0','0.0','-1.0']
613 ,['proj1-sp3','0.000','0.000','0.00','0.0','0.0','1.0','1.0','0.0','0.0']]
614 Goes to,
615 <Wannier.Initial.Projectors
616 proj1-sp3 0.250 0.250 0.250 -1.0 0.0 0.0 0.0 0.0 -1.0
617 proj1-sp3 0.000 0.000 0.000 0.0 0.0 1.0 1.0 0.0 0.0
618 Wannier.Initial.Projectors>
619 """
620 return parameters.get('wannier_initial_projectors', [])
623def get_kpath(self, kpts=None, symbols=None, band_kpath=None, eps=1e-5):
624 """
625 Convert band_kpath <-> kpts. Symbols will be guess automatically
626 by using dft space group method
627 For example,
628 kpts = [(0, 0, 0), (0.125, 0, 0) ... (0.875, 0, 0),
629 (1, 0, 0), (1, 0.0625, 0) .. (1, 0.4375,0),
630 (1, 0.5,0),(0.9375, 0.5,0).. ( ... ),
631 (0.5, 0.5, 0.5) ... ... ,
632 ... ... ... ,
633 ... (0.875, 0, 0),(1.0, 0.0, 0.0)]
634 band_kpath =
635 [['15','0.0','0.0','0.0','1.0','0.0','0.0','g','X'],
636 ['15','1.0','0.0','0.0','1.0','0.5','0.0','X','W'],
637 ['15','1.0','0.5','0.0','0.5','0.5','0.5','W','L'],
638 ['15','0.5','0.5','0.5','0.0','0.0','0.0','L','g'],
639 ['15','0.0','0.0','0.0','1.0','0.0','0.0','g','X']]
640 where, it will be written as
641 <Band.kpath
642 15 0.0 0.0 0.0 1.0 0.0 0.0 g X
643 15 1.0 0.0 0.0 1.0 0.5 0.0 X W
644 15 1.0 0.5 0.0 0.5 0.5 0.5 W L
645 15 0.5 0.5 0.5 0.0 0.0 0.0 L g
646 15 0.0 0.0 0.0 1.0 0.0 0.0 g X
647 Band.kpath>
648 """
649 if kpts is None:
650 kx_linspace = np.linspace(
651 band_kpath[0]['start_point'][0],
652 band_kpath[0]['end_point'][0],
653 band_kpath[0][0],
654 )
655 ky_linspace = np.linspace(
656 band_kpath[0]['start_point'][1],
657 band_kpath[0]['end_point'][1],
658 band_kpath[0]['kpts'],
659 )
660 kz_linspace = np.linspace(
661 band_kpath[0]['start_point'][2],
662 band_kpath[0]['end_point'][2],
663 band_kpath[0]['kpts'],
664 )
665 kpts = np.array([kx_linspace, ky_linspace, kz_linspace]).T
666 for path in band_kpath[1:]:
667 kx_linspace = np.linspace(
668 path['start_point'][0], path['end_point'][0], path['kpts']
669 )
670 ky_linspace = np.linspace(
671 path['start_point'][1], path['end_point'][1], path['kpts']
672 )
673 kz_linspace = np.linspace(
674 path['start_point'][2], path['end_point'][2], path['kpts']
675 )
676 k_lin = np.array([kx_linspace, ky_linspace, kz_linspace]).T
677 kpts = np.append(kpts, k_lin, axis=0)
678 return kpts
679 elif band_kpath is None:
680 band_kpath = []
681 points = np.asarray(kpts)
682 diffs = points[1:] - points[:-1]
683 kinks = abs(diffs[1:] - diffs[:-1]).sum(1) > eps
684 N = len(points)
685 indices = [0]
686 indices.extend(np.arange(1, N - 1)[kinks])
687 indices.append(N - 1)
688 for start, end, s_sym, e_sym in zip(
689 indices[1:], indices[:-1], symbols[1:], symbols[:-1]
690 ):
691 band_kpath.append(
692 {
693 'start_point': start,
694 'end_point': end,
695 'kpts': 20,
696 'path_symbols': (s_sym, e_sym),
697 }
698 )
699 else:
700 raise KeyError('You should specify band_kpath or kpts')
701 return band_kpath
704def write_string(fd, key, value):
705 fd.write(' '.join([key, value]))
706 fd.write('\n')
709def write_tuple_integer(fd, key, value):
710 fd.write(' '.join([key, '%d %d %d' % value]))
711 fd.write('\n')
714def write_tuple_float(fd, key, value):
715 fd.write(' '.join([key, '%.4f %.4f %.4f' % value]))
716 fd.write('\n')
719def write_tuple_bool(fd, key, value):
720 omx_bl = {True: 'On', False: 'Off'}
721 fd.write(
722 ' '.join([key, '%s %s %s' % tuple([omx_bl[bl] for bl in value])])
723 )
724 fd.write('\n')
727def write_integer(fd, key, value):
728 fd.write(' '.join([key, '%d' % value]))
729 fd.write('\n')
732def write_float(fd, key, value):
733 fd.write(' '.join([key, '%.8g' % value]))
734 fd.write('\n')
737def write_bool(fd, key, value):
738 omx_bl = {True: 'On', False: 'Off'}
739 fd.write(' '.join([key, f'{omx_bl[value]}']))
740 fd.write('\n')
743def write_list_int(fd, key, value):
744 fd.write(''.join(key) + ' ' + ' '.join(map(str, value)))
747def write_list_bool(fd, key, value):
748 omx_bl = {True: 'On', False: 'Off'}
749 fd.write(''.join(key) + ' ' + ' '.join([omx_bl[bl] for bl in value]))
752def write_list_float(fd, key, value):
753 fd.write(''.join(key) + ' ' + ' '.join(map(str, value)))
756def write_matrix(fd, key, value):
757 fd.write('<' + key)
758 fd.write('\n')
759 for line in value:
760 fd.write(' ' + ' '.join(map(str, line)))
761 fd.write('\n')
762 fd.write(key + '>')
763 fd.write('\n\n')
766def get_openmx_key(key):
767 """
768 For the writing purpose, we need to know Original OpenMX keyword format.
769 By comparing keys in the parameters.py, restore the original key
770 """
771 for openmx_key in keys:
772 for openmx_keyword in openmx_key:
773 if key == get_standard_key(openmx_keyword):
774 return openmx_keyword