Skip to content

Commit

Permalink
Replace np.complex with complex from builtins
Browse files Browse the repository at this point in the history
  • Loading branch information
gmatteo committed May 31, 2024
1 parent 5686707 commit 7f7c4ca
Show file tree
Hide file tree
Showing 9 changed files with 49 additions and 76 deletions.
66 changes: 25 additions & 41 deletions abipy/embedding/embedding_ifc.py
Original file line number Diff line number Diff line change
@@ -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) :
"""
Expand All @@ -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,
Expand All @@ -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
########################
Expand All @@ -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)

Expand All @@ -131,32 +125,29 @@ def from_phonopy_instances(cls,

ifc_pristine=np.append(ifc_pristine,np.zeros(shape=[len(ifc_pristine),1,3,3]),axis=1)



########################
# Print infos
########################

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)}")

########################
Expand Down Expand Up @@ -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()

Expand All @@ -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):
"""
Expand All @@ -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
Expand All @@ -267,7 +255,3 @@ def to_ddb(self,embedded_ddb_path='out_DDB',workdir=None):
tolsym=None,workdir=workdir,nsym=1)

return ddb_sc




8 changes: 4 additions & 4 deletions abipy/eph/gkq.py
Original file line number Diff line number Diff line change
Expand Up @@ -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))
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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 = [], []
Expand Down
10 changes: 3 additions & 7 deletions abipy/flowtk/abiphonopy.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 2 additions & 2 deletions abipy/flowtk/effmass_works.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion abipy/flowtk/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion abipy/flowtk/gw_works.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 5 additions & 11 deletions abipy/flowtk/lumi_works.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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:
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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()
14 changes: 7 additions & 7 deletions abipy/flowtk/qutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from __future__ import annotations

import os
#import json

from subprocess import Popen, PIPE, run
from monty.string import is_string
Expand Down Expand Up @@ -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:
Expand All @@ -324,23 +323,24 @@ 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:
print(f"An error occurred: {e}")
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
Expand Down Expand Up @@ -451,4 +451,4 @@ def get_custodian_template() -> str:
# Run the Custodian job
c.run()
"""
"""
Loading

0 comments on commit 7f7c4ca

Please sign in to comment.