Coverage for ase/db/jsondb.py: 91.43%

175 statements  

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

1import os 

2import sys 

3from contextlib import ExitStack 

4 

5import numpy as np 

6 

7from ase.db.core import Database, lock, now, ops 

8from ase.db.row import AtomsRow 

9from ase.io.jsonio import decode, encode 

10from ase.parallel import parallel_function, world 

11 

12 

13class JSONDatabase(Database): 

14 def __enter__(self): 

15 return self 

16 

17 def __exit__(self, exc_type, exc_value, tb): 

18 pass 

19 

20 def _write(self, atoms, key_value_pairs, data, id): 

21 Database._write(self, atoms, key_value_pairs, data) 

22 

23 bigdct = {} 

24 ids = [] 

25 nextid = 1 

26 

27 if isinstance(self.filename, str) and os.path.isfile(self.filename): 

28 try: 

29 bigdct, ids, nextid = self._read_json() 

30 except (SyntaxError, ValueError): 

31 pass 

32 

33 mtime = now() 

34 

35 if isinstance(atoms, AtomsRow): 

36 row = atoms 

37 else: 

38 row = AtomsRow(atoms) 

39 row.ctime = mtime 

40 row.user = os.getenv('USER') 

41 

42 dct = {} 

43 for key in row.__dict__: 

44 if key[0] == '_' or key in row._keys or key == 'id': 

45 continue 

46 dct[key] = row[key] 

47 

48 dct['mtime'] = mtime 

49 

50 if key_value_pairs: 

51 dct['key_value_pairs'] = key_value_pairs 

52 

53 if data: 

54 dct['data'] = data 

55 

56 constraints = row.get('constraints') 

57 if constraints: 

58 dct['constraints'] = constraints 

59 

60 if id is None: 

61 id = nextid 

62 ids.append(id) 

63 nextid += 1 

64 else: 

65 assert id in bigdct 

66 

67 bigdct[id] = dct 

68 self._write_json(bigdct, ids, nextid) 

69 return id 

70 

71 def _read_json(self): 

72 if isinstance(self.filename, str): 

73 with open(self.filename) as fd: 

74 bigdct = decode(fd.read()) 

75 else: 

76 bigdct = decode(self.filename.read()) 

77 if self.filename is not sys.stdin: 

78 self.filename.seek(0) 

79 

80 if not isinstance(bigdct, dict) or ( 

81 'ids' not in bigdct and 1 not in bigdct 

82 ): 

83 from ase.io.formats import UnknownFileTypeError 

84 

85 raise UnknownFileTypeError('Does not resemble ASE JSON database') 

86 

87 ids = bigdct.get('ids') 

88 if ids is None: 

89 # Allow for missing "ids" and "nextid": 

90 assert 1 in bigdct 

91 return bigdct, [1], 2 

92 if not isinstance(ids, list): 

93 ids = ids.tolist() 

94 return bigdct, ids, bigdct['nextid'] 

95 

96 def _write_json(self, bigdct, ids, nextid): 

97 if world.rank > 0: 

98 return 

99 

100 with ExitStack() as stack: 

101 if isinstance(self.filename, str): 

102 fd = stack.enter_context(open(self.filename, 'w')) 

103 else: 

104 fd = self.filename 

105 print('{', end='', file=fd) 

106 for id in ids: 

107 dct = bigdct[id] 

108 txt = ',\n '.join( 

109 f'"{key}": {encode(dct[key])}' for key in sorted(dct.keys()) 

110 ) 

111 print(f'"{id}": {{\n {txt}}},', file=fd) 

112 if self._metadata is not None: 

113 print(f'"metadata": {encode(self.metadata)},', file=fd) 

114 print(f'"ids": {ids},', file=fd) 

115 print(f'"nextid": {nextid}}}', file=fd) 

116 

117 @parallel_function 

118 @lock 

119 def delete(self, ids): 

120 bigdct, myids, nextid = self._read_json() 

121 for id in ids: 

122 del bigdct[id] 

123 myids.remove(id) 

124 self._write_json(bigdct, myids, nextid) 

125 

126 def _get_row(self, id): 

127 bigdct, ids, _nextid = self._read_json() 

128 if id is None: 

129 assert len(ids) == 1 

130 id = ids[0] 

131 dct = bigdct[id] 

132 dct['id'] = id 

133 return AtomsRow(dct) 

134 

135 def _select( 

136 self, 

137 keys, 

138 cmps, 

139 explain=False, 

140 verbosity=0, 

141 limit=None, 

142 offset=0, 

143 sort=None, 

144 include_data=True, 

145 columns='all', 

146 ): 

147 if explain: 

148 yield {'explain': (0, 0, 0, 'scan table')} 

149 return 

150 

151 if sort: 

152 if sort[0] == '-': 

153 reverse = True 

154 sort = sort[1:] 

155 else: 

156 reverse = False 

157 

158 def f(row): 

159 return row.get(sort, missing) 

160 

161 rows = [] 

162 missing = [] 

163 for row in self._select(keys, cmps): 

164 key = row.get(sort) 

165 if key is None: 

166 missing.append((0, row)) 

167 else: 

168 rows.append((key, row)) 

169 

170 rows.sort(reverse=reverse, key=lambda x: x[0]) 

171 rows += missing 

172 

173 if limit: 

174 rows = rows[offset : offset + limit] 

175 for key, row in rows: 

176 yield row 

177 return 

178 

179 try: 

180 bigdct, ids, _nextid = self._read_json() 

181 except OSError: 

182 return 

183 

184 if not limit: 

185 limit = -offset - 1 

186 

187 cmps = [(key, ops[op], val) for key, op, val in cmps] 

188 n = 0 

189 for id in ids: 

190 if n - offset == limit: 

191 return 

192 dct = bigdct[id] 

193 if not include_data: 

194 dct.pop('data', None) 

195 row = AtomsRow(dct) 

196 row.id = id 

197 for key in keys: 

198 if key not in row: 

199 break 

200 else: 

201 for key, op, val in cmps: 

202 if isinstance(key, int): 

203 value = np.equal(row.numbers, key).sum() 

204 else: 

205 value = row.get(key) 

206 if key == 'pbc': 

207 assert op in [ops['='], ops['!=']] 

208 value = ''.join('FT'[x] for x in value) 

209 if value is None or not op(value, val): 

210 break 

211 else: 

212 if n >= offset: 

213 yield row 

214 n += 1 

215 

216 @property 

217 def metadata(self): 

218 if self._metadata is None: 

219 bigdct, _myids, _nextid = self._read_json() 

220 self._metadata = bigdct.get('metadata', {}) 

221 return self._metadata.copy() 

222 

223 @metadata.setter 

224 def metadata(self, dct): 

225 bigdct, ids, nextid = self._read_json() 

226 self._metadata = dct 

227 self._write_json(bigdct, ids, nextid) 

228 

229 def get_all_key_names(self): 

230 keys = set() 

231 bigdct, ids, _nextid = self._read_json() 

232 for id in ids: 

233 dct = bigdct[id] 

234 kvp = dct.get('key_value_pairs') 

235 if kvp: 

236 keys.update(kvp) 

237 return keys