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

1# fmt: off 

2 

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

4 

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

6""" 

7import json 

8 

9import numpy as np 

10 

11from ase import Atoms 

12from ase.cell import Cell 

13 

14 

15# contract and lower case string 

16def contract(dictionary): 

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

18 dictionary} 

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