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