From 7f7c4caff236eb2ca1565674ad3eb3d7fd2f295a Mon Sep 17 00:00:00 2001 From: Matteo Giantomassi Date: Fri, 31 May 2024 11:29:29 +0200 Subject: [PATCH] Replace np.complex with complex from builtins --- abipy/embedding/embedding_ifc.py | 66 ++++++++++++-------------------- abipy/eph/gkq.py | 8 ++-- abipy/flowtk/abiphonopy.py | 10 ++--- abipy/flowtk/effmass_works.py | 4 +- abipy/flowtk/flows.py | 2 +- abipy/flowtk/gw_works.py | 2 +- abipy/flowtk/lumi_works.py | 16 +++----- abipy/flowtk/qutils.py | 14 +++---- abipy/ml/aseml.py | 3 +- 9 files changed, 49 insertions(+), 76 deletions(-) diff --git a/abipy/embedding/embedding_ifc.py b/abipy/embedding/embedding_ifc.py index f40f5065f..e541f6fd3 100644 --- a/abipy/embedding/embedding_ifc.py +++ b/abipy/embedding/embedding_ifc.py @@ -1,25 +1,25 @@ +from __future__ import annotations -from phonopy import Phonopy import numpy as np +import os, shutil +from phonopy import Phonopy from pymatgen.io.phonopy import get_pmg_structure,get_phonopy_structure from abipy.core.abinit_units import eV_to_THz +from abipy.core.structure import Structure from abipy.dfpt.converters import phonopy_to_abinit -import os,shutil from abipy.embedding.utils_ifc import accoustic_sum,map_two_structures_coords,clean_structure -from abipy.core.structure import Structure class Embedded_phonons(Phonopy): """ Defines a Phonopy object implementing the Interatomic Force Constants embedding method defined in: - https://pubs.acs.org/doi/10.1021/acs.chemmater.3c00537 - https://iopscience.iop.org/article/10.1088/1367-2630/16/7/073026/meta - https://journals.aps.org/prmaterials/abstract/10.1103/PhysRevMaterials.5.084603 + https://pubs.acs.org/doi/10.1021/acs.chemmater.3c00537 + https://iopscience.iop.org/article/10.1088/1367-2630/16/7/073026/meta + https://journals.aps.org/prmaterials/abstract/10.1103/PhysRevMaterials.5.084603 """ - # Inherits from Phonopy class def __init__(self,stru_pristine,stru_defect,stru_emb,ifc_emb,nac_params) : """ @@ -38,8 +38,6 @@ def __init__(self,stru_pristine,stru_defect,stru_emb,ifc_emb,nac_params) : self.stru_defect=stru_defect self.stru_emb=stru_emb - - @classmethod def from_phonopy_instances(cls, phonopy_pristine, @@ -56,34 +54,31 @@ def from_phonopy_instances(cls, verbose=0, asr=True) -> Phonopy : """ - Args: phonopy_pristine: Phonopy object of the pristine structure - phonopy_defect : Phonopy object of the defect structure - structure_defect_wo_relax : Supercell structure associated to the defect structure, but without relaxation. Needed for an easier mapping. + phonopy_defect: Phonopy object of the defect structure + structure_defect_wo_relax: Supercell structure associated to the defect structure, but without relaxation. Needed for an easier mapping. Should corresponds to order of phonopy_defect structure! - main_defect_coords_in_pristine : Main coordinates of the defect in pristine structure, if defect complex, can be set to the + main_defect_coords_in_pristine: Main coordinates of the defect in pristine structure, if defect complex, can be set to the center of mass of the complex main_defect_coords_in_defect : Main coordinates of the defect in defect structure, if defect complex, can be set to the center of mass of the complex - substitutions_list : List of substitutions infos [index,specie], ex : [[0, "Eu"],[1,"N"]] - vacancies_list : List of indices where the vacancies are, ex: [13,14] - interstitial_list : List of interstitial infos [specie, cart_coord], ex [['Eu',[0,0,0]],['Ce','[0,0,3]']] - tol_mapping : Tolerance in angstrom for the mapping between structures - cut_off_mode : Cut off mode for the radii of the sphere centered around the defect (rc_2). if 'auto' : the code tries to find the largest sphere + substitutions_list: List of substitutions infos [index,specie], ex : [[0, "Eu"],[1,"N"]] + vacancies_list: List of indices where the vacancies are, ex: [13,14] + interstitial_list: List of interstitial infos [specie, cart_coord], ex [['Eu',[0,0,0]],['Ce','[0,0,3]']] + tol_mapping: Tolerance in angstrom for the mapping between structures + cut_off_mode: Cut off mode for the radii of the sphere centered around the defect (rc_2). if 'auto' : the code tries to find the largest sphere inscribed in the defect supercell. If 'manual' : rc_1 and rc_2 should be provided. - rc_1 : Radii of the sphere centered around the defect outside which the IFCs are set to zero, allows to get sparse matrix. - rc_2 : Radii of the sphere centered around the defect where the IFCs of the defect computation are included - factor_ifc : Multiply the IFCs inside the sphere of radii rc_2 by factor_ifc, usefull to introduce fictious high-frequency local mode + rc_1: Radii of the sphere centered around the defect outside which the IFCs are set to zero, allows to get sparse matrix. + rc_2: Radii of the sphere centered around the defect where the IFCs of the defect computation are included + factor_ifc: Multiply the IFCs inside the sphere of radii rc_2 by factor_ifc, usefull to introduce fictious high-frequency local mode verbose : Print explicitely all the IFCs replacements - asr : If True, re-enforce acoustic sum rule after IFCs embedding, following eq. (S4) of https://pubs.acs.org/doi/10.1021/acs.chemmater.3c00537 + asr: If True, re-enforce acoustic sum rule after IFCs embedding, following eq. (S4) of https://pubs.acs.org/doi/10.1021/acs.chemmater.3c00537 Returns: A new phonopy object with the embedded structure and embedded IFCs. - """ - - + ######################## # Structures manipulations and mapping ######################## @@ -107,7 +102,6 @@ def from_phonopy_instances(cls, stru_emb=clean_structure(stru_emb,defect_coord=main_defect_coords_in_pristine) structure_defect_wo_relax=clean_structure(structure_defect_wo_relax,defect_coord=main_defect_coords_in_defect) - mapping=map_two_structures_coords(structure_defect_wo_relax,stru_emb,tol=tol_mapping) @@ -131,8 +125,6 @@ def from_phonopy_instances(cls, ifc_pristine=np.append(ifc_pristine,np.zeros(shape=[len(ifc_pristine),1,3,3]),axis=1) - - ######################## # Print infos ######################## @@ -140,23 +132,22 @@ def from_phonopy_instances(cls, print(f"Number of atoms in the pristine supercell : {len(stru_pristine)}") print(f"Number of atoms in the defective supercell : {len(stru_defect)}") - print(f"Defect infos") + print("Defect infos") if substitutions_list is not None: - print(f" Substitutions :") + print(" Substitutions:") for sub in substitutions_list: print(f" {sub[0]}, {stru_pristine[sub[0]].coords}, {stru_pristine[sub[0]].species} replaced by {sub[1]}") if vacancies_list is not None: - print(f" Vacancies :" ) + print(" Vacancies:" ) for vac in vacancies_list: print(f" {vac}, {stru_pristine[vac].coords}, {stru_pristine[vac].species} removed") if interstitial_list is not None: - print(f" Interstitials :" ) + print(" Interstitials:") for inter in interstitial_list: print(f" {inter[0]}, {inter[1]} added") - print(f"Mapping after structure manipulation : {len(mapping)}/{len(stru_defect)}") ######################## @@ -220,7 +211,6 @@ def from_phonopy_instances(cls, ######################## if phonopy_pristine.nac_params is not None: - # Simply copy the nac params from the pristine nac_params_emb=phonopy_pristine.nac_params.copy() @@ -231,10 +221,9 @@ def from_phonopy_instances(cls, ######################## - print(f"\n Embedding procedure done") + print("\n Embedding procedure done") return cls(stru_pristine,stru_defect,stru_emb,ifc_emb,nac_params_emb) - def get_gamma_freq_with_vec_abipy_fmt(self): """ @@ -252,7 +241,6 @@ def get_gamma_freq_with_vec_abipy_fmt(self): return ph_freq, ph_vec - def to_ddb(self,embedded_ddb_path='out_DDB',workdir=None): """ Call the converter to go from phonopy to a DDB @@ -267,7 +255,3 @@ def to_ddb(self,embedded_ddb_path='out_DDB',workdir=None): tolsym=None,workdir=workdir,nsym=1) return ddb_sc - - - - diff --git a/abipy/eph/gkq.py b/abipy/eph/gkq.py index f708acbba..231a20faa 100644 --- a/abipy/eph/gkq.py +++ b/abipy/eph/gkq.py @@ -148,7 +148,7 @@ def read_all_gkq(self, mode="phonon"): natom3 = natom * 3 phfreqs_ha, phdispl_red = self.phfreqs_ha, self.phdispl_red gkq_nu = np.empty_like(gkq_atm) - cwork = np.empty((natom3, nb2), dtype=np.complex) + cwork = np.empty((natom3, nb2), dtype=complex) for spin in range(self.ebands.nsppol): for ik in range(self.ebands.nkpt): g = np.reshape(gkq_atm[spin, ik], (-1, nb2)) @@ -177,7 +177,7 @@ def read_all_gkq(self, mode="phonon"): # gkq_atm = gkq_atm[:, 0] + 1j * gkq_atm[:, 1] # # # Transform the gkk matrix elements from (atom, red_direction) basis to phonon-mode basis. - # gkq_nu = np.zeros(natom3), dtype=np.complex) + # gkq_nu = np.zeros(natom3), dtype=complex) # for nu in range(natom3): # if self.phfreqs_ha[nu] < eph_wtol: continue # gkq_nu[nu] = np.dot(self.phdispl_red[nu], gkq_atm) / np.sqrt(2.0 * self.phfreqs_ha[nu]) @@ -441,8 +441,8 @@ def plot_gkq2_qpath(self, band_kq, band_k, kpoint=0, with_glr=False, qdamp=None, natom3 = len(self.abifiles[0].structure) * 3 nsppol = self.abifiles[0].nsppol nqpt = len(self.abifiles) - gkq_snuq = np.empty((nsppol, natom3, nqpt), dtype=np.complex) - if with_glr: gkq_lr = np.empty((nsppol, natom3, nqpt), dtype=np.complex) + gkq_snuq = np.empty((nsppol, natom3, nqpt), dtype=complex) + if with_glr: gkq_lr = np.empty((nsppol, natom3, nqpt), dtype=complex) # TODO: Should take into account possible degeneracies in k and kq... xticks, xlabels = [], [] diff --git a/abipy/flowtk/abiphonopy.py b/abipy/flowtk/abiphonopy.py index 6a66f72ff..e92aceb9f 100644 --- a/abipy/flowtk/abiphonopy.py +++ b/abipy/flowtk/abiphonopy.py @@ -5,13 +5,9 @@ import os import numpy as np -try: - from phonopy import Phonopy, file_IO - from phonopy.interface.vasp import read_vasp_from_strings - from phonopy.interface.abinit import parse_set_of_forces -except ImportError: - import warnings - warnings.warn("phonopy is required by abiphonopy. Install it with conda or pip install phonopy") +from phonopy import Phonopy, file_IO +from phonopy.interface.vasp import read_vasp_from_strings +from phonopy.interface.abinit import parse_set_of_forces from abipy.core.structure import Structure from abipy.flowtk.works import Work diff --git a/abipy/flowtk/effmass_works.py b/abipy/flowtk/effmass_works.py index 1b8be3617..063496d48 100644 --- a/abipy/flowtk/effmass_works.py +++ b/abipy/flowtk/effmass_works.py @@ -80,8 +80,8 @@ def from_scf_input(cls, scf_input: AbinitInput, new.register_nscf_task(nscf_input, deps={scf_task: "DEN"}) if ndivsm != 0: - ebands_inp = scf_input.make_ebands_input(ndivsm=ndivsm) - new.register_nscf_task(ebands_inp, deps={scf_task: "DEN"}) + ebands_inp = scf_input.make_ebands_input(ndivsm=ndivsm) + new.register_nscf_task(ebands_inp, deps={scf_task: "DEN"}) return new diff --git a/abipy/flowtk/flows.py b/abipy/flowtk/flows.py index f0443e347..2ecc31e4f 100644 --- a/abipy/flowtk/flows.py +++ b/abipy/flowtk/flows.py @@ -2612,7 +2612,7 @@ def polish_doc(doc: str, node_type) -> str: app(make_banner(s, mark="=")) app(polish_doc(task_cls.__doc__, "task")) app("Tasks belonging to this class (%s):" % len(tasks)) - for task in tasks: + for task in tasks: app(4 * " " + str(task) + ", status: " + task.status.colored) return "\n".join(lines) diff --git a/abipy/flowtk/gw_works.py b/abipy/flowtk/gw_works.py index 10cf423a5..a6a25e6f5 100644 --- a/abipy/flowtk/gw_works.py +++ b/abipy/flowtk/gw_works.py @@ -5,7 +5,7 @@ from __future__ import annotations import os -import numpy as np +#import numpy as np from . import wrappers from .nodes import Node diff --git a/abipy/flowtk/lumi_works.py b/abipy/flowtk/lumi_works.py index 3da8a0f25..ea4a08d66 100644 --- a/abipy/flowtk/lumi_works.py +++ b/abipy/flowtk/lumi_works.py @@ -6,6 +6,7 @@ from abipy.abilab import abiopen from abipy.lumi.deltaSCF import DeltaSCF + class LumiWork(Work): """ This Work implements Fig 1 of https://arxiv.org/abs/2010.00423. @@ -18,7 +19,7 @@ class LumiWork(Work): """ @classmethod - def from_scf_inputs(cls, gs_scf_inp, ex_scf_inp, relax_kwargs_gs, relax_kwargs_ex, ndivsm=0, nb_extra=10, + def from_scf_inputs(cls, gs_scf_inp, ex_scf_inp, relax_kwargs_gs, relax_kwargs_ex, ndivsm=0, nb_extra=10, tolwfr=1e-12, four_points=True, meta=None, manager=None) -> LumiWork: """ Args: @@ -82,7 +83,7 @@ def on_all_ok(self): #with self.gs_relax_task.open_gsr() as gsr: # ag_relaxed_structure = gsr.structure with abiopen(self.gs_relax_task.output_file.path) as relax_gs_abo: - ag_relaxed_structure = relax_gs_abo.final_structure + ag_relaxed_structure = relax_gs_abo.final_structure if self.iteration_step == 0: print("in iteration step 0") @@ -131,7 +132,6 @@ def on_all_ok(self): ae_scf_inp = self.gs_scf_inp.new_with_structure(aestar_relaxed_structure) self.ae_scf_task = self.register_scf_task((ae_scf_inp),deps={self.ex_relax_task: "DEN"}) - if self.ndivsm != 0: # Compute band structure for Ag configuration. self.ag_scf_task.add_ebands_task_to_work(self, ndivsm=self.ndivsm, @@ -165,7 +165,6 @@ def on_all_ok(self): #with self.ex_relax_task.open_gsr() as gsr: self.json_data["ex_relax_filepath"]=self.ex_relax_task.gsr_path - if self.four_points == True: # Get Ag total energy. #with self.ag_scf_task.open_gsr() as gsr: @@ -200,6 +199,7 @@ def on_all_ok(self): return super().on_all_ok() + class LumiWork_relaxations(Work): """ This Work implements the ground and excited state relaxations only. @@ -236,7 +236,6 @@ def from_scf_inputs(cls, gs_scf_inp, ex_scf_inp, relax_kwargs_gs, relax_kwargs_e new.gs_relax_task = new.register_relax_task(gs_scf_inp.new_with_vars(relax_kwargs_gs)) new.ex_relax_task = new.register_relax_task(ex_scf_inp.new_with_vars(relax_kwargs_ex)) - new.json_data = {} return new @@ -260,8 +259,6 @@ def on_all_ok(self): return super().on_all_ok() - - class LumiWorkFromRelax(Work): """ Same as LumiWork, without the relaxations. Typically used after a LumiWork_relaxations work. @@ -321,7 +318,6 @@ def from_scf_inputs(cls, gs_scf_inp, ex_scf_inp, gs_structure, ex_structure, ndi aestar_scf_inp = new.ex_scf_inp.new_with_structure(ex_structure) new.aestar_scf_task = new.register_scf_task(aestar_scf_inp) - # Build GS SCF input for the Ag* configuration: # use same structure as Ag but with excited occupation factors. ae_scf_inp = new.gs_scf_inp.new_with_structure(ex_structure) @@ -347,7 +343,6 @@ def on_all_ok(self): self.json_data["meta"] = self.meta - # Get Ag total energy. # with self.ag_scf_task.open_gsr() as gsr: self.json_data["Ag_gsr_filepath"] = self.ag_scf_task.gsr_path @@ -378,5 +373,4 @@ def on_all_ok(self): # save d in json format. self.write_json_in_outdir("Delta_SCF.json", d) - return super().on_all_ok() - + return super().on_all_ok() \ No newline at end of file diff --git a/abipy/flowtk/qutils.py b/abipy/flowtk/qutils.py index c60c02aa7..303631d42 100644 --- a/abipy/flowtk/qutils.py +++ b/abipy/flowtk/qutils.py @@ -9,7 +9,6 @@ from __future__ import annotations import os -#import json from subprocess import Popen, PIPE, run from monty.string import is_string @@ -315,7 +314,7 @@ def get_sacct_info(): try: result = run(['sacct', '--format=JobID,JobName,Partition,Account,AllocCPUS,State,ExitCode', '--noheader'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + stdout=PIPE, stderr=PIPE, text=True) # Check if the command was successful if result.returncode != 0: @@ -324,7 +323,8 @@ def get_sacct_info(): # Process the output jobs_info = result.stdout.strip().split('\n') - jobs = [dict(zip(['JobID', 'JobName', 'Partition', 'Account', 'AllocCPUS', 'State', 'ExitCode'], job.split())) for job in jobs_info] + jobs = [dict(zip(['JobID', 'JobName', 'Partition', 'Account', 'AllocCPUS', 'State', 'ExitCode'], job.split())) + for job in jobs_info] return jobs except Exception as e: @@ -332,15 +332,15 @@ def get_sacct_info(): return None -def get_completed_job_info(job_id): +def get_completed_job_info(job_id: int | str): try: # Define the fields we want to retrieve fields = "JobID,JobName,Partition,Account,AllocCPUS,State,ExitCode,Start,End,Elapsed,TotalCPU,MaxRSS" # Run the sacct command with the specified fields for the given job ID result = run( - ['sacct', '--jobs', job_id, '--format', fields, '--noheader', '--parsable2'], - stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True + ['sacct', '--jobs', str(job_id), '--format', fields, '--noheader', '--parsable2'], + stdout=PIPE, stderr=PIPE, text=True ) # Check if the command was successful @@ -451,4 +451,4 @@ def get_custodian_template() -> str: # Run the Custodian job c.run() -""" +""" \ No newline at end of file diff --git a/abipy/ml/aseml.py b/abipy/ml/aseml.py index 1a8ea7c5f..3df72c229 100644 --- a/abipy/ml/aseml.py +++ b/abipy/ml/aseml.py @@ -1294,7 +1294,7 @@ def calculate( forces += delta_forces print(f"{delta_forces=}") #AA: TODO: save the delta in list and call method... - dict ={'delta_forces': delta_forces,} + dict = {'delta_forces': delta_forces,} with open('delta_forces.json', 'a') as outfile: json.dump(dict, outfile, indent=1, cls=MontyEncoder) @@ -2330,7 +2330,6 @@ def read_neb_data(self) -> dict: return json.load(fh) - class MlGsList(_MlNebBase): """ Perform ground-state calculations for a list of atoms with ASE and ML-potential.