-
Notifications
You must be signed in to change notification settings - Fork 0
/
xmdyn_to_opmd.py
264 lines (236 loc) · 10.1 KB
/
xmdyn_to_opmd.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
##########################################################################
# #
# Copyright (C) 2019 Juncheng E #
# Contact: juncheng E <[email protected]> #
# #
# This file is part of SimEx python library. #
# SimEx is free software: you can redistribute it and/or modify #
# it under the terms of the GNU General Public License as published by #
# the Free Software Foundation, either version 3 of the License, or #
# (at your option) any later version. #
# #
# SimEx is distributed in the hope that it will be useful, #
# but WITHOUT ANY WARRANTY; without even the implied warranty of #
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
# GNU General Public License for more details. #
# #
# You should have received a copy of the GNU General Public License #
# along with this program. If not, see <http://www.gnu.org/licenses/>. #
# #
##########################################################################
#%%
# initialize
import os
from argparse import ArgumentParser
import numpy as np
import h5py
import openpmd_api as api
from mendeleev import element
import warnings
warnings.simplefilter("ignore")
def convertToOPMD(args):
input_path = args.input_file
# output setting
if args.ff:
output_path = os.path.splitext(input_path)[0]+'.opmd.ff'+'.h5'
else:
output_path = os.path.splitext(input_path)[0]+'.opmd'+'.h5'
if os.path.isfile(output_path):
overwrite = input(output_path+" existed, overwrite? [y/n]").strip()
if (overwrite == "y"):
os.remove(output_path)
print (output_path+" overwritten")
else:
print ('did not overwrite, exit.')
exit()
# record running time
import atexit
from time import time, strftime, localtime
from datetime import timedelta
def secondsToStr(elapsed=None):
if elapsed is None:
return strftime("%Y-%m-%d %H:%M:%S", localtime())
else:
return str(timedelta(seconds=elapsed))
def log(s, elapsed=None):
line = "="*40
print(line)
print(secondsToStr(), '-', s)
if elapsed:
print("Elapsed time:", elapsed)
print(line)
def endlog():
end = time()
elapsed = end-start
log("End Program", secondsToStr(elapsed))
start = time()
atexit.register(endlog)
log("Start Program")
# set output hierarchy
series = api.Series(
output_path,
api.Access_Type.create)
series.set_openPMD("1.1.0")
series.set_openPMD_extension(2)
series.set_iteration_encoding(api.Iteration_Encoding.group_based)
series.set_software("XMDYN")
# convert from XMDYN to openPMD
xmdyn_attributes = dict()
with h5py.File(input_path, 'r') as xmdyn_h5:
# from misc
xmdyn_path = 'misc/run/start_0'
try:
xmdyn_attributes['date'] = xmdyn_h5[xmdyn_path][()]
series.set_software_version(xmdyn_attributes['date'])
except KeyError:
warnings.warn(xmdyn_path+' does not exist in xmdyn_h5', Warning)
# from params
xmdyn_path = 'params/xparams'
try:
xmdyn_attributes['comment'] = xmdyn_h5[xmdyn_path][()].decode('ascii')
series.set_comment(xmdyn_attributes['comment'])
except KeyError:
warnings.warn(xmdyn_path+' does not exist in xmdyn_h5', Warning)
# from info
xmdyn_path = 'info/package_version'
try:
xmdyn_attributes['version'] = xmdyn_h5[xmdyn_path][()]
series.set_software_version(xmdyn_attributes['version'])
except KeyError:
warnings.warn(xmdyn_path+' does not exist in xmdyn_h5', Warning)
xmdyn_path = 'info/package_version'
try:
xmdyn_attributes['forceField'] = xmdyn_h5[xmdyn_path][()].decode('ascii')
series.set_attribute('forceField', xmdyn_attributes['forceField'])
except KeyError:
warnings.warn(xmdyn_path+' does not exist in xmdyn_h5', Warning)
# get particle type mask
snp = 'snp_'+str(1).zfill(7)
Z = xmdyn_h5['data/'+snp]['Z']
uZ = np.sort(np.unique(Z))
type_masks = []
for z in uZ:
type_masks.append(Z[:] == z)
t0 = 0
it = 0
for snp in xmdyn_h5['data/']:
if snp.strip()[:3] == 'snp':
it += 1
curStep = series.iterations[it]
try:
# set real time for each step
t1 = xmdyn_h5['misc/time/'+snp][0]
dt = t1-t0
curStep.set_time(t1) .set_time_unit_SI(1) .set_dt(dt)
# for next loop
t0 = t1
except KeyError:
warnings.warn(
'misc/time/'+' does not exist in xmdyn_h5', Warning)
# convert position
# Z = xmdyn_h5['data/'+snp]['Z']
r = xmdyn_h5['data/'+snp]['r']
# uZ = np.sort(np.unique(Z))
for i_Z, z in enumerate(uZ):
# get element symbol
particle = curStep.particles[element(int(z)).symbol]
particle["position"].set_attribute(
"coordinate", "absolute")
particle["position"].set_unit_dimension(
{api.Unit_Dimension.L: 1})
position = r[type_masks[i_Z], :]
p_list = []
for ax in range(3):
p_list.append(position[:, ax].astype(np.float64))
dShape = api.Dataset(p_list[0].dtype, p_list[0].shape)
particle["position"]["x"].reset_dataset(dShape)
particle["position"]["y"].reset_dataset(dShape)
particle["position"]["z"].reset_dataset(dShape)
for i, axis in enumerate(particle["position"]):
particle["position"][axis].set_unit_SI(1.0)
particle["position"][axis].store_chunk(p_list[i])
series.flush()
# if args.debug:
# print(it,'/',len(xmdyn_h5['data/'].items()))
# else:
print(it)
print('number of snapshots:', it)
del series
def copyExtra(input_file):
output_file = os.path.splitext(input_file)[0]+'.opmd.ff'+'.h5'
def try_copy(h5_in,h5_out,group_name):
try:
h5_in.copy(group_name, h5_out['/'])
# Some keys may not exist, e.g. if the input file comes from a non-simex wpg run.
except KeyError:
pass
except:
raise
with h5py.File(input_file, 'r') as xmdyn_h5:
with h5py.File(output_file, 'a') as opmd_h5:
try_copy(xmdyn_h5,opmd_h5,'history')
try_copy(xmdyn_h5,opmd_h5,'info')
try_copy(xmdyn_h5,opmd_h5,'misc')
try_copy(xmdyn_h5,opmd_h5,'params')
try_copy(xmdyn_h5,opmd_h5,'version')
opmd_h5.close()
def copyFF(input_file):
output_file = os.path.splitext(input_file)[0]+'.opmd.ff'+'.h5'
with h5py.File(input_file, 'r') as xmdyn_h5:
with h5py.File(output_file, 'a') as opmd_h5:
it = 0
opmd_data = opmd_h5['data/']
for snp in xmdyn_h5['data/']:
if snp.strip()[:3] == 'snp':
it += 1
try:
opmd_it = opmd_data[str(it)]
xmdyn_h5.copy('data/'+snp+'/halfQ', opmd_it)
xmdyn_h5.copy('data/'+snp+'/Nph', opmd_it)
xmdyn_h5.copy('data/'+snp+'/Sq_halfQ', opmd_it)
xmdyn_h5.copy('data/'+snp+'/Sq_bound', opmd_it)
xmdyn_h5.copy('data/'+snp+'/Sq_free', opmd_it)
except (RuntimeError, KeyError):
pass
except:
raise
opmd_it_p = opmd_it['particles']
n_type = len(opmd_it_p.items())
a_types = np.zeros(n_type)
for idx, a_name in enumerate(opmd_it_p):
atom = element(a_name)
a_number = atom.atomic_number
a_types[idx] = a_number
a_types = np.sort(a_types)
for a_name in opmd_it_p:
atom = element(a_name)
a_number = atom.atomic_number
xmdyn_ff = xmdyn_h5['data/'+snp+'/ff'][...]
mark = np.where(a_types == a_number)
opmd_ff = xmdyn_ff[mark]
opmd_it_p[a_name].create_dataset("ff", opmd_ff.shape, dtype='f',
data= opmd_ff)
opmd_h5.flush()
opmd_h5.close()
xmdyn_h5.close()
#%%
if __name__ == "__main__":
# Parse arguments.
parser = ArgumentParser(description="Convert XMDYN output to openPMD-conforming hdf5. [v1.1]")
parser.add_argument("input_file", metavar="input_file",
help="name of the file to convert.")
parser.add_argument("-f","--ff", action="store_true",
help="also copy ff and extra fields from XMDYN output")
#parser.add_argument('-d','--debug',action='store_true',
#help="DEBUG mode")
args = parser.parse_args()
print(args)
# Call the converter routine.
convertToOPMD(args)
if args.ff:
# Extra fields
copyExtra(args.input_file)
# Scattering factor fields
copyFF(args.input_file)
else:
pass