Coverage for /builds/ase/ase/ase/io/cjson.py: 100.00%
29 statements
« prev ^ index » next coverage.py v7.5.3, created at 2025-08-02 00:12 +0000
« prev ^ index » next coverage.py v7.5.3, created at 2025-08-02 00:12 +0000
1# fmt: off
3"""Module to read atoms in chemical json file format.
5https://wiki.openchemistry.org/Chemical_JSON
6"""
7import json
9import numpy as np
11from ase import Atoms
12from ase.cell import Cell
15# contract and lower case string
16def contract(dictionary):
17 dcopy = {key.replace(' ', '').lower(): dictionary[key] for key in
18 dictionary}
19 return dcopy
22def read_cjson(fileobj):
23 """Read a Chemical Json file as written by avogadro2 (>=1.93.0)
25 See https://wiki.openchemistry.org/Chemical_JSON
26 """
27 data = contract(json.load(fileobj))
28 atoms = Atoms()
29 datoms = data['atoms']
31 atoms = Atoms(datoms['elements']['number'])
33 if 'unitcell' in data:
34 cell = data['unitcell']
35 a = cell['a']
36 b = cell['b']
37 c = cell['c']
38 alpha = cell['alpha']
39 beta = cell['beta']
40 gamma = cell['gamma']
41 atoms.cell = Cell.fromcellpar([a, b, c, alpha, beta, gamma])
42 atoms.pbc = True
44 coords = contract(datoms['coords'])
45 if '3d' in coords:
46 positions = np.array(coords['3d']).reshape(len(atoms), 3)
47 atoms.set_positions(positions)
48 else:
49 positions = np.array(coords['3dfractional']).reshape(len(atoms), 3)
50 atoms.set_scaled_positions(positions)
52 yield atoms