def read_files(mol_files): mol_strings = [] try: # open files describing input molecules for file in mol_files: if os.path.exists(file): f = open(file, "r") else: raise IOError("Cannot find " + file) mystr = f.read() f.close() mol_strings.append(mystr) return mol_strings except IOError, e: msg = "IOError" + str(e) raise ParseError(msg)
def number(self, dot=True, test=False, inc=True): num = '' first = True pos = self.pos while self.more(pos): char = self.source[pos] if char == '-' and first: pass elif not char.isdigit(): break first = False num += char pos += 1 if char == '.' and dot: num += '.' pos += 1 self.pos, tmp = pos, self.pos try: num += str(self.number(dot=False)) except ParseError: pass pos, self.pos = self.pos, tmp if inc and not test: self.pos = pos if is_number(num): if test: return True try: n = int(num) except ValueError: n = float(num) return n else: if test: return False lines = self.source[:pos] line = lines.count('\n') + 1 col = max(self.pos - lines.rfind('\n'), 0) raise ParseError('invalid number ending at {}:{}: {}'.format( line, col, num))
def error(self, msg): raise ParseError(msg)
def parse(self): while self.more(): char = self.source[self.pos] result = None if self.lines and self.lines[-1]: token = self.lines[-1][-1] else: token = None if token and hasattr(token, 'dynamic') and hasattr( token.dynamic, '__call__') and token.dynamic(char): self.inc() continue elif char in ('\n', ':'): self.close_brackets() self.inc() self.line += 1 continue elif char in ' \t': self.inc() continue elif char in '([{': if char == '(': cls = ParenExpr elif char == '[': if self.more(self.pos + 1) and self.source[self.pos + 1].isalpha(): result = self.matrix() else: cls = MatrixExpr elif char == '{': cls = ListExpr if result is None: self.stack.append(cls(char)) self.inc() continue elif char in ')]}': if self.stack: stacks = [] l = len(self.stack) for i in xrange(l): stack = self.stack.pop(l - i - 1) if isinstance(stack, Bracketed): if stack.close(char): for s in stacks: stack.append(s) if not isinstance(stack, FunctionArgs): result = stack stack.finish() self.inc() break elif char != stack.end: self.error( 'tried to end \'%s\' with: "%s" (expecting "%s")' % (stack, char, stack.end)) else: stacks.append(stack) else: stacks.append(stack) else: self.error( 'encountered "%s" but we have no expression on the stack to terminate' % char) elif char == ',': if len(self.stack) > 1 and isinstance(self.stack[-2], Tuple)\ and not isinstance(self.stack[-1], Tuple): expr = self.stack.pop() tup = self.stack[-1] tup.append(expr) tup.sep() elif self.stack and isinstance(self.stack[-1], Tuple): self.stack[-1].sep() elif self.stack: raise ParseError( 'comma encountered with an unclosed non-tuple expression on the stack' ) else: if self.lines[-1]: token = self.lines[-1].pop() else: self.error( 'Encountered comma, but cannot find anything to put in the tuple' ) tup = Tuple() tup.append(token) self.stack.append(tup) tup.sep() if isinstance(self.stack[-1], FunctionArgs): self.stack.append(Expression()) self.inc() continue elif '0' <= char <= '9' or char == '.'\ or isinstance(self.token(sub=True, inc=False), tokens.Minus) and self.number(test=True): result = tokens.Value(self.number()) elif char in u'l∟' and self.more(self.pos + 1) and self.source[ self.pos + 1] in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789': result = self.list() elif char.isalpha(): result = self.token() elif char in self.SYMBOLS: result = self.symbol() elif char == '"': result = tokens.Value(self.string()) else: self.error('could not tokenize: %s' % repr(char)) if isinstance(result, tokens.Stor): self.close_brackets() if result is not None: self.add(result) argument = False if isinstance(result, tokens.Function): argument = True if isinstance(result, (tokens.List, tokens.Matrix)): if self.more() and self.source[self.pos] == '(': self.inc() argument = True # we were told to push the stack into argument mode if argument: args = FunctionArgs('(') self.stack.append(args) self.stack.append(Expression()) result.absorb(args) self.close_brackets() return [line for line in self.post()]
def neb_calc(molinterface, calc_man, params): """Setup NEB object, optimiser, etc.""" spr_const = float(params["spr_const"]) beads_count = int(params["beads_count"]) neb = pts.searcher.NEB(molinterface.reagent_coords, calc_man, spr_const, beads_count, parallel=True) # initial path #dump_beads(molinterface, neb, params) dump_steps(neb) # callback function mycb = lambda x: generic_callback(x, molinterface, neb, **params) # opt params maxit = params['maxit'] tol = params['tol'] print "Launching optimiser..." if params["optimizer"] == "l_bfgs_b": import cosopt.lbfgsb as so #import ase #dyn = ase.LBFGS(neb) #dyn.run() opt, energy, dict = so.fmin_l_bfgs_b(neb.obj_func, neb.get_state_as_array(), fprime=neb.obj_func_grad, callback=mycb, pgtol=tol, maxfun=maxit) elif params["optimizer"] == "bfgs": from scipy.optimize import fmin_bfgs opt = fmin_bfgs(neb.obj_func, neb.get_state_as_array(), fprime=neb.obj_func_grad, callback=mycb, maxiter=maxit) elif params["optimizer"] == "ase_lbfgs": import ase optimizer = ase.LBFGS(neb) optimizer.run(fmax=tol) opt = neb.state_vec elif params["optimizer"] == "grad_descent": opt = opt_gd(neb.obj_func, neb.get_state_as_array(), fprime=neb.obj_func_grad, callback=mycb) else: raise ParseError("Unknown optimizer: " + params["optimizer"]) # PRODUCE OUTPUT print "Finished" # print opt # print energy dump_beads(molinterface, neb, params) print "steps" dump_steps(neb)
def string_calc(molinterface, calc_man, reagent_coords, params): """Setup String object, optimiser, etc.""" beads_count = int(params["beads_count"]) string = pts.searcher.GrowingString(molinterface.reagent_coords, calc_man, beads_count, rho=lambda x: 1, growing=params['growing'], parallel=True) # initial path dump_beads(molinterface, string, params) #dump_steps(string) mycb = lambda x: generic_callback(x, molinterface, string, **params) # opt params maxit = params['maxit'] tol = params['tol'] print "Launching optimiser..." if params['growing']: gqs = pts.searcher.QuadraticStringMethod(string, callback=mycb, update_trust_rads=True) while True: opt = gqs.opt() # grow the string, but break if not possible print "Growing" if not string.grow_string(): break elif params["optimizer"] == "l_bfgs_b": import cosopt.lbfgsb as so opt, energy, dict = so.fmin_l_bfgs_b(string.obj_func, string.get_state_as_array(), fprime=string.obj_func_grad, callback=mycb, pgtol=tol, maxfun=maxit) print opt print energy print dict elif params["optimizer"] == "quadratic_string": qs = pts.searcher.QuadraticStringMethod(string, callback=mycb, update_trust_rads=True) opt = qs.opt() print opt elif params["optimizer"] == "ase_lbfgs": import ase dyn = ase.LBFGS(string) dyn.run() else: raise ParseError("Unknown optimizer: " + params["optimizer"])
print >> sys.stderr, "for help use --help" return 2 # try to parse config file mol_files = [] params = [] try: config = ConfigParser.RawConfigParser() config.read(inputfile) if config.has_section('parameters'): params = dict(config.items('parameters')) params["name"] = os.path.splitext(inputfile)[0] else: print config.sections() raise ParseError("Could not find section 'parameters'") # extract ASE calculator specification if config.has_section('calculator'): calc_params = dict(config.items('calculator')) # TODO: add some error checking for the following values cons = eval(calc_params['constructor']) args = eval(calc_params['args']) kwargs = eval(calc_params['kwargs']) kwargs = dict(kwargs) calc_tuple = cons, args, kwargs params['calculator'] = calc_tuple mask = calc_params.get('mask')