This repository has been archived by the owner on May 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Calculator.py
1798 lines (1436 loc) · 71.5 KB
/
Calculator.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
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
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# The Chemtech Codex simple CLI-based chemistry calculator that solves and integrates
# General Chemistry 2 concepts.
# Copyright (C) 2024 Louis Raphael V. Panaligan
# This program is free software: you can redistribute it and/or modify it under the
# terms of the GNU General Public License as published by the Free Software Foundation,
# either version 3 of the License, or (at your option) any later version.
# This program is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
# PARTICULAR PURPOSE. See the GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along with this
# program. If not, see <https://www.gnu.org/licenses/>.
from functools import reduce
from math import e, fsum, log, log10
from os import path, remove
from prettytable import PrettyTable
# Defines the path to where the file containing the results would be created.
file_path = "results.txt"
def subscript(formula: str) -> str:
"""Converts all the integers in a string of a chemical formula into its subscript form.
Args:
formula (str): The string of a formula.
Returns:
str: The string of a chemical formula with subscripts.
"""
# Create a translation dictionary for the integers and their subscript form.
subscript_translation = str.maketrans("0123456789", "₀₁₂₃₄₅₆₇₈₉")
# Separates the parts of the given chemical formula into its coefficient and main.
coefficient = formula[0]
main_formula = formula[1:]
# Translates the integers in the main chemical formula into their subscript forms.
main_formula = main_formula.translate(subscript_translation)
# Returns the string of a chemical formula with subscripts.
return coefficient + main_formula
def superscript(integers: str) -> str:
"""Converts all the integers in a string into its subscript form.
Args:
formula (str): The string.
Returns:
str: The string with subscripts.
"""
# Create a translation dictionary for the integers and their superscript form.
superscript_translation = str.maketrans("0123456789", "⁰¹²³⁴⁵⁶⁷⁸⁹")
# Translates the integers into their superscript forms and returns it.
return integers.translate(superscript_translation)
def calculate_thermochemistry(raw_chemical_equation: str):
"""Runs the thermodynamics calculator."""
# Creates a new ASCII table to store the givens.
givens_table = PrettyTable(
["Formula", "Type", "Number", "Standard Heat (ΔH°f)", "Standard Entropy (S°)"]
)
# Separates the chemical equation into its reactants and products.
chemical_equation = raw_chemical_equation.replace(" ", "").split("->")
# Formats and splits the reactants and products into individual formulas.
reactants = list(map(subscript, chemical_equation[0].split("+")))
products = list(map(subscript, chemical_equation[1].split("+")))
# Rejoins the reactants and products into a stylized chemical equation.
chemical_equation = " → ".join([" + ".join(reactants), " + ".join(products)])
def get_thermodynamic_values(
formulas: list[str], formula_type: str
) -> tuple[list[float], list[float]]:
"""Gets the thermodynamic values of chemical formulas through inputs from the user.
Args:
formulas (list[str]): The chemical formulas.
formula_type (str): The type of the thermodynamic values.
Returns:
tuple[list[float], list[float]]: The user given standard heats and entropies.
"""
# Create lists to store the standard heats and entropies of the given formulas.
standard_heats: list[float] = []
standard_entropies: list[float] = []
# Loop through each of the given chemical formulas.
for formula in formulas:
# Resets the variable to allow for looping if inputted value is invalid
successful = False
# Loops the input prompt until the user gives a valid thermodynamic value.
while not successful:
# Tries to prompt the user to input the thermodynamic values.
try:
# Checks if a chemical formula has a coefficient.
if formula[0].isdigit():
# Separates the parts of the given chemical formula into its coefficient and main.
coefficient = int(formula[0])
main_formula = formula[1:]
# Asks the user for the standard heat value and multiplies it to the coefficient.
given_standard_heat = float(
input(
f'\nPlease input the STANDARD HEAT (ΔH°f) of "{main_formula}" (float or int ONLY): '
)
)
standard_heat = given_standard_heat * coefficient
# Asks the user for the standard entropy value and multiplies it to the coefficient.
given_standard_entropy = float(
input(
f'Please input the STANDARD ENTROPY (S°) of "{main_formula}" (float or int ONLY): '
)
)
standard_entropy = given_standard_entropy * coefficient
# Adds the given thermodynamic values to the table of givens
givens_table.add_row( # type: ignore
[
main_formula,
formula_type,
coefficient,
f"{given_standard_heat} kJ/mol",
f"{given_standard_entropy} J/K × mol",
]
)
else:
# Asks the user for the standard heat value.
standard_heat = given_standard_heat = float(
input(
f'\nPlease input the STANDARD HEAT (ΔH°f) of "{formula}" (float or int ONLY): '
)
)
# Asks the user for the standard entropy value.
standard_entropy = given_standard_entropy = float(
input(
f'Please input the STANDARD ENTROPY (S°) of "{formula}" (float or int ONLY): '
)
)
# Adds the given thermodynamic values to the table of givens
givens_table.add_row( # type: ignore
[
formula,
formula_type,
1,
f"{given_standard_heat} kJ/mol",
f"{given_standard_entropy} J/K × mol",
]
)
# Adds the given standard heat and entropy to the lists that will be returned by the function
standard_heats.append(standard_heat)
standard_entropies.append(standard_entropy)
# Stops the input prompt from repeating.
successful = True
# Catches error exception for when the given value is invalid.
except ValueError:
# Informs the user what values are valid.
print(
"\nThe given thermodynamic value must be a valid float or int ONLY."
)
# Repeats the input prompt.
successful = False
# Returns the lists of given standard heat and entropy values.
return standard_heats, standard_entropies
def calculate_rxn_enthalpy(
product_standard_heats: list[float],
reactant_standard_heats: list[float],
) -> float:
"""Calculates the standard enthalpy of the standard heats of the products and reactants.
Args:
product_standard_heats (list[float]): The standard heats of the products.
reactant_standard_heats (list[float]): The standard heats of the reactants.
Returns:
float: The calculated standard enthalpy.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the standard enthalpy.
file.write(
"\n\nEquation for standard enthalpy (ΔH°rxn):\nΔH°rxn = Σ(nΔS° products) - Σ(nΔS° reactants)"
)
# Writes to the file the solution for calculating the standard enthalpy.
file.write(
f'\n\nSolution for the standard enthalpy (ΔH°rxn) of "{chemical_equation}":'
)
file.write(
f"\nΔH°rxn = ({' + '.join(map(str, product_standard_heats))}) - ({' + '.join(map(str, reactant_standard_heats))}) kJ/mol"
)
# Calculates the standard enthalpy.
standard_enthalpy = fsum(product_standard_heats) - fsum(reactant_standard_heats)
# Writes to the file the calculated standard enthalpy.
file.write(f"\nΔH°rxn = {standard_enthalpy} kJ/mol")
# Checks if the enthalpy is greater than zero then writes to the file that the reaction is endothermic.
if standard_enthalpy > 0:
file.write(
"\n\nBecause the standard enthalpy (ΔH°rxn) is greater than 0, the reaction must be ENDOTHERMIC."
)
# Checks if the enthalpy is less than zero then writes to the file that the reaction is exothermic.
elif standard_enthalpy < 0:
file.write(
"\n\nBecause the standard enthalpy (ΔH°rxn) is less than 0, the reaction must be EXOTHERMIC."
)
# Writes to the file that the reaction is neither endothermic or exothermic.
else:
file.write(
"\n\nBecause the standard enthalpy (ΔH°rxn) is equal to 0, the reaction is neither endothermic or exothermic."
)
# Closes the opened file.
file.close()
# Returns the calculated standard enthalpy.
return standard_enthalpy
def calculate_rxn_entropy(
product_standard_entropies: list[float],
reactant_standard_entropies: list[float],
) -> float:
"""Calculates the standard entropy change of the standard entropies of the products and reactants.
Args:
product_standard_entropies (list[float]): The standard entropies of the products.
reactant_standard_entropies (list[float]): The standard entropies of the reactants.
Returns:
float: The calculated standard entropy change.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the standard entropy change.
file.write(
"\n\nEquation for standard entropy change / entropy of the system (ΔS°rxn / ΔS°sys):\nΔS°rxn = Σ(nΔH°f products) - Σ(nΔH°f reactants)"
)
# Writes to the file the solution for calculating the standard entropy change.
file.write(
f'\n\nSolution for the standard entropy change / entropy of the system (ΔS°rxn / ΔS°sys) of "{chemical_equation}":'
)
file.write(
f"\nΔS°rxn = {' + '.join(map(str, product_standard_entropies))} - {' + '.join(map(str, reactant_standard_entropies))} J/K × mol"
)
# Calculates the standard entropy change.
standard_entropy_change = fsum(product_standard_entropies) - fsum(
reactant_standard_entropies
)
# Writes to the file the calculated standard entropy change.
file.write(f"\nΔS°rxn = {standard_entropy_change} J/K × mol")
# Closes the opened file.
file.close()
# Returns the calculated standard entropy change.
return standard_entropy_change
def calculate_surr_entropy(system_entropy: float, temperature: float) -> float:
"""Calculates the enthalpy of the surroundings of the system entropy and temperature.
Args:
system_entropy (list[float]): The system entropy or standard entropy change.
temperature (list[float]): The temperature.
Returns:
float: The calculated entropy of the surroundings.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the entropy of the surroundings.
file.write(
"\n\nEquation for entropy of the surroundings (ΔS°surr):\nΔS°surr = -(ΔS°sys) / T"
)
# Writes to the file the solution for calculating the entropy of the surroundings.
file.write(
f'\n\nSolution for the entropy of the surroundings (ΔS°surr) of "{chemical_equation} at {temperature} K":'
)
file.write(f"\nΔS°surr = -({system_entropy}) J/mol / {temperature} K")
# Calculates the entropy of the surroundings.
surrounding_entropy = (system_entropy * -1) / temperature
# Writes to the file the calculated entropy of the surroundings.
file.write(f"\nΔS°surr = {surrounding_entropy} J/K × mol")
# Closes the opened file.
file.close()
# Returns the calculated entropy of the surroundings.
return surrounding_entropy
def calculate_univ_entropy(
system_entropy: float,
surrounding_entropy: float,
) -> float:
"""Calculates the entropy of the universe of the the system entropy and entropy of the surroundings.
Args:
system_entropy (list[float]): The system entropy or standard entropy change.
surrounding_entropy (list[float]): The entropy of the surroundings.
Returns:
float: The calculated entropy of the universe.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the entropy of the universe.
file.write(
"\n\nEquation for entropy of the universe (ΔS°univ):\nΔS°univ = ΔS°sys ΔS°surr"
)
# Writes to the file the solution for calculating the entropy of the universe.
file.write(
f'\n\nSolution for the entropy of the universe (ΔS°univ) of "{chemical_equation}":'
)
file.write(
f"\nΔS°univ = {system_entropy} J/K × mol + {surrounding_entropy} J/K × mol"
)
# Calculates the entropy of the universe.
universal_entropy = system_entropy + surrounding_entropy
# Writes to the file the calculated entropy of the universe.
file.write(f"\nΔS°univ = {universal_entropy} J/K × mol")
# Checks if the enthalpy is greater than zero then writes to the file that the reaction is spontaneous.
if universal_entropy > 0:
file.write(
"\n\nBecause the entropy of the universe (ΔS°univ) is greater than 0, the reaction must be SPONTANEOUS."
)
# Checks if the enthalpy is less than zero then writes to the file that the reaction is non-spontaneous.
elif universal_entropy < 0:
file.write(
"\n\nBecause the entropy of the universe (ΔS°univ) is less than 0, the reaction must be NON-SPONTANEOUS."
)
# Writes to the file that the reaction is at equilibrium.
else:
file.write(
"\n\nBecause the entropy of the universe (ΔS°univ) is equal to 0, the reaction is at equilibrium."
)
# Closes the opened file.
file.close()
# Returns the calculated entropy of the universe.
return universal_entropy
# Declares the default temperature value.
temperature = 298.0
# Resets the variable to allow for looping if inputted value is invalid
successful = False
# Loops the input prompt until the user gives a valid temperature value.
while not successful:
# Tries to prompt the user to input the temperature value.
try:
# Asks the user for the temperature that the chemical reaction occurs in.
given_temperature = input(
"Please input the temperature in Kelvins (float, int, or [press ENTER for 298] ONLY): "
)
# Checks if the user gave a temperature
if not given_temperature == "":
# Sets the temperature to the given temperature.
temperature = float(given_temperature)
# Stops the input prompt from repeating.
successful = True
# Catches error exception for when the given value is invalid.
except ValueError:
# Informs the user what values are valid.
print("\nThe given temperature value must be a valid float or int ONLY.")
# Repeats the input prompt.
successful = False
# Gets the thermodynamic values of the reactants and products.
reactant_standard_heats, reactant_standard_entropies = get_thermodynamic_values(
reactants, "Reactant"
)
product_standard_heats, product_standard_entropies = get_thermodynamic_values(
products, "Product"
)
# Creates or opens a file to store where the results will be contained.
file = open(file_path, "w+", encoding="utf-8")
# Writes to the file the given chemical equation.
file.write(f"The given chemical equation:\n{chemical_equation}")
# Writes to the file the given temperature and the table of givens.
file.write("\n\nGivens:")
file.write(f"\nTemperature: {temperature} K")
file.write("\n" + givens_table.get_string()) # type: ignore
# Writes to the file the required values to be calculated.
file.write("\n\nRequired:\nΔH°rxn, ΔS°rxn, and ΔS°univ")
# Closes the created or opened file.
file.close()
# Calculates for the required values.
standard_enthalpy = calculate_rxn_enthalpy(
product_standard_heats, reactant_standard_heats
)
standard_entropy_change = calculate_rxn_entropy(
product_standard_entropies, reactant_standard_entropies
)
surrounding_entropy = calculate_surr_entropy(
standard_entropy_change,
temperature,
)
universal_entropy = calculate_univ_entropy(
standard_entropy_change, surrounding_entropy
)
# Opens the file where the results are contained.
file = open(file_path, "a+", encoding="utf-8")
# Writes to the file the final answers to the required values.
file.write("\n\nThe FINAL ANSWERS:")
file.write(f"\nΔH°rxn = {standard_enthalpy} J/K × mol")
file.write(f"\nΔS°rxn = {standard_entropy_change} J/K × mol")
file.write(f"\nΔS°univ = {universal_entropy} J/K × mol")
# Closes the opened file.
file.close()
def calculate_chemical_kinetics():
"""Runs the chemical kinetics calculator."""
def calculate_concentration_after_time(
temperature: float,
rate_constant: float,
initial_concentration: float,
time: float,
) -> float:
"""Calculates the concentration after time.
Args:
temperature (float): The temperature.
rate_constant (float): The rate constant.
initial_concentration (float): The initial concentration.
time (float): The time in seconds.
Returns:
float: The calculated concentration after time.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the concentration after time.
file.write(
f"\n\nEquation for the concentration ([A]ₜ) after {time} seconds at {temperature} °C:\nln [A]ₜ = -kt + ln [A]₀"
)
# Writes to the file the solution for calculating the concentration after time.
file.write(
f"\n\nSolution for the concentration ([A]ₜ) after {time} seconds at {temperature} °C:"
)
file.write(
f"\nln [A]{subscript(str(round(time)))}ₛ = -({rate_constant} /s)({time} s) + ln ({initial_concentration} M)"
)
# Calculates the concentration after time.
concentration_after_time = rate_constant * time
concentration_after_time *= -1
concentration_after_time += log(initial_concentration)
concentration_after_time = e**concentration_after_time
# Writes to the file the calculated concentration after time.
file.write(f"\n[A]{subscript(str(round(time)))} = {concentration_after_time} M")
# Closes the opened file.
file.close()
# Returns the calculated concentration after time.
return concentration_after_time
def calculate_time_of_concentration(
temperature: float,
rate_constant: float,
initial_concentration: float,
final_concentration: float,
) -> float:
"""Calculates the time to get a concentration.
Args:
temperature (float): The temperature.
rate_constant (float): The rate constant.
initial_concentration (float): The initial concentration.
final_concentration (float): The final concentration.
Returns:
float: The calculated time to get a concentration.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the time to get a concentration.
file.write(
f"\n\nEquation for the time (t) at {temperature} °C:\nln [A]ₜ / [A]₀ = -kt"
)
# Writes to the file the solution for calculating the time to get a concentration.
file.write(f"\n\nSolution for the time (t) at {temperature} °C:")
file.write(
f"\nln {final_concentration} M / {initial_concentration} M = -({rate_constant}t)"
)
# Calculates the time to get a concentration.
time_of_concentration = log(final_concentration / initial_concentration)
rate_constant *= -1
time_of_concentration /= rate_constant
# Writes to the file the calculated time to get a concentration.
file.write(f"\nt = {time_of_concentration} s")
# Closes the opened file.
file.close()
# Returns the calculated time to get a concentration.
return time_of_concentration
def calculate_half_life_of_reaction(
temperature: float, rate_constant: float
) -> float:
"""Calculates the half-life of a reaction.
Args:
temperature (float): The temperature.
rate_constant (float): The rate constant.
Returns:
float: The half-life of a reaction.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the half-life of a reaction.
file.write(
f"\n\nEquation for the half-life (t1/2) at {temperature} °C:\nt1/2 = ln 2 / k"
)
# Writes to the file the solution for calculating the half-life of a reaction.
file.write(f"\n\nSolution for the time (t) at {temperature} °C:")
file.write(f"\nt1/2 = ln 2 / {rate_constant}")
# Calculates the half-life of a reaction.
half_time_of_concentration = log(2) / rate_constant
# Writes to the file the calculated half-life of a reaction.
file.write(f"\nt1/2 = {half_time_of_concentration} s")
# Closes the opened file.
file.close()
# Returns the calculated half-life of a reaction.
return half_time_of_concentration
# Resets the variable to allow for looping if inputted value is invalid
successful = False
# Loops the input prompt until the user gives valid temperature and rate constant values.
while not successful:
# Tries to prompt the user to input the time and rate constant values.
try:
# Asks the user for the temperature.
given_temperature = float(
input("\nPlease input the temperature in Celsius (float or int ONLY): ")
)
# Asks the user for the rate constant.
given_rate_constant = float(
input("Please input the rate constant (float or int ONLY): ")
)
# Stops the input prompt from repeating.
successful = True
# Catches error exception for when the given value is invalid.
except ValueError:
# Informs the user what values are valid.
print(
"\nThe given temperature or rate constant value must be a valid float or int ONLY."
)
# Repeats the input prompt.
successful = False
# Resets the variable to allow for looping if inputted value is invalid
successful = False
# Loops the input prompt until the user gives a valid temperature value.
while not successful:
# Gives the user the instructions for providing the topic.
print("""
Please input the corresponding integer for the topic that you need this calculator for.
1.) Determine the concentration of the reactant after a certain time elapsed?
2.) Determine how much time has passed to get to a certain concentration of the reactant?
3.) Determine the half-life of a reaction?
""")
# Asks the user for the topic.
given_topic = input("Topic: ")
# Checks whether the given input is a "1" value.
if given_topic == "1":
try:
# Asks the user for the initial concentration
given_initial_concentration = float(
input(
"\nPlease input the initial concentration (float or int ONLY): "
)
)
# Asks the user for the elapsed time.
given_time = float(
input("Please input the time in seconds (float or int ONLY): ")
)
# Creates or opens a file to store where the results will be contained.
file = open(file_path, "w+", encoding="utf-8")
# Writes to the file the given temperature, rate constant, initial concentration, and time.
file.write("Givens:")
file.write(f"\nT = {given_temperature}") # type: ignore
file.write(f"\nk = {given_rate_constant}") # type: ignore
file.write(f"\n[A]₀ = {given_initial_concentration}")
file.write(f"\nt = {given_time}")
# Writes to the file the required values to be calculated.
file.write("\n\nRequired:\n[A]ₜ")
# Closes the created or opened file.
file.close()
# Calculates for the concentration after time.
concentration_after_time = calculate_concentration_after_time(
given_temperature, # type: ignore
given_rate_constant, # type: ignore
given_initial_concentration,
given_time,
)
# Opens the file where the results are contained.
file = open(file_path, "a+", encoding="utf-8")
# Writes to the file the final answers to the required values.
file.write("\n\nThe FINAL ANSWERS:")
file.write(
f"\n[A]{subscript(str(round(given_time)))} = {concentration_after_time} M"
)
# Closes the opened file.
file.close()
# Stops the input prompt from repeating.
successful = True
# Catches error exception for when the given value is invalid.
except ValueError:
# Informs the user what values are valid.
print("\nThe given time value must be a valid float or int ONLY.")
# Repeats the input prompt.
successful = False
# Checks whether the given input is a "2" value.
elif given_topic == "2":
try:
# Asks the user for the initial concentration
given_initial_concentration = float(
input(
"\nPlease input the initial concentration (float or int ONLY): "
)
)
# Asks the user for the final concentration
given_final_concentration = float(
input("Please input the final concentration (float or int ONLY): ")
)
# Creates or opens a file to store where the results will be contained.
file = open(file_path, "w+", encoding="utf-8")
# Writes to the file the given temperature, rate constant, initial concentration, and final concentration.
file.write("Givens:")
file.write(f"\nT = {given_temperature}") # type: ignore
file.write(f"\nk = {given_rate_constant}") # type: ignore
file.write(f"\n[A]₀ = {given_initial_concentration}")
file.write(f"\n[A]ₜ] = {given_final_concentration}")
# Writes to the file the required values to be calculated.
file.write("\n\nRequired:\nt")
# Closes the created or opened file.
file.close()
# Calculates for the time to get a concentration.
concentration_after_time = calculate_time_of_concentration(
given_temperature, # type: ignore
given_rate_constant, # type: ignore
given_initial_concentration,
given_final_concentration,
)
# Opens the file where the results are contained.
file = open(file_path, "a+", encoding="utf-8")
# Writes to the file the final answers to the required values.
file.write("\n\nThe FINAL ANSWERS:")
file.write(f"\nt = {concentration_after_time} s")
# Closes the opened file.
file.close()
# Stops the input prompt from repeating.
successful = True
# Catches error exception for when the given value is invalid.
except ValueError:
# Informs the user what values are valid.
print("\nThe given time value must be a valid float or int ONLY.")
# Repeats the input prompt.
successful = False
# Checks whether the given input is a "3" value.
elif given_topic == "3":
# Creates or opens a file to store where the results will be contained.
file = open(file_path, "w+", encoding="utf-8")
# Writes to the file the given temperature, rate constant, initial concentration, and final concentration.
file.write("Givens:")
file.write(f"\nT = {given_temperature}") # type: ignore
file.write(f"\nk = {given_rate_constant}") # type: ignore
# Writes to the file the required values to be calculated.
file.write("\n\nRequired:\nt")
# Closes the created or opened file.
file.close()
# Calculates for the half-life of the reaction.
half_time_of_concentration = calculate_half_life_of_reaction(
given_temperature, # type: ignore
given_rate_constant, # type: ignore
)
# Opens the file where the results are contained.
file = open(file_path, "a+", encoding="utf-8")
# Writes to the file the final answers to the required values.
file.write("\n\nThe FINAL ANSWERS:")
file.write(f"\nt1/2 = {half_time_of_concentration} s")
# Closes the opened file.
file.close()
# Stops the input prompt from repeating.
successful = True
else:
# Informs the user what values are valid.
print('\nThe given value must be "1", "2", or "3" only.')
# Repeats the input prompt.
successful = False
continue
def calculate_chemical_equilibrium(raw_chemical_equation: str):
"""Runs the chemical equilibrium calculator."""
# Creates a new ASCII table to store the givens.
givens_table = PrettyTable(
["Formula", "Type", "Number", "Molarity (M)", "Pressure (atm)"]
)
# Separates the chemical equation into its reactants and products.
chemical_equation = raw_chemical_equation.replace(" ", "").split("<=>")
# Formats and splits the reactants and products into individual formulas.
reactants = list(map(subscript, chemical_equation[0].split("+")))
products = list(map(subscript, chemical_equation[1].split("+")))
# Rejoins the reactants and products into a stylized chemical equation.
chemical_equation = " ⇌ ".join([" + ".join(reactants), " + ".join(products)])
def get_values(
formulas: list[str], formula_type: str, type: str
) -> tuple[list[float], list[int]]:
"""Gets the molarity values of chemical formulas through inputs from the user.
Args:
formulas (list[str]): The chemical formulas.
formula_type (str): The type of the thermodynamic values.
type (str): The type of equilibrium constant
Returns:
tuple[list[float], list[int]]: The user given values.
"""
# Create lists to store the values and coefficients of the given formulas.
values: list[float] = []
coefficients: list[int] = []
for formula in formulas:
# Resets the variable to allow for looping if inputted value is invalid
successful = False
# Loops the input prompt until the user gives a valid value.
while not successful:
# Tries to prompt the user to input the values.
try:
if formula[0].isdigit():
# Separates the parts of the given chemical formula into its coefficient and main.
coefficient = int(formula[0])
main_formula = formula[1:]
# Asks the user for the value and exponentiates it to the coefficient.
given_value = float(
input(
f'\nPlease input the {"MOLARITY (M)" if type == "c" else "PRESSURE (atm)"} of "{main_formula}" (float or int ONLY): '
)
)
value = given_value**coefficient
# Adds the given values to the table of givens
givens_table.add_row( # type: ignore
[
main_formula,
formula_type,
coefficient,
f"{given_value} M" if type == "c" else "N/A",
f"{given_value} atm" if type == "p" else "N/A",
]
)
coefficients.append(coefficient)
else:
# Asks the user for the value.
value = given_value = float(
input(
f'\nPlease input the {"MOLARITY (M)" if type == "c" else "PRESSURE (atm)"} of "{formula}" (float or int ONLY): '
)
)
# Adds the given values to the table of givens
givens_table.add_row( # type: ignore
[
formula,
formula_type,
1,
f"{given_value} M" if type == "c" else "N/A",
f"{given_value} atm" if type == "p" else "N/A",
]
)
coefficients.append(1)
# Adds the given values to the list that will be returned by the function
values.append(value)
# Stops the input prompt from repeating.
successful = True
# Catches error exception for when the given value is invalid.
except ValueError:
# Informs the user what values are valid.
print("\nThe given value must be a valid float or int ONLY.")
# Repeats the input prompt.
successful = False
# Returns the list of given values and formula coefficients.
return values, coefficients
def calculate_m(
product_molarities: list[float],
product_moles: list[int],
reactant_molarities: list[float],
reactant_moles: list[int],
) -> tuple[float, float]:
"""Calculates the equilibrium constant of the molarities of the reactants and products.
Args:
product_molarities (list[float]): The molarities of the products.
product_moles (list[int]): The moles of the products.
reactant_molarities (list[float]): The molarities of the reactants.
reactant_moles (list[int]):The moles of the products.
Returns:
float: The calculated equilibrium constant.
"""
# Opens the file where the results are contained.
file = open(file_path, "a", encoding="utf-8")
# Writes to the file the equation that will be used to calculate the equilibrium constant.
file.write("\n\nEquation for the equilibrium constant (Kc):\nKc = [B]ᵇ / [A]ᵃ")
# Writes to the file the solution for calculating the equilibrium constant.
file.write(
f'\n\nSolution for the equilibrium constant (Kc) of "{chemical_equation}":'
)
file.write(
f"\nKc = ({' × '.join(map(str, product_molarities))}) / ({' × '.join(map(str, reactant_molarities))})"
)
# Calculates the equilibrium constant.
kc = reduce(lambda x, y: x * y, product_molarities) / reduce(
lambda x, y: x * y, reactant_molarities
)
# Writes to the file the calculated equilibrium constant.
file.write(f"\nKc = {kc}")
file.write(f"\nKc = 1 / {kc}")
# Calculates the backwards equilibrium constant.
backward_kc = 1 / kc
# Writes to the file the calculated backwards equilibrium constant.
file.write(f"\nKc of backward = {backward_kc}")
# Checks if the equilibrium constant is greater than zero then writes to the file that forward is favored.
if kc > 0:
file.write(
"\n\nBecause the equilibrium constant (Kc) is greater than 0, FORWARD is more favored."
)
# Checks if the equilibrium constant is less than zero then writes to the file that backward is favored.
elif kc < 0:
file.write(
"\n\nBecause the equilibrium constant (Kc) is less than 0, BACKWARD is more favored."
)
# Writes to the file that the reaction is at equilibrium.
else:
file.write(
"\n\nBecause the equilibrium constant (Kc) is equal to 0, the reaction would not proceed and no products formed."
)
# Writes to the file the equation that will be used to calculate the equilibrium constant.
file.write(
"\n\nEquation for the equilibrium constant (Kp):\nKp = Kc(0.0821 × T)ⁿ"
)
# Writes to the file the solution for calculating the equilibrium constant.
file.write(
f'\n\nSolution for the equilibrium constant (Kp) of "{chemical_equation}":'
)
file.write("\nT = 800 C + 273.15\nT = 1073.15 K")
file.write(f"\nΔn = {fsum(product_moles)} - {fsum(reactant_moles)}")
# Calculates the number of moles.
moles = fsum(product_moles) - fsum(reactant_moles)
file.write(f"\nΔn = {moles} mole/s")
file.write(f"\nKp = {kc}(0.0821 × 1073.15 K){superscript(str(int(moles)))}")
# Calculates the equilibrium constant.
kp = 0.0821 * 1073.15
kp **= moles
kp *= kc
# Writes to the file the calculated equilibrium constant.
file.write(f"\nKp = {kp}")
# Closes the opened file.
file.close()
# Returns the calculated equilibrium constant.
return kc, kp
def calculate_p(
product_pressures: list[float],
product_moles: list[int],
reactant_pressures: list[float],
reactant_moles: list[int],
) -> tuple[float, float]:
"""Calculates the equilibrium constant of the pressures of the reactants and products.
Args: