source: utils/boxmaker.py@ c0c85f

Action_Thermostats Add_AtomRandomPerturbation Add_FitFragmentPartialChargesAction Add_RotateAroundBondAction Add_SelectAtomByNameAction Added_ParseSaveFragmentResults AddingActions_SaveParseParticleParameters Adding_Graph_to_ChangeBondActions Adding_MD_integration_tests Adding_ParticleName_to_Atom Adding_StructOpt_integration_tests AtomFragments Automaking_mpqc_open AutomationFragmentation_failures Candidate_v1.5.4 Candidate_v1.6.0 Candidate_v1.6.1 ChangeBugEmailaddress ChangingTestPorts ChemicalSpaceEvaluator CombiningParticlePotentialParsing Combining_Subpackages Debian_Package_split Debian_package_split_molecuildergui_only Disabling_MemDebug Docu_Python_wait EmpiricalPotential_contain_HomologyGraph EmpiricalPotential_contain_HomologyGraph_documentation Enable_parallel_make_install Enhance_userguide Enhanced_StructuralOptimization Enhanced_StructuralOptimization_continued Example_ManyWaysToTranslateAtom Exclude_Hydrogens_annealWithBondGraph FitPartialCharges_GlobalError Fix_BoundInBox_CenterInBox_MoleculeActions Fix_ChargeSampling_PBC Fix_ChronosMutex Fix_FitPartialCharges Fix_FitPotential_needs_atomicnumbers Fix_ForceAnnealing Fix_IndependentFragmentGrids Fix_ParseParticles Fix_ParseParticles_split_forward_backward_Actions Fix_PopActions Fix_QtFragmentList_sorted_selection Fix_Restrictedkeyset_FragmentMolecule Fix_StatusMsg Fix_StepWorldTime_single_argument Fix_Verbose_Codepatterns Fix_fitting_potentials Fixes ForceAnnealing_goodresults ForceAnnealing_oldresults ForceAnnealing_tocheck ForceAnnealing_with_BondGraph ForceAnnealing_with_BondGraph_continued ForceAnnealing_with_BondGraph_continued_betteresults ForceAnnealing_with_BondGraph_contraction-expansion FragmentAction_writes_AtomFragments FragmentMolecule_checks_bonddegrees GeometryObjects Gui_Fixes Gui_displays_atomic_force_velocity ImplicitCharges IndependentFragmentGrids IndependentFragmentGrids_IndividualZeroInstances IndependentFragmentGrids_IntegrationTest IndependentFragmentGrids_Sole_NN_Calculation JobMarket_RobustOnKillsSegFaults JobMarket_StableWorkerPool JobMarket_unresolvable_hostname_fix MoreRobust_FragmentAutomation ODR_violation_mpqc_open PartialCharges_OrthogonalSummation PdbParser_setsAtomName PythonUI_with_named_parameters QtGui_reactivate_TimeChanged_changes Recreated_GuiChecks Rewrite_FitPartialCharges RotateToPrincipalAxisSystem_UndoRedo SaturateAtoms_findBestMatching SaturateAtoms_singleDegree StoppableMakroAction Subpackage_CodePatterns Subpackage_JobMarket Subpackage_LinearAlgebra Subpackage_levmar Subpackage_mpqc_open Subpackage_vmg Switchable_LogView ThirdParty_MPQC_rebuilt_buildsystem TrajectoryDependenant_MaxOrder TremoloParser_IncreasedPrecision TremoloParser_MultipleTimesteps TremoloParser_setsAtomName Ubuntu_1604_changes stable
Last change on this file since c0c85f was c0c85f, checked in by Frederik Heber <heber@…>, 14 years ago

Restructured Code

  • temp_source.xyz is created only once
  • boolean mapping with dict rather than if-tree
  • Property mode set to 100644
File size: 10.0 KB
Line 
1import re, os, os.path, sys, operator
2
3avogadro = 6.022143e23
4
5class 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
41def 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
80def 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
123def 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
141def GetSourceMolareMass(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 mass_sum = 0.0
151
152 with open('temp_source.xyz') as f:
153 N = int(f.readline())
154 comment = f.readline()
155
156 for i in range(N):
157 elem = f.readline().split(None, 1)[0].strip()
158 mass_sum += elementmasses[elem]
159
160 return mass_sum*avogadro
161
162
163def UpdateSettingsAndSource(opt):
164 # Map boolean values
165 boolmap = {'on': True, 'off': False}
166
167 for name in ['cubicdomain', 'cubiccell', 'autorotate', 'autodim', 'postprocess', 'automass']:
168 value = eval('opt.' + name)
169
170 if value in boolmap:
171 value = boolmap[value]
172 else:
173 print 'Not a boolean value:', value
174 exit()
175
176 exec('opt.' + name + '= value')
177
178 # Convert dimensions
179 if opt.autodim:
180 units = ReadUnits(opt)
181
182 if not opt.automass:
183 have = opt.molarmass
184 want = '%f*%s / mol' % tuple(units['mass'])
185 opt.molarmass = ConvertUnits(have, want)
186
187 have = opt.density
188 want = '(%f*%s) ' % tuple(units['mass']) + '/ (%f*%s)**3' % tuple(units['length'])
189 opt.density = ConvertUnits(have, want)
190
191 if opt.temp:
192 have = opt.temp
193 want = '%f*%s' % tuple(units['temperature'])
194 opt.temp = ConvertUnits(have, want)
195 else:
196 if not opt.automass:
197 opt.molarmass = float(opt.molarmass)
198
199 opt.density = float(opt.density)
200
201 if opt.temp:
202 opt.temp = float(opt.temp)
203
204 # Number might be an integer or a 3-vector
205 nvec = opt.number.split()
206 if len(nvec) == 3:
207 opt.number = [0]*3
208
209 for i in range(3):
210 opt.number[i] = int(nvec[i])
211 else:
212 opt.number = int(opt.number)
213
214 UpdateSource(opt)
215
216 # Automatic source mass
217 if opt.automass:
218 opt.molarmass = GetSourceMolareMass(opt)
219 print '======== MOLAR MASS:', opt.molarmass
220
221
222def FindBestCube(opt):
223 newroot = int( round(opt.number**(1./3)) )
224 newnumber = newroot**3
225
226 if newnumber != opt.number:
227 print 'Warning: Number changed to %d.' % newnumber
228
229 return [newroot] * 3
230
231
232def FindBestCuboid(opt):
233 n = opt.number
234
235 # Prime factors of n
236 factors = []
237
238 for i in [2, 3]:
239 while n % i == 0:
240 factors.append(i)
241 n /= 2
242
243 t = 5
244 diff = 2
245
246 while t*t <= n:
247 while n % t == 0:
248 factors.append(t)
249 n /= t
250
251 t = t + diff
252 diff = 6 - diff
253
254 if n > 1:
255 factors.append(n)
256
257 # Even distribution of current biggest prime to each vector -> similar sizes
258 if len(factors) < 3:
259 print 'Warning: Not enough prime factors - falling back to cubic placement'
260 return FindBestCube(opt)
261
262 factors.sort()
263 distri = [[],[],[]]
264 current = 0
265
266 for factor in factors:
267 distri[current].append(factor)
268 current += 1
269 if current == 3:
270 current = 0
271
272 result = [0]*3
273
274 print '======== CUBOID USED:',
275
276 for i in range(3):
277 result[i] = int( reduce(operator.mul, distri[i]) )
278
279 print result
280 return result
281
282
283def GetSourceBBabs(opt):
284 bbmax = [0.0]*3
285 bbmin = [float('inf')]*3
286
287 s_name_ext = os.path.basename(opt.source).rsplit('.', 1)
288 s_namepart = s_name_ext[0]
289
290 if len(s_name_ext) > 1:
291 s_ext = s_name_ext[1]
292 else:
293 s_ext = ''
294
295 # Calculate bounding box from xyz-file
296 with open('temp_source.xyz') as f:
297 N = int(f.readline())
298 comment = f.readline()
299
300 for i in xrange(N):
301 buf = f.readline()
302 xyz = buf.split()[1:]
303
304 for i in range(3):
305 bbmax[i] = max(bbmax[i], float(xyz[i]))
306 bbmin[i] = min(bbmin[i], float(xyz[i]))
307
308 bb = [0.0]*3
309
310 for i in range(3):
311 bb[i] = abs(bbmax[i] - bbmin[i])
312
313 return bb
314
315
316def UpdateSource(opt):
317 potfilepath = opt.potentialsfiledir + opt.basename + '.potentials'
318
319 cmd = 'molecuilder -o xyz tremolo --parse-tremolo-potentials %s -i temp_source.xyz -l %s' % (potfilepath, opt.source)
320
321 if opt.autorotate:
322 cmd += ' --select-all-atoms --rotate-to-principal-axis-system "0, 1, 0"'
323
324 os.system(cmd)
325
326 opt.source = 'temp_source.data'
327
328
329# Global options with sensible default parameters
330opt = c_opt()
331
332ReadSettings(opt)
333UpdateSettingsAndSource(opt)
334
335if type(opt.number) == type([]):
336 # Number is a vector - use it without any modification
337 nbox = opt.number
338else:
339 if opt.cubicdomain:
340 nbox = FindBestCube(opt)
341 else:
342 nbox = FindBestCuboid(opt)
343
344VolumePerMolecule = opt.molarmass / (avogadro * opt.density)
345cell = [VolumePerMolecule**(1./3)] * 3
346
347if not opt.cubiccell:
348 try:
349 bb = GetSourceBBabs(opt)
350 print '======== BBOX:', bb
351 # Scaling factor - the molecules bounding box is scaled to fit the volume suiting the density
352 s = (VolumePerMolecule / (bb[0]*bb[1]*bb[2])) ** (1./3)
353
354 if s < 1:
355 print 'Warning: Molecular cells will overlap.'
356
357 for i in range(3):
358 cell[i] = bb[i]*s
359 except ZeroDivisionError:
360 print 'Warning: Singularity in bounding box, falling back to cubic cell.'
361
362
363print '======== CELL: ', cell
364
365import pyMoleCuilder as mol
366mol.CommandVerbose('0')
367mol.ParserParseTremoloPotentials(opt.potentialsfiledir + opt.basename + '.potentials')
368mol.WorldInput(opt.source)
369mol.WorldCenterInBox('%f 0 0 %f 0 %f' % tuple(cell))
370mol.WorldRepeatBox('%d %d %d' % tuple(nbox))
371mol.WorldOutput(opt.outfilename + '.data')
372mol.WorldOutput(opt.outfilename + '.xyz')
373
374domain = [0.0]*3
375
376for i in range(3):
377 domain[i] = cell[i]*nbox[i]
378
379print '======== DOMAIN: ', domain
380
381# Postprocessing
382
383if opt.postprocess:
384 with open(opt.outfilename + '.data') as f:
385 ofile = f.read()
386
387 with open(opt.outfilename + '.data', 'w') as f:
388 f.write('# INPUTCONV shift center\n')
389
390 if opt.temp:
391 f.write('# INPUTCONV temp %.4f\n' % opt.temp)
392
393 f.write(ofile)
394
395os.system('rm temp_source.data temp_source.xyz')
Note: See TracBrowser for help on using the repository browser.