Coverage for ase/io/cjson.py: 100.00%

29 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1"""Module to read atoms in chemical json file format. 

2 

3https://wiki.openchemistry.org/Chemical_JSON 

4""" 

5 

6import json 

7 

8import numpy as np 

9 

10from ase import Atoms 

11from ase.cell import Cell 

12 

13 

14# contract and lower case string 

15def contract(dictionary): 

16 dcopy = { 

17 key.replace(' ', '').lower(): dictionary[key] for key in dictionary 

18 } 

19 return dcopy 

20 

21 

22def read_cjson(fileobj): 

23 """Read a Chemical Json file as written by avogadro2 (>=1.93.0) 

24 

25 See https://wiki.openchemistry.org/Chemical_JSON 

26 """ 

27 data = contract(json.load(fileobj)) 

28 atoms = Atoms() 

29 datoms = data['atoms'] 

30 

31 atoms = Atoms(datoms['elements']['number']) 

32 

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 

43 

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) 

51 

52 yield atoms