forked from SUNCAT-Center/CatalysisHubBackend
-
Notifications
You must be signed in to change notification settings - Fork 0
/
models.py
421 lines (357 loc) · 15.6 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
# global imports
import os
import datetime
import sqlalchemy
import sqlalchemy.types
import sqlalchemy.ext.declarative
from sqlalchemy import or_
from sqlalchemy.dialects.postgresql import JSONB, TSVECTOR, BYTEA
from sqlalchemy import String, Float, Integer
from sqlalchemy.types import ARRAY
from sqlalchemy.ext.associationproxy import association_proxy
import graphene.types.json
try:
import io as StringIO
except ImportError:
# Fallback solution for python2.7
import StringIO
import numpy as np
import json
import sqlalchemy as sqla
from sqlalchemy.ext import mutable
from sqlalchemy.ext.hybrid import hybrid_property
# more unstable imports
import ase.atoms
from ase.constraints import dict2constraint
from ase.calculators.singlepoint import SinglePointCalculator
from ase.calculators.calculator import Calculator
import ase.db.sqlite
import ase.db.core
import ase.io
from ase.utils import formula_metal
class JsonEncodedDict(sqla.TypeDecorator):
"""Enables JSON storage by encoding and decoding on the fly."""
impl = sqla.String
def process_bind_param(self, value, dialect):
return json.dumps(value)
def process_result_value(self, value, dialect):
return json.loads(value)
SCHEMA = 'public'
Base = sqlalchemy.ext.declarative.declarative_base()
association_pubsys = \
sqlalchemy.Table('publication_system',
Base.metadata,
sqlalchemy.Column('ase_id', sqlalchemy.String,
sqlalchemy.ForeignKey('{}.systems.unique_id'.format(SCHEMA)),
# if PRODUCTION# else 'main.systems.pub_id'),
primary_key=True),
sqlalchemy.Column('pub_id', sqlalchemy.String,
sqlalchemy.ForeignKey('{}.publication.pub_id'.format(SCHEMA)),
# if PRODUCTION else 'main.publication.pub_id'),
primary_key=True)
)
class Publication(Base):
__tablename__ = 'publication'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
pub_id = sqlalchemy.Column(sqlalchemy.String, unique=True)
title = sqlalchemy.Column(sqlalchemy.String, )
authors = sqlalchemy.Column(JSONB, )
journal = sqlalchemy.Column(sqlalchemy.String, )
volume = sqlalchemy.Column(sqlalchemy.String, )
number = sqlalchemy.Column(sqlalchemy.String, )
pages = sqlalchemy.Column(sqlalchemy.String, )
year = sqlalchemy.Column(sqlalchemy.Integer, )
publisher = sqlalchemy.Column(sqlalchemy.String, )
doi = sqlalchemy.Column(sqlalchemy.String, )
tags = sqlalchemy.Column(JSONB, )
pubtextsearch = sqlalchemy.Column(TSVECTOR, )
reactions = sqlalchemy.orm.relationship("Reaction", backref="publication", uselist=True)
systems = sqlalchemy.orm.relationship("System",
secondary=association_pubsys, uselist=True)
class ReactionSystem(Base):
__tablename__ = 'reaction_system'
__table_args__ = ({'schema': SCHEMA})
name = sqlalchemy.Column(sqlalchemy.String, )
energy_correction = sqlalchemy.Column(sqlalchemy.Float, )
ase_id = sqlalchemy.Column(sqlalchemy.String,
sqlalchemy.ForeignKey('{}.systems.unique_id'.format(SCHEMA)),
primary_key=True)
id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey('{}.reaction.id'.format(SCHEMA)),
primary_key=True)
class Log(Base):
__tablename__ = 'log'
__table_args__ = ({'schema': SCHEMA})
ase_id = sqlalchemy.Column(sqlalchemy.String,
sqlalchemy.ForeignKey('{}.systems.unique_id'.format(SCHEMA)),
primary_key=True)
logfile = sqlalchemy.Column(sqlalchemy.String, )
@hybrid_property
def _logtext(self):
return bytes(self.logfile).decode('utf-8')
class Reaction(Base):
__tablename__ = 'reaction'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
#rowid = sqlalchemy.sqlalchemy.Column(sqlalchemy.Integer)
chemical_composition = sqlalchemy.Column(sqlalchemy.String, )
surface_composition = sqlalchemy.Column(sqlalchemy.String, )
facet = sqlalchemy.Column(sqlalchemy.String, )
sites = sqlalchemy.Column(JSONB, )
coverages = sqlalchemy.Column(JSONB, )
reactants = sqlalchemy.Column(JSONB, )
products = sqlalchemy.Column(JSONB, )
reaction_energy = sqlalchemy.Column(sqlalchemy.Float, )
activation_energy = sqlalchemy.Column(sqlalchemy.Float, )
dft_code = sqlalchemy.Column(sqlalchemy.String, )
dft_functional = sqlalchemy.Column(sqlalchemy.String, )
username = sqlalchemy.Column(sqlalchemy.String, )
pub_id = sqlalchemy.Column(sqlalchemy.String, sqlalchemy.ForeignKey(
'{}.publication.pub_id'.format(SCHEMA)))
textsearch = sqlalchemy.Column(TSVECTOR, )
reaction_systems = sqlalchemy.orm.relationship("ReactionSystem",
#primaryjoin="""ReactionSystem.id==Reaction.id""",
#uselist=False,
backref="reactions")
systems = sqlalchemy.orm.relationship("System",
primaryjoin="""ReactionSystem.id==Reaction.id""",
secondaryjoin="ReactionSystem.ase_id==System.unique_id",
secondary=sqlalchemy.inspect(ReactionSystem).tables[0],
#lazy='joined',
uselist=True,
backref='reactions')
@hybrid_property
def _equation(self):
equation = ''
arrow = 0
for column in (self.reactants, self.products):
if arrow == 1:
equation += ' -> '
arrow += 1
i = 0
for key in sorted(column, key=len, reverse=True):
prefactor = column[key]#[1]
#state = column[key][0]
if 'gas' in key:
key = key.replace('gas', '(g)')
if 'star' in key:
key = key.replace('star', '*')
if not i == 0:
if prefactor > 0:
equation += ' + '
else:
equation += ' - '
prefactor *= -1
if prefactor == 1:
prefactor = ''
equation += str(prefactor) + key
i += 1
return equation
class Information(Base):
__tablename__ = 'information'
__table_args__ = ({'schema': SCHEMA})
name = sqlalchemy.Column(sqlalchemy.String, primary_key=True)
value = sqlalchemy.Column(sqlalchemy.String, )
class System(Base):
__tablename__ = 'systems'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True)
#rowid = sqlalchemy.Column(sqlalchemy.Integer, )
unique_id = sqlalchemy.Column(sqlalchemy.String, )
ctime = sqlalchemy.Column(sqlalchemy.Float, )
mtime = sqlalchemy.Column(sqlalchemy.Float, )
username = sqlalchemy.Column(sqlalchemy.String)
numbers = sqlalchemy.Column(ARRAY(Integer), ) # ARRAY
positions = sqlalchemy.Column(ARRAY(Float), ) # ARRAY
cell = sqlalchemy.Column(ARRAY(Float)) # ARRAY
pbc = sqlalchemy.Column(sqlalchemy.Integer,)
initial_magmoms = sqlalchemy.Column(ARRAY(Float),) # ARRAY,
initial_charges = sqlalchemy.Column(ARRAY(Float),) # ARRAY,
masses = sqlalchemy.Column(ARRAY(Float),) # ARRAY,
tags = sqlalchemy.Column(ARRAY(String), ) # ARRAY
momenta = sqlalchemy.Column(ARRAY(String), ) # ARRAY,
constraints = sqlalchemy.Column(ARRAY(String), ) # ARRAY
calculator = sqlalchemy.Column(sqlalchemy.String, )
calculator_parameters = sqlalchemy.Column(sqlalchemy.String, )
energy = sqlalchemy.Column(sqlalchemy.Float, )
free_energy = sqlalchemy.Column(sqlalchemy.Float, )
forces = sqlalchemy.Column(ARRAY(Float)) # ARRAY
stress = sqlalchemy.Column(ARRAY(Float)) # ARRAY
dipole = sqlalchemy.Column(ARRAY(Float)) # ARRAY
magmoms = sqlalchemy.Column(ARRAY(Float)) # ARRAY
magmom = sqlalchemy.Column(sqlalchemy.Float, )
charges = sqlalchemy.Column(ARRAY(Float)) # ARRAY
key_value_pairs = sqlalchemy.Column(JSONB, )
data = sqlalchemy.Column(JSONB,)
natoms = sqlalchemy.Column(sqlalchemy.Integer,)
fmax = sqlalchemy.Column(sqlalchemy.Float, )
smax = sqlalchemy.Column(sqlalchemy.Float, )
volume = sqlalchemy.Column(sqlalchemy.Float, )
mass = sqlalchemy.Column(sqlalchemy.Float, )
charge = sqlalchemy.Column(sqlalchemy.Float, )
keys = sqlalchemy.orm.relationship("Key", backref="systems", uselist=True)
species = sqlalchemy.orm.relationship(
"Species", backref="systems", uselist=True)
text_keys = sqlalchemy.orm.relationship(
"TextKeyValue", backref="systems", uselist=True)
number_keys = sqlalchemy.orm.relationship(
"NumberKeyValue", backref="systems", uselist=True)
reaction_systems= sqlalchemy.orm.relationship(
"ReactionSystem",
backref="systems",
uselist=True)
log = sqlalchemy.orm.relationship(
"Log",
backref="systems",
uselist=True)
#reaction = sqlalchemy.orm.relationship("ReactionSystems", backref='systems', uselist=True)
publication = sqlalchemy.orm.relationship("Publication",
secondary=association_pubsys,
uselist=True
)
###################################
# GENERAL ATOMS FORMATS
###################################
def _toatoms(self, include_results=False):
if not include_results:
return ase.atoms.Atoms(
self.numbers,
self.positions,
cell=self.cell,
pbc=(self.pbc & np.array([1, 2, 4])).astype(bool),
)
if self.constraints:
constraints = json.loads(self.constraints)
if len(constraints[0]['kwargs']['indices']) > 0:
constraints = [dict2constraint(d) for d in constraints]
else:
constraints = None
atoms = ase.atoms.Atoms(self.numbers,
self.positions,
cell=self.cell,
pbc=(self.pbc & np.array([1, 2, 4])).astype(bool),
magmoms=self.initial_magmoms,
charges=self.initial_charges,
tags=self.tags,
masses=self.masses,
momenta=self.momenta,
constraint=constraints)
atoms.info = {}
atoms.info['unique_id'] = self.unique_id
atoms.info['key_value_pairs'] = self.key_value_pairs
data = self.data
if data:
atoms.info['data'] = data
if not self.calculator == "unknown":
params = self.calculator_parameters
atoms.calc = Calculator(self.calculator, **params)
atoms.calc.name = self.calculator
else:
all_properties = ['energy', 'forces', 'stress', 'dipole',
'charges', 'magmom', 'magmoms', 'free_energy']
results = {}
for prop in all_properties:
result = getattr(self, prop, None)
if result is not None:
results[prop] = result
if results:
atoms.calc = SinglePointCalculator(atoms, **results)
atoms.calc.name = getattr(self, 'calculator', 'unknown')
return atoms
@hybrid_property
def _formula(self):
return formula_metal(self.numbers)
@hybrid_property
def _cifdata(self):
mem_file = StringIO.StringIO()
ase.io.write(mem_file, self._toatoms(), 'cif')
return mem_file.getvalue()
@hybrid_property
def _trajdata(self):
mem_file = StringIO.StringIO()
ase.io.write(mem_file, self._toatoms(include_results=True), 'json')
return mem_file.getvalue()
@hybrid_property
def _pbc(self):
return (self.pbc & np.array([1, 2, 4])).astype(bool).tolist()
@hybrid_property
def _ctime(self):
return (
datetime.datetime(2000, 1, 1, 0, 0)
+ datetime.timedelta(
seconds=int(round(self.ctime * ase.db.core.seconds['y'], 0))
)
).strftime('%c')
@hybrid_property
def _mtime(self):
return (
datetime.datetime(2000, 1, 1, 0, 0)
+ datetime.timedelta(
seconds=int(round(self.mtime * ase.db.core.seconds['y'], 0))
)
).strftime('%c')
@hybrid_property
def _adsorbate(self):
return self.key_value_pairs.get('adsorbate', '')
@hybrid_property
def _reaction(self):
return self.key_value_pairs.get('reaction', '')
@hybrid_property
def _username(self):
return self.key_value_pairs.get('username', '')
@hybrid_property
def _substrate(self):
return self.key_value_pairs.get('substrate', '')
@hybrid_property
def _facet(self):
return self.key_value_pairs.get('facet', '').strip("()")
@hybrid_property
def _dft_code(self):
return self.key_value_pairs.get('dft_code', '')
@hybrid_property
def _dft_functional(self):
return self.key_value_pairs.get('dft_functional', '')
class Species(Base):
__tablename__ = 'species'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey('{}.systems.id'.format(SCHEMA)),
primary_key=True)
z = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True,)
n = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True,)
class Key(Base):
__tablename__ = 'keys'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey('{}.systems.id'.format(SCHEMA)),
primary_key=True)
key = sqlalchemy.Column(sqlalchemy.String, primary_key=True)
class NumberKeyValue(Base):
__tablename__ = 'number_key_values'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey('{}.systems.id'.format(SCHEMA)),
primary_key=True)
key = sqlalchemy.Column(sqlalchemy.String, primary_key=True)
value = sqlalchemy.Column(sqlalchemy.Float,)
class TextKeyValue(Base):
__tablename__ = 'text_key_values'
__table_args__ = ({'schema': SCHEMA})
id = sqlalchemy.Column(sqlalchemy.Integer,
sqlalchemy.ForeignKey('{}.systems.id'.format(SCHEMA)),
primary_key=True)
key = sqlalchemy.Column(sqlalchemy.String, primary_key=True)
value = sqlalchemy.Column(sqlalchemy.String,)
def hybrid_prop_parameters(key):
h_parameters = {'Formula': ['id', 'numbers'],
'Equation': ['id', 'reactants', 'products'],
'Cifdata': ['id', 'numbers', 'positions', 'cell', 'pbc'],
'Ctime': ['id', 'ctime'],
'Mtime': ['id', 'mtime'],
'Pbc': ['id', 'pbc'],
'Trajdata': ['all'],
'Logtext': ['logfile']}
if key not in h_parameters:
return ['id', 'key_value_pairs']
return h_parameters[key]