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 Candidate_v1.7.0 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
RevLine 
[5735ba]1import re, os, os.path, sys, operator
2
[0c83d8]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'
[32bc47]18 autorotate = 'off'
[0c83d8]19 autodim = 'on'
[32bc47]20 postprocess = 'on'
[0c83d8]21
22 def update(self, name, value):
[751d7f1]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
[0c83d8]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
[5735ba]36 if len(sys.argv) >= 2:
[0c83d8]37 opt.basename = sys.argv[1]
[5735ba]38 else:
[0c83d8]39 print 'Usage: boxmaker.py <basename> [options]'
[5735ba]40 exit()
[0c83d8]41
42 # Read settings file
[751d7f1]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'
[0c83d8]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:
[5735ba]77 for line in f:
78 if len(line) > 0 and line[0] != '#':
79 line = line.strip()
[0c83d8]80 lines.append(line)
81
[5735ba]82 if 'systemofunits' in line:
83 L, S, SOU = line.partition('=')
[0c83d8]84 SOU = SOU.strip()[:-1] # Remove semicolon
85
[5735ba]86 if SOU == 'custom':
87 units = {}
88 quantities = ['length', 'mass']
[0c83d8]89
[5735ba]90 for quantity in quantities:
[0c83d8]91 units[quantity] = [None, None] # Init with scaling factor and unit 'None'.
92
[5735ba]93 for line in lines:
94 for quantity in quantities:
95 if quantity in line:
96 L, S, R = line.partition('=')
[0c83d8]97 R = R.strip()[:-1] # Remove semicolon
98
[5735ba]99 if 'scalingfactor' in line:
100 units[quantity][0] = R
101 else:
102 units[quantity][1] = R
[0c83d8]103
[5735ba]104 elif SOU == 'kcalpermole':
105 units = {'length': ['1', 'angstrom'], 'mass': ['1', 'u']}
[0c83d8]106
[5735ba]107 elif SOU == 'evolt':
108 units = {'length': ['1', 'angstrom'], 'mass': ['1', 'u']}
[0c83d8]109
[5735ba]110 else: # SI
111 units = {'length': ['1', 'm'], 'mass': ['1', 'kg']}
[0c83d8]112
[5735ba]113 return units
[0c83d8]114
115
[5735ba]116def ConvertUnits(have, want):
[0c83d8]117 # Redo with pipes?
[5735ba]118 ret = os.system("units '%s' '%s' > temp_units_output" % (have, want))
[0c83d8]119
[5735ba]120 if ret == 0:
121 with open('temp_units_output') as f:
122 line = f.readline()
[0c83d8]123
[5735ba]124 os.system('rm temp_units_output')
[0c83d8]125
[5735ba]126 return float(line[3:-1])
127 else:
128 raise NameError('UnitError')
[0c83d8]129
130
131def UpdateSettings(opt):
132 # Map boolean values
[32bc47]133 for name in ['cubicdomain', 'cubiccell', 'autorotate', 'autodim', 'postprocess']:
[0c83d8]134 value = eval('opt.' + name)
[5735ba]135
[0c83d8]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
[5735ba]166 for i in range(3):
[0c83d8]167 opt.number[i] = int(nvec[i])
[5735ba]168 else:
[0c83d8]169 opt.number = int(opt.number)
[32bc47]170
171 # Temp should be float or None
172 if opt.temp:
173 opt.temp = float(opt.temp)
[0c83d8]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
[5735ba]197 t = 5
198 diff = 2
[0c83d8]199
[5735ba]200 while t*t <= n:
[0c83d8]201 while n % t == 0:
202 factors.append(t)
203 n /= t
204
[5735ba]205 t = t + diff
206 diff = 6 - diff
[0c83d8]207
[5735ba]208 if n > 1:
[0c83d8]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()
[5735ba]217 distri = [[],[],[]]
218 current = 0
[0c83d8]219
220 for factor in factors:
221 distri[current].append(factor)
[5735ba]222 current += 1
223 if current == 3:
224 current = 0
[0c83d8]225
226 result = [0]*3
227
228 print '======== CUBOID USED:',
229
[5735ba]230 for i in range(3):
[0c83d8]231 result[i] = int( reduce(operator.mul, distri[i]) )
232
233 print result
[5735ba]234 return result
[0c83d8]235
236
237def GetSourceBBabs(opt):
[5735ba]238 bbmax = [0.0]*3
[0c83d8]239 bbmin = [float('inf')]*3
240
241 s_name_ext = os.path.basename(opt.source).rsplit('.', 1)
[5735ba]242 s_namepart = s_name_ext[0]
[0c83d8]243
244 if len(s_name_ext) > 1:
[5735ba]245 s_ext = s_name_ext[1]
246 else:
247 s_ext = ''
[0c83d8]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
[5735ba]253 with open('temp_source.xyz') as f:
254 N = int(f.readline())
255 comment = f.readline()
[0c83d8]256
[5735ba]257 for i in xrange(N):
258 buf = f.readline()
259 xyz = buf.split()[1:]
[0c83d8]260
[5735ba]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
[0c83d8]266
[5735ba]267 for i in range(3):
[0c83d8]268 bb[i] = abs(bbmax[i] - bbmin[i])
269
[5735ba]270 os.system('rm temp_source.*')
271 return bb
272
[0c83d8]273# Global options with sensible default parameters
274opt = c_opt()
[5735ba]275
[0c83d8]276ReadSettings(opt)
277UpdateSettings(opt)
[5735ba]278
[0c83d8]279if type(opt.number) == type([]):
280 # Number is a vector - use it without any modification
281 nbox = opt.number
[5735ba]282else:
[0c83d8]283 if opt.cubicdomain:
284 nbox = FindBestCube(opt)
[5735ba]285 else:
[0c83d8]286 nbox = FindBestCuboid(opt)
[32bc47]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'
[5735ba]292
293avogadro = 6.022143e23
[0c83d8]294VolumePerMolecule = opt.molarmass / (avogadro * opt.density)
295cell = [VolumePerMolecule**(1./3)] * 3
[5735ba]296
[0c83d8]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.'
[5735ba]311
[0c83d8]312
[5735ba]313print '======== CELL: ', cell
314
315import pyMoleCuilder as mol
316mol.CommandVerbose('0')
[0c83d8]317mol.ParserParseTremoloPotentials(opt.potentialsfiledir + opt.basename + '.potentials')
318mol.WorldInput(opt.source)
[5735ba]319mol.WorldCenterInBox('%f 0 0 %f 0 %f' % tuple(cell))
320mol.WorldRepeatBox('%d %d %d' % tuple(nbox))
[0c83d8]321mol.WorldOutput(opt.outfilename + '.data')
322mol.WorldOutput(opt.outfilename + '.xyz')
[5735ba]323
324domain = [0.0]*3
325
326for i in range(3):
327 domain[i] = cell[i]*nbox[i]
[0c83d8]328
[5735ba]329print '======== DOMAIN: ', domain
[32bc47]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.