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

1import functools 

2import json 

3import numbers 

4import operator 

5import os 

6import re 

7import warnings 

8from time import time 

9from typing import Any 

10 

11import numpy as np 

12 

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 

21 

22T2000 = 946681200.0 # January 1. 2000 

23YEAR = 31557600.0 # 365.25 days 

24 

25 

26@functools.total_ordering 

27class KeyDescription: 

28 _subscript = re.compile(r'`(.)_(.)`') 

29 _superscript = re.compile(r'`(.*)\^\{?(.*?)\}?`') 

30 

31 def __init__(self, key, shortdesc=None, longdesc=None, unit=''): 

32 self.key = key 

33 

34 if shortdesc is None: 

35 shortdesc = key 

36 

37 if longdesc is None: 

38 longdesc = shortdesc 

39 

40 self.shortdesc = shortdesc 

41 self.longdesc = longdesc 

42 

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('}', '') 

48 

49 self.unit = unit 

50 

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 ) 

57 

58 # The templates like to sort key descriptions by shortdesc. 

59 def __eq__(self, other): 

60 return self.shortdesc == getattr(other, 'shortdesc', None) 

61 

62 def __lt__(self, other): 

63 return self.shortdesc < getattr(other, 'shortdesc', self.shortdesc) 

64 

65 

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 } 

93 

94 

95def now(): 

96 """Return time since January 1. 2000 in years.""" 

97 return (time() - T2000) / YEAR 

98 

99 

100seconds = { 

101 's': 1, 

102 'm': 60, 

103 'h': 3600, 

104 'd': 86400, 

105 'w': 604800, 

106 'M': 2629800, 

107 'y': YEAR, 

108} 

109 

110longwords = { 

111 's': 'second', 

112 'm': 'minute', 

113 'h': 'hour', 

114 'd': 'day', 

115 'w': 'week', 

116 'M': 'month', 

117 'y': 'year', 

118} 

119 

120ops = { 

121 '<': operator.lt, 

122 '<=': operator.le, 

123 '=': operator.eq, 

124 '>=': operator.ge, 

125 '>': operator.gt, 

126 '!=': operator.ne, 

127} 

128 

129invop = {'<': '>=', '<=': '>', '>=': '<', '>': '<=', '=': '!=', '!=': '='} 

130 

131word = re.compile('[_a-zA-Z][_0-9a-zA-Z]*$') 

132 

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) 

156 

157numeric_keys = {'id', 'energy', 'magmom', 'charge', 'natoms'} 

158 

159 

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 

166 

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 ) 

195 

196 

197def str_represents(value, t=int): 

198 new_value = convert_str_to_int_float_bool_or_str(value) 

199 return isinstance(new_value, t) 

200 

201 

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. 

212 

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 """ 

227 

228 if isinstance(name, PurePath): 

229 name = str(name) 

230 

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') 

244 

245 if type is None: 

246 return Database(**db_kwargs) 

247 

248 if not append and world.rank == 0: 

249 if isinstance(name, str) and os.path.isfile(name): 

250 os.remove(name) 

251 

252 if type not in ['postgresql', 'mysql'] and isinstance(name, str): 

253 name = os.path.abspath(name) 

254 

255 if type == 'json': 

256 from ase.db.jsondb import JSONDatabase 

257 

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 

263 

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 

269 

270 return PostgreSQLDatabase(name, **db_kwargs) 

271 

272 if type == 'mysql': 

273 from ase_db_backends.mysql import MySQLDatabase 

274 

275 return MySQLDatabase(name, **db_kwargs) 

276 

277 if type == 'aselmdb': 

278 from ase_db_backends.aselmdb import LMDBDatabase 

279 

280 return LMDBDatabase(name, **db_kwargs) 

281 

282 raise ValueError('Unknown database type: ' + type) 

283 

284 

285def lock(method): 

286 """Decorator for using a lock-file.""" 

287 

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) 

295 

296 return new_method 

297 

298 

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 

309 

310 

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)) 

353 

354 cmps = [] 

355 for key, value in kwargs.items(): 

356 comparisons.append((key, '=', value)) 

357 

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)) 

383 

384 return keys, cmps 

385 

386 

387class Database: 

388 """Base class for all databases.""" 

389 

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. 

398 

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 

412 

413 # Decription of columns and other stuff: 

414 self._metadata = None 

415 

416 @property 

417 def metadata(self) -> dict[str, Any]: 

418 raise NotImplementedError 

419 

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. 

424 

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. 

435 

436 Key-value pairs can also be set using keyword arguments:: 

437 

438 connection.write(atoms, name='ABC', frequency=42.0) 

439 

440 Returns integer id of the new row. 

441 """ 

442 

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() 

449 

450 kvp = dict(key_value_pairs) # modify a copy 

451 kvp.update(kwargs) 

452 

453 id = self._write(atoms, kvp, data, id) 

454 return id 

455 

456 def _write(self, atoms, key_value_pairs, data, id=None): 

457 check(key_value_pairs) 

458 return 1 

459 

460 @parallel_function 

461 @lock 

462 def reserve(self, **key_value_pairs): 

463 """Write empty row if not already present. 

464 

465 Usage:: 

466 

467 id = conn.reserve(key1=value1, key2=value2, ...) 

468 

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 """ 

473 

474 for _ in self._select( 

475 [], [(key, '=', value) for key, value in key_value_pairs.items()] 

476 ): 

477 return None 

478 

479 atoms = Atoms() 

480 

481 calc_name = key_value_pairs.pop('calculator', None) 

482 

483 if calc_name: 

484 # Allow use of calculator key 

485 assert calc_name.lower() == calc_name 

486 

487 # Fake calculator class: 

488 class Fake: 

489 name = calc_name 

490 

491 def todict(self): 

492 return {} 

493 

494 def check_state(self, atoms): 

495 return ['positions'] 

496 

497 atoms.calc = Fake() 

498 

499 id = self._write(atoms, key_value_pairs, {}, None) 

500 

501 return id 

502 

503 def __delitem__(self, id): 

504 self.delete([id]) 

505 

506 def get_atoms( 

507 self, selection=None, add_additional_information=False, **kwargs 

508 ): 

509 """Get Atoms object. 

510 

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. 

515 

516 In addition, one can use keyword arguments to select specific 

517 key-value pairs. 

518 """ 

519 

520 row = self.get(selection, **kwargs) 

521 return row.toatoms(add_additional_information) 

522 

523 def __getitem__(self, selection): 

524 return self.get(selection) 

525 

526 def get(self, selection=None, **kwargs): 

527 """Select a single row and return it as a dictionary. 

528 

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] 

537 

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. 

553 

554 Return AtomsRow iterator with results. Selection is done 

555 using key-value pairs and the special keys: 

556 

557 formula, age, user, calculator, natoms, energy, magmom 

558 and/or charge. 

559 

560 selection: int, str or list 

561 Can be: 

562 

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 """ 

588 

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' 

596 

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 

611 

612 def count(self, selection=None, **kwargs): 

613 """Count rows. 

614 

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 

622 

623 def __len__(self): 

624 return self.count() 

625 

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). 

632 

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. 

641 

642 Use keyword arguments to add new key-value pairs. 

643 

644 Returns number of key-value pairs added and removed. 

645 """ 

646 

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') 

660 

661 check(add_key_value_pairs) 

662 

663 row = self._get_row(id) 

664 kvp = row.key_value_pairs 

665 

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) 

673 

674 moredata = data 

675 data = row.get('data', {}) 

676 if moredata: 

677 data.update(moredata) 

678 if not data: 

679 data = None 

680 

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 

691 

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 

697 

698 def delete(self, ids): 

699 """Delete rows.""" 

700 raise NotImplementedError 

701 

702 

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 

715 

716 

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}' 

727 

728 

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) 

740 

741 

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) 

750 

751 

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 ) 

778 

779 

780def b2o(obj: Any, b: bytes) -> Any: 

781 if isinstance(obj, (int, float, bool, str, type(None))): 

782 return obj 

783 

784 if isinstance(obj, list): 

785 return [b2o(value, b) for value in obj] 

786 

787 assert isinstance(obj, dict) 

788 

789 x = obj.get('__complex__') 

790 if x is not None: 

791 return complex(*x) 

792 

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 

802 

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)