def set_calculator(self, atoms, name): cls = get_calculator(self.calculator_name) parameters = str2dict(self.args.parameters) if getattr(cls, 'nolabel', False): atoms.calc = cls(**parameters) else: atoms.calc = cls(label=self.get_filename(name), **parameters)
def dict2atoms(dct, attach_calculator=False): constraint_dicts = dct.get('constraints') if constraint_dicts: constraints = [dict2constraint(c) for c in constraint_dicts] else: constraints = None atoms = Atoms(dct['numbers'], dct['positions'], cell=dct['cell'], pbc=dct['pbc'], magmoms=dct.get('initial_magmoms'), charges=dct.get('initial_charges'), tags=dct.get('tags'), masses=dct.get('masses'), momenta=dct.get('momenta'), constraint=constraints) if attach_calculator: atoms.calc = get_calculator( dct['calculator'])(**dct['calculator_parameters']) else: results = {} for prop in all_properties: if prop in dct: results[prop] = dct[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) return atoms
def run(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name + '_bandgap', xc='PBE', # abinit, aims, elk - do not recognize the syntax below: # https://trac.fysik.dtu.dk/projects/ase/ticket/98 # kpts={'size': kpts, 'gamma': True}, **par) kpts=kpts, **par) si = bulk('Si', crystalstructure='diamond', a=5.43) si.calc = calc si.get_potential_energy() print(name, bandgap(si.calc)) del si.calc # test spin-polarization calc = Calculator(label=name + '_bandgap_spinpol', xc='PBE', # abinit, aims, elk - do not recognize the syntax below: # https://trac.fysik.dtu.dk/projects/ase/ticket/98 # kpts={'size': kpts, 'gamma': True}, **par) kpts=kpts, **par) si.set_initial_magnetic_moments([-0.1, 0.1]) # this should not be necessary in the new ase interface standard ... if si.get_initial_magnetic_moments().any(): # spin-polarization if name == 'aims': calc.set(spin='collinear') if name == 'elk': calc.set(spinpol=True) si.set_calculator(calc) si.get_potential_energy() print(name, bandgap(si.calc))
def h2dft(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', **par) h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) e2 = h2.get_potential_energy() calc.set(xc='PBE') e2pbe = h2.get_potential_energy() h1 = h2.copy() del h1[1] h1.set_initial_magnetic_moments([1]) h1.calc = calc e1pbe = h1.get_potential_energy() calc.set(xc='LDA') e1 = h1.get_potential_energy() try: m1 = h1.get_magnetic_moment() except NotImplementedError: pass else: print m1 print(2 * e1 - e2) print(2 * e1pbe - e2pbe) print e1, e2, e1pbe, e2pbe calc = Calculator(name) print calc.parameters, calc.results, calc.atoms assert not calc.calculation_required(h1, ['energy']) h1 = calc.get_atoms() print h1.get_potential_energy() label = 'dir/' + name + '-h1' calc = Calculator(label=label, atoms=h1, xc='LDA', **par) print h1.get_potential_energy() print Calculator.read_atoms(label).get_potential_energy()
def dict2atoms(dct, attach_calculator=False): constraint_dicts = dct.get('constraints') if constraint_dicts: constraints = [dict2constraint(c) for c in constraint_dicts] else: constraints = None atoms = Atoms(dct['numbers'], dct['positions'], cell=dct['cell'], pbc=dct['pbc'], magmoms=dct.get('initial_magmoms'), charges=dct.get('initial_charges'), tags=dct.get('tags'), masses=dct.get('masses'), momenta=dct.get('momenta'), constraint=constraints) if attach_calculator: atoms.calc = get_calculator(dct['calculator'])( **dct['calculator_parameters']) else: results = {} for prop in all_properties: if prop in dct: results[prop] = dct[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) return atoms
def dict2atoms(dct, attach_calculator=False): constraint_dicts = dct.get('constraints') if constraint_dicts: constraints = [] for c in constraint_dicts: assert c.pop('__name__') == 'ase.constraints.FixAtoms' constraints.append(FixAtoms(**c)) else: constraints = None atoms = Atoms(dct['numbers'], dct['positions'], cell=dct['cell'], pbc=dct['pbc'], magmoms=dct.get('magmoms'), charges=dct.get('charges'), tags=dct.get('tags'), masses=dct.get('masses'), momenta=dct.get('momenta'), constraint=constraints) results = dct.get('results') if attach_calculator: atoms.calc = get_calculator( dct['calculator_name'])(**dct['calculator_parameters']) elif results: atoms.calc = SinglePointCalculator(atoms, **results) return atoms
def h2dft(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', **par) h2 = molecule('H2', calculator=calc) h2.center(vacuum=2.0) e2 = h2.get_potential_energy() calc.set(xc='PBE') e2pbe = h2.get_potential_energy() h1 = h2.copy() del h1[1] h1.set_initial_magnetic_moments([1]) h1.calc = calc e1pbe = h1.get_potential_energy() calc.set(xc='LDA') e1 = h1.get_potential_energy() try: m1 = h1.get_magnetic_moment() except NotImplementedError: pass else: print(m1) print(2 * e1 - e2) print(2 * e1pbe - e2pbe) print(e1, e2, e1pbe, e2pbe) calc = Calculator(name) print(calc.parameters, calc.results, calc.atoms) assert not calc.calculation_required(h1, ['energy']) h1 = calc.get_atoms() print(h1.get_potential_energy()) label = 'dir/' + name + '-h1' calc = Calculator(label=label, atoms=h1, xc='LDA', **par) print(h1.get_potential_energy()) print(Calculator.read_atoms(label).get_potential_energy())
def dict2atoms(dct, attach_calculator=False): constraint_dicts = dct.get("constraints") if constraint_dicts: constraints = [dict2constraint(c) for c in constraint_dicts] else: constraints = None atoms = Atoms( dct["numbers"], dct["positions"], cell=dct["cell"], pbc=dct["pbc"], magmoms=dct.get("initial_magmoms"), charges=dct.get("initial_charges"), tags=dct.get("tags"), masses=dct.get("masses"), momenta=dct.get("momenta"), constraint=constraints, ) if attach_calculator: atoms.calc = get_calculator(dct["calculator"])(**dct["calculator_parameters"]) else: results = {} for prop in all_properties: if prop in dct: results[prop] = dct[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) return atoms
def dict2atoms(dct, attach_calculator=False): constraint_dicts = dct.get('constraints') if constraint_dicts: constraints = [] for c in constraint_dicts: assert c.pop('__name__') == 'ase.constraints.FixAtoms' constraints.append(FixAtoms(**c)) else: constraints = None atoms = Atoms(dct['numbers'], dct['positions'], cell=dct['cell'], pbc=dct['pbc'], magmoms=dct.get('magmoms'), charges=dct.get('charges'), tags=dct.get('tags'), masses=dct.get('masses'), momenta=dct.get('momenta'), constraint=constraints) results = dct.get('results') if attach_calculator: atoms.calc = get_calculator(dct['calculator_name'])( **dct['calculator_parameters']) elif results: atoms.calc = SinglePointCalculator(atoms, **results) return atoms
def run(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator( label=name + '_bandgap', xc='PBE', # abinit, aims, elk - do not recognize the syntax below: # https://trac.fysik.dtu.dk/projects/ase/ticket/98 # kpts={'size': kpts, 'gamma': True}, **par) kpts=kpts, **par) si = bulk('Si', crystalstructure='diamond', a=5.43) si.calc = calc si.get_potential_energy() print(name, bandgap(si.calc)) del si.calc # test spin-polarization calc = Calculator( label=name + '_bandgap_spinpol', xc='PBE', # abinit, aims, elk - do not recognize the syntax below: # https://trac.fysik.dtu.dk/projects/ase/ticket/98 # kpts={'size': kpts, 'gamma': True}, **par) kpts=kpts, **par) si.set_initial_magnetic_moments([-0.1, 0.1]) # this should not be necessary in the new ase interface standard ... if si.get_initial_magnetic_moments().any(): # spin-polarization if name == 'aims': calc.set(spin='collinear') if name == 'elk': calc.set(spinpol=True) si.set_calculator(calc) si.get_potential_energy() print(name, bandgap(si.calc))
def main(args=None): parser = optparse.OptionParser(usage='%prog [options] filename', description=description) add = parser.add_option add('-n', '--band-index', type=int, metavar='INDEX', help='Band index counting from zero.') add('-s', '--spin-index', type=int, metavar='SPIN', help='Spin index: zero or one.') add('-c', '--contours', default='4', help='Use "-c 3" for 3 contours or "-c -0.5,0.5" for specific ' + 'values. Default is four contours.') add('-r', '--repeat', help='Example: "-r 2,2,2".') add('-C', '--calculator-name', metavar='NAME', help='Name of calculator.') opts, args = parser.parse_args(args) if len(args) != 1: parser.error('Incorrect number of arguments') arg = args[0] if arg.endswith('.cube'): data, atoms = read_cube_data(arg) else: calc = get_calculator(opts.calculator_name)(arg, txt=None) atoms = calc.get_atoms() if opts.band_index is None: data = calc.get_pseudo_density(opts.spin_index) else: data = calc.get_pseudo_wave_function(opts.band_index, opts.spin_index or 0) if data.dtype == complex: data = abs(data) mn = data.min() mx = data.max() print('Min: %16.6f' % mn) print('Max: %16.6f' % mx) if opts.contours.isdigit(): n = int(opts.contours) d = (mx - mn) / n contours = np.linspace(mn + d / 2, mx - d / 2, n).tolist() else: contours = [float(x) for x in opts.contours.split(',')] if len(contours) == 1: print('1 contour:', contours[0]) else: print('%d contours: %.6f, ..., %.6f' % (len(contours), contours[0], contours[-1])) if opts.repeat: repeat = [int(r) for r in opts.repeat.split(',')] data = np.tile(data, repeat) atoms *= repeat plot(atoms, data, contours)
def h2(name, par): h2 = molecule('H2', pbc=par.pop('pbc', False)) h2.center(vacuum=2.0) h2.calc = get_calculator(name)(**par) e = h2.get_potential_energy() f = h2.get_forces() assert not h2.calc.calculation_required(h2, ['energy', 'forces']) write('h2.traj', h2) h2 = read('h2.traj') assert abs(e - h2.get_potential_energy()) < 1e-12 assert abs(f - h2.get_forces()).max() < 1e-12
def set_calculator(self, atoms, name): args = self.args cls = get_calculator(args.calculator) if self._calculator is None: namespace = {} else: namespace = self._calculator.namespace parameters = str2dict(args.parameters, namespace) if getattr(cls, 'nolabel', False): atoms.calc = cls(**parameters) else: atoms.calc = cls(label=self.get_filename(name), **parameters)
def disable_calculators(names): def __init__(self, *args, **kwargs): raise NotAvailable for name in names: if name in ['emt', 'lj', 'eam', 'morse']: continue try: cls = get_calculator(name) except ImportError: pass else: cls.__init__ = __init__
def run(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', kpts=1.0, **par) al = bulk('AlO', crystalstructure='rocksalt', a=4.5) al.calc = calc e = al.get_potential_energy() calc.set(xc='PBE', kpts=(2, 2, 2)) epbe = al.get_potential_energy() print(e, epbe) calc = Calculator(name) print calc.parameters, calc.results, calc.atoms assert not calc.calculation_required(al, ['energy']) al = calc.get_atoms() print al.get_potential_energy() label = 'dir/' + name + '-2' calc = Calculator(label=label, atoms=al, xc='LDA', kpts=1.0, **par) print al.get_potential_energy() print Calculator.read_atoms(label).get_potential_energy()
def disable_calculators(names): for name in names: if name in ['emt', 'lj', 'eam', 'morse', 'tip3p']: continue try: cls = get_calculator(name) except ImportError: pass else: def get_mock_init(name): def mock_init(obj, *args, **kwargs): raise NotAvailable('use --calculators={0} to enable' .format(name)) return mock_init def mock_del(obj): pass cls.__init__ = get_mock_init(name) cls.__del__ = mock_del
def run(name): Calculator = get_calculator(name) par = required.get(name, {}) calc = Calculator(label=name, xc='LDA', kpts=1.0, **par) al = bulk('AlO', crystalstructure='rocksalt', a=4.5) al.calc = calc e = al.get_potential_energy() calc.set(xc='PBE', kpts=(2, 2, 2)) epbe = al.get_potential_energy() print(e, epbe) calc = Calculator(name) print(calc.parameters, calc.results, calc.atoms) assert not calc.calculation_required(al, ['energy']) al = calc.get_atoms() print(al.get_potential_energy()) label = 'dir/' + name + '-2' calc = Calculator(label=label, atoms=al, xc='LDA', kpts=1.0, **par) print(al.get_potential_energy()) print(Calculator.read_atoms(label).get_potential_energy())
def toatoms(self, attach_calculator=False, add_additional_information=False): """Create Atoms object.""" atoms = Atoms(self.numbers, self.positions, cell=self.cell, pbc=self.pbc, magmoms=self.get('initial_magmoms'), charges=self.get('initial_charges'), tags=self.get('tags'), masses=self.get('masses'), momenta=self.get('momenta'), constraint=self.constraints) if attach_calculator: params = self.get('calculator_parameters', {}) atoms.calc = get_calculator(self.calculator)(**params) else: results = {} for prop in all_properties: if prop in self: results[prop] = self[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) atoms.calc.name = self.calculator if add_additional_information: atoms.info = {} atoms.info['unique_id'] = self.unique_id if self._keys: atoms.info['key_value_pairs'] = self.key_value_pairs data = self.get('data') if data: atoms.info['data'] = data return atoms
def toatoms(self, attach_calculator=False, add_additional_information=False): """Create Atoms object.""" atoms = Atoms(self.numbers, self.positions, cell=self.cell, pbc=self.pbc, magmoms=self.get('initial_magmoms'), charges=self.get('initial_charges'), tags=self.get('tags'), masses=self.get('masses'), momenta=self.get('momenta'), constraint=self.constraints) if attach_calculator: params = decode(self.get('calculator_parameters', '{}')) atoms.calc = get_calculator(self.calculator)(**params) else: results = {} for prop in all_properties: if prop in self: results[prop] = self[prop] if results: atoms.calc = SinglePointCalculator(atoms, **results) atoms.calc.name = self.calculator if add_additional_information: atoms.info = {} atoms.info['unique_id'] = self.unique_id if self._keys: atoms.info['key_value_pairs'] = self.key_value_pairs data = self.get('data') if data: atoms.info['data'] = data return atoms
def run(opts, args, verbosity): filename = args.pop(0) query = ','.join(args) if query.isdigit(): query = int(query) add_key_value_pairs = {} if opts.add_key_value_pairs: for pair in opts.add_key_value_pairs.split(','): key, value = pair.split('=') add_key_value_pairs[key] = convert_str_to_int_float_or_str(value) if opts.delete_keys: delete_keys = opts.delete_keys.split(',') else: delete_keys = [] con = connect(filename, use_lock_file=not opts.no_lock_file) def out(*args): if verbosity > 0: print(*args) if opts.analyse: con.analyse() return if opts.add_from_file: filename = opts.add_from_file if ':' in filename: calculator_name, filename = filename.split(':') atoms = get_calculator(calculator_name)(filename).get_atoms() else: atoms = ase.io.read(filename) con.write(atoms, key_value_pairs=add_key_value_pairs) out('Added {0} from {1}'.format(atoms.get_chemical_formula(), filename)) return if opts.count: n = con.count(query) print('%s' % plural(n, 'row')) return if opts.explain: for row in con.select(query, explain=True, verbosity=verbosity, limit=opts.limit, offset=opts.offset): print(row['explain']) return if opts.insert_into: nkvp = 0 nrows = 0 with connect(opts.insert_into, use_lock_file=not opts.no_lock_file) as con2: for row in con.select(query): kvp = row.get('key_value_pairs', {}) nkvp -= len(kvp) kvp.update(add_key_value_pairs) nkvp += len(kvp) if opts.unique: row['unique_id'] = '%x' % randint(16**31, 16**32 - 1) con2.write(row, data=row.get('data'), **kvp) nrows += 1 out('Added %s (%s updated)' % (plural(nkvp, 'key-value pair'), plural(len(add_key_value_pairs) * nrows - nkvp, 'pair'))) out('Inserted %s' % plural(nrows, 'row')) return if add_key_value_pairs or delete_keys: ids = [row['id'] for row in con.select(query)] m, n = con.update(ids, delete_keys, **add_key_value_pairs) out('Added %s (%s updated)' % (plural(m, 'key-value pair'), plural(len(add_key_value_pairs) * len(ids) - m, 'pair'))) out('Removed', plural(n, 'key-value pair')) return if opts.delete: ids = [row['id'] for row in con.select(query)] if ids and not opts.yes: msg = 'Delete %s? (yes/No): ' % plural(len(ids), 'row') if input(msg).lower() != 'yes': return con.delete(ids) out('Deleted %s' % plural(len(ids), 'row')) return if opts.plot_data: from ase.db.plot import dct2plot dct2plot(con.get(query).data, opts.plot_data) return if opts.plot: if ':' in opts.plot: tags, keys = opts.plot.split(':') tags = tags.split(',') else: tags = [] keys = opts.plot keys = keys.split(',') plots = collections.defaultdict(list) X = {} labels = [] for row in con.select(query, sort=opts.sort): name = ','.join(str(row[tag]) for tag in tags) x = row.get(keys[0]) if x is not None: if isinstance(x, basestring): if x not in X: X[x] = len(X) labels.append(x) x = X[x] plots[name].append([x] + [row.get(key) for key in keys[1:]]) import matplotlib.pyplot as plt for name, plot in plots.items(): xyy = zip(*plot) x = xyy[0] for y, key in zip(xyy[1:], keys[1:]): plt.plot(x, y, label=name + ':' + key) if X: plt.xticks(range(len(labels)), labels, rotation=90) plt.legend() plt.show() return if opts.long: row = con.get(query) summary = Summary(row) summary.write() elif opts.json: row = con.get(query) con2 = connect(sys.stdout, 'json', use_lock_file=False) kvp = row.get('key_value_pairs', {}) con2.write(row, data=row.get('data'), **kvp) else: if opts.open_web_browser: import ase.db.app as app app.db = con app.app.run(host='0.0.0.0', debug=True) else: columns = list(all_columns) c = opts.columns if c and c.startswith('++'): keys = set() for row in con.select(query, limit=opts.limit, offset=opts.offset): keys.update(row._keys) columns.extend(keys) if c[2:3] == ',': c = c[3:] else: c = '' if c: if c[0] == '+': c = c[1:] elif c[0] != '-': columns = [] for col in c.split(','): if col[0] == '-': columns.remove(col[1:]) else: columns.append(col.lstrip('+')) table = Table(con, verbosity, opts.cut) table.select(query, columns, opts.sort, opts.limit, opts.offset) if opts.csv: table.write_csv() else: table.write(query)
def run(opts, args, verbosity): filename = args.pop(0) query = ','.join(args) if query.isdigit(): query = int(query) if opts.add_keywords: add_keywords = opts.add_keywords.split(',') else: add_keywords = [] if opts.delete_keywords: delete_keywords = opts.delete_keywords.split(',') else: delete_keywords = [] add_key_value_pairs = {} if opts.add_key_value_pairs: for pair in opts.add_key_value_pairs.split(','): key, value = pair.split('=') for type in [int, float]: try: value = type(value) except ValueError: pass else: break add_key_value_pairs[key] = value if opts.delete_key_value_pairs: delete_key_value_pairs = opts.delete_key_value_pairs.split(',') else: delete_key_value_pairs = [] con = connect(filename) def out(*args): if verbosity > 0: print(*args) if opts.add_from_file: filename = opts.add_from_file if ':' in filename: calculator_name, filename = filename.split(':') atoms = get_calculator(calculator_name)(filename).get_atoms() else: atoms = ase.io.read(filename) con.write(atoms, add_keywords, key_value_pairs=add_key_value_pairs) out('Added {0} from {1}'.format(atoms.get_chemical_formula(), filename)) return if opts.count: n = 0 for dct in con.select(query): n += 1 print('%s' % plural(n, 'row')) return if opts.explain: for dct in con.select(query, explain=True, verbosity=verbosity, limit=opts.limit): print(dct['explain']) return if opts.insert_into: con2 = connect(opts.insert_into) nkw = 0 nkvp = 0 nrows = 0 for dct in con.select(query): keywords = dct.get('keywords', []) for keyword in add_keywords: if keyword not in keywords: keywords.append(keyword) nkw += 1 kvp = dct.get('key_value_pairs', {}) nkvp = -len(kvp) kvp.update(add_key_value_pairs) nkvp += len(kvp) con2.write(dct, keywords, data=dct.get('data'), **kvp) nrows += 1 out('Added %s and %s (%s updated)' % (plural(nkw, 'keyword'), plural(nkvp, 'key-value pair'), plural(len(add_key_value_pairs) * nrows - nkvp, 'pair'))) out('Inserted %s' % plural(nrows, 'row')) return if add_keywords or add_key_value_pairs: ids = [dct['id'] for dct in con.select(query)] nkw, nkv = con.update(ids, add_keywords, **add_key_value_pairs) out('Added %s and %s (%s updated)' % (plural(nkw, 'keyword'), plural(nkv, 'key-value pair'), plural(len(add_key_value_pairs) * len(ids) - nkv, 'pair'))) return if opts.delete: ids = [dct['id'] for dct in con.select(query)] if ids and not opts.yes: msg = 'Delete %s? (yes/No): ' % plural(len(ids), 'row') if raw_input(msg).lower() != 'yes': return con.delete(ids) out('Deleted %s' % plural(len(ids), 'row')) return if delete_keywords or delete_key_value_pairs: ids = [dct['id'] for dct in con.select(query)] nkw, nkv = con.delete_keywords_and_key_value_pairs( ids, delete_keywords, delete_key_value_pairs) print('Removed %s and %s' % (plural(nkw, 'keyword'), plural(nkv, 'key-value pair'))) return if opts.python_expression: for dct in con.select(query): row = eval(opts.python_expression, dct) if not isinstance(row, (list, tuple, np.ndarray)): row = [row] print(', '.join(str(x) for x in row)) return if opts.long: dct = con.get(query) summary = Summary(dct) summary.write() else: if opts.open_web_browser: import ase.db.app as app app.connection = con app.app.run(host='0.0.0.0', debug=True) else: columns = list(all_columns) c = opts.columns if c: if c[0] == '+': c = c[1:] elif c[0] != '-': columns = [] for col in c.split(','): if col[0] == '-': columns.remove(col[1:]) else: columns.append(col.lstrip('+')) table = Table(con, verbosity, opts.cut) table.select(query, columns, opts.sort, opts.limit) if opts.csv: table.write_csv() else: table.write()
def run(opts, args, verbosity): filename = args.pop(0) query = ','.join(args) if query.isdigit(): query = int(query) add_key_value_pairs = {} if opts.add_key_value_pairs: for pair in opts.add_key_value_pairs.split(','): key, value = pair.split('=') add_key_value_pairs[key] = convert_str_to_float_or_str(value) if opts.delete_keys: delete_keys = opts.delete_keys.split(',') else: delete_keys = [] con = connect(filename, use_lock_file=not opts.no_lock_file) def out(*args): if verbosity > 0: print(*args) if opts.analyse: con.analyse() return if opts.add_from_file: filename = opts.add_from_file if ':' in filename: calculator_name, filename = filename.split(':') atoms = get_calculator(calculator_name)(filename).get_atoms() else: atoms = ase.io.read(filename) con.write(atoms, key_value_pairs=add_key_value_pairs) out('Added {0} from {1}'.format(atoms.get_chemical_formula(), filename)) return if opts.count: n = con.count(query) print('%s' % plural(n, 'row')) return if opts.explain: for dct in con.select(query, explain=True, verbosity=verbosity, limit=opts.limit, offset=opts.offset): print(dct['explain']) return if opts.insert_into: nkvp = 0 nrows = 0 with connect(opts.insert_into, use_lock_file=not opts.no_lock_file) as con2: for dct in con.select(query): kvp = dct.get('key_value_pairs', {}) nkvp -= len(kvp) kvp.update(add_key_value_pairs) nkvp += len(kvp) if opts.unique: dct['unique_id'] = '%x' % randint(16**31, 16**32 - 1) con2.write(dct, data=dct.get('data'), **kvp) nrows += 1 out('Added %s (%s updated)' % (plural(nkvp, 'key-value pair'), plural(len(add_key_value_pairs) * nrows - nkvp, 'pair'))) out('Inserted %s' % plural(nrows, 'row')) return if add_key_value_pairs or delete_keys: ids = [dct['id'] for dct in con.select(query)] m, n = con.update(ids, delete_keys, **add_key_value_pairs) out('Added %s (%s updated)' % (plural(m, 'key-value pair'), plural(len(add_key_value_pairs) * len(ids) - m, 'pair'))) out('Removed', plural(n, 'key-value pair')) return if opts.delete: ids = [dct['id'] for dct in con.select(query)] if ids and not opts.yes: msg = 'Delete %s? (yes/No): ' % plural(len(ids), 'row') if input(msg).lower() != 'yes': return con.delete(ids) out('Deleted %s' % plural(len(ids), 'row')) return if opts.plot_data: from ase.db.plot import dct2plot dct2plot(con.get(query).data, opts.plot_data) return if opts.plot: if ':' in opts.plot: tags, keys = opts.plot.split(':') tags = tags.split(',') else: tags = [] keys = opts.plot keys = keys.split(',') plots = collections.defaultdict(list) X = {} labels = [] for row in con.select(query, sort=opts.sort): name = ','.join(str(row[tag]) for tag in tags) x = row.get(keys[0]) if x is not None: if isinstance(x, basestring): if x not in X: X[x] = len(X) labels.append(x) x = X[x] plots[name].append([x] + [row.get(key) for key in keys[1:]]) import matplotlib.pyplot as plt for name, plot in plots.items(): xyy = zip(*plot) x = xyy[0] for y, key in zip(xyy[1:], keys[1:]): plt.plot(x, y, label=name + ':' + key) if X: plt.xticks(range(len(labels)), labels, rotation=90) plt.legend() plt.show() return if opts.long: dct = con.get(query) summary = Summary(dct) summary.write() elif opts.json: dct = con.get(query) con2 = connect(sys.stdout, 'json', use_lock_file=False) kvp = dct.get('key_value_pairs', {}) con2.write(dct, data=dct.get('data'), **kvp) else: if opts.open_web_browser: import ase.db.app as app app.db = con app.app.run(host='0.0.0.0', debug=True) else: columns = list(all_columns) c = opts.columns if c and c.startswith('++'): keys = set() for row in con.select(query, limit=opts.limit, offset=opts.offset): keys.update(row._keys) columns.extend(keys) if c[2:3] == ',': c = c[3:] else: c = '' if c: if c[0] == '+': c = c[1:] elif c[0] != '-': columns = [] for col in c.split(','): if col[0] == '-': columns.remove(col[1:]) else: columns.append(col.lstrip('+')) table = Table(con, verbosity, opts.cut) table.select(query, columns, opts.sort, opts.limit, opts.offset) if opts.csv: table.write_csv() else: table.write(query)
def run(opts, args, verbosity): filename = args.pop(0) query = ','.join(args) if query.isdigit(): query = int(query) add_key_value_pairs = {} if opts.add_key_value_pairs: for pair in opts.add_key_value_pairs.split(','): key, value = pair.split('=') for type in [int, float]: try: value = type(value) except ValueError: pass else: break add_key_value_pairs[key] = value if opts.delete_keys: delete_keys = opts.delete_keys.split(',') else: delete_keys = [] con = connect(filename, use_lock_file=not opts.no_lock_file) def out(*args): if verbosity > 0: print(*args) if opts.add_from_file: filename = opts.add_from_file if ':' in filename: calculator_name, filename = filename.split(':') atoms = get_calculator(calculator_name)(filename).get_atoms() else: atoms = ase.io.read(filename) con.write(atoms, key_value_pairs=add_key_value_pairs) out('Added {0} from {1}'.format(atoms.get_chemical_formula(), filename)) return if opts.count: n = con.count(query) print('%s' % plural(n, 'row')) return if opts.explain: for dct in con.select(query, explain=True, verbosity=verbosity, limit=opts.limit, offset=opts.offset): print(dct['explain']) return if opts.insert_into: nkvp = 0 nrows = 0 with connect(opts.insert_into, use_lock_file=not opts.no_lock_file) as con2: for dct in con.select(query): kvp = dct.get('key_value_pairs', {}) nkvp = -len(kvp) kvp.update(add_key_value_pairs) nkvp += len(kvp) con2.write(dct, data=dct.get('data'), **kvp) nrows += 1 out('Added %s (%s updated)' % (plural(nkvp, 'key-value pair'), plural(len(add_key_value_pairs) * nrows - nkvp, 'pair'))) out('Inserted %s' % plural(nrows, 'row')) return if add_key_value_pairs or delete_keys: ids = [dct['id'] for dct in con.select(query)] m, n = con.update(ids, delete_keys, **add_key_value_pairs) out('Added %s (%s updated)' % (plural(m, 'key-value pair'), plural(len(add_key_value_pairs) * len(ids) - m, 'pair'))) out('Removed', plural(n, 'key-value pair')) return if opts.delete: ids = [dct['id'] for dct in con.select(query)] if ids and not opts.yes: msg = 'Delete %s? (yes/No): ' % plural(len(ids), 'row') if raw_input(msg).lower() != 'yes': return con.delete(ids) out('Deleted %s' % plural(len(ids), 'row')) return if opts.python_expression: for dct in con.select(query): row = eval(opts.python_expression, dct) if not isinstance(row, (list, tuple, np.ndarray)): row = [row] print(', '.join(str(x) for x in row)) return if opts.long: dct = con.get(query) summary = Summary(dct) summary.write() else: if opts.open_web_browser: import ase.db.app as app app.db = con app.app.run(host='0.0.0.0', debug=True) else: columns = list(all_columns) c = opts.columns if c: if c[0] == '+': c = c[1:] elif c[0] != '-': columns = [] for col in c.split(','): if col[0] == '-': columns.remove(col[1:]) else: columns.append(col.lstrip('+')) table = Table(con, verbosity, opts.cut) table.select(query, columns, opts.sort, opts.limit, opts.offset) if opts.csv: table.write_csv() else: table.write()
""" Test if we can find vasp2 using get_calculator() """ from ase.test.vasp import installed2 as installed from ase.calculators.calculator import get_calculator assert installed() get_calculator('vasp2')
def run(opts, args, verbosity): filename = args.pop(0) query = ",".join(args) if query.isdigit(): query = int(query) add_key_value_pairs = {} if opts.add_key_value_pairs: for pair in opts.add_key_value_pairs.split(","): key, value = pair.split("=") add_key_value_pairs[key] = convert_str_to_float_or_str(value) if opts.delete_keys: delete_keys = opts.delete_keys.split(",") else: delete_keys = [] con = connect(filename, use_lock_file=not opts.no_lock_file) def out(*args): if verbosity > 0: print(*args) if opts.analyse: con.analyse() return if opts.add_from_file: filename = opts.add_from_file if ":" in filename: calculator_name, filename = filename.split(":") atoms = get_calculator(calculator_name)(filename).get_atoms() else: atoms = ase.io.read(filename) con.write(atoms, key_value_pairs=add_key_value_pairs) out("Added {0} from {1}".format(atoms.get_chemical_formula(), filename)) return if opts.count: n = con.count(query) print("%s" % plural(n, "row")) return if opts.explain: for dct in con.select(query, explain=True, verbosity=verbosity, limit=opts.limit, offset=opts.offset): print(dct["explain"]) return if opts.insert_into: nkvp = 0 nrows = 0 with connect(opts.insert_into, use_lock_file=not opts.no_lock_file) as con2: for dct in con.select(query): kvp = dct.get("key_value_pairs", {}) nkvp -= len(kvp) kvp.update(add_key_value_pairs) nkvp += len(kvp) if opts.unique: dct["unique_id"] = "%x" % randint(16 ** 31, 16 ** 32 - 1) con2.write(dct, data=dct.get("data"), **kvp) nrows += 1 out( "Added %s (%s updated)" % (plural(nkvp, "key-value pair"), plural(len(add_key_value_pairs) * nrows - nkvp, "pair")) ) out("Inserted %s" % plural(nrows, "row")) return if add_key_value_pairs or delete_keys: ids = [dct["id"] for dct in con.select(query)] m, n = con.update(ids, delete_keys, **add_key_value_pairs) out( "Added %s (%s updated)" % (plural(m, "key-value pair"), plural(len(add_key_value_pairs) * len(ids) - m, "pair")) ) out("Removed", plural(n, "key-value pair")) return if opts.delete: ids = [dct["id"] for dct in con.select(query)] if ids and not opts.yes: msg = "Delete %s? (yes/No): " % plural(len(ids), "row") if input(msg).lower() != "yes": return con.delete(ids) out("Deleted %s" % plural(len(ids), "row")) return if opts.plot: if ":" in opts.plot: tags, keys = opts.plot.split(":") tags = tags.split(",") else: tags = [] keys = opts.plot keys = keys.split(",") plots = collections.defaultdict(list) X = {} labels = [] for row in con.select(query, sort=opts.sort): name = ",".join(row[tag] for tag in tags) x = row.get(keys[0]) if x is not None: if isinstance(x, (unicode, str)): if x not in X: X[x] = len(X) labels.append(x) x = X[x] plots[name].append([x] + [row.get(key) for key in keys[1:]]) import matplotlib.pyplot as plt for name, plot in plots.items(): xyy = zip(*plot) x = xyy[0] for y, key in zip(xyy[1:], keys[1:]): plt.plot(x, y, label=name + key) if X: plt.xticks(range(len(labels)), labels, rotation=90) plt.legend() plt.show() return if opts.long: dct = con.get(query) summary = Summary(dct) summary.write() elif opts.json: dct = con.get(query) con2 = connect(sys.stdout, "json", use_lock_file=False) kvp = dct.get("key_value_pairs", {}) con2.write(dct, data=dct.get("data"), **kvp) else: if opts.open_web_browser: import ase.db.app as app app.db = con app.app.run(host="0.0.0.0", debug=True) else: columns = list(all_columns) c = opts.columns if c and c.startswith("++"): keys = set() for row in con.select(query, limit=opts.limit, offset=opts.offset): keys.update(row._keys) columns.extend(keys) if c[2:3] == ",": c = c[3:] else: c = "" if c: if c[0] == "+": c = c[1:] elif c[0] != "-": columns = [] for col in c.split(","): if col[0] == "-": columns.remove(col[1:]) else: columns.append(col.lstrip("+")) table = Table(con, verbosity, opts.cut) table.select(query, columns, opts.sort, opts.limit, opts.offset) if opts.csv: table.write_csv() else: table.write(query)
def main(args): verbosity = 1 - args.quiet + args.verbose query = ','.join(args.query) if args.sort.endswith('-'): args.sort = '-' + args.sort[:-1] if query.isdigit(): query = int(query) add_key_value_pairs = {} if args.add_key_value_pairs: for pair in args.add_key_value_pairs.split(','): key, value = pair.split('=') add_key_value_pairs[key] = convert_str_to_int_float_or_str(value) if args.delete_keys: delete_keys = args.delete_keys.split(',') else: delete_keys = [] db = connect(args.database, use_lock_file=not args.no_lock_file) def out(*args): if verbosity > 0: print(*args) if args.analyse: db.analyse() return if args.add_from_file: filename = args.add_from_file if ':' in filename: calculator_name, filename = filename.split(':') atoms = get_calculator(calculator_name)(filename).get_atoms() else: atoms = ase.io.read(filename) db.write(atoms, key_value_pairs=add_key_value_pairs) out('Added {0} from {1}'.format(atoms.get_chemical_formula(), filename)) return if args.count: n = db.count(query) print('%s' % plural(n, 'row')) return if args.explain: for row in db.select(query, explain=True, verbosity=verbosity, limit=args.limit, offset=args.offset): print(row['explain']) return if args.show_metadata: print(json.dumps(db.metadata, sort_keys=True, indent=4)) return if args.set_metadata: with open(args.set_metadata) as fd: db.metadata = json.load(fd) return if args.insert_into: nkvp = 0 nrows = 0 with connect(args.insert_into, use_lock_file=not args.no_lock_file) as db2: for row in db.select(query, sort=args.sort): kvp = row.get('key_value_pairs', {}) nkvp -= len(kvp) kvp.update(add_key_value_pairs) nkvp += len(kvp) if args.unique: row['unique_id'] = '%x' % randint(16**31, 16**32 - 1) db2.write(row, data=row.get('data'), **kvp) nrows += 1 out('Added %s (%s updated)' % (plural(nkvp, 'key-value pair'), plural(len(add_key_value_pairs) * nrows - nkvp, 'pair'))) out('Inserted %s' % plural(nrows, 'row')) return if add_key_value_pairs or delete_keys: ids = [row['id'] for row in db.select(query)] m, n = db.update(ids, delete_keys, **add_key_value_pairs) out('Added %s (%s updated)' % (plural(m, 'key-value pair'), plural(len(add_key_value_pairs) * len(ids) - m, 'pair'))) out('Removed', plural(n, 'key-value pair')) return if args.delete: ids = [row['id'] for row in db.select(query)] if ids and not args.yes: msg = 'Delete %s? (yes/No): ' % plural(len(ids), 'row') if input(msg).lower() != 'yes': return db.delete(ids) out('Deleted %s' % plural(len(ids), 'row')) return if args.plot_data: from ase.db.plot import dct2plot dct2plot(db.get(query).data, args.plot_data) return if args.plot: if ':' in args.plot: tags, keys = args.plot.split(':') tags = tags.split(',') else: tags = [] keys = args.plot keys = keys.split(',') plots = collections.defaultdict(list) X = {} labels = [] for row in db.select(query, sort=args.sort, include_data=False): name = ','.join(str(row[tag]) for tag in tags) x = row.get(keys[0]) if x is not None: if isinstance(x, basestring): if x not in X: X[x] = len(X) labels.append(x) x = X[x] plots[name].append([x] + [row.get(key) for key in keys[1:]]) import matplotlib.pyplot as plt for name, plot in plots.items(): xyy = zip(*plot) x = xyy[0] for y, key in zip(xyy[1:], keys[1:]): plt.plot(x, y, label=name + ':' + key) if X: plt.xticks(range(len(labels)), labels, rotation=90) plt.legend() plt.show() return if args.json: row = db.get(query) db2 = connect(sys.stdout, 'json', use_lock_file=False) kvp = row.get('key_value_pairs', {}) db2.write(row, data=row.get('data'), **kvp) return db.python = args.metadata_from_python_script db.meta = process_metadata(db, html=args.open_web_browser) if args.long: # Remove .png files so that new ones will be created. for func, filenames in db.meta.get('functions', []): for filename in filenames: try: os.remove(filename) except OSError: # Python 3 only: FileNotFoundError pass row = db.get(query) summary = Summary(row, db.meta) summary.write() else: if args.open_web_browser: import ase.db.app as app app.databases['default'] = db app.app.run(host='0.0.0.0', debug=True) else: columns = list(all_columns) c = args.columns if c and c.startswith('++'): keys = set() for row in db.select(query, limit=args.limit, offset=args.offset, include_data=False): keys.update(row._keys) columns.extend(keys) if c[2:3] == ',': c = c[3:] else: c = '' if c: if c[0] == '+': c = c[1:] elif c[0] != '-': columns = [] for col in c.split(','): if col[0] == '-': columns.remove(col[1:]) else: columns.append(col.lstrip('+')) table = Table(db, verbosity, args.cut) table.select(query, columns, args.sort, args.limit, args.offset) if args.csv: table.write_csv() else: table.write(query)