API reference
chemsynthcalc
Python package for calculating the masses of substances required for chemical synthesis directly from the reaction string. It includes solutions for all intermediate steps, including chemical formula parsing, molar mass calculation and reaction balancing with different matrix methods.
Example use
Let's say that we need to prepare 3 grams of YBCO by solid-state synthesis from respective carbonates. The reaction string will look something like this (to simplify, let's leave it without oxygen nonstoichiometry):
from chemsynthcalc import ChemicalReaction
reaction_string = "BaCO3 + Y2(CO3)3 + CuCO3 + O2 → YBa2Cu3O7 + CO2"
Now, we can create a chemical reaction object of the ChemicalReaction
class, which will be used in the calculation. We need to specify the arguments for our particular case:
>>> reaction = ChemicalReaction(
reaction = reaction_string, # our reaction string
target = 0, # index of target compound in the product list
target_mass = 3, # desired mass of target compound,
mode = "balance" # mode of coefficients calculations,
)
Now, to perform the automatic calculation, all we need to do is to put:
>>> reaction.print_results(print_rounding_order=4)
# assuming that we use analytical balances with 4 digit presicion
And we get our output in the terminal:
initial reaction: BaCO3+Y2(CO3)3+CuCO3+O2→YBa2Cu3O7+CO2
reaction matrix:
[[1. 0. 0. 0. 2. 0.]
[1. 3. 1. 0. 0. 1.]
[3. 9. 3. 2. 7. 2.]
[0. 2. 0. 0. 1. 0.]
[0. 0. 1. 0. 3. 0.]]
mode: balance
formulas: ['BaCO3', 'Y2(CO3)3', 'CuCO3', 'O2', 'YBa2Cu3O7', 'CO2']
coefficients: [8, 2, 12, 1, 4, 26]
normalized coefficients: [2, 0.5, 3, 0.25, 1, 6.5]
algorithm: inverse
is balanced: True
final reaction: 8BaCO3+2Y2(CO3)3+12CuCO3+O2→4YBa2Cu3O7+26CO2
final reaction normalized: 2BaCO3+0.5Y2(CO3)3+3CuCO3+0.25O2→YBa2Cu3O7+6.5CO2
molar masses: [197.335, 357.835676, 123.554, 31.998, 666.190838, 44.009]
target: YBa2Cu3O7
masses: [1.7773, 0.8057, 1.6692, 0.036, 3.0, 1.2882]
BaCO3: M = 197.3350 g/mol, m = 1.7773 g
Y2(CO3)3: M = 357.8357 g/mol, m = 0.8057 g
CuCO3: M = 123.5540 g/mol, m = 1.6692 g
O2: M = 31.9980 g/mol, m = 0.0360 g
YBa2Cu3O7: M = 666.1908 g/mol, m = 3.0000 g
CO2: M = 44.0090 g/mol, m = 1.2882 g
balancer
Balancer
Bases: BalancingAlgorithms
A class for balancing chemical equations automatically by different matrix methods.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
matrix
|
NDArray[float64]
|
Reaction matrix |
required |
separator_pos
|
int
|
Position of the reaction separator (usually the separator is "=") |
required |
round_precision
|
int
|
Coefficients rounding precision |
required |
intify
|
bool
|
Determines whether the coefficients should be integers |
True
|
Attributes:
Name | Type | Description |
---|---|---|
coef_limit |
int
|
max integer coefficient for _intify_coefficients method |
Source code in src/chemsynthcalc/balancer.py
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 |
|
_intify_coefficients(coefficients, limit)
Reduce the coefficients to integers by finding the greatest common divider.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coefficients
|
list
|
List of coefficients to intify |
required |
limit
|
int
|
Upper limit (max int coef) |
required |
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of intified coefficients |
Source code in src/chemsynthcalc/balancer.py
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 |
|
is_reaction_balanced(reactant_matrix, product_matrix, coefficients, tolerance=1e-08)
staticmethod
Checks if reaction is balanced by multiplying reactant matrix and product matrix by the respective coefficient vector. Method is static to call it outside of balancer instance.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reactant_matrix
|
NDArray[float64]
|
Matrix of reactants property generated by ChemicalReaction class |
required |
product_matrix
|
NDArray[float64]
|
Matrix of products property generated by ChemicalReaction class |
required |
coefficients
|
list[float] | list[int]
|
Coefficients |
required |
tolerance
|
float
|
tolerance limit for the np.allclose function |
1e-08
|
Returns:
Type | Description |
---|---|
bool
|
True if balanced within tolerance |
Examples:
>>> reaction = ChemicalReaction("NH4ClO4+HNO3+HCl=HClO4+NOCl+N2O+N2O3+H2O+Cl2")
>>> Balancer.is_reaction_balanced(reaction.reactant_matrix, reaction.product_matrix, [64, 167, 137, 80, 43, 64, 30, 240, 39])
True
>>> reaction = ChemicalReaction("H2+O2=H2O")
>>> Balancer.is_reaction_balanced(reaction.reactant_matrix, reaction.product_matrix, [2,2,2])
False
Source code in src/chemsynthcalc/balancer.py
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 |
|
_calculate_by_method(method)
Compute the coefficients list by a specific method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
method
|
str
|
One of 4 currently implemented methods (inv, gpinv, ppinv, comb) |
required |
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of coefficients |
Raise
ValueError if method is not found.
BalancingError if can't balance reaction by specified method.
Source code in src/chemsynthcalc/balancer.py
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 |
|
inv()
A high-level function call to compute coefficients by Thorne method.
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of coefficients |
Source code in src/chemsynthcalc/balancer.py
181 182 183 184 185 186 187 188 |
|
gpinv()
A high-level function call to compute coefficients by Risteski general pseudoinverse method.
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of coefficients |
Source code in src/chemsynthcalc/balancer.py
190 191 192 193 194 195 196 197 198 |
|
ppinv()
A high-level function call to compute coefficients by Risteski partial pseudoinverse method.
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of coefficients |
Source code in src/chemsynthcalc/balancer.py
200 201 202 203 204 205 206 207 208 |
|
comb()
A high-level function call to compute coefficients by combinatorial method.
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of coefficients |
Source code in src/chemsynthcalc/balancer.py
210 211 212 213 214 215 216 217 218 |
|
auto()
A high-level function call to automatically compute coefficients by sequentially calling inv, gpinv, ppinv methods.
Returns:
Type | Description |
---|---|
tuple[list[float | int] | list[int], str]
|
A list of coefficients |
Raise
BalancingError if can't balance reaction by any method.
Source code in src/chemsynthcalc/balancer.py
220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 |
|
balancing_algos
BalancingAlgorithms
A collection of functions for balancing chemical reactions
Currently implemented: Thorne algorithm (see _inv_algorithm method for details), Risteski general pseudo-inverse algorithm (see _gpinv_algorithm method for details), Risteski partial pseudo-inverse algorithm (see _ppinv_algorithm method for details), and naive combinational search algorithm (see _comb_algorithm method for details).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
matrix
|
NDArray[float64]
|
Reaction matrix |
required |
separator_pos
|
int
|
Position of the reaction separator (usually the separator is "=") |
required |
Attributes:
Name | Type | Description |
---|---|---|
reactant_matrix |
NDArray[float64]
|
A matrix of the left part of the equation |
product_matrix |
NDArray[float64]
|
A matrix of the right part of the equation |
Note
Why use scipy.linalg.pinv, when numpy.linalg.pinv is doing the same thing and does not require the whole SciPy import?
There are some peculiar reaction cases where (especially for _ppinv_algorithm method) the results for numpy.linalg.pinv differs from system to system (np version, OS, python version etc.). My understanding is that the cause of this behaviour lies in small differences for pinv algorithm in numpy C-libraries and BLAS-libraries, hence the difference. To avoid this, a more consistent method scipy.linalg.pinv was used.
Source code in src/chemsynthcalc/balancing_algos.py
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 |
|
_inv_algorithm()
Matrix inverse algorithm for reaction balancing.
A reaction matrix inverse algorithm proposed by Thorne. The calculation is based on the nullity, or dimensionality, of the matrix.
The algorithm can be described in steps:
1) If the number of rows is greater than the number of columns, add zero columns until the matrix becomes square (Note: this is a modification of the original Thorne method described in the article).
2) If reaction matrix is square (which means that the number of atoms involved is equal to the number of compounds) than we turn matrix in its row-echelon form by singular value decomposition.
3) Calculation of the nullity of the matrix, which is basically number of compounds minus rank of the matrix.
4) Create a matrix augumented by nullity number of rows of flipped identity matrix. If any rows are zeros, replace them with identity matrix rows.
5) Inverse the augumented matrix.
6) Exctract and transpose rightmost column.
7) Normalize this value with the absolute min value of the vector.
8) Round up float operations errors.
The absolute values of this vector are coefficients of the reaction.
Note
While this method works great for reactions with 0 and 1 nullity, it generally cannot work with nullities 2 and higher. Thorne claims that for higher nullities, a nullity number of vectors should be extracted, and each of them contains a set of correct coefficients. However, if number of rows in the flipped augmentation identity matrix is 2 or more, one can easily see that each vector will contain nullity-1 zeroes, therefore they cannot be a correct vector of coefficients.
Returns:
Type | Description |
---|---|
NDArray[float64]
|
A 1D NumPy array of calculated coefficients |
Source code in src/chemsynthcalc/balancing_algos.py
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 |
|
_gpinv_algorithm()
Matrix gerenal pseudoinverse algorithm for reaction balancing.
A reaction matrix pseudoinverse algorithm proposed by Risteski. There are other articles and methods of chemical equation balancing by this author, however, this particular algorithm seems to be most convenient for matrix calculations. The algorithm can be described in steps:
1) Stack reactant matrix and negative product matrix.
2) Calculate MP pseudoinverse of this matrix.
3) Calculate coefficients by formula: x = (I – A+A)a, where x is the coefficients vector, I - identity matrix, A+ - MP inverse, A - matrix, a - arbitrary vector (in this case, vector of ones).
Note
This method is more general than Thorne's method, although it has some peculiarities of its own. First of all, the output of this method is float array, so, to generate an int coefs list, it needs to be converted, which is not always leads to a good result. Secondly, MP pseudoinverse is sensetive to row order in the reaction matrix. The rows should be ordered by atoms apperances in the reaction string.
Returns:
Type | Description |
---|---|
NDArray[float64]
|
A 1D NumPy array of calculated coefficients |
Source code in src/chemsynthcalc/balancing_algos.py
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 |
|
_ppinv_algorithm()
Matrix partial pseudoinverse algorithm for reaction balancing.
A reaction matrix pseudoinverse algorithm also proposed by Risteski. The method is founded on virtue of the solution of a Diophantine matrix equation by using of a Moore-Penrose pseudoinverse matrix.
The algorithm can be described in steps:
1) Take the Moore-Penrose pseudoinverse of the reactant matrix.
2) Create a G matrix in the form of (I-AA^-)B, where I is the identity matrix, A is the reactant matrix, A^- is the MP pseudoinverse of A and B is the product matrix.
3) Then, the vector y (coefficients of products) is equal to (I-G^-G)u.
4) Vector x (coefficients of reactants) is equal to A^-By + (I-A^-A)v, where u and v are columns of ones.
Note
While this algorithm and _gpinv_algorithm are very similar, there are some differences in output results. This method exists mostly for legacy purposes, like balancing some reactions according to Risteski.
Returns:
Type | Description |
---|---|
NDArray[float64]
|
A 1D NumPy array of calculated coefficients |
Source code in src/chemsynthcalc/balancing_algos.py
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 |
|
_comb_algorithm(max_number_of_iterations=100000000.0)
Matrix combinatorial algorithm for reaction balancing.
Finds a solution solution of a Diophantine matrix equation by simply enumerating of all possible solutions of number_of_iterations coefficients. The solution space is created by Cartesian product (in this case, np.meshgrid function), and therefore it is very limited by memory. There must a better, clever and fast solution to this!
Important
Only for integer coefficients less than 128. Only for reactions with total compound count <=10. A GPU-accelerated version of this method can be done by importing CuPy and replacing np. with cp.
Note
All possible variations of coefficients vectors are combinations = max_coefficients**number_of_compounds, therefore this method is most effective for reaction with small numbers of compounds.
Returns:
Type | Description |
---|---|
NDArray[int32] | None
|
A 1D NumPy array of calculated coefficients of None if can't compute |
Source code in src/chemsynthcalc/balancing_algos.py
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 |
|
chem_errors
Module that contains custom errors for use in ChemSynthCalc
EmptyFormula
Bases: Exception
The formula string is empty
Source code in src/chemsynthcalc/chem_errors.py
6 7 8 9 10 11 |
|
NoSuchAtom
Bases: Exception
Found atom(s) that are not in the periodic table.
Source code in src/chemsynthcalc/chem_errors.py
14 15 16 17 18 19 |
|
InvalidCharacter
Bases: Exception
Found some characters that do not belong in the chemical formula or reaction.
Source code in src/chemsynthcalc/chem_errors.py
22 23 24 25 26 27 28 |
|
MoreThanOneAdduct
Bases: Exception
There is more than one adduct (*).
Source code in src/chemsynthcalc/chem_errors.py
31 32 33 34 35 36 |
|
BracketsNotPaired
Bases: Exception
Some brackets do not come in pairs.
Source code in src/chemsynthcalc/chem_errors.py
39 40 41 42 43 44 |
|
EmptyReaction
Bases: Exception
The reaction string is empty
Source code in src/chemsynthcalc/chem_errors.py
47 48 49 50 51 52 |
|
NoSuchMode
Bases: Exception
Invalid calculation mode detected.
Source code in src/chemsynthcalc/chem_errors.py
55 56 57 58 59 60 |
|
NoSuchAlgorithm
Bases: Exception
Invalid calculation algorithm detected.
Source code in src/chemsynthcalc/chem_errors.py
63 64 65 66 67 68 |
|
NoSeparator
Bases: Exception
No separator was found in the reaction string.
Source code in src/chemsynthcalc/chem_errors.py
71 72 73 74 75 76 |
|
ReactionNotBalanced
Bases: Exception
This reaction is not balanced.
Source code in src/chemsynthcalc/chem_errors.py
79 80 81 82 83 84 |
|
ReactantProductDifference
Bases: Exception
The elements in reaction are not evenly distributed in reactants and products: some of atoms are only in one part of reaction.
Source code in src/chemsynthcalc/chem_errors.py
87 88 89 90 91 92 93 94 95 |
|
BadCoeffiecients
Bases: Exception
The coefficients are not not compliant (they have no physical meaning).
Source code in src/chemsynthcalc/chem_errors.py
98 99 100 101 102 103 104 |
|
BalancingError
Bases: Exception
Can't balance reaction by this method
Source code in src/chemsynthcalc/chem_errors.py
107 108 109 110 111 112 |
|
chem_output
ChemicalOutput
Methods of this class prepare output from ChemicalFormula and ChemicalReaction objects and output it in different ways.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
output
|
dict[str, object]
|
Output dictionary |
required |
print_precision
|
int
|
How many decimal places to print out |
required |
obj
|
str
|
Type of object ("formula" or "reaction") |
required |
Attributes:
Name | Type | Description |
---|---|---|
rounded_values |
dict[str, object]
|
Output dictionary rounded to print_precision |
original_stdout |
TextIO | Any
|
Default stdout |
Raise
ValueError if print_precision <= 0
ValueError if obj is not "ChemicalFormula" or "ChemicalReaction"
Source code in src/chemsynthcalc/chem_output.py
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 |
|
_round_values()
Round values of output dictionary to the print_precision. Rounding is different depending on the type of the value.
Returns:
Type | Description |
---|---|
dict[str, object]
|
Rounded dictionary |
Source code in src/chemsynthcalc/chem_output.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
|
_generate_filename(file_type)
Generates a filename for an output file in the form of: "CSC_object type_formula or target_nanosec since the Epoch.txt or json"
Returns:
Type | Description |
---|---|
str
|
String of a filename |
Source code in src/chemsynthcalc/chem_output.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
|
_print_additional_reaction_results()
Print output masses in a user-friendly human-readable format.
Source code in src/chemsynthcalc/chem_output.py
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 |
|
_print_stream()
Final print stream that can go to different outputs.
Source code in src/chemsynthcalc/chem_output.py
109 110 111 112 113 114 115 116 117 118 119 |
|
print_results()
Print a final result of calculations in stdout.
Source code in src/chemsynthcalc/chem_output.py
121 122 123 124 125 126 |
|
write_to_txt(filename)
Export the final result of the calculations in a txt file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename
|
str
|
filename string (should end with .txt) |
required |
Source code in src/chemsynthcalc/chem_output.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 |
|
dump_to_json()
Serialization of output into JSON object.
Returns:
Type | Description |
---|---|
str
|
A JSON-type object |
Source code in src/chemsynthcalc/chem_output.py
144 145 146 147 148 149 150 151 |
|
write_to_json_file(filename)
Export a final result of calculations in a JSON file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename
|
str
|
filename string (should end with .json) |
required |
Source code in src/chemsynthcalc/chem_output.py
153 154 155 156 157 158 159 160 161 162 163 164 |
|
chemical_formula
ChemicalFormula
A class for operations on a single chemical formula.
It constructs with a formula string and can calculate parsed formula, molar mass, mass percent, atomic percent, oxide percent from this string using ChemicalFormulaParser and MolarMassCalculation.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
formula
|
str
|
String of chemical formula |
''
|
*custom_oxides
|
tuple[str, ...]
|
An arbitrary number of non-default oxide formulas |
()
|
precision
|
int
|
Value of rounding precision (8 by default) |
8
|
Raise
ValueError: if precision <= 0
Examples:
>>> ChemicalFormula("H2O")
H2O
>>> ChemicalFormula("H2O").molar_mass
18.015
>>> ChemicalFormula("H2O").mass_percent
{'H': 11.19067444, 'O': 88.80932556}
Source code in src/chemsynthcalc/chemical_formula.py
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 |
|
formula
cached
property
A string of chemical formula. It is made a property to be relatively immutable.
Returns:
Type | Description |
---|---|
str
|
The formula string |
Examples:
>>> ChemicalFormula("K2SO4").formula
K2SO4
parsed_formula
cached
property
Formula parsed into dictionary keeping the initial atom order.
Returns:
Type | Description |
---|---|
dict[str, float]
|
Parsed dictionary representation of formula string created by ChemicalFormulaParser |
Examples:
>>> ChemicalFormula("K2SO4").parsed_formula
{'K': 2.0, 'S': 1.0, 'O': 4.0}
molar_mass
cached
property
Molar mass of the compound.
Returns:
Type | Description |
---|---|
float
|
The molar mass of the formula (in g/mol), calculated from parsed the formula using MolarMassCalculation. |
Examples:
>>> ChemicalFormula("K2SO4").molar_mass
174.252
mass_percent
cached
property
The percentage of mass of atoms in the formula.
Returns:
Type | Description |
---|---|
dict[str, float]
|
A mass percent or relative mass fraction of atoms in parsed chemical formula. The values of mass content are in % (with 100% sum), not fraction. |
Examples:
>>> ChemicalFormula("K2SO4").mass_percent
{'K': 44.87523816, 'S': 18.39864105, 'O': 36.72612079}
atomic_percent
cached
property
Atomic percents of atoms in the formula.
Returns:
Type | Description |
---|---|
dict[str, float]
|
An atomic percent or relative mole fraction dictionary of atoms in a parsed chemical formula. The values of mole content are in % (with 100% sum), not fraction. |
Examples:
>>> ChemicalFormula("K2SO4").atomic_percent
{'K': 28.57142857, 'S': 14.28571429, 'O': 57.14285714}
oxide_percent
cached
property
Oxide percents of metals in formula. Custom oxide formulas can be provided with object init.
Returns:
Type | Description |
---|---|
dict[str, float]
|
An oxide percent or oxide fraction dictionary of atoms in parsed chemical formula. Oxide types are listed in the chemsynthcalc.periodic_table file and can be changed to any oxide formula. The values of oxide content are in % (with 100% sum), not fraction. |
Examples:
>>> ChemicalFormula("K2SO4").oxide_percent
{'K2O': 54.05676836, 'SO3': 45.94323164}
>>> ChemicalFormula("K2FeO4", "FeO3").oxide_percent
{'K2O': 47.56434404, 'FeO3': 52.43565596}
output_results
cached
property
Dictionary of the calculation result output for class.
Returns:
Type | Description |
---|---|
dict[str, object]
|
Output dictionary for all properties listed above |
Examples:
>>> ChemicalFormula("K2SO4").output_results
{'formula': 'K2SO4', 'parsed formula': {'K': 2.0, 'S': 1.0, 'O': 4.0},
'molar mass': 174.252, 'mass percent': {'K': 44.87523816, 'S': 18.39864105, 'O': 36.72612079},
'atomic percent': {'K': 28.57142857, 'S': 14.28571429, 'O': 57.14285714},
'oxide percent': {'K2O': 54.05676836, 'SO3': 45.94323164}}
print_results(print_precision=4)
Print a final result of calculations in stdout.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Source code in src/chemsynthcalc/chemical_formula.py
198 199 200 201 202 203 204 205 206 207 |
|
to_txt(filename='default', print_precision=4)
Export the final result of the calculations in a txt file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename
|
str
|
filename string (should end with .txt) |
'default'
|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Source code in src/chemsynthcalc/chemical_formula.py
209 210 211 212 213 214 215 216 217 218 219 |
|
to_json(print_precision=4)
Serialization of output into JSON object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Returns:
Type | Description |
---|---|
str
|
A JSON-type object |
Source code in src/chemsynthcalc/chemical_formula.py
221 222 223 224 225 226 227 228 229 230 231 232 233 |
|
to_json_file(filename='default', print_precision=4)
Export a final result of calculations in a JSON file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename
|
str
|
filename string (should end with .json) |
'default'
|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Source code in src/chemsynthcalc/chemical_formula.py
235 236 237 238 239 240 241 242 243 244 245 |
|
chemical_reaction
ChemicalReaction
A class that represents a chemical reaction and do operations on it.
There are three calculation modes:
-
The "force" mode is used when a user enters coefficients in the reaction string and wants the masses to be calculated whether the reaction is balanced or not.
-
"check" mode is the same as force, but with reaction balance checks.
-
"balance" mode tries to automatically calculate coefficients from the reaction string.
Important
Unlike other properties of this class, the coefficients property can be set directly.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reaction
|
str
|
A reaction string |
''
|
mode
|
str
|
Coefficients calculation mode |
'balance'
|
target
|
int
|
Index of target compound (0 by default, or first compound in the products), can be negative (limited by reactant) |
0
|
target_mass
|
float
|
Desired mass of target compound (in grams) |
1.0
|
precision
|
int
|
Value of rounding precision (8 by default) |
8
|
intify
|
bool
|
Is it required to convert the coefficients to integer values? |
True
|
Attributes:
Name | Type | Description |
---|---|---|
algorithm |
str
|
Currently used calculation algorithm |
Raise
ValueError if precision or target mass <= 0
Source code in src/chemsynthcalc/chemical_reaction.py
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 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 |
|
reaction
cached
property
A string of chemical reaction. It is made a property to be relatively immutable.
Returns:
Type | Description |
---|---|
str
|
The reaction string |
Examples:
>>> ChemicalReaction("H2+O2=H2O").reaction
H2+O2=H2O
decomposed_reaction
cached
property
Decomposition of chemical reaction string and extraction of reaction separator, reactants, products and initial coefficients.
Returns:
Type | Description |
---|---|
ReactionDecomposer
|
A ReactionDecomposer object |
Examples:
>>> ChemicalReaction("H2+O2=H2O").decomposed_reaction
separator: =; reactants: ['H2', 'O2']; products: ['H2O']
_calculated_target
cached
property
Checks if initial_target is in the reaction's compounds range, and calculates the usable target integer.
Returns:
Type | Description |
---|---|
int
|
Final target |
Raise
IndexError if The target integer is not in the range
Examples:
>>> ChemicalReaction("H2+O2=H2O")._calculated_target
2
chemformula_objs
cached
property
Decomposition of a list of formulas from the decomposed_reaction.
Returns:
Type | Description |
---|---|
list[ChemicalFormula]
|
Every compound as ChemicalFormula object |
Examples:
>>> ChemicalReaction("H2+O2=H2O").chemformula_objs
[ChemicalFormula('H2', 8), ChemicalFormula('O2', 8), ChemicalFormula('H2O', 8)]
parsed_formulas
cached
property
List of formulas parsed by ChemicalFormulaParser
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").parsed_formulas
[{'K': 1.0, 'Mn': 1.0, 'O': 4.0}, {'H': 1.0, 'Cl': 1.0}, {'Mn': 1.0, 'Cl': 2.0}, {'Cl': 2.0}, {'H': 2.0, 'O': 1.0}, {'K': 1.0, 'Cl': 1.0}]
matrix
cached
property
Chemical reaction matrix.
The first implementation of reaction matrix method is probably belongs to Blakley. In general, a chemical reaction matrix is composed of the coefficients of each atom in each compound, giving a 2D array. The matrix composes naturally from previously parsed formulas.
Returns:
Type | Description |
---|---|
NDArray[float64]
|
2D array of each atom amount in each formula |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").matrix
[[1. 0. 0. 0. 0. 1.] (K)
[1. 0. 1. 0. 0. 0.] (Mn)
[4. 0. 0. 0. 1. 0.] (O)
[0. 1. 0. 0. 2. 0.] (H)
[0. 1. 2. 2. 0. 1.]] (Cl)
balancer
cached
property
A balancer to automatically balance chemical reaction by different matrix methods.
Returns:
Type | Description |
---|---|
Balancer
|
A Balancer object |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").balancer
Balancer object for matrix
[[1. 0. 0. 0. 0. 1.]
[1. 0. 1. 0. 0. 0.]
[4. 0. 0. 0. 1. 0.]
[0. 1. 0. 0. 2. 0.]
[0. 1. 2. 2. 0. 1.]]
molar_masses
cached
property
List of molar masses (in g/mol)
Returns:
Type | Description |
---|---|
list[float]
|
List of molar masses of each compound in chemformula_objs" |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").molar_masses
[158.032043, 36.458, 125.838043, 70.9, 18.015, 74.548]
coefficients
cached
property
Coefficients of the chemical reaction. Can be calculated (balance mode), striped off the initial reaction string (force or check modes) or set directly.
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
A list of coefficients |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl", mode="balance").coefficients
[2, 16, 2, 5, 8, 2]
>>> reaction = ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl", mode="check")
>>> reaction.coefficients = [2, 16, 2, 5, 8, 2]
>>> reaction.coefficients
[2, 16, 2, 5, 8, 2]
>>> ChemicalReaction("2H2+2O2=H2O", mode="force").coefficients
[2, 2, 1]
normalized_coefficients
cached
property
List of coefficients normalized on target compound.
Target coefficient = 1.0
Returns:
Type | Description |
---|---|
list[float | int] | list[int]
|
Normalized coefficients |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").normalized_coefficients
[1, 8, 1, 2.5, 4, 1]
is_balanced
property
Is the reaction balanced with the current coefficients?
Returns:
Type | Description |
---|---|
bool
|
True if the reaction is balanced |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").is_balanced
True
final_reaction
cached
property
Final representation of the reaction with coefficients.
Returns:
Type | Description |
---|---|
str
|
A string of the final reaction |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").final_reaction
2KMnO4+16HCl=2MnCl2+5Cl2+8H2O+2KCl
final_reaction_normalized
cached
property
Final representation of the reaction with normalized coefficients.
Returns:
Type | Description |
---|---|
str
|
A string of the normalized final reaction |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").final_reaction_normalized
KMnO4+8HCl=MnCl2+2.5Cl2+4H2O+KCl
masses
cached
property
List of masses of compounds (in grams).
List of masses of the of formulas in reaction calculated with coefficients obtained by any of the 3 methods. Calculates masses by calculating amount of substance nu (nu=mass/molar mass). Coefficients of reaction are normalized to the target. After nu of target compound is calculated, it broadcasted to other compounds (with respect to their coefficients).
Returns:
Type | Description |
---|---|
list[float]
|
A list of masses of compounds |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").masses
[1.25583678, 2.31777285, 1.0, 1.40855655, 0.57264082, 0.59241226]
output_results
cached
property
Collection of every output of calculated ChemicalReaction properties.
Returns:
Type | Description |
---|---|
dict[str, object]
|
All outputs collected in one dictionary. |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl").output_results
{'initial reaction': 'KMnO4+HCl=MnCl2+Cl2+H2O+KCl',
'reaction matrix': array([[1., 0., 0., 0., 0., 1.],
[1., 0., 1., 0., 0., 0.],
[4., 0., 0., 0., 1., 0.],
[0., 1., 0., 0., 2., 0.],
[0., 1., 2., 2., 0., 1.]]),
'mode': 'balance',
'formulas': ['KMnO4', 'HCl', 'MnCl2', 'Cl2', 'H2O', 'KCl'],
'coefficients': [2, 16, 2, 5, 8, 2],
'normalized coefficients': [1, 8, 1, 2.5, 4, 1],
'algorithm': 'inverse',
'is balanced': True,
'final reaction': '2KMnO4+16HCl=2MnCl2+5Cl2+8H2O+2KCl',
'final reaction normalized': 'KMnO4+8HCl=MnCl2+2.5Cl2+4H2O+KCl',
'molar masses': [158.032043, 36.458, 125.838043, 70.9, 18.015, 74.548],
'target': 'MnCl2',
'masses': [1.25583678, 2.31777285, 1.0, 1.40855655, 0.57264082, 0.59241226]}
_generate_final_reaction(coefs)
Final reaction string with connotated formulas and calculated coefficients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coefs
|
list[float | int] | list[int]
|
list of coefficients |
required |
Returns:
Type | Description |
---|---|
str
|
String of the final reaction |
Examples:
>>> ChemicalReaction("KMnO4+HCl=MnCl2+Cl2+H2O+KCl")._generate_final_reaction([2, 16, 2, 5, 8, 2])
2KMnO4+16HCl=2MnCl2+5Cl2+8H2O+2KCl
Source code in src/chemsynthcalc/chemical_reaction.py
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 |
|
print_results(print_precision=4)
Print a final result of calculations in stdout.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Source code in src/chemsynthcalc/chemical_reaction.py
445 446 447 448 449 450 451 452 453 454 |
|
to_txt(filename='default', print_precision=4)
Export the final result of the calculations in a txt file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename
|
str
|
filename string (should end with .txt) |
'default'
|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Source code in src/chemsynthcalc/chemical_reaction.py
456 457 458 459 460 461 462 463 464 465 466 |
|
to_json(print_precision=4)
Serialization of output into JSON object.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Returns:
Type | Description |
---|---|
str
|
A JSON-type object |
Source code in src/chemsynthcalc/chemical_reaction.py
468 469 470 471 472 473 474 475 476 477 478 479 480 |
|
to_json_file(filename='default', print_precision=4)
Export a final result of calculations in a JSON file.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
filename
|
str
|
filename string (should end with .json) |
'default'
|
print_precision
|
int
|
print precision (4 digits by default) |
4
|
Source code in src/chemsynthcalc/chemical_reaction.py
482 483 484 485 486 487 488 489 490 491 492 |
|
coefs
Coefficients
A class to calculate and validate reaction coefficients depending on the calculation "mode".
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mode
|
str
|
Calculation mode ("force", "check", "balance") |
required |
parsed_formulas
|
list[dict[str, float]]
|
List of formulas parsed by ChemicalFormulaParser |
required |
matrix
|
NDArray[float64]
|
Reaction matrix created by ChemicalReactionMatrix |
required |
balancer
|
Balancer
|
A Balancer object |
required |
decomposed_reaction
|
ReactionDecomposer
|
A ReactionDecomposer object |
required |
Attributes:
Name | Type | Description |
---|---|---|
initial_coefficients |
list[float]
|
List of initial coefficients from decomposed reaction |
Source code in src/chemsynthcalc/coefs.py
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 |
|
_calculate_coefficients()
Match a mode string and get coefficients depending on the mode
Returns:
Type | Description |
---|---|
tuple[list[float | int] | list[int], str]
|
Tuple of (coefficients, algorithm) |
Raise
ReactionNotBalanced if reaction is not balanced in the "check" mode
NoSuchMode if there is no mode with that name
Source code in src/chemsynthcalc/coefs.py
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 |
|
coefficients_validation(coefficients)
Validate a list of coefs.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coefficients
|
list[float | int] | list[int]
|
List of coefs |
required |
Raise
BadCoeffiecients if any coef <= 0 or lenght of list is not equal to the number of compounds.
Source code in src/chemsynthcalc/coefs.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
|
_element_count_validation()
Calculate a symmetric difference of two sets - left and right parts of the reaction. If this set is not empty, than some atoms are only in one part of the reaction (which is impossible).
Raise
ReactantProductDifference if diff set is not empty.
Source code in src/chemsynthcalc/coefs.py
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 |
|
get_coefficients()
Validate atom's diff and coefs list and finally get a proper coefficients list.
Returns:
Type | Description |
---|---|
tuple[list[float | int] | list[int], str]
|
Tuple of (coefficients, algorithm) |
Source code in src/chemsynthcalc/coefs.py
130 131 132 133 134 135 136 137 138 139 140 |
|
formula
Formula
A base class for ChemicalFormulaParser and FormulaValidator containing regexes and symbols.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
formula
|
str
|
Formula string |
required |
Attributes:
Name | Type | Description |
---|---|---|
atom_regex |
str
|
Regular expression for finding atoms in formula |
coefficient_regex |
str
|
Regular expression for atoms amounts in formula |
atom_and_coefficient_regex |
str
|
atom_regex+coefficient_regex |
opener_brackets |
str
|
Opener brackets variations |
closer_brackets |
str
|
Closer brackets variations |
adduct_symbols |
str
|
Symbols for adduct notation (water of crystallization most often) |
Source code in src/chemsynthcalc/formula.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 |
|
formula_parser
ChemicalFormulaParser
Bases: Formula
Parser of chemical formulas.
Methods of this class take string of compound's chemical formula and turn it into a dict of atoms as keys and their coefficients as values.
Source code in src/chemsynthcalc/formula_parser.py
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 |
|
_dictify(tuples)
Transform list of tuples to a dict of atoms.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
tuples
|
list[tuple[str, ...]]
|
List of tuples of atoms |
required |
Returns:
Type | Description |
---|---|
dict[str, float]
|
Dictionary of atoms and they quantities |
Source code in src/chemsynthcalc/formula_parser.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
|
_fuse(mol1, mol2, weight=1.0)
Fuse together 2 dicts representing molecules.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mol1
|
dict[str, float]
|
Dict of atoms 1 |
required |
mol2
|
dict[str, float]
|
Dict of atoms 2 |
required |
weight
|
float
|
Weight |
1.0
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
A new fused dict |
Source code in src/chemsynthcalc/formula_parser.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
|
_parse(formula)
Parse the formula string
Recurse on opening brackets to parse the subpart and return on closing ones because it is the end of said subpart. Formula is the argument of this method due to the complications of self. Constructions in recursive functions.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
formula
|
str
|
Formula string |
required |
Returns:
Type | Description |
---|---|
tuple[dict[str, float], int]
|
A tuple of the molecule dict and length of parsed part |
Source code in src/chemsynthcalc/formula_parser.py
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 |
|
_order_output_dict(parsed)
Arranges the unparsed formula in the order in which the chemical elements appear in it.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parsed
|
dict[str, float]
|
A formula parsed by _parse |
required |
Returns:
Type | Description |
---|---|
dict[str, float]
|
An ordered dictionary |
Source code in src/chemsynthcalc/formula_parser.py
129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 |
|
parse_formula()
Parsing and ordering of formula
Returns:
Type | Description |
---|---|
dict[str, float]
|
Parsed formula |
Source code in src/chemsynthcalc/formula_parser.py
146 147 148 149 150 151 152 153 154 |
|
formula_validator
FormulaValidator
Bases: Formula
Methods of this class validate the initial input formula.
Source code in src/chemsynthcalc/formula_validator.py
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 |
|
_check_empty_formula()
Checks if formula is an empty string.
Source code in src/chemsynthcalc/formula_validator.py
20 21 22 23 24 |
|
_invalid_charachers()
Checks if formula contains invalid characters.
Returns:
Type | Description |
---|---|
list[str]
|
List of invalid characters |
Source code in src/chemsynthcalc/formula_validator.py
26 27 28 29 30 31 32 33 |
|
_invalid_atoms()
Checks whether the formula contains atoms that are not in the periodic system.
Returns:
Type | Description |
---|---|
list[str]
|
List of invalid atoms |
Source code in src/chemsynthcalc/formula_validator.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
|
_bracket_balance()
Checks whether all of the brackets come in pairs.
Source code in src/chemsynthcalc/formula_validator.py
56 57 58 59 60 61 62 63 64 |
|
_num_of_adducts()
Counts a number of adduct symbols (listed in Formula base class).
Returns:
Type | Description |
---|---|
int
|
A number of adduct symbols |
Source code in src/chemsynthcalc/formula_validator.py
66 67 68 69 70 71 72 73 74 75 76 77 78 |
|
validate_formula()
Validation of the formula string. Calls the private methods of this class in order.
Raise
EmptyFormula if the formula is an empty string.
InvalidCharacter if there is an invalid character(s) in the string.
NoSuchAtom if there is an invalid atom(s) in the string.
BracketsNotPaired if the brackets are not in pairs.
MoreThanOneAdduct if there are more than 1 adduct symbols in the string.
Returns:
Type | Description |
---|---|
bool
|
True if all the checks are OK |
Source code in src/chemsynthcalc/formula_validator.py
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 |
|
molar_mass
Oxide
Bases: NamedTuple
A named tuple to represent oxide properties: a first atom (usually metal), full oxide compound string and mass percent of the first atom in the initial formula.
Source code in src/chemsynthcalc/molar_mass.py
7 8 9 10 11 12 13 14 15 16 |
|
MolarMassCalculation
Class for the calculation of molar masses and percentages of a compound.
Compound should be parsed by ChemicalFormulaParser first.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parsed_formula
|
dict
|
Formula parsed by ChemicalFormulaParser |
required |
Attributes:
Name | Type | Description |
---|---|---|
p_table |
dict[str, Atom]
|
Periodic table of elements |
Source code in src/chemsynthcalc/molar_mass.py
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 |
|
_calculate_atomic_masses()
Calculation of the molar masses of all atoms in a parsed formula.
Returns:
Type | Description |
---|---|
list[float]
|
List of atomic masses multiplied by the number of corresponding atoms |
Source code in src/chemsynthcalc/molar_mass.py
37 38 39 40 41 42 43 44 45 46 47 48 49 |
|
calculate_molar_mass()
Calculation of the molar mass of compound from the atomic masses of atoms in a parsed formula.
Returns:
Type | Description |
---|---|
float
|
Molar mass (in g/mol) |
Examples:
>>> MolarMassCalculation({'H':2, 'O':1}).calculate_molar_mass()
18.015
>>> MolarMassCalculation({'C':2, 'H':6, 'O':1}).calculate_molar_mass()
46.069
Source code in src/chemsynthcalc/molar_mass.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
calculate_mass_percent()
Calculation of mass percents of atoms in parsed formula.
Returns:
Type | Description |
---|---|
dict[str, float]
|
Mass percentages of atoms in the formula |
Examples:
>>> MolarMassCalculation({'H':2, 'O':1}).calculate_mass_percent()
{'H': 11.19067443796836, 'O': 88.80932556203163}
>>> MolarMassCalculation({'C':2, 'H':6, 'O':1}).calculate_mass_percent()
{'C': 52.14352384466777, 'H': 13.12813388612733, 'O': 34.72834226920489}
Source code in src/chemsynthcalc/molar_mass.py
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
|
calculate_atomic_percent()
Calculation of atomic percents of atoms in the parsed formula.
Returns:
Type | Description |
---|---|
dict[str, float]
|
Atomic percentages of atoms in the formula |
Examples:
>>> MolarMassCalculation({'H':2, 'O':1}).calculate_atomic_percent()
{'H': 66.66666666666666, 'O': 33.33333333333333
>>> MolarMassCalculation({'C':2, 'H':6, 'O':1}).calculate_atomic_percent()
{'C': 22.22222222222222, 'H': 66.66666666666666, 'O': 11.11111111111111}
Source code in src/chemsynthcalc/molar_mass.py
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
|
_custom_oxides_input(*args)
Checks if passed non-default oxide formulas can be applied to any atom in parsed formula. If so, replaces it with said non-default oxide. If not, the default oxide is chosen.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
tuple[str, ...]
|
An arbitrary number of non-default oxide formulas |
()
|
Returns:
Type | Description |
---|---|
list[Oxide]
|
A list of Oxide objects |
Raise
ValueError if compound is not binary or second element is not oxygen
Source code in src/chemsynthcalc/molar_mass.py
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 |
|
calculate_oxide_percent(*args)
Calculation of oxide percents in parsed formula.
Calculation of oxide percents in parsed formula from the types of oxide declared in the periodic table file. This type of data is mostly used in XRF spectrometry and mineralogy. The oxide percents are calculated by finding the convertion factor between element and its respective oxide and normalizing the total sum to 100%. One can change the oxide type for certain elements in the periodic_table.py file. Theoretically, this function should work for other types of binary compound (sulfides, fluorides etc.) or even salts, however, modification of this function is required (for instance, in case of binary compound, removing X atom from the list of future compounds should have X as an argument of this function).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
*args
|
tuple[str, ...]
|
An arbitrary number of non-default oxide formulas |
()
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
Percentages of oxides in the formula |
Examples:
>>> MolarMassCalculation({'C':2, 'H':6, 'O':1}).calculate_oxide_percent()
{'CO2': 61.9570190690046, 'H2O': 38.04298093099541}
>>> MolarMassCalculation({'Ba':1, 'Ti':1, 'O':3}).calculate_oxide_percent()
{'BaO': 65.7516917244869, 'TiO2': 34.24830827551309}
Source code in src/chemsynthcalc/molar_mass.py
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 |
|
periodic_table
Atom
Bases: NamedTuple
Named tuple for representing atomic properties: atomic weight and type of oxide that will be used by default.
Source code in src/chemsynthcalc/periodic_table.py
4 5 6 7 8 9 10 11 |
|
PeriodicTable
Periodic table of elements in the form of "Atom symbol": Atom NamedTuple. The standard atomic weights are taken from IUPAC.
Source code in src/chemsynthcalc/periodic_table.py
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 |
|
reaction
Reaction
A base class for ReactionDecomposer and ReactionValidator containing regexes and symbols.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reaction
|
str
|
Reaction string |
required |
Attributes:
Name | Type | Description |
---|---|---|
allowed_symbols |
str
|
Regex of all symbols allowed in a reaction string |
possible_reaction_separators |
list[str]
|
List of all allowed reaction separators (left and right part separator) |
reactant_separator |
str
|
Only one possible reactant separator ("+") |
Source code in src/chemsynthcalc/reaction.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 |
|
extract_separator()
Extract one of possible reaction separator from the reaction string.
Returns:
Type | Description |
---|---|
str
|
Separator string if separator is found, empty string if not |
Source code in src/chemsynthcalc/reaction.py
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
|
reaction_decomposer
ReactionDecomposer
Bases: Reaction
Decomposition of chemical reaction string and extraction of reaction separator, reactants, products and initial coefficients.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
reaction
|
str
|
A reaction string |
required |
Attributes:
Name | Type | Description |
---|---|---|
separator |
str
|
A reactants - products separator (usually "+") |
initial_coefficients |
list[float]
|
A list of coefficients striped from the formulas |
reactants |
list[str]
|
A list of compound from letf part of the reaction equation |
products |
list[str]
|
A list of compound from right part of the reaction equation |
compounds |
list[str]
|
reactants + products |
Source code in src/chemsynthcalc/reaction_decomposer.py
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 |
|
split_coefficient_from_formula(formula)
Split the coefficient (int or float) from string containing formula and coef.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
formula
|
str
|
Formula string |
required |
Returns:
Type | Description |
---|---|
tuple[float, str]
|
A tuple of (coefficient, formula) |
Source code in src/chemsynthcalc/reaction_decomposer.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
|
reaction_matrix
ChemicalReactionMatrix
A class to create a dense float matrix from the parsed formulas.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
parsed_formulas
|
list[dict[str, float]]
|
A list of formulas parsed by ChemicalFormulaParser |
required |
Source code in src/chemsynthcalc/reaction_matrix.py
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 |
|
create_reaction_matrix()
Creates a 2D NumPy array from nested Python lists. The content of lists are exctracted from parsed dicts.
Returns:
Type | Description |
---|---|
NDArray[float64]
|
A 2D NumPy array of the reaction matrix |
Source code in src/chemsynthcalc/reaction_matrix.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
|
reaction_validator
ReactionValidator
Bases: Reaction
Methods of this class validate the initial input reaction.
Source code in src/chemsynthcalc/reaction_validator.py
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 |
|
_check_empty_reaction()
Checks if reaction is an empty string.
Source code in src/chemsynthcalc/reaction_validator.py
12 13 14 15 16 |
|
_invalid_charachers()
Checks if reaction string contains invalid characters.
Returns:
Type | Description |
---|---|
list[str]
|
List of invalid characters |
Source code in src/chemsynthcalc/reaction_validator.py
18 19 20 21 22 23 24 25 |
|
_no_reaction_separator()
Checks if reaction string contains a separator.
Source code in src/chemsynthcalc/reaction_validator.py
27 28 29 30 31 |
|
_no_reactant_separator()
Checks if reaction string contains a "+".
Source code in src/chemsynthcalc/reaction_validator.py
33 34 35 36 37 |
|
validate_reaction()
Validation of the reaction string. Calls the private methods of this class in order.
Raise
EmptyReaction if reaction string is empty.
InvalidCharacter if some characters are invalid.
NoSeparator if any of separators (reaction or reactant) are missing.
Returns:
Type | Description |
---|---|
bool
|
True if all the checks are OK |
Source code in src/chemsynthcalc/reaction_validator.py
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 |
|
utils
A module with some useful utilities functions.
round_dict_content(input, precision, plus=0)
Round all values of a dictionary to arbitrary precision (with optional surplus value).
Parameters:
Name | Type | Description | Default |
---|---|---|---|
input
|
dict[str, float]
|
An input dict |
required |
precision
|
int
|
Precision |
required |
plus
|
int
|
An optional surplus |
0
|
Returns:
Type | Description |
---|---|
dict[str, float]
|
Rounded dictionary |
Source code in src/chemsynthcalc/utils.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
|
to_integer(coefficients)
Cast a float to int if this float is some x.0 (integer), otherwise keep a float.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
coefficients
|
list[float | int]
|
Mixed list of floats and ints |
required |
Returns:
Type | Description |
---|---|
list[float | int]
|
Mixed list of floats and ints |
Source code in src/chemsynthcalc/utils.py
27 28 29 30 31 32 33 34 35 36 37 38 |
|
find_lcm(int_list)
Find Least Common Multiplyer of list of integers
Parameters:
Name | Type | Description | Default |
---|---|---|---|
int_list
|
list[int]
|
A list of integers |
required |
Returns:
Type | Description |
---|---|
int
|
The LCM |
Source code in src/chemsynthcalc/utils.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 |
|
find_gcd(int_list)
Find Greatest Common Divisor of list of integers
Parameters:
Name | Type | Description | Default |
---|---|---|---|
int_list
|
list[int]
|
A list of integers |
required |
Returns:
Type | Description |
---|---|
int
|
The GCD |
Source code in src/chemsynthcalc/utils.py
57 58 59 60 61 62 63 64 65 66 67 68 |
|