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

31 statements  

« prev     ^ index     » next       coverage.py v7.2.7, created at 2023-12-10 11:04 +0000

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

2 

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

4""" 

5import json 

6 

7import numpy as np 

8 

9from ase import Atoms 

10from ase.cell import Cell 

11 

12 

13# contract and lower case string 

14def contract(dictionary): 

15 dcopy = {} 

16 for key in dictionary: 

17 dcopy[key.replace(' ', '').lower()] = dictionary[key] 

18 return dcopy 

19 

20 

21def read_cjson(fileobj): 

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

23 

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

25 """ 

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

27 atoms = Atoms() 

28 datoms = data['atoms'] 

29 

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

31 

32 if 'unitcell' in data: 

33 cell = data['unitcell'] 

34 a = cell['a'] 

35 b = cell['b'] 

36 c = cell['c'] 

37 alpha = cell['alpha'] 

38 beta = cell['beta'] 

39 gamma = cell['gamma'] 

40 atoms.cell = Cell.fromcellpar([a, b, c, alpha, beta, gamma]) 

41 atoms.pbc = True 

42 

43 coords = contract(datoms['coords']) 

44 if '3d' in coords: 

45 positions = np.array(coords['3d']).reshape(len(atoms), 3) 

46 atoms.set_positions(positions) 

47 else: 

48 positions = np.array(coords['3dfractional']).reshape(len(atoms), 3) 

49 atoms.set_scaled_positions(positions) 

50 

51 yield atoms