forked from pycalphad/pycalphad
-
Notifications
You must be signed in to change notification settings - Fork 2
/
variables.py
402 lines (338 loc) · 14.2 KB
/
variables.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
#pylint: disable=C0103,R0903,W0232
"""
Classes and constants for representing thermodynamic variables.
"""
import sys
from symengine import Float, Symbol
from pycalphad.io.grammar import parse_chemical_formula
class Species(object):
"""
A chemical species.
Attributes
----------
name : string
Name of the specie
constituents : dict
Dictionary of {element: quantity} where the element is a string and the quantity a float.
charge : int
Integer charge. Can be positive or negative.
"""
def __new__(cls, name, constituents=None, charge=0):
if constituents is not None:
new_self = object.__new__(cls)
new_self.name = name
new_self.constituents = constituents
new_self.charge = charge
return new_self
else:
arg = name
# if a Species is passed in, return it
if arg.__class__ == cls:
return arg
new_self = object.__new__(cls)
if arg == '*':
new_self = object.__new__(cls)
new_self.name = '*'
new_self.constituents = dict()
new_self.charge = 0
return new_self
if arg is None:
new_self = object.__new__(cls)
new_self.name = ''
new_self.constituents = dict()
new_self.charge = 0
return new_self
if isinstance(arg, str):
parse_list = parse_chemical_formula(arg.upper())
else:
parse_list = arg
new_self.name = name
new_self.charge = parse_list[1]
parse_list = parse_list[0]
new_self.constituents = dict(parse_list)
return new_self
def __getnewargs__(self):
return self.name, self.constituents, self.charge
def __eq__(self, other):
"""Two species are the same if their names and constituents are the same."""
if isinstance(other, self.__class__):
return (self.name == other.name) and (self.constituents == other.constituents)
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __lt__(self, other):
return self.name < other.name
def __str__(self):
return self.name
@property
def escaped_name(self):
"Name safe to embed in the variable name of complex arithmetic expressions."
return str(self).replace('-', '_NEG').replace('+', '_POS').replace('/', 'Z')
@property
def number_of_atoms(self):
"Number of atoms per formula unit. Vacancies do not count as atoms."
return sum(value for key, value in self.constituents.items() if key != 'VA')
@property
def weight(self):
"Number of grams per formula unit."
return NotImplementedError
def __repr__(self):
if self.name == '*':
return str(self.__class__.__name__)+'(\'*\')'
if self.name == '':
return str(self.__class__.__name__)+"(None)"
species_constituents = ''.join(
['{}{}'.format(el, val) for el, val in sorted(self.constituents.items(), key=lambda t: t[0])])
if self.charge == 0:
repr_str = "(\'{0}\', \'{1}\')"
else:
repr_str = "(\'{0}\', \'{1}\', charge={2})"
return str(self.__class__.__name__)+repr_str.format(self.name.upper(), species_constituents, self.charge)
def __hash__(self):
return hash(self.name)
class StateVariable(Symbol):
"""
State variables are symbols with built-in assumptions of being real.
"""
def __init__(self, name):
super().__init__(name.upper())
def __reduce__(self):
return self.__class__, (self.name,)
def __eq__(self, other):
"""Two species are the same if their names are the same."""
if isinstance(other, self.__class__):
return self.name == other.name
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash((self.__class__, self.name))
class SiteFraction(StateVariable):
"""
Site fractions are symbols with built-in assumptions of being real
and nonnegative. The constructor handles formatting of the name.
"""
def __init__(self, phase_name, subl_index, species): #pylint: disable=W0221
varname = phase_name + str(subl_index) + Species(species).escaped_name
#pylint: disable=E1121
super().__init__(varname)
self.phase_name = phase_name.upper()
self.sublattice_index = subl_index
self.species = Species(species)
def __reduce__(self):
return self.__class__, (self.phase_name, self.sublattice_index, self.species)
def __eq__(self, other):
"""Two species are the same if their names and constituents are the same."""
if isinstance(other, self.__class__):
return self.name == other.name
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash((self.phase_name, self.sublattice_index, self.species))
def _latex(self, printer=None):
"LaTeX representation."
#pylint: disable=E1101
return 'y^{\mathrm{'+self.phase_name.replace('_', '-') + \
'}}_{'+str(self.sublattice_index)+',\mathrm{'+self.species.escaped_name+'}}'
def __str__(self):
"String representation."
#pylint: disable=E1101
return 'Y(%s,%d,%s)' % \
(self.phase_name, self.sublattice_index, self.species.escaped_name)
class PhaseFraction(StateVariable):
"""
Phase fractions are symbols with built-in assumptions of being real
and nonnegative. The constructor handles formatting of the name.
"""
def __init__(self, phase_name): #pylint: disable=W0221
varname = 'NP_' + str(phase_name)
super().__init__(varname)
self.phase_name = phase_name.upper()
def _latex(self, printer=None):
"LaTeX representation."
#pylint: disable=E1101
return 'f^{'+self.phase_name.replace('_', '-')
class MoleFraction(StateVariable):
"""
MoleFractions are symbols with built-in assumptions of being real
and nonnegative.
"""
def __init__(self, *args): #pylint: disable=W0221
varname = None
phase_name = None
species = None
if len(args) == 1:
# this is an overall composition variable
species = Species(args[0])
varname = 'X_' + species.escaped_name.upper()
elif len(args) == 2:
# this is a phase-specific composition variable
phase_name = args[0].upper()
species = Species(args[1])
varname = 'X_' + phase_name + '_' + species.escaped_name.upper()
else:
# not defined
raise ValueError('MoleFraction not defined for args: '+args)
#pylint: disable=E1121
super().__init__(varname)
self.phase_name = phase_name
self.species = species
def __reduce__(self):
if self.phase_name is None:
return self.__class__, (self.species,)
else:
return self.__class__, (self.phase_name, self.species,)
def _latex(self, printer=None):
"LaTeX representation."
#pylint: disable=E1101
if self.phase_name:
return 'x^{'+self.phase_name.replace('_', '-') + \
'}_{'+self.species.escaped_name+'}'
else:
return 'x_{'+self.species.escaped_name+'}'
class MassFraction(StateVariable):
"""
Weight fractions are symbols with built-in assumptions of being real and nonnegative.
"""
def __init__(self, *args): # pylint: disable=W0221
varname = None
phase_name = None
species = None
if len(args) == 1:
# this is an overall composition variable
species = Species(args[0])
varname = 'W_' + species.escaped_name.upper()
elif len(args) == 2:
# this is a phase-specific composition variable
phase_name = args[0].upper()
species = Species(args[1])
varname = 'W_' + phase_name + '_' + species.escaped_name.upper()
else:
# not defined
raise ValueError('Weight fraction not defined for args: '+args)
# pylint: disable=E1121
super().__init__(varname)
self.phase_name = phase_name
self.species = species
def __reduce__(self):
if self.phase_name is None:
return self.__class__, (self.species,)
else:
return self.__class__, (self.phase_name, self.species,)
def _latex(self, printer=None):
"LaTeX representation."
# pylint: disable=E1101
if self.phase_name:
return 'w^{'+self.phase_name.replace('_', '-') + \
'}_{'+self.species.escaped_name+'}'
else:
return 'w_{'+self.species.escaped_name+'}'
def get_mole_fractions(mass_fractions, dependent_species, pure_element_mass_dict):
"""
Return a mapping of MoleFractions for a point composition.
Parameters
----------
mass_fractions : Mapping[MassFraction, float]
dependent_species : Union[Species, str]
Dependent species not appearing in the independent mass fractions.
pure_element_mass_dict : Union[Mapping[str, float], pycalphad.Database]
Either a mapping from pure elements to their mass, or a Database from
which they can be retrieved.
Returns
-------
Dict[MoleFraction, float]
"""
if not all(isinstance(mf, MassFraction) for mf in mass_fractions):
from pycalphad.core.errors import ConditionError
raise ConditionError("All mass_fractions must be instances of MassFraction (v.W). Got ", mass_fractions)
dependent_species = Species(dependent_species)
species_mass_fracs = {mf.species: frac for mf, frac in mass_fractions.items()}
all_species = set(species_mass_fracs.keys()) | {dependent_species}
# Check if the mass dict is a Database, which is the source of the mass_dict
from pycalphad import Database # Imported here to avoid circular import
if isinstance(pure_element_mass_dict, Database):
pure_element_mass_dict = {el: refdict['mass'] for el, refdict in pure_element_mass_dict.refstates.items()}
species_mass_dict = {}
for species in all_species:
species_mass_dict[species] = sum([pure_element_mass_dict[pe]*natoms for pe, natoms in species.constituents.items()])
# add dependent species
species_mass_fracs[dependent_species] = 1 - sum(species_mass_fracs.values())
# compute moles
species_moles = {species: mass_frac/species_mass_dict[species] for species, mass_frac in species_mass_fracs.items()}
# normalize
total_moles = sum(species_moles.values())
species_mole_fractions = {species: moles/total_moles for species, moles in species_moles.items()}
# remove dependent species
species_mole_fractions.pop(dependent_species)
return {MoleFraction(species): fraction for species, fraction in species_mole_fractions.items()}
def get_mass_fractions(mole_fractions, dependent_species, pure_element_mass_dict):
"""
Return a mapping of MassFractions for a point composition.
Parameters
----------
mass_fractions : Mapping[MoleFraction, float]
dependent_species : Union[Species, str]
Dependent species not appearing in the independent mass fractions.
pure_element_mass_dict : Union[Mapping[str, float], pycalphad.Database]
Either a mapping from pure elements to their mass, or a Database from
which they can be retrieved.
Returns
-------
Dict[MassFraction, float]
"""
if not all(isinstance(mf, MoleFraction) for mf in mole_fractions):
from pycalphad.core.errors import ConditionError
raise ConditionError("All mole_fractions must be instances of MoleFraction (v.X). Got ", mole_fractions)
dependent_species = Species(dependent_species)
species_mole_fracs = {mf.species: frac for mf, frac in mole_fractions.items()}
all_species = set(species_mole_fracs.keys()) | {dependent_species}
# Check if the mass dict is a Database, which is the source of the mass_dict
from pycalphad import Database # Imported here to avoid circular import
if isinstance(pure_element_mass_dict, Database):
pure_element_mass_dict = {el: refdict['mass'] for el, refdict in pure_element_mass_dict.refstates.items()}
species_mass_dict = {}
for species in all_species:
species_mass_dict[species] = sum([pure_element_mass_dict[pe]*natoms for pe, natoms in species.constituents.items()])
# add dependent species
species_mole_fracs[dependent_species] = 1 - sum(species_mole_fracs.values())
# compute mass
species_mass = {species: mole_frac*species_mass_dict[species] for species, mole_frac in species_mole_fracs.items()}
# normalize
total_mass = sum(species_mass.values())
species_mass_fractions = {species: mass/total_mass for species, mass in species_mass.items()}
# remove dependent species
species_mass_fractions.pop(dependent_species)
return {MassFraction(species): fraction for species, fraction in species_mass_fractions.items()}
class ChemicalPotential(StateVariable):
"""
Chemical potentials are symbols with built-in assumptions of being real.
"""
def __init__(self, species):
species = Species(species)
varname = 'MU_' + species.escaped_name.upper()
super().__init__(varname)
self.species = species
def _latex(self, printer=None):
"LaTeX representation."
return '\mu_{'+self.species.escaped_name+'}'
def __str__(self):
"String representation."
return 'MU_%s' % self.species.name
temperature = T = StateVariable('T')
entropy = S = StateVariable('S')
pressure = P = StateVariable('P')
volume = V = StateVariable('V')
moles = N = StateVariable('N')
site_fraction = Y = SiteFraction
X = MoleFraction
W = MassFraction
MU = ChemicalPotential
NP = PhaseFraction
si_gas_constant = R = Float(8.3145) # ideal gas constant
CONDITIONS_REQUIRING_HESSIANS = {ChemicalPotential, PhaseFraction}
# When loading databases, these symbols should be replaced by their StateVariable counter-parts defined above
supported_variables_in_databases = {Symbol('T'): T, Symbol('P'): P, Symbol('R'): R}