1 | import re, os, os.path, sys, operator
|
---|
2 |
|
---|
3 | avogadro = 6.022143e23
|
---|
4 |
|
---|
5 | class c_opt():
|
---|
6 | basename = None
|
---|
7 | tremofiledir = './'
|
---|
8 | potentialsfiledir = './'
|
---|
9 | outfilename = 'out'
|
---|
10 |
|
---|
11 | source = None
|
---|
12 | molarmass = None
|
---|
13 | density = None
|
---|
14 | temp = None
|
---|
15 |
|
---|
16 | number = '1000'
|
---|
17 |
|
---|
18 | cubicdomain = 'on'
|
---|
19 | cubiccell = 'off'
|
---|
20 | autorotate = 'off'
|
---|
21 | autodim = 'on'
|
---|
22 | postprocess = 'on'
|
---|
23 | automass = 'on'
|
---|
24 |
|
---|
25 | def update(self, name, value):
|
---|
26 | shortcuts = {'tf': 'temofiledir', 'pf': 'potentialsfiledir', 'o': 'outfilename',
|
---|
27 | 'i': 'source', 'm': 'molarmass', 'rho': 'density',
|
---|
28 | 't': 'temp', 'n': 'number', 'cd': 'cubicdomain',
|
---|
29 | 'cc': 'cubiccell', 'ar': 'autorotate', 'ad': 'autodim',
|
---|
30 | 'pp': 'postprocess', 'am': 'automass'}
|
---|
31 |
|
---|
32 | if name in shortcuts:
|
---|
33 | name = shortcuts[name]
|
---|
34 |
|
---|
35 | if name in dir(self):
|
---|
36 | exec('self.%s = "%s"' % (name, value))
|
---|
37 | else:
|
---|
38 | print 'Warning: Unknown option:', name
|
---|
39 |
|
---|
40 |
|
---|
41 | def ReadSettings(opt):
|
---|
42 | # Obtain basename
|
---|
43 | if len(sys.argv) >= 2:
|
---|
44 | opt.basename = sys.argv[1]
|
---|
45 | else:
|
---|
46 | print 'Usage: boxmaker.py <basename> [options]'
|
---|
47 | exit()
|
---|
48 |
|
---|
49 | # Read settings file
|
---|
50 | try:
|
---|
51 | with open('boxmaker.' + opt.basename) as f:
|
---|
52 | for line in f:
|
---|
53 | if len(line) > 0 and line[0] != '#':
|
---|
54 | L, S, R = line.partition('=')
|
---|
55 | opt.update(L.strip(), R.strip())
|
---|
56 | except IOError:
|
---|
57 | print 'Warning: Configuration file not readable, CLI only'
|
---|
58 |
|
---|
59 | # Parse parameters
|
---|
60 | i = 2
|
---|
61 | while i < len(sys.argv):
|
---|
62 | L = sys.argv[i]
|
---|
63 |
|
---|
64 | if L[0] in '+-':
|
---|
65 | LN = L[1:]
|
---|
66 |
|
---|
67 | if L[0] == '+':
|
---|
68 | R = 'on'
|
---|
69 | else:
|
---|
70 | R = 'off'
|
---|
71 | else:
|
---|
72 | LN = L
|
---|
73 | i += 1
|
---|
74 | R = sys.argv[i]
|
---|
75 |
|
---|
76 | opt.update(LN, R)
|
---|
77 | i += 1
|
---|
78 |
|
---|
79 |
|
---|
80 | def ReadUnits(opt):
|
---|
81 | lines = [] # The file needs to be processed twice, so we save the lines in the first run
|
---|
82 |
|
---|
83 | with open(opt.tremofiledir + opt.basename + '.tremolo') as f:
|
---|
84 | for line in f:
|
---|
85 | if len(line) > 0 and line[0] != '#':
|
---|
86 | line = line.strip()
|
---|
87 | lines.append(line)
|
---|
88 |
|
---|
89 | if 'systemofunits' in line:
|
---|
90 | L, S, SOU = line.partition('=')
|
---|
91 | SOU = SOU.strip()[:-1] # Remove semicolon
|
---|
92 |
|
---|
93 | if SOU == 'custom':
|
---|
94 | units = {}
|
---|
95 | quantities = ['length', 'mass', 'temperature']
|
---|
96 |
|
---|
97 | for quantity in quantities:
|
---|
98 | units[quantity] = [None, None] # Init with scaling factor and unit 'None'.
|
---|
99 |
|
---|
100 | for line in lines:
|
---|
101 | for quantity in quantities:
|
---|
102 | if quantity in line:
|
---|
103 | L, S, R = line.partition('=')
|
---|
104 | R = R.strip()[:-1] # Remove semicolon
|
---|
105 |
|
---|
106 | if 'scalingfactor' in line:
|
---|
107 | units[quantity][0] = float(R)
|
---|
108 | else:
|
---|
109 | units[quantity][1] = R
|
---|
110 |
|
---|
111 | elif SOU == 'kcalpermole':
|
---|
112 | units = {'length': [1.0, 'angstrom'], 'mass': [1.0, 'u'], 'temperature': [503.556, 'K']}
|
---|
113 |
|
---|
114 | elif SOU == 'evolt':
|
---|
115 | units = {'length': [1.0, 'angstrom'], 'mass': [1.0, 'u'], 'temperature': [11604.0, 'K']}
|
---|
116 |
|
---|
117 | else: # SI
|
---|
118 | units = {'length': [1.0, 'm'], 'mass': [1.0, 'kg'], 'temperature': [1.0, 'K']}
|
---|
119 |
|
---|
120 | return units
|
---|
121 |
|
---|
122 |
|
---|
123 | def ConvertUnits(have, want):
|
---|
124 | if have[0] == '!':
|
---|
125 | return float(have[1:])
|
---|
126 |
|
---|
127 | # Redo with pipes?
|
---|
128 | ret = os.system("units '%s' '%s' > temp_units_output" % (have, want))
|
---|
129 |
|
---|
130 | if ret == 0:
|
---|
131 | with open('temp_units_output') as f:
|
---|
132 | line = f.readline()
|
---|
133 |
|
---|
134 | os.system('rm temp_units_output')
|
---|
135 |
|
---|
136 | return float(line[3:-1])
|
---|
137 | else:
|
---|
138 | raise NameError('UnitError')
|
---|
139 |
|
---|
140 |
|
---|
141 | def GetSourcMolareMass(opt):
|
---|
142 | with open(opt.potentialsfiledir+opt.basename+'.potentials') as f:
|
---|
143 | potfile = f.read()
|
---|
144 |
|
---|
145 | elementmasses = dict(re.findall(r'element_name=(\w{1,2}).*?mass=([0-9.]*)', potfile))
|
---|
146 |
|
---|
147 | for key in elementmasses:
|
---|
148 | elementmasses[key] = float(elementmasses[key])
|
---|
149 |
|
---|
150 | # Convert from any format to xyz
|
---|
151 | os.system('molecuilder -o xyz --parse-tremolo-potentials %s -i temp_source.xyz -l %s' % (opt.potentialsfiledir+opt.basename+'.potentials', opt.source))
|
---|
152 |
|
---|
153 | mass_sum = 0.0
|
---|
154 |
|
---|
155 | with open('temp_source.xyz') as f:
|
---|
156 | N = int(f.readline())
|
---|
157 | comment = f.readline()
|
---|
158 |
|
---|
159 | for i in range(N):
|
---|
160 | elem = f.readline().split(None, 1)[0].strip()
|
---|
161 | mass_sum += elementmasses[elem]
|
---|
162 |
|
---|
163 | os.system('rm temp_source*')
|
---|
164 | return mass_sum*avogadro
|
---|
165 |
|
---|
166 |
|
---|
167 | def UpdateSettings(opt):
|
---|
168 | # Map boolean values
|
---|
169 | for name in ['cubicdomain', 'cubiccell', 'autorotate', 'autodim', 'postprocess', 'automass']:
|
---|
170 | value = eval('opt.' + name)
|
---|
171 |
|
---|
172 | if value == 'on':
|
---|
173 | value = True
|
---|
174 | elif value == 'off':
|
---|
175 | value = False
|
---|
176 | else:
|
---|
177 | print 'Not a boolean value:', value
|
---|
178 | exit()
|
---|
179 |
|
---|
180 | exec('opt.' + name + '= value')
|
---|
181 |
|
---|
182 | # Convert dimensions
|
---|
183 | if opt.autodim:
|
---|
184 | units = ReadUnits(opt)
|
---|
185 |
|
---|
186 | if not opt.automass:
|
---|
187 | have = opt.molarmass
|
---|
188 | want = '%f*%s / mol' % tuple(units['mass'])
|
---|
189 | opt.molarmass = ConvertUnits(have, want)
|
---|
190 |
|
---|
191 | have = opt.density
|
---|
192 | want = '(%f*%s) ' % tuple(units['mass']) + '/ (%f*%s)**3' % tuple(units['length'])
|
---|
193 | opt.density = ConvertUnits(have, want)
|
---|
194 |
|
---|
195 | if opt.temp:
|
---|
196 | have = opt.temp
|
---|
197 | want = '%f*%s' % tuple(units['temperature'])
|
---|
198 | opt.temp = ConvertUnits(have, want)
|
---|
199 | else:
|
---|
200 | if not opt.automass:
|
---|
201 | opt.molarmass = float(opt.molarmass)
|
---|
202 |
|
---|
203 | opt.density = float(opt.density)
|
---|
204 |
|
---|
205 | if opt.temp:
|
---|
206 | opt.temp = float(opt.temp)
|
---|
207 |
|
---|
208 | # Number might be an integer or a 3-vector
|
---|
209 | nvec = opt.number.split()
|
---|
210 | if len(nvec) == 3:
|
---|
211 | opt.number = [0]*3
|
---|
212 |
|
---|
213 | for i in range(3):
|
---|
214 | opt.number[i] = int(nvec[i])
|
---|
215 | else:
|
---|
216 | opt.number = int(opt.number)
|
---|
217 |
|
---|
218 | # Automatic source mass
|
---|
219 | if opt.automass:
|
---|
220 | opt.molarmass = GetSourcMolareMass(opt)
|
---|
221 | print '======== MOLAR MASS:', opt.molarmass
|
---|
222 |
|
---|
223 |
|
---|
224 | def FindBestCube(opt):
|
---|
225 | newroot = int( round(opt.number**(1./3)) )
|
---|
226 | newnumber = newroot**3
|
---|
227 |
|
---|
228 | if newnumber != opt.number:
|
---|
229 | print 'Warning: Number changed to %d.' % newnumber
|
---|
230 |
|
---|
231 | return [newroot] * 3
|
---|
232 |
|
---|
233 |
|
---|
234 | def FindBestCuboid(opt):
|
---|
235 | n = opt.number
|
---|
236 |
|
---|
237 | # Prime factors of n
|
---|
238 | factors = []
|
---|
239 |
|
---|
240 | for i in [2, 3]:
|
---|
241 | while n % i == 0:
|
---|
242 | factors.append(i)
|
---|
243 | n /= 2
|
---|
244 |
|
---|
245 | t = 5
|
---|
246 | diff = 2
|
---|
247 |
|
---|
248 | while t*t <= n:
|
---|
249 | while n % t == 0:
|
---|
250 | factors.append(t)
|
---|
251 | n /= t
|
---|
252 |
|
---|
253 | t = t + diff
|
---|
254 | diff = 6 - diff
|
---|
255 |
|
---|
256 | if n > 1:
|
---|
257 | factors.append(n)
|
---|
258 |
|
---|
259 | # Even distribution of current biggest prime to each vector -> similar sizes
|
---|
260 | if len(factors) < 3:
|
---|
261 | print 'Warning: Not enough prime factors - falling back to cubic placement'
|
---|
262 | return FindBestCube(opt)
|
---|
263 |
|
---|
264 | factors.sort()
|
---|
265 | distri = [[],[],[]]
|
---|
266 | current = 0
|
---|
267 |
|
---|
268 | for factor in factors:
|
---|
269 | distri[current].append(factor)
|
---|
270 | current += 1
|
---|
271 | if current == 3:
|
---|
272 | current = 0
|
---|
273 |
|
---|
274 | result = [0]*3
|
---|
275 |
|
---|
276 | print '======== CUBOID USED:',
|
---|
277 |
|
---|
278 | for i in range(3):
|
---|
279 | result[i] = int( reduce(operator.mul, distri[i]) )
|
---|
280 |
|
---|
281 | print result
|
---|
282 | return result
|
---|
283 |
|
---|
284 |
|
---|
285 | def GetSourceBBabs(opt):
|
---|
286 | bbmax = [0.0]*3
|
---|
287 | bbmin = [float('inf')]*3
|
---|
288 |
|
---|
289 | s_name_ext = os.path.basename(opt.source).rsplit('.', 1)
|
---|
290 | s_namepart = s_name_ext[0]
|
---|
291 |
|
---|
292 | if len(s_name_ext) > 1:
|
---|
293 | s_ext = s_name_ext[1]
|
---|
294 | else:
|
---|
295 | s_ext = ''
|
---|
296 |
|
---|
297 | # Convert from any format to xyz
|
---|
298 | os.system('molecuilder -o xyz --parse-tremolo-potentials %s -i temp_source.xyz -l %s' % (opt.potentialsfiledir+opt.basename+'.potentials', opt.source))
|
---|
299 |
|
---|
300 | # Calculate bounding box from xyz-file
|
---|
301 | with open('temp_source.xyz') as f:
|
---|
302 | N = int(f.readline())
|
---|
303 | comment = f.readline()
|
---|
304 |
|
---|
305 | for i in xrange(N):
|
---|
306 | buf = f.readline()
|
---|
307 | xyz = buf.split()[1:]
|
---|
308 |
|
---|
309 | for i in range(3):
|
---|
310 | bbmax[i] = max(bbmax[i], float(xyz[i]))
|
---|
311 | bbmin[i] = min(bbmin[i], float(xyz[i]))
|
---|
312 |
|
---|
313 | bb = [0.0]*3
|
---|
314 |
|
---|
315 | for i in range(3):
|
---|
316 | bb[i] = abs(bbmax[i] - bbmin[i])
|
---|
317 |
|
---|
318 | os.system('rm temp_source.*')
|
---|
319 | return bb
|
---|
320 |
|
---|
321 | # Global options with sensible default parameters
|
---|
322 | opt = c_opt()
|
---|
323 |
|
---|
324 | ReadSettings(opt)
|
---|
325 | UpdateSettings(opt)
|
---|
326 |
|
---|
327 | if type(opt.number) == type([]):
|
---|
328 | # Number is a vector - use it without any modification
|
---|
329 | nbox = opt.number
|
---|
330 | else:
|
---|
331 | if opt.cubicdomain:
|
---|
332 | nbox = FindBestCube(opt)
|
---|
333 | else:
|
---|
334 | nbox = FindBestCuboid(opt)
|
---|
335 |
|
---|
336 | # Autorotate
|
---|
337 | if opt.autorotate:
|
---|
338 | os.system('molecuilder --parse-tremolo-potentials %s -i rotated_temp_source.data -l %s --rotate-to-principal-axis-system "1, 0, 0"' % (opt.potentialsfiledir+opt.basename+'.potentials', opt.source))
|
---|
339 | opt.source = 'rotated_temp_source.data'
|
---|
340 |
|
---|
341 | VolumePerMolecule = opt.molarmass / (avogadro * opt.density)
|
---|
342 | cell = [VolumePerMolecule**(1./3)] * 3
|
---|
343 |
|
---|
344 | if not opt.cubiccell:
|
---|
345 | try:
|
---|
346 | bb = GetSourceBBabs(opt)
|
---|
347 | print '======== BBOX:', bb
|
---|
348 | # Scaling factor - the molecules bounding box is scaled to fit the volume suiting the density
|
---|
349 | s = (VolumePerMolecule / (bb[0]*bb[1]*bb[2])) ** (1./3)
|
---|
350 |
|
---|
351 | if s < 1:
|
---|
352 | print 'Warning: Molecular cells will overlap.'
|
---|
353 |
|
---|
354 | for i in range(3):
|
---|
355 | cell[i] = bb[i]*s
|
---|
356 | except ZeroDivisionError:
|
---|
357 | print 'Warning: Singularity in bounding box, falling back to cubic cell.'
|
---|
358 |
|
---|
359 |
|
---|
360 | print '======== CELL: ', cell
|
---|
361 |
|
---|
362 | import pyMoleCuilder as mol
|
---|
363 | mol.CommandVerbose('0')
|
---|
364 | mol.ParserParseTremoloPotentials(opt.potentialsfiledir + opt.basename + '.potentials')
|
---|
365 | mol.WorldInput(opt.source)
|
---|
366 | mol.WorldCenterInBox('%f 0 0 %f 0 %f' % tuple(cell))
|
---|
367 | mol.WorldRepeatBox('%d %d %d' % tuple(nbox))
|
---|
368 | mol.WorldOutput(opt.outfilename + '.data')
|
---|
369 | mol.WorldOutput(opt.outfilename + '.xyz')
|
---|
370 |
|
---|
371 | domain = [0.0]*3
|
---|
372 |
|
---|
373 | for i in range(3):
|
---|
374 | domain[i] = cell[i]*nbox[i]
|
---|
375 |
|
---|
376 | print '======== DOMAIN: ', domain
|
---|
377 |
|
---|
378 | # Postprocessing
|
---|
379 |
|
---|
380 | if opt.postprocess:
|
---|
381 | with open(opt.outfilename + '.data') as f:
|
---|
382 | ofile = f.read()
|
---|
383 |
|
---|
384 | with open(opt.outfilename + '.data', 'w') as f:
|
---|
385 | f.write('# INPUTCONV shift center\n')
|
---|
386 |
|
---|
387 | if opt.temp:
|
---|
388 | f.write('# INPUTCONV temp %.4f\n' % opt.temp)
|
---|
389 |
|
---|
390 | f.write(ofile)
|
---|
391 |
|
---|
392 | if opt.autorotate:
|
---|
393 | os.system('rm ' + opt.source)
|
---|