def dscf_load_band(filename, paw, molecule=None): """Load and distribute all information for a band from a tar file.""" if not paw.wfs: paw.initialize() world, bd, gd, kd = paw.wfs.world, paw.wfs.bd, paw.wfs.gd, \ KPointDescriptor(paw.wfs.nspins, paw.wfs.nibzkpts, paw.wfs.kpt_comm, \ paw.wfs.gamma, paw.wfs.dtype) if bd.comm.size != 1: raise NotImplementedError('Undefined action for band parallelization.') r = Reader(filename) assert (r.dimension('nspins') == kd.nspins and \ r.dimension('nibzkpts') == kd.nibzkpts), 'Incompatible spin/kpoints.' # Read wave function for every spin/kpoint owned by this rank psit_uG = gd.empty(kd.mynks, kd.dtype) for myu, psit_G in enumerate(psit_uG): u = kd.global_index(myu) s, k = kd.what_is(u) if gd.comm.rank == 0: big_psit_G = np.array(r.get('PseudoWaveFunction', s, k), kd.dtype) else: big_psit_G = None gd.distribute(big_psit_G, psit_G) # Find domain ranks for each atom atoms = paw.get_atoms() spos_ac = atoms.get_scaled_positions() % 1.0 rank_a = gd.get_ranks_from_positions(spos_ac) #my_atom_indices = np.argwhere(rank_a == gd.comm.rank).ravel() #assert np.all(my_atom_indices == paw.wfs.pt.my_atom_indices) assert r.dimension('nproj') == sum([setup.ni for setup in paw.wfs.setups]) if molecule is None: molecule = range(len(atoms)) # Read projections for every spin/kpoint and atom owned by this rank P_uai = [{}] * kd.mynks #[paw.wfs.pt.dict() for myu in range(kd.mynks)] for myu, P_ai in enumerate(P_uai): u = kd.global_index(myu) s, k = kd.what_is(u) P_i = r.get('Projection', s, k) i1 = 0 for a in molecule: setup = paw.wfs.setups[a] i2 = i1 + setup.ni if gd.comm.rank == rank_a[a]: P_ai[a] = np.array(P_i[i1:i2], kd.dtype) i1 = i2 return psit_uG, P_uai
def read(self, filename, mode='', ws='all', idiotproof=True): if idiotproof and not filename.endswith('.ind'): raise IOError('Filename must end with `.ind`.') reads = self._parse_readwritemode(mode) # Open reader (handles masters) tar = Reader(filename) # Actual read self.nw = tar.dimension('nw') if ws == 'all': ws = range(self.nw) self.nw = len(ws) self._read(tar, reads, ws) # Close tar.close() self.world.barrier()
def read(self, filename, idiotproof=True): if idiotproof and not filename.endswith('.ftd'): raise IOError('Filename must end with `.ftd`.') tar = Reader(filename) # Test data type dtype = {'Float':float, 'Complex':complex}[tar['DataType']] if dtype != self.dtype: raise IOError('Data is an incompatible type.') # Test time time = tar['Time'] if idiotproof and abs(time-self.time) >= 1e-9: raise IOError('Timestamp is incompatible with calculator.') # Test timestep (non-critical) timestep = tar['TimeStep'] if abs(timestep - self.timestep) > 1e-12: print 'Warning: Time-step has been altered. (%lf -> %lf)' \ % (self.timestep, timestep) self.timestep = timestep # Test dimensions nw = tar.dimension('nw') nspins = tar.dimension('nspins') ng = (tar.dimension('ngptsx'), tar.dimension('ngptsy'), \ tar.dimension('ngptsz'),) if (nw != self.nw or nspins != self.nspins or (ng != self.gd.get_size_of_global_array()).any()): raise IOError('Data has incompatible shapes.') # Test width (non-critical) sigma = tar['Width'] if ((sigma is None)!=(self.sigma is None) or # float <-> None (sigma is not None and self.sigma is not None and \ abs(sigma - self.sigma) > 1e-12)): # float -> float print 'Warning: Width has been altered. (%s -> %s)' \ % (self.sigma, sigma) self.sigma = sigma # Read frequencies self.omega_w[:] = tar.get('Frequency') # Read cumulative phase factors self.gamma_w[:] = tar.get('PhaseFactor') # Read average densities on master and distribute for s in range(self.nspins): all_Ant_G = tar.get('Average', s) self.gd.distribute(all_Ant_G, self.Ant_sG[s]) # Read fourier transforms on master and distribute for w in range(self.nw): for s in range(self.nspins): all_Fnt_G = tar.get('FourierTransform', w, s) self.gd.distribute(all_Fnt_G, self.Fnt_wsG[w,s]) # Close for good measure tar.close()
def read(self, filename, idiotproof=True): if idiotproof and not filename.endswith('.ftd'): raise IOError('Filename must end with `.ftd`.') tar = Reader(filename) # Test data type dtype = {'Float': float, 'Complex': complex}[tar['DataType']] if dtype != self.dtype: raise IOError('Data is an incompatible type.') # Test time time = tar['Time'] if idiotproof and abs(time - self.time) >= 1e-9: raise IOError('Timestamp is incompatible with calculator.') # Test timestep (non-critical) timestep = tar['TimeStep'] if abs(timestep - self.timestep) > 1e-12: print('Warning: Time-step has been altered. (%lf -> %lf)' \ % (self.timestep, timestep)) self.timestep = timestep # Test dimensions nw = tar.dimension('nw') nspins = tar.dimension('nspins') ng = (tar.dimension('ngptsx'), tar.dimension('ngptsy'), \ tar.dimension('ngptsz'),) if (nw != self.nw or nspins != self.nspins or (ng != self.gd.get_size_of_global_array()).any()): raise IOError('Data has incompatible shapes.') # Test width (non-critical) sigma = tar['Width'] if ((sigma is None)!=(self.sigma is None) or # float <-> None (sigma is not None and self.sigma is not None and \ abs(sigma - self.sigma) > 1e-12)): # float -> float print('Warning: Width has been altered. (%s -> %s)' \ % (self.sigma, sigma)) self.sigma = sigma # Read frequencies self.omega_w[:] = tar.get('Frequency') # Read cumulative phase factors self.gamma_w[:] = tar.get('PhaseFactor') # Read average densities on master and distribute for s in range(self.nspins): all_Ant_G = tar.get('Average', s) self.gd.distribute(all_Ant_G, self.Ant_sG[s]) # Read fourier transforms on master and distribute for w in range(self.nw): for s in range(self.nspins): all_Fnt_G = tar.get('FourierTransform', w, s) self.gd.distribute(all_Fnt_G, self.Fnt_wsG[w, s]) # Close for good measure tar.close()
def wrap_old_gpw_reader(filename): warnings.warn('You are reading an old-style gpw-file. Please check ' 'the results carefully!') r = Reader(filename) data = { 'version': -1, 'gpaw_version': '1.0', 'ha': Ha, 'bohr': Bohr, 'scf.': { 'converged': True }, 'atoms.': {}, 'wave_functions.': {} } class DictBackend: def write(self, **kwargs): data['atoms.'].update(kwargs) write_atoms(DictBackend(), read_atoms(r)) e_total_extrapolated = r.get('PotentialEnergy').item() * Ha magmom_a = r.get('MagneticMoments') data['results.'] = { 'energy': e_total_extrapolated, 'magmoms': magmom_a, 'magmom': magmom_a.sum() } if r.has_array('CartesianForces'): data['results.']['forces'] = r.get('CartesianForces') * Ha / Bohr p = data['parameters.'] = {} p['xc'] = r['XCFunctional'] p['nbands'] = r.dimension('nbands') p['spinpol'] = (r.dimension('nspins') == 2) bzk_kc = r.get('BZKPoints', broadcast=True) if r.has_array('NBZKPoints'): p['kpts'] = r.get('NBZKPoints', broadcast=True) if r.has_array('MonkhorstPackOffset'): offset_c = r.get('MonkhorstPackOffset', broadcast=True) if offset_c.any(): p['kpts'] = monkhorst_pack(p['kpts']) + offset_c else: p['kpts'] = bzk_kc if r['version'] < 4: usesymm = r['UseSymmetry'] if usesymm is None: p['symmetry'] = {'time_reversal': False, 'point_group': False} elif usesymm: p['symmetry'] = {'time_reversal': True, 'point_group': True} else: p['symmetry'] = {'time_reversal': True, 'point_group': False} else: p['symmetry'] = { 'point_group': r['SymmetryOnSwitch'], 'symmorphic': r['SymmetrySymmorphicSwitch'], 'time_reversal': r['SymmetryTimeReversalSwitch'], 'tolerance': r['SymmetryToleranceCriterion'] } p['basis'] = r['BasisSet'] try: h = r['GridSpacing'] except KeyError: # CMR can't handle None! h = None if h is not None: p['h'] = Bohr * h if r.has_array('GridPoints'): p['gpts'] = r.get('GridPoints') p['lmax'] = r['MaximumAngularMomentum'] p['setups'] = r['SetupTypes'] p['fixdensity'] = r['FixDensity'] nbtc = r['NumberOfBandsToConverge'] if not isinstance(nbtc, (int, str)): # The string 'all' was eval'ed to the all() function! nbtc = 'all' p['convergence'] = { 'density': r['DensityConvergenceCriterion'], 'energy': r['EnergyConvergenceCriterion'] * Ha, 'eigenstates': r['EigenstatesConvergenceCriterion'], 'bands': nbtc } mixer = r['MixClass'] weight = r['MixWeight'] for key in ['basis', 'setups']: dct = p[key] if isinstance(dct, dict) and None in dct: dct['default'] = dct.pop(None) if mixer == 'Mixer': from gpaw.mixer import Mixer elif mixer == 'MixerSum': from gpaw.mixer import MixerSum as Mixer elif mixer == 'MixerSum2': from gpaw.mixer import MixerSum2 as Mixer elif mixer == 'MixerDif': from gpaw.mixer import MixerDif as Mixer elif mixer == 'DummyMixer': from gpaw.mixer import DummyMixer as Mixer else: Mixer = None if Mixer is None: p['mixer'] = None else: p['mixer'] = Mixer(r['MixBeta'], r['MixOld'], weight) p['stencils'] = (r['KohnShamStencil'], r['InterpolationStencil']) vt_sG = r.get('PseudoPotential') * Ha ps = r['PoissonStencil'] if isinstance(ps, int) or ps == 'M': poisson = {'name': 'fd'} poisson['nn'] = ps if data['atoms.']['pbc'] == [1, 1, 0]: v1, v2 = vt_sG[0, :, :, [0, -1]].mean(axis=(1, 2)) if abs(v1 - v2) > 0.01: warnings.warn('I am guessing that this calculation was done ' 'with a dipole-layer correction?') poisson['dipolelayer'] = 'xy' p['poissonsolver'] = poisson p['charge'] = r['Charge'] fixmom = r['FixMagneticMoment'] p['occupations'] = FermiDirac(r['FermiWidth'] * Ha, fixmagmom=fixmom) p['mode'] = r['Mode'] if p['mode'] == 'pw': p['mode'] = PW(ecut=r['PlaneWaveCutoff'] * Ha) if len(bzk_kc) == 1 and not bzk_kc[0].any(): # Gamma point only: if r['DataType'] == 'Complex': p['dtype'] = complex data['occupations.'] = { 'fermilevel': r['FermiLevel'] * Ha, 'split': r.parameters.get('FermiSplit', 0) * Ha, 'h**o': np.nan, 'lumo': np.nan } data['density.'] = { 'density': r.get('PseudoElectronDensity') * Bohr**-3, 'atomic_density_matrices': r.get('AtomicDensityMatrices') } data['hamiltonian.'] = { 'e_coulomb': r['Epot'] * Ha, 'e_entropy': -r['S'] * Ha, 'e_external': r['Eext'] * Ha, 'e_kinetic': r['Ekin'] * Ha, 'e_total_extrapolated': e_total_extrapolated, 'e_xc': r['Exc'] * Ha, 'e_zero': r['Ebar'] * Ha, 'potential': vt_sG, 'atomic_hamiltonian_matrices': r.get('NonLocalPartOfHamiltonian') * Ha } data['hamiltonian.']['e_total_free'] = (sum( data['hamiltonian.'][e] for e in [ 'e_coulomb', 'e_entropy', 'e_external', 'e_kinetic', 'e_xc', 'e_zero' ])) if r.has_array('GLLBPseudoResponsePotential'): data['hamiltonian.']['xc.'] = { 'gllb_pseudo_response_potential': r.get('GLLBPseudoResponsePotential') * Ha, 'gllb_dxc_pseudo_response_potential': r.get('GLLBDxcPseudoResponsePotential') * Ha / Bohr, 'gllb_atomic_density_matrices': r.get('GLLBAtomicDensityMatrices'), 'gllb_atomic_response_matrices': r.get('GLLBAtomicResponseMatrices'), 'gllb_dxc_atomic_density_matrices': r.get('GLLBDxcAtomicDensityMatrices'), 'gllb_dxc_atomic_response_matrices': r.get('GLLBDxcAtomicResponseMatrices') } special = [('eigenvalues', 'Eigenvalues'), ('occupations', 'OccupationNumbers'), ('projections', 'Projections')] if r['Mode'] == 'pw': special.append(('coefficients', 'PseudoWaveFunctions')) try: data['wave_functions.']['indices'] = r.get('PlaneWaveIndices') except KeyError: pass elif r['Mode'] == 'fd': special.append(('values', 'PseudoWaveFunctions')) else: special.append(('coefficients', 'WaveFunctionCoefficients')) for name, old in special: try: fd, shape, size, dtype = r.get_file_object(old, ()) except KeyError: continue offset = fd data['wave_functions.'][name + '.'] = { 'ndarray': (shape, dtype.name, offset) } new = ulm.Reader(devnull, data=data, little_endian=r.byteswap ^ np.little_endian) for ref in new._data['wave_functions']._data.values(): try: ref.fd = ref.offset except AttributeError: continue ref.offset = 0 return new
def read_data(filename, keys=None, ws='all'): """ Read data arrays for post processing. Not parallel safe. No GridDescriptor, only numpy arrays. Parameters ---------- filename: string File to be read. keys: list of strings Keys to be read. ws: list of ints Indices of frequencies to be read. """ key_to_tarname = { 'n0t_sG': 'n0t_sG', 'Fnt_wsG': 'Fnt_wsG', 'Frho_wg': 'Frho_wg', 'Fphi_wg': 'Fphi_wg', 'Fef_wvg': 'Fef_wvg', 'Ffe_wg': 'Ffe_wg', 'eps0_G': 'eps0_G' } print('Reading %s' % (filename)) if keys is None: keys = key_to_tarname.keys() # all keys tar = Reader(filename) omega_w = tar.get('omega_w') if ws == 'all': ws = range(len(omega_w)) else: omega_w = omega_w[ws] freq_w = omega_w * aufrequency_to_eV try: nspins = tar.dimension('nspins') except KeyError: nspins = None na = tar['na'] try: atomnum_a = tar.get('atomnum_a') atompos_av = tar.get('atompos_a') atomcell_cv = tar.get('atomcell_cv') Fbgef_v = tar.get('Fbgef_v') atom_a = [] for a in range(na): atom_a.append({'atom': atomnum_a[a], 'pos': atompos_av[a]}) except KeyError: atom_a = None atomcell_cv = None Fbgef_v = None print('no atoms') data = dict() data['freq_w'] = freq_w data['nspins'] = nspins data['na'] = na data['atom_a'] = atom_a data['cell_cv'] = atomcell_cv data['Fbgef_v'] = Fbgef_v try: data['corner1_v'] = tar.get('corner1_v') data['corner2_v'] = tar.get('corner2_v') except: print('no corners') try: FD_awsp = {} D0_asp = {} for a in range(na): FD_awsp[a] = tar.get('FD_%dwsp' % a) D0_asp[a] = tar.get('D0_%dsp' % a) data['FD_awsp'] = FD_awsp data['D0_asp'] = D0_asp except KeyError: print('no FD_awsp') for key in keys: try: if '_w' in key: tmp = zero_pad(tar.get(key_to_tarname[key], ws[0])) data[key] = np.empty((len(ws), ) + tmp.shape, tmp.dtype) data[key][0] = tmp for w, wread in enumerate(ws[1:], 1): data[key][w] = zero_pad(tar.get(key_to_tarname[key], wread)) else: data[key] = zero_pad(tar.get(key_to_tarname[key])) except KeyError: print('no %s' % key) pass tar.close() return data