source: utils/boxmaker.py@ 751d7f1

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 751d7f1 was 751d7f1, checked in by Frederik Heber <heber@…>, 14 years ago

Update: Shortcuts for common Parameters

  • Property mode set to 100644
File size: 8.8 KB
Line 
1import re, os, os.path, sys, operator
2
3class 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
34def 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
73def 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']
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] = R
101 else:
102 units[quantity][1] = R
103
104 elif SOU == 'kcalpermole':
105 units = {'length': ['1', 'angstrom'], 'mass': ['1', 'u']}
106
107 elif SOU == 'evolt':
108 units = {'length': ['1', 'angstrom'], 'mass': ['1', 'u']}
109
110 else: # SI
111 units = {'length': ['1', 'm'], 'mass': ['1', 'kg']}
112
113 return units
114
115
116def ConvertUnits(have, want):
117 # Redo with pipes?
118 ret = os.system("units '%s' '%s' > temp_units_output" % (have, want))
119
120 if ret == 0:
121 with open('temp_units_output') as f:
122 line = f.readline()
123
124 os.system('rm temp_units_output')
125
126 return float(line[3:-1])
127 else:
128 raise NameError('UnitError')
129
130
131def UpdateSettings(opt):
132 # Map boolean values
133 for name in ['cubicdomain', 'cubiccell', 'autorotate', 'autodim', 'postprocess']:
134 value = eval('opt.' + name)
135
136 if value == 'on':
137 value = True
138 elif value == 'off':
139 value = False
140 else:
141 print 'Not a boolean value:', value
142 exit()
143
144 exec('opt.' + name + '= value')
145
146 # Convert dimensions
147 if opt.autodim:
148 units = ReadUnits(opt)
149
150 have = opt.molarmass
151 want = '%s*%s / mol' % tuple(units['mass'])
152 opt.molarmass = ConvertUnits(have, want)
153
154 have = opt.density
155 want = '(%s*%s) ' % tuple(units['mass']) + '/ (%s*%s)**3' % tuple(units['length'])
156 opt.density = ConvertUnits(have, want)
157 else:
158 opt.molarmass = float(opt.molarmass)
159 opt.density = float(opt.density)
160
161 # Number might be an integer or a 3-vector
162 nvec = opt.number.split()
163 if len(nvec) == 3:
164 opt.number = [0]*3
165
166 for i in range(3):
167 opt.number[i] = int(nvec[i])
168 else:
169 opt.number = int(opt.number)
170
171 # Temp should be float or None
172 if opt.temp:
173 opt.temp = float(opt.temp)
174
175
176def FindBestCube(opt):
177 newroot = int( round(opt.number**(1./3)) )
178 newnumber = newroot**3
179
180 if newnumber != opt.number:
181 print 'Warning: Number changed to %d.' % newnumber
182
183 return [newroot] * 3
184
185
186def FindBestCuboid(opt):
187 n = opt.number
188
189 # Prime factors of n
190 factors = []
191
192 for i in [2, 3]:
193 while n % i == 0:
194 factors.append(i)
195 n /= 2
196
197 t = 5
198 diff = 2
199
200 while t*t <= n:
201 while n % t == 0:
202 factors.append(t)
203 n /= t
204
205 t = t + diff
206 diff = 6 - diff
207
208 if n > 1:
209 factors.append(n)
210
211 # Even distribution of current biggest prime to each vector -> similar sizes
212 if len(factors) < 3:
213 print 'Warning: Not enough prime factors - falling back to cubic placement'
214 return FindBestCube(opt)
215
216 factors.sort()
217 distri = [[],[],[]]
218 current = 0
219
220 for factor in factors:
221 distri[current].append(factor)
222 current += 1
223 if current == 3:
224 current = 0
225
226 result = [0]*3
227
228 print '======== CUBOID USED:',
229
230 for i in range(3):
231 result[i] = int( reduce(operator.mul, distri[i]) )
232
233 print result
234 return result
235
236
237def GetSourceBBabs(opt):
238 bbmax = [0.0]*3
239 bbmin = [float('inf')]*3
240
241 s_name_ext = os.path.basename(opt.source).rsplit('.', 1)
242 s_namepart = s_name_ext[0]
243
244 if len(s_name_ext) > 1:
245 s_ext = s_name_ext[1]
246 else:
247 s_ext = ''
248
249 # Convert from any format to xyz
250 os.system('molecuilder -o xyz --parse-tremolo-potentials %s -i temp_source.xyz -l %s' % (opt.potentialsfiledir+opt.basename+'.potentials', opt.source))
251
252 # Calculate bounding box from xyz-file
253 with open('temp_source.xyz') as f:
254 N = int(f.readline())
255 comment = f.readline()
256
257 for i in xrange(N):
258 buf = f.readline()
259 xyz = buf.split()[1:]
260
261 for i in range(3):
262 bbmax[i] = max(bbmax[i], float(xyz[i]))
263 bbmin[i] = min(bbmin[i], float(xyz[i]))
264
265 bb = [0.0]*3
266
267 for i in range(3):
268 bb[i] = abs(bbmax[i] - bbmin[i])
269
270 os.system('rm temp_source.*')
271 return bb
272
273# Global options with sensible default parameters
274opt = c_opt()
275
276ReadSettings(opt)
277UpdateSettings(opt)
278
279if type(opt.number) == type([]):
280 # Number is a vector - use it without any modification
281 nbox = opt.number
282else:
283 if opt.cubicdomain:
284 nbox = FindBestCube(opt)
285 else:
286 nbox = FindBestCuboid(opt)
287
288# Autorotate
289if opt.autorotate:
290 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))
291 opt.source = 'rotated_temp_source.data'
292
293avogadro = 6.022143e23
294VolumePerMolecule = opt.molarmass / (avogadro * opt.density)
295cell = [VolumePerMolecule**(1./3)] * 3
296
297if not opt.cubiccell:
298 try:
299 bb = GetSourceBBabs(opt)
300 print '======== BBOX:', bb
301 # Scaling factor - the molecules bounding box is scaled to fit the volume suiting the density
302 s = (VolumePerMolecule / (bb[0]*bb[1]*bb[2])) ** (1./3)
303
304 if s < 1:
305 print 'Warning: Molecular cells will overlap.'
306
307 for i in range(3):
308 cell[i] = bb[i]*s
309 except ZeroDivisionError:
310 print 'Warning: Singularity in bounding box, falling back to cubic cell.'
311
312
313print '======== CELL: ', cell
314
315import pyMoleCuilder as mol
316mol.CommandVerbose('0')
317mol.ParserParseTremoloPotentials(opt.potentialsfiledir + opt.basename + '.potentials')
318mol.WorldInput(opt.source)
319mol.WorldCenterInBox('%f 0 0 %f 0 %f' % tuple(cell))
320mol.WorldRepeatBox('%d %d %d' % tuple(nbox))
321mol.WorldOutput(opt.outfilename + '.data')
322mol.WorldOutput(opt.outfilename + '.xyz')
323
324domain = [0.0]*3
325
326for i in range(3):
327 domain[i] = cell[i]*nbox[i]
328
329print '======== DOMAIN: ', domain
330
331# Postprocessing
332
333if opt.postprocess:
334 with open(opt.outfilename + '.data') as f:
335 ofile = f.read()
336
337 with open(opt.outfilename + '.data', 'w') as f:
338 f.write('# INPUTCONV shift center\n')
339
340 if opt.temp:
341 f.write('# INPUTCONV temp %.4f\n' % opt.temp)
342
343 f.write(ofile)
344
345if opt.autorotate:
346 os.system('rm ' + opt.source)
Note: See TracBrowser for help on using the repository browser.