-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmyfunc.py
222 lines (170 loc) · 6.24 KB
/
myfunc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 8 09:51:05 2022
@author: kangming
"""
import numpy as np
import pandas as pd
# For structure object conversion
import ast
from jarvis.core.atoms import Atoms
from pymatgen.core.structure import Structure
def strAtoms2objAtoms(str_atoms):
"""
Convert back to a jarvis.core.atoms object from a string that was previously
converted from a jarvis.core.atoms object
Parameters
----------
str_atoms : str
The string to which a jarvis.core.atoms object is converted.
Returns
-------
obj_Atoms : jarvis.core.atoms
"""
# convert the string of dict into dict:
# https://stackoverflow.com/questions/988228/convert-a-string-representation-of-a-dictionary-to-a-dictionary
dict_atom = ast.literal_eval(str_atoms) # need module ast
# need module jarvis
obj_Atoms = Atoms(lattice_mat=dict_atom['lattice_mat'],
coords=dict_atom['coords'],
elements=dict_atom['elements'])
# seems that we can simply do (https://jarvis-tools.readthedocs.io/en/master/databases.html)
# obj_Atoms = Atoms.from_dict(str_atoms)
return obj_Atoms
def strAtoms2objStructure(str_atom):
"""
Convert strAtoms to objStructure
Parameters
----------
str_atoms : str
The string to which a jarvis.core.atoms object is converted.
Returns
-------
obj_structure : pymatgen.core.structure.Structure
"""
strAtoms2objAtoms(str_atom).write_poscar() # Write POSCAR
obj_structure = Structure.from_file('POSCAR')
[site.to_unit_cell(in_place=True) for site in obj_structure.sites]
return obj_structure
def dictAtoms2objStructure(dict_atom):
"""
Convert strAtoms to objStructure
Parameters
----------
str_atoms : dict
The dict to which a jarvis.core.atoms object is converted.
Returns
-------
obj_structure : pymatgen.core.structure.Structure
"""
obj_Atom = Atoms.from_dict(dict_atom)
obj_Atom.write_poscar() # Write POSCAR
obj_structure = Structure.from_file('POSCAR')
[site.to_unit_cell(in_place=True) for site in obj_structure.sites]
return obj_structure
def count_sg_num(df, col='spacegroup.number'):
'''
Count space group occurrence in the column 'spacegroup.number' of a dataframe
Parameters
----------
df : TYPE
DESCRIPTION.
col : TYPE, optional
DESCRIPTION. The default is 'spacegroup.number'.
Returns
-------
TYPE
DESCRIPTION.
'''
df_sg = df[col].astype(int).value_counts().sort_index()
tot_sg = 230 # total number of space group
for i in range(1,tot_sg+1):
if i not in df_sg.index:
df_sg[i]=0
return df_sg.sort_index()
def dict2struct(str_struct):
dict_struct = ast.literal_eval(str_struct) # convert sting to dict
structure = Structure.from_dict(dict_struct)
[site.to_unit_cell(in_place=True) for site in structure.sites]
return structure # convert dict to Structure object
def to_unitcell(structure):
[site.to_unit_cell(in_place=True) for site in structure.sites]
return structure
def StructureFeaturizer(
df_in,
col_id='structure',
ignore_errors=True,
chunksize=30
):
"""
Featurize a dataframe using Matminter Structure featurizer
Parameters
----------
df : Pandas.DataFrame
DataFrame with a column named "structure"
Returns
-------
A DataFrame containing 273 features (columns)
"""
# For featurization
from matminer.featurizers.base import MultipleFeaturizer
from matminer.featurizers.composition import (ElementProperty,
Stoichiometry,
ValenceOrbital,
IonProperty)
from matminer.featurizers.structure import (SiteStatsFingerprint,
StructuralHeterogeneity,
ChemicalOrdering,
StructureComposition,
MaximumPackingEfficiency)
if isinstance(df_in, pd.Series):
df = df_in.to_frame()
else:
df = df_in
df[col_id] = df[col_id].apply(to_unitcell)
# 128 structural feature
struc_feat = [
SiteStatsFingerprint.from_preset("CoordinationNumber_ward-prb-2017"),
SiteStatsFingerprint.from_preset("LocalPropertyDifference_ward-prb-2017"),
StructuralHeterogeneity(),
MaximumPackingEfficiency(),
ChemicalOrdering()
]
# 145 compositional features
compo_feat = [
StructureComposition(Stoichiometry()),
StructureComposition(ElementProperty.from_preset("magpie")),
StructureComposition(ValenceOrbital(props=['frac'])),
StructureComposition(IonProperty(fast=True))
]
featurizer = MultipleFeaturizer(struc_feat+compo_feat)
# Set the chunksize used for Pool.map parallelisation
featurizer.set_chunksize(chunksize=chunksize)
featurizer.fit(df[col_id])
X = featurizer.featurize_dataframe(df=df,col_id=col_id,ignore_errors=ignore_errors)
# check failed entries
print('Featurization completed.')
failed = np.any(pd.isnull(X.iloc[:,df.shape[1]:]), axis=1)
if np.sum(failed) > 0:
print(f'Number failed: {np.sum(failed)}/{len(failed)}')
return X
def custom_matplotlib():
import matplotlib as mpl
''' Figure '''
mpl.rcParams['figure.figsize'] = [4.5,4.5]
mpl.rcParams['figure.dpi'] = 150
mpl.rcParams['figure.autolayout'] = True
mpl.rcParams['savefig.dpi'] = 300
mpl.rcParams['savefig.transparent'] = False
mpl.rcParams['legend.framealpha'] = 1
'''
Font:
https://www.statology.org/change-font-size-matplotlib/#:~:text=Note%3A%20The%20default%20font%20size%20for%20all%20elements%20is%2010.
https://stackoverflow.com/questions/3899980/how-to-change-the-font-size-on-a-matplotlib-plot
'''
font = {
#'family' : 'normal',
# 'weight' : 'bold',
'size' : 14}
mpl.rc('font', **font)