Coverage for ase/db/core.py: 82.87%
397 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import functools
2import json
3import numbers
4import operator
5import os
6import re
7import warnings
8from time import time
9from typing import Any
11import numpy as np
13from ase.atoms import Atoms
14from ase.calculators.calculator import all_changes, all_properties
15from ase.data import atomic_numbers
16from ase.db.row import AtomsRow
17from ase.formula import Formula
18from ase.io.jsonio import create_ase_object
19from ase.parallel import DummyMPI, parallel_function, parallel_generator, world
20from ase.utils import Lock, PurePath
22T2000 = 946681200.0 # January 1. 2000
23YEAR = 31557600.0 # 365.25 days
26@functools.total_ordering
27class KeyDescription:
28 _subscript = re.compile(r'`(.)_(.)`')
29 _superscript = re.compile(r'`(.*)\^\{?(.*?)\}?`')
31 def __init__(self, key, shortdesc=None, longdesc=None, unit=''):
32 self.key = key
34 if shortdesc is None:
35 shortdesc = key
37 if longdesc is None:
38 longdesc = shortdesc
40 self.shortdesc = shortdesc
41 self.longdesc = longdesc
43 # Somewhat arbitrary that we do this conversion. Can we avoid that?
44 # Previously done in create_key_descriptions().
45 unit = self._subscript.sub(r'\1<sub>\2</sub>', unit)
46 unit = self._superscript.sub(r'\1<sup>\2</sup>', unit)
47 unit = unit.replace(r'\text{', '').replace('}', '')
49 self.unit = unit
51 def __repr__(self):
52 cls = type(self).__name__
53 return (
54 f'{cls}({self.key!r}, {self.shortdesc!r}, {self.longdesc!r}, '
55 f'unit={self.unit!r})'
56 )
58 # The templates like to sort key descriptions by shortdesc.
59 def __eq__(self, other):
60 return self.shortdesc == getattr(other, 'shortdesc', None)
62 def __lt__(self, other):
63 return self.shortdesc < getattr(other, 'shortdesc', self.shortdesc)
66def get_key_descriptions():
67 KD = KeyDescription
68 return {
69 keydesc.key: keydesc
70 for keydesc in [
71 KD('id', 'ID', 'Uniqe row ID'),
72 KD('age', 'Age', 'Time since creation'),
73 KD('formula', 'Formula', 'Chemical formula'),
74 KD('pbc', 'PBC', 'Periodic boundary conditions'),
75 KD('user', 'Username'),
76 KD('calculator', 'Calculator', 'ASE-calculator name'),
77 KD('energy', 'Energy', 'Total energy', unit='eV'),
78 KD('natoms', 'Number of atoms'),
79 KD('fmax', 'Maximum force', unit='eV/Å'),
80 KD(
81 'smax',
82 'Maximum stress',
83 'Maximum stress on unit cell',
84 unit='eV/ų',
85 ),
86 KD('charge', 'Charge', 'Net charge in unit cell', unit='|e|'),
87 KD('mass', 'Mass', 'Sum of atomic masses in unit cell', unit='au'),
88 KD('magmom', 'Magnetic moment', unit='μ_B'),
89 KD('unique_id', 'Unique ID', 'Random (unique) ID'),
90 KD('volume', 'Volume', 'Volume of unit cell', unit='ų'),
91 ]
92 }
95def now():
96 """Return time since January 1. 2000 in years."""
97 return (time() - T2000) / YEAR
100seconds = {
101 's': 1,
102 'm': 60,
103 'h': 3600,
104 'd': 86400,
105 'w': 604800,
106 'M': 2629800,
107 'y': YEAR,
108}
110longwords = {
111 's': 'second',
112 'm': 'minute',
113 'h': 'hour',
114 'd': 'day',
115 'w': 'week',
116 'M': 'month',
117 'y': 'year',
118}
120ops = {
121 '<': operator.lt,
122 '<=': operator.le,
123 '=': operator.eq,
124 '>=': operator.ge,
125 '>': operator.gt,
126 '!=': operator.ne,
127}
129invop = {'<': '>=', '<=': '>', '>=': '<', '>': '<=', '=': '!=', '!=': '='}
131word = re.compile('[_a-zA-Z][_0-9a-zA-Z]*$')
133reserved_keys = set(
134 all_properties
135 + all_changes
136 + list(atomic_numbers)
137 + [
138 'id',
139 'unique_id',
140 'ctime',
141 'mtime',
142 'user',
143 'fmax',
144 'smax',
145 'momenta',
146 'constraints',
147 'natoms',
148 'formula',
149 'age',
150 'calculator',
151 'calculator_parameters',
152 'key_value_pairs',
153 'data',
154 ]
155)
157numeric_keys = {'id', 'energy', 'magmom', 'charge', 'natoms'}
160def check(key_value_pairs):
161 for key, value in key_value_pairs.items():
162 if key == 'external_tables':
163 # Checks for external_tables are not
164 # performed
165 continue
167 if not word.match(key) or key in reserved_keys:
168 raise ValueError(f'Bad key: {key}')
169 try:
170 Formula(key, strict=True)
171 except ValueError:
172 pass
173 else:
174 warnings.warn(
175 'It is best not to use keys ({0}) that are also a '
176 'chemical formula. If you do a "db.select({0!r})",'
177 'you will not find rows with your key. Instead, you wil get '
178 'rows containing the atoms in the formula!'.format(key)
179 )
180 if not isinstance(value, (numbers.Real, str, np.bool_)):
181 raise ValueError(f'Bad value for {key!r}: {value}')
182 if isinstance(value, str):
183 for t in [bool, int, float]:
184 if str_represents(value, t):
185 raise ValueError(
186 'Value '
187 + value
188 + ' is put in as string '
189 + 'but can be interpreted as '
190 + f'{t.__name__}! Please convert '
191 + f'to {t.__name__} before '
192 + 'writing to the database OR change '
193 + 'to a different string.'
194 )
197def str_represents(value, t=int):
198 new_value = convert_str_to_int_float_bool_or_str(value)
199 return isinstance(new_value, t)
202def connect(
203 name,
204 type='extract_from_name',
205 create_indices=True,
206 use_lock_file=True,
207 append=True,
208 serial=False,
209 **db_kwargs,
210):
211 """Create connection to database.
213 name: str
214 Filename or address of database.
215 type: str
216 One of 'json', 'db', 'postgresql', 'mysql', 'aselmdb'
217 (JSON, SQLite, PostgreSQL, MYSQL, ASELMDB).
218 Default is 'extract_from_name', which will guess the type
219 from the name.
220 use_lock_file: bool
221 You can turn this off if you know what you are doing ...
222 append: bool
223 Use append=False to start a new database.
224 db_kwargs: dict
225 Optional extra kwargs to pass on to the underlying db
226 """
228 if isinstance(name, PurePath):
229 name = str(name)
231 if type == 'extract_from_name':
232 if name is None:
233 type = None
234 elif not isinstance(name, str):
235 type = 'json'
236 elif name.startswith('postgresql://') or name.startswith('postgres://'):
237 type = 'postgresql'
238 elif name.startswith('mysql://') or name.startswith('mariadb://'):
239 type = 'mysql'
240 else:
241 type = os.path.splitext(name)[1][1:]
242 if type == '':
243 raise ValueError('No file extension or database type given')
245 if type is None:
246 return Database(**db_kwargs)
248 if not append and world.rank == 0:
249 if isinstance(name, str) and os.path.isfile(name):
250 os.remove(name)
252 if type not in ['postgresql', 'mysql'] and isinstance(name, str):
253 name = os.path.abspath(name)
255 if type == 'json':
256 from ase.db.jsondb import JSONDatabase
258 return JSONDatabase(
259 name, use_lock_file=use_lock_file, serial=serial, **db_kwargs
260 )
261 if type == 'db':
262 from ase.db.sqlite import SQLite3Database
264 return SQLite3Database(
265 name, create_indices, use_lock_file, serial=serial, **db_kwargs
266 )
267 if type == 'postgresql':
268 from ase_db_backends.postgresql import PostgreSQLDatabase
270 return PostgreSQLDatabase(name, **db_kwargs)
272 if type == 'mysql':
273 from ase_db_backends.mysql import MySQLDatabase
275 return MySQLDatabase(name, **db_kwargs)
277 if type == 'aselmdb':
278 from ase_db_backends.aselmdb import LMDBDatabase
280 return LMDBDatabase(name, **db_kwargs)
282 raise ValueError('Unknown database type: ' + type)
285def lock(method):
286 """Decorator for using a lock-file."""
288 @functools.wraps(method)
289 def new_method(self, *args, **kwargs):
290 if self.lock is None:
291 return method(self, *args, **kwargs)
292 else:
293 with self.lock:
294 return method(self, *args, **kwargs)
296 return new_method
299def convert_str_to_int_float_bool_or_str(value):
300 """Safe eval()"""
301 try:
302 return int(value)
303 except ValueError:
304 try:
305 value = float(value)
306 except ValueError:
307 value = {'True': True, 'False': False}.get(value, value)
308 return value
311def parse_selection(selection, **kwargs):
312 if selection is None or selection == '':
313 expressions = []
314 elif isinstance(selection, int):
315 expressions = [('id', '=', selection)]
316 elif isinstance(selection, list):
317 expressions = selection
318 else:
319 expressions = [w.strip() for w in selection.split(',')]
320 keys = []
321 comparisons = []
322 for expression in expressions:
323 if isinstance(expression, (list, tuple)):
324 comparisons.append(expression)
325 continue
326 if expression.count('<') == 2:
327 value, expression = expression.split('<', 1)
328 if expression[0] == '=':
329 op = '>='
330 expression = expression[1:]
331 else:
332 op = '>'
333 key = expression.split('<', 1)[0]
334 comparisons.append((key, op, value))
335 for op in ['!=', '<=', '>=', '<', '>', '=']:
336 if op in expression:
337 break
338 else: # no break
339 if expression in atomic_numbers:
340 comparisons.append((expression, '>', 0))
341 else:
342 try:
343 count = Formula(expression).count()
344 except ValueError:
345 keys.append(expression)
346 else:
347 comparisons.extend(
348 (symbol, '>', n - 1) for symbol, n in count.items()
349 )
350 continue
351 key, value = expression.split(op)
352 comparisons.append((key, op, value))
354 cmps = []
355 for key, value in kwargs.items():
356 comparisons.append((key, '=', value))
358 for key, op, value in comparisons:
359 if key == 'age':
360 key = 'ctime'
361 op = invop[op]
362 value = now() - time_string_to_float(value)
363 elif key == 'formula':
364 if op != '=':
365 raise ValueError('Use fomula=...')
366 f = Formula(value)
367 count = f.count()
368 cmps.extend(
369 (atomic_numbers[symbol], '=', n) for symbol, n in count.items()
370 )
371 key = 'natoms'
372 value = len(f)
373 elif key in atomic_numbers:
374 key = atomic_numbers[key]
375 value = int(value)
376 elif isinstance(value, str):
377 if key != 'unique_id':
378 value = convert_str_to_int_float_bool_or_str(value)
379 if key in numeric_keys and not isinstance(value, (int, float)):
380 msg = 'Wrong type for "{}{}{}" - must be a number'
381 raise ValueError(msg.format(key, op, value))
382 cmps.append((key, op, value))
384 return keys, cmps
387class Database:
388 """Base class for all databases."""
390 def __init__(
391 self,
392 filename: str | None = None,
393 create_indices: bool = True,
394 use_lock_file: bool = False,
395 serial: bool = False,
396 ):
397 """Database object.
399 serial: bool
400 Let someone else handle parallelization. Default behavior is
401 to interact with the database on the master only and then
402 distribute results to all slaves.
403 """
404 if isinstance(filename, str):
405 filename = os.path.expanduser(filename)
406 self.filename = filename
407 self.create_indices = create_indices
408 self.lock = None
409 if use_lock_file and isinstance(filename, str):
410 self.lock = Lock(filename + '.lock', world=DummyMPI())
411 self.serial = serial
413 # Decription of columns and other stuff:
414 self._metadata = None
416 @property
417 def metadata(self) -> dict[str, Any]:
418 raise NotImplementedError
420 @parallel_function
421 @lock
422 def write(self, atoms, key_value_pairs=None, data=None, id=None, **kwargs):
423 """Write atoms to database with key-value pairs.
425 atoms: Atoms object
426 Write atomic numbers, positions, unit cell and boundary
427 conditions. If a calculator is attached, write also already
428 calculated properties such as the energy and forces.
429 key_value_pairs: dict
430 Dictionary of key-value pairs. Values must be strings or numbers.
431 data: dict
432 Extra stuff (not for searching).
433 id: int
434 Overwrite existing row.
436 Key-value pairs can also be set using keyword arguments::
438 connection.write(atoms, name='ABC', frequency=42.0)
440 Returns integer id of the new row.
441 """
443 if data is None:
444 data = {}
445 if key_value_pairs is None:
446 key_value_pairs = {}
447 if atoms is None:
448 atoms = Atoms()
450 kvp = dict(key_value_pairs) # modify a copy
451 kvp.update(kwargs)
453 id = self._write(atoms, kvp, data, id)
454 return id
456 def _write(self, atoms, key_value_pairs, data, id=None):
457 check(key_value_pairs)
458 return 1
460 @parallel_function
461 @lock
462 def reserve(self, **key_value_pairs):
463 """Write empty row if not already present.
465 Usage::
467 id = conn.reserve(key1=value1, key2=value2, ...)
469 Write an empty row with the given key-value pairs and
470 return the integer id. If such a row already exists, don't write
471 anything and return None.
472 """
474 for _ in self._select(
475 [], [(key, '=', value) for key, value in key_value_pairs.items()]
476 ):
477 return None
479 atoms = Atoms()
481 calc_name = key_value_pairs.pop('calculator', None)
483 if calc_name:
484 # Allow use of calculator key
485 assert calc_name.lower() == calc_name
487 # Fake calculator class:
488 class Fake:
489 name = calc_name
491 def todict(self):
492 return {}
494 def check_state(self, atoms):
495 return ['positions']
497 atoms.calc = Fake()
499 id = self._write(atoms, key_value_pairs, {}, None)
501 return id
503 def __delitem__(self, id):
504 self.delete([id])
506 def get_atoms(
507 self, selection=None, add_additional_information=False, **kwargs
508 ):
509 """Get Atoms object.
511 selection: int, str or list
512 See the select() method.
513 add_additional_information: bool
514 Put key-value pairs and data into Atoms.info dictionary.
516 In addition, one can use keyword arguments to select specific
517 key-value pairs.
518 """
520 row = self.get(selection, **kwargs)
521 return row.toatoms(add_additional_information)
523 def __getitem__(self, selection):
524 return self.get(selection)
526 def get(self, selection=None, **kwargs):
527 """Select a single row and return it as a dictionary.
529 selection: int, str or list
530 See the select() method.
531 """
532 rows = list(self.select(selection, limit=2, **kwargs))
533 if not rows:
534 raise KeyError('no match')
535 assert len(rows) == 1, 'more than one row matched'
536 return rows[0]
538 @parallel_generator
539 def select(
540 self,
541 selection=None,
542 filter=None,
543 explain=False,
544 verbosity=1,
545 limit=None,
546 offset=0,
547 sort=None,
548 include_data=True,
549 columns='all',
550 **kwargs,
551 ):
552 """Select rows.
554 Return AtomsRow iterator with results. Selection is done
555 using key-value pairs and the special keys:
557 formula, age, user, calculator, natoms, energy, magmom
558 and/or charge.
560 selection: int, str or list
561 Can be:
563 * an integer id
564 * a string like 'key=value', where '=' can also be one of
565 '<=', '<', '>', '>=' or '!='.
566 * a string like 'key'
567 * comma separated strings like 'key1<value1,key2=value2,key'
568 * list of strings or tuples: [('charge', '=', 1)].
569 filter: function
570 A function that takes as input a row and returns True or False.
571 explain: bool
572 Explain query plan.
573 verbosity: int
574 Possible values: 0, 1 or 2.
575 limit: int or None
576 Limit selection.
577 offset: int
578 Offset into selected rows.
579 sort: str
580 Sort rows after key. Prepend with minus sign for a decending sort.
581 include_data: bool
582 Use include_data=False to skip reading data from rows.
583 columns: 'all' or list of str
584 Specify which columns from the SQL table to include.
585 For example, if only the row id and the energy is needed,
586 queries can be speeded up by setting columns=['id', 'energy'].
587 """
589 if sort:
590 if sort == 'age':
591 sort = '-ctime'
592 elif sort == '-age':
593 sort = 'ctime'
594 elif sort.lstrip('-') == 'user':
595 sort += 'name'
597 keys, cmps = parse_selection(selection, **kwargs)
598 for row in self._select(
599 keys,
600 cmps,
601 explain=explain,
602 verbosity=verbosity,
603 limit=limit,
604 offset=offset,
605 sort=sort,
606 include_data=include_data,
607 columns=columns,
608 ):
609 if filter is None or filter(row):
610 yield row
612 def count(self, selection=None, **kwargs):
613 """Count rows.
615 See the select() method for the selection syntax. Use db.count() or
616 len(db) to count all rows.
617 """
618 n = 0
619 for _ in self.select(selection, **kwargs):
620 n += 1
621 return n
623 def __len__(self):
624 return self.count()
626 @parallel_function
627 @lock
628 def update(
629 self, id, atoms=None, delete_keys=None, data=None, **add_key_value_pairs
630 ):
631 """Update and/or delete key-value pairs of row(s).
633 id: int
634 ID of row to update.
635 atoms: Atoms object
636 Optionally update the Atoms data (positions, cell, ...).
637 data: dict
638 Data dict to be added to the existing data.
639 delete_keys: list of str
640 Keys to remove.
642 Use keyword arguments to add new key-value pairs.
644 Returns number of key-value pairs added and removed.
645 """
647 if delete_keys is None:
648 delete_keys = []
649 if not isinstance(id, numbers.Integral):
650 if isinstance(id, list):
651 err = (
652 'First argument must be an int and not a list.\n'
653 'Do something like this instead:\n\n'
654 'with db:\n'
655 ' for id in ids:\n'
656 ' db.update(id, ...)'
657 )
658 raise ValueError(err)
659 raise TypeError('id must be an int')
661 check(add_key_value_pairs)
663 row = self._get_row(id)
664 kvp = row.key_value_pairs
666 n = len(kvp)
667 for key in delete_keys:
668 kvp.pop(key, None)
669 n -= len(kvp)
670 m = -len(kvp)
671 kvp.update(add_key_value_pairs)
672 m += len(kvp)
674 moredata = data
675 data = row.get('data', {})
676 if moredata:
677 data.update(moredata)
678 if not data:
679 data = None
681 if atoms:
682 oldrow = row
683 row = AtomsRow(atoms)
684 # Copy over data, kvp, ctime, user and id
685 row._data = oldrow._data
686 row.__dict__.update(kvp)
687 row._keys = list(kvp)
688 row.ctime = oldrow.ctime
689 row.user = oldrow.user
690 row.id = id
692 if atoms or os.path.splitext(self.filename)[1] == '.json':
693 self._write(row, kvp, data, row.id)
694 else:
695 self._update(row.id, kvp, data)
696 return m, n
698 def delete(self, ids):
699 """Delete rows."""
700 raise NotImplementedError
703def time_string_to_float(s):
704 if isinstance(s, (float, int)):
705 return s
706 s = s.replace(' ', '')
707 if '+' in s:
708 return sum(time_string_to_float(x) for x in s.split('+'))
709 if s[-2].isalpha() and s[-1] == 's':
710 s = s[:-1]
711 i = 1
712 while s[i].isdigit():
713 i += 1
714 return seconds[s[i:]] * int(s[:i]) / YEAR
717def float_to_time_string(t, long=False):
718 t *= YEAR
719 for s in 'yMwdhms':
720 x = t / seconds[s]
721 if x > 5:
722 break
723 if long:
724 return f'{x:.3f} {longwords[s]}s'
725 else:
726 return f'{round(x):.0f}{s}'
729def object_to_bytes(obj: Any) -> bytes:
730 """Serialize Python object to bytes."""
731 parts = [b'12345678']
732 obj = o2b(obj, parts)
733 offset = sum(len(part) for part in parts)
734 x = np.array(offset, np.int64)
735 if not np.little_endian:
736 x.byteswap(True)
737 parts[0] = x.tobytes()
738 parts.append(json.dumps(obj, separators=(',', ':')).encode())
739 return b''.join(parts)
742def bytes_to_object(b: bytes) -> Any:
743 """Deserialize bytes to Python object."""
744 x = np.frombuffer(b[:8], np.int64)
745 if not np.little_endian:
746 x = x.byteswap()
747 offset = x.item()
748 obj = json.loads(b[offset:].decode())
749 return b2o(obj, b)
752def o2b(obj: Any, parts: list[bytes]):
753 if isinstance(obj, (int, float, bool, str, type(None))):
754 return obj
755 if isinstance(obj, dict):
756 return {key: o2b(value, parts) for key, value in obj.items()}
757 if isinstance(obj, (list, tuple)):
758 return [o2b(value, parts) for value in obj]
759 if isinstance(obj, np.ndarray):
760 assert obj.dtype != object, (
761 'Cannot convert ndarray of type "object" to bytes.'
762 )
763 offset = sum(len(part) for part in parts)
764 if not np.little_endian:
765 obj = obj.byteswap()
766 parts.append(obj.tobytes())
767 return {'__ndarray__': [obj.shape, obj.dtype.name, offset]}
768 if isinstance(obj, complex):
769 return {'__complex__': [obj.real, obj.imag]}
770 objtype = obj.ase_objtype
771 if objtype:
772 dct = o2b(obj.todict(), parts)
773 dct['__ase_objtype__'] = objtype
774 return dct
775 raise ValueError(
776 'Objects of type {type} not allowed'.format(type=type(obj))
777 )
780def b2o(obj: Any, b: bytes) -> Any:
781 if isinstance(obj, (int, float, bool, str, type(None))):
782 return obj
784 if isinstance(obj, list):
785 return [b2o(value, b) for value in obj]
787 assert isinstance(obj, dict)
789 x = obj.get('__complex__')
790 if x is not None:
791 return complex(*x)
793 x = obj.get('__ndarray__')
794 if x is not None:
795 shape, name, offset = x
796 dtype = np.dtype(name)
797 size = dtype.itemsize * np.prod(shape).astype(int)
798 a = np.frombuffer(b[offset : offset + size], dtype).reshape(shape)
799 if not np.little_endian:
800 a = a.byteswap()
801 return a
803 dct = {key: b2o(value, b) for key, value in obj.items()}
804 objtype = dct.pop('__ase_objtype__', None)
805 if objtype is None:
806 return dct
807 return create_ase_object(objtype, dct)