-
Notifications
You must be signed in to change notification settings - Fork 0
/
matrix.py
2560 lines (2030 loc) · 72.8 KB
/
matrix.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
import csv, os, glob
import copy
from fractions import Fraction
import sympy
import numpy as np
DEBUG = False
import inspect
def debug_print(message):
line_number = inspect.currentframe().f_back.f_lineno
if DEBUG:
print(f"[Line {line_number}] - {message}")
def get_name(default):
name = input(f"Use: {default} ('1' to except)?\nor enter new name: ")
if name == '1':
return default
else:
return name
# CLEAR SCREEN
def clear_screen():
if os.name == 'posix': # For UNIX or Linux or MacOS
os.system('clear')
elif os.name == 'nt': # For Windows
os.system('cls')
def expression_output_options():
print("Select Output Format:")
print("1) for LaTex")
print("2) for pretty SymPy")
print("3) for plain SymPy")
user_input = input(": ")
if user_input == '1':
return sympy.latex
if user_input == '2':
return sympy.pretty
else:
return lambda x: x
def format_sci_notation(expr):
try:
# Check if it's a SymPy expression
if isinstance(expr, sympy.Expr):
# Simplify and evaluate the expression
return '{:.3e}'.format(float(expr))
else:
return expr
except (ValueError, TypeError):
return expr
class Matrix_Calc:
def __init__(self):
self.matrices = []
self.precision = 2
self.mode = 'pretty'
self.print_expr_function = sympy.pretty
self.print_matrix_function = sympy.pretty
# allow user to flip between display modes inside most methods
def toggle_print_mode(self):
if self.mode == 'pretty':
self.mode = 'latex'
self.print_expr_function = sympy.latex
self.print_matrix_function = sympy.latex
elif self.mode == 'latex':
self.mode = 'pretty'
self.print_expr_function = sympy.pretty
self.print_matrix_function = sympy.pretty
'''
self.mode = 'sci-pretty'
self.print_expr_function = lambda expr : sympy.pretty(format_sci_notation(expr))
self.print_matrix_function = lambda matr : sympy.pretty(matr.applyfunc(format_sci_notation))
elif self.mode == 'sci-pretty':
self.mode = 'sci-latex'
self.print_expr_function = lambda expr : sympy.latex('{:.1e}'.format(expr.evalf()))
self.print_matrix_function = lambda matr : sympy.latex(matr.applyfunc(format_sci_notation))
elif self.mode == 'sci-latex':
self.mode = 'pretty'
self.print_expr_function = sympy.pretty
self.print_matrix_function = sympy.pretty
'''
def get_matrix_choices(self, mode=None):
remaining = [i for i in range(len(self.matrices))]
mask = []
choices = []
invalid = ""
while True:
if remaining == []:
return choices
clear_screen()
if invalid:
print(invalid)
invalid = ""
print("Matrix choices")
self.print_matrix_indices(remaining)
if mode == 'Matrix Algebra' and len(choices) == 0:
print("Choose LHS Matrix:")
elif mode == 'Matrix Algebra' and len(choices) == 1:
print("Choose RHS Matrix:")
elif mode == 'Matrix Algebra' and len(choices) == 2:
return choices
self.print_heading(mask=mask)
user_input = input("Enter your choice. 'x' to finish\n")
if user_input.lower() == 'x':
return choices
else:
try:
user_input = int(user_input) - 1
if user_input not in remaining:
invalid = "Invalid selection, choose from the available options"
continue
else:
mask.append(user_input)
choices.append(user_input)
remaining.remove(user_input)
except ValueError:
invalid = "Invalid selection, enter an integer"
# File handling methods
# # # # # # # # # # # #
def load_from_file(self, overwrite=True):
folder_path = './matrix_files/'
if not os.path.exists(folder_path):
os.mkdir(folder_path)
files = [f for f in os.listdir(folder_path) if os.path.isfile(os.path.join(folder_path, f)) and f.endswith('.txt')]
if files == []:
return "No saved files found"
files = sorted(files)
while True:
clear_screen()
print("\nAvailable files:")
for i, file in enumerate(files):
print(f"{i + 1}: {file}")
file_choice = input("Enter the number of the file you want to load or 'x' to cancel: ")
if file_choice == 'x':
return
elif file_choice.isdigit() and int(file_choice) - 1 in range(len(files)):
break
else:
print("Invalid selection. Please try again.")
file_name = os.path.join(folder_path, files[int(file_choice) - 1])
if not self.matrices:
overwrite = False
else:
invalid = False
while overwrite:
clear_screen()
print("\nCurrent matrices:")
for i, matrix in enumerate(self.matrices):
print(f"{i + 1}: {matrix[0]}")
if invalid:
print("Invalid selection. Please try again.")
invalid = False
matrix_choice = input("Enter the number of the matrix to overwrite, 'n' to add a new matrix, or 'x' to cancel: ")
if matrix_choice == 'x':
return
elif matrix_choice.isdigit() and int(matrix_choice) - 1 in range(len(self.matrices)):
overwrite = True
break
elif matrix_choice.lower() == 'n':
overwrite = False
break
else:
invalid = True
with open(file_name, 'r') as f:
reader = csv.reader(f)
data = [[sympy.sympify(i) for i in row] for row in reader]
data = sympy.Matrix(data)
if overwrite:
self.matrices[int(matrix_choice) - 1] = [file_name.replace(folder_path,''), data]
else:
self.matrices.append([file_name.replace(folder_path,''), data])
return
def save_to_file(self):
invalid = False
while True:
clear_screen()
for i, (file_name, matrix) in enumerate(self.matrices):
print(f"{i + 1}) loaded from '{file_name}'")
if invalid:
print(f"Invalid matrix choice. Please choose a number between 1 and {len(self.matrices)}.")
invalid = False
matrix_choice = input("Please choose a matrix to save or 'x' to cancel: ")
if matrix_choice == 'x':
return
elif matrix_choice.isdigit() and int(matrix_choice)-1 in range(len(self.matrices)):
break
else:
invalid = True
matrix_choice = int(matrix_choice) - 1
file_name = input("Please enter the name for the new file (without .txt) or 'x' to cancel: ")
if file_name == 'x':
return
file_name = './matrix_files/' + file_name
with open(file_name + '.txt', 'w', newline='') as f:
writer = csv.writer(f)
matrix = self.matrices[matrix_choice][1]
for row in matrix.tolist():
writer.writerow(row)
def delete_files(self):
directory = "matrix_files"
invalid = False
while True:
clear_screen()
files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f)) and f.endswith('.txt')]
if not files:
print("No files available for deletion.")
return
print("\nAvailable files:")
for i, file in enumerate(files):
print(f"{i + 1}: {file}")
if invalid:
print("Invalid selection. Please try again.")
invalid = False
file_choice = input("Enter the number of the file you want to delete or 'x' to cancel: ")
if file_choice == 'x':
return
elif file_choice.isdigit() and int(file_choice) - 1 in range(len(files)):
file_name = files[int(file_choice) - 1]
os.remove(os.path.join(directory, file_name))
print(f"Deleted file: {file_name}")
else:
invalid = True
# Create and Delete Matrices
# # # # # # # # # # # # # #
def delete_matrix(self):
invalid = False
while True:
clear_screen()
print("\nPlease choose a matrix to delete:")
self.print_heading()
if invalid:
print(f"Invalid matrix choice. Please choose a number between 1 and {len(self.matrices)}.")
invalid = False
matrix_choice = input("\nEnter your choice ('c' to clear all, 'x' to go back): ")
if matrix_choice.lower() == 'x':
return False
if matrix_choice.lower() == 'c':
self.matrices = []
return True
if matrix_choice.isdigit() and int(matrix_choice) - 1 in range(len(self.matrices)):
del self.matrices[int(matrix_choice) - 1]
print("Matrix deleted successfully.")
return False
else:
invalid = True
def create_matrix(self):
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid input. The name cannot be an empty string. Please try again.")
invalid = False
name = input("Enter a name for the new matrix: ").strip() # strip() removes leading/trailing white space
if name: # if the name is not an empty string
break
else:
invalid = True
# Request and validate the width of the matrix
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid input. Please enter a positive integer.")
invalid = False
width = input("Enter the width of the matrix ('x' to go back): ")
if width.lower() == 'x':
return False
if width.isdigit() and int(width) > 0:
width = int(width)
break
else:
invalid = True
# Request and validate the height of the matrix
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid input. Please enter a positive integer.")
invalid = False
height = input("Enter the height of the matrix ('x' to go back): ")
if height.lower() == 'x':
return False
if height.isdigit() and int(height) > 0:
height = int(height)
break
else:
invalid = True
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid selection.")
invalid = False
print("Matrix Options")
if width == height:
print("I) identity matrix")
matrix_type = input("M) Manual entry\nU) unit matrix\nV) variable matrix\nR) random matrix\n Choose options ('x' to go back)? ")
if matrix_type.lower() == 'x':
return False
elif matrix_type.lower() == 'm':
matrix = self.manual_entry(width, height)
elif matrix_type.lower() == 'i' and width == height:
matrix = sympy.Matrix.eye(width)
elif matrix_type.lower() == 'u':
matrix = sympy.Matrix.ones(height, width)
elif matrix_type.lower() == 'v':
matrix = self.create_variable_matrix(width, height)
elif matrix_type.lower() == 'r':
matrix = self.create_random_matrix(width, height)
else:
invalid = True
continue
if matrix is None:
return False
else:
self.matrices.append([name, matrix])
self.single_matrix_print(self.matrices[-1][1])
return True
def manual_entry(self, width, height):
# create a matrix by manual cell-by-cell data entry
i = 0
j = 0
new_matrix = []
while i < height:
new_column = []
while j < width:
value, status = self.input_value(i, n=j, col_mode=True)
if status == 'back':
if j > 0:
j -= 1
new_column.pop(-1)
elif j == 0:
if i > 0:
i -= 1
j = width - 1
new_column = new_matrix.pop(-1)
new_column.pop(-1)
elif i == 0:
return False
elif status == 'quit':
return False
elif status == 'continue':
new_column.append(value)
j += 1
i += 1
j = 0
new_matrix.append(new_column)
return sympy.Matrix(new_matrix)
def get_character(self):
invalid = ""
while True:
clear_screen()
if invalid:
print(invalid)
invalid = ""
user_input = input("Input a character for variable matrix\n")
if len(user_input) == 1 and user_input.isalpha():
return user_input
else:
invalid = "Invalid choice"
def get_float_input(self, prompt):
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid input. Please enter a number or a fraction.")
invalid = False
user_input = input(prompt)
if user_input.lower() == 'x':
return None
try:
# Convert input to number or fraction
scaling_factor = Fraction(user_input)
scaling_factor = float(scaling_factor)
return scaling_factor
except ValueError:
invalid = True
continue
def create_random_matrix(self, width, height):
invalid = ""
while True:
clear_screen()
if invalid:
print(invalid)
invalid = ""
print("Random Matrix Options:")
print("1) Bernoulli")
print("2) Discrete uniform")
print("3) Binomial")
print("4) Poisson")
print("5) Geometric")
print("6) Hypergeometric")
print("7) Negative binomial")
distribution = input("Choose an option ('x' to go back): ")
if distribution.lower() == 'x':
return None
if distribution == '1': # Bernoulli
p = self.get_float_input("Enter the probability of success: ")
matrix = np.random.binomial(1, p, (height, width))
return sympy.Matrix(matrix)
elif distribution == '2': # Discrete uniform
lower_bound = int(self.get_float_input("Enter the lower integer bound: "))
upper_bound = int(self.get_float_input("Enter the upper integer bound: "))
matrix = np.random.randint(lower_bound, upper_bound + 1, (height, width))
return sympy.Matrix(matrix)
elif distribution == '3': # Binomial
n = int(self.get_float_input("Enter the number of trials: "))
p = self.get_float_input("Enter the probability of success: ")
matrix = np.random.binomial(n, p, (height, width))
return sympy.Matrix(matrix)
elif distribution == '4': # Poisson
lam = self.get_float_input("Enter the lambda parameter: ")
matrix = np.random.poisson(lam, (height, width))
return sympy.Matrix(matrix)
elif distribution == '5': # Geometric
p = self.get_float_input("Enter the probability of success: ")
matrix = np.random.geometric(p, (height, width))
return sympy.Matrix(matrix)
elif distribution == '6': # Hypergeometric
M = int(self.get_float_input("Enter the total number of objects: "))
n = int(self.get_float_input("Enter the number of type 1 objects: "))
N = int(self.get_float_input("Enter the number of draws: "))
matrix = np.random.hypergeometric(n, M - n, N, (height, width))
return sympy.Matrix(matrix)
elif distribution == '7': # Negative binomial
r = int(self.get_float_input("Enter the number of successes: "))
p = self.get_float_input("Enter the probability of success: ")
matrix = np.random.negative_binomial(r, p, (height, width))
return sympy.Matrix(matrix)
else:
invalid = "Invalid selection."
def create_variable_matrix(self, width, height):
matrix = []
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid input. Please enter 1, 2 or 3.")
invalid = False
print("Matrix variable options:")
print("1) All variables unique (a,b,c...).")
print("2) All variables unique (double index).")
if width == height:
print("3) Diagonal matrix")
option = input("Choose an option ('x' to go back): ")
if option.lower() == 'x':
return None
else:
character = self.get_character()
if option == '1':
counter = 0
if option == '3':
user_input = input("All variables the same? ('y' for yes)\n")
for i in range(height):
row = []
for j in range(width):
if option == '1':
# Variables are unique to each column
row.append(sympy.symbols(f'{chr(ord(character) + counter)}'))
counter += 1
elif option == '2':
# All variables are unique double index
row.append(sympy.symbols(f'{character}_{i+1}{j+1}'))
elif option == '3' and width == height:
# All variables are unique a,b,c
if j == i:
if user_input.lower() == 'y':
row.append(sympy.symbols(f'{chr(ord(character))}'))
else:
row.append(sympy.symbols(f'{chr(ord(character) + i)}'))
else:
row.append(0)
else:
invalid = True
continue
matrix.append(row)
break
return sympy.Matrix(matrix)
# Single Matrix Operations
# # # # # # # # # # # # #
def eval_variables_operation(self, index, substitutions, new):
matrix_title, matrix = self.matrices[index]
new_matrix = matrix.subs(substitutions)
if new:
# Append new matrix to matrices
self.matrices.append([get_name(f"{matrix_title}_evaluated"), new_matrix])
else:
self.matrices[index][1] = new_matrix
def eval_variables(self, matrix_num, new=False, reverse_mode=False):
# Add functionality to perform simultenous operations on
# a array of matrices. Each single matrix operation will
# treat matrix_num as a tuple of list indices, print matrices
# side-by-side, perform operations a selected matrices or print
# error messages if matrices are not compatible
if isinstance(matrix_num, list):
symbols_in_matrix = set()
# Iterate over the indices in the list
for index in matrix_num:
if index < len(self.matrices):
matrix_title, matrix = self.matrices[index]
# Add symbols in the matrix to the set
symbols_in_matrix.update(matrix.free_symbols)
else:
print(f"Index {index} is out of range.")
# Handle error or break loop
symbols_in_matrix = sorted(list(symbols_in_matrix), key=lambda s: str(s))
if not symbols_in_matrix:
print("No variables to evaluate in the selected matrices.")
else:
matrix_title, matrix = self.matrices[matrix_num]
symbols_in_matrix = sorted(list(matrix.free_symbols), key=lambda s: str(s))
if not symbols_in_matrix:
print("No variables to evaluate in this matrix.")
input("Enter to continue")
return
substitutions = {}
i = 0
invalid = False
while i < len(symbols_in_matrix):
clear_screen()
if invalid:
print("Invalid input. Please enter a number or a fraction.")
invalid = False
self.print_matrix_indices(matrix_num)
print(f"Enter a value: 'c' to keep constant,'-' to go back, 'x' to quit")
symbol = symbols_in_matrix[i]
user_input = input(f" > {sympy.pretty(symbol)}: ")
if user_input.lower() == 'c':
i += 1
elif user_input.lower() == '-' and i != 0:
i -= 1
elif user_input.lower() == 'x':
return False
else:
try:
# Convert input to number or fraction
value = sympy.sympify(user_input)
substitutions[symbol] = value
i += 1
except (sympy.SympifyError):
invalid = True
# Create new matrix with evaluated variables
if substitutions != {}:
if isinstance(matrix_num,list):
for i in matrix_num:
self.eval_variables_operation(i,substitutions,new)
else:
self.eval_variables_operation(matrix_num,substitutions,new)
return True
else:
print("All variables where constant")
input("Enter to continue")
return False
def get_scale_factor(self, matrix_num, message=""):
invalid = False
while True:
clear_screen()
if invalid:
print("Invalid input. Please enter a number or a fraction.")
invalid = False
if message:
print(message)
self.print_matrix_indices(matrix_num)
user_input = input("Enter the scaling factor (e.g., 3 or 1/2, 'x' to go back): ")
if user_input.lower() == 'x':
return None
try:
# Convert input to number or fraction
scale_factor = sympy.sympify(user_input)
return scale_factor
except (sympy.SympifyError):
invalid = True
def get_row_number(self, message, matrix_num, col=False):
invalid = ""
while True:
clear_screen()
if invalid:
print(invalid)
invalid = ""
if isinstance(matrix_num,list):
self.print_matrix_indices(matrix_num)
_, matrix = self.matrices[matrix_num[0]]
else:
matrix_title, matrix = self.matrices[matrix_num]
print(f"\nMatrix {matrix_title}:\n")
self.single_matrix_print(matrix)
n = matrix.rows if not col else matrix.cols
row_num = input(f"{message} (1-{n}) or 'x' to go back: ")
if row_num.lower() == 'x':
return None
try:
row_num = int(row_num) - 1
if row_num in range(n):
return row_num
else:
invalid = "Invalid row number."
except ValueError:
invalid = "Invalid input. Please enter an integer."
def scale_matrix_operation(self, index, scaling_factor, new):
if new:
matrix_title, matrix = self.matrices[index]
new_matrix = self.matrices[index][1] * scaling_factor
self.matrices.append([get_name(f"({scaling_factor}){matrix_title}"), new_matrix])
else:
self.matrices[index][1] *= scaling_factor
def scale_matrix(self, matrix_num, new=False, reverse_mode=False):
scaling_factor = self.get_scale_factor(matrix_num)
if scaling_factor is not None:
if isinstance(matrix_num, list):
for i in matrix_num:
self.scale_matrix_operation(i, scaling_factor, new)
else:
self.scale_matrix_operation(matrix_num, scaling_factor, new)
return True
def same_height(self, indices):
h = self.matrices[indices[0]][1].rows
for i in indices:
if self.matrices[i][1].rows != h:
return False
return True
def scale_row_operation(self, index, row_num, scaling_factor, new):
matrix_title ,matrix = self.matrices[index]
new_matrix = sympy.Matrix(matrix.tolist())
new_matrix[row_num,:] = new_matrix[row_num,:] * scaling_factor
new_matrix[row_num,:].simplify
if new:
self.matrices.append([get_name(f"({scaling_factor})R{row_num + 1}\\rightarrow R{row_num + 1}"), new_matrix])
else:
self.matrices[index][1] = new_matrix
def scale_row(self, matrix_num, new=False, reverse_mode=False):
if isinstance(matrix_num,list):
if not self.same_height(matrix_num):
print("Row Operations restricted to matrices of the same height")
input("Select different matrices. Enter to continue\n")
return False
invalid = False
while True:
clear_screen()
self.print_matrix_indices(matrix_num)
# Get row number
row_num = self.get_row_number("Enter the row number to scale", matrix_num)
if row_num is None:
return False
# Get scaling factor
scaling_factor = self.get_scale_factor(matrix_num)
if scaling_factor is None:
return False
# Scale row elements
if isinstance(matrix_num,list):
for i in matrix_num:
if reverse_mode == False or i == matrix_num[0]:
self.scale_row_operation(i, row_num, scaling_factor, new)
else:
self.scale_row_operation(i, row_num, 1/scaling_factor, new)
else:
self.scale_row_operation(matrix_num, row_num, scaling_factor, new)
# Return from the method
return True
def rearrange_operation(self, index, row1, row2, new):
matrix_title ,matrix = self.matrices[index]
new_matrix = sympy.Matrix(matrix.tolist())
new_matrix.row_swap(row1, row2)
if new:
self.matrices.append([get_name(f"R{row1 + 1}\\leftrightarrow R{row2 + 1}"), new_matrix])
else:
self.matrices[index][1] = new_matrix
def rearrange(self, matrix_num, new=False, reverse_mode=False):
if isinstance(matrix_num,list):
if not self.same_height(matrix_num):
print("Row Operations restricted to matrices of the same height")
input("Select different matrices. Enter to continue\n")
return False
# get row1
clear_screen()
self.print_matrix_indices(matrix_num)
row1 = self.get_row_number("Enter the first row number", matrix_num)
if row1 is None:
return False
# get row2
clear_screen()
self.print_matrix_indices(matrix_num)
row2 = self.get_row_number("Enter the second row number", matrix_num)
if row2 is None:
return False
if isinstance(matrix_num,list):
for i in matrix_num:
self.rearrange_operation(i, row1, row2, new)
else:
self.rearrange_operation(matrix_num, row1, row2, new)
return True
def scale_and_combine_operation(self, index, row_to_scale, row_to_add, scaling_factor, new):
# Scale and combine
matrix_title, matrix = self.matrices[index]
new_matrix = sympy.Matrix(matrix.tolist())
scaled_row = new_matrix.row(row_to_scale) * scaling_factor
combined_row = new_matrix.row(row_to_add) + scaled_row
combined_row.simplify()
# Update matrix with new row
new_matrix[row_to_add,:] = combined_row
if new:
self.matrices.append([get_name(f"(R{row_to_add + 1}) + ({scaling_factor})(R{row_to_scale + 1})\\rightarrow R{row_to_add + 1}"), new_matrix])
else:
self.matrices[index][1] = new_matrix
def scale_and_combine(self, matrix_num, new=False, reverse_mode=False):
if isinstance(matrix_num,list):
if not self.same_height(matrix_num):
print("Row Operations restricted to matrices of the same height")
input("Select different matrices. Enter to continue\n")
return False
# Get row to scale
clear_screen()
self.print_matrix_indices(matrix_num)
row_to_scale = self.get_row_number("Enter the row to scale", matrix_num)
if row_to_scale is None:
return False
# Get row to add to
clear_screen()
self.print_matrix_indices(matrix_num)
row_to_add = self.get_row_number("Enter the row to add to", matrix_num)
if row_to_add is None:
return False
# Get scaling factor
scaling_factor = self.get_scale_factor(matrix_num)
if isinstance(matrix_num, list):
for i in matrix_num:
if reverse_mode == False or i == matrix_num[0]:
self.scale_and_combine_operation(i, row_to_scale, row_to_add, scaling_factor, new)
else:
self.scale_and_combine_operation(i, row_to_scale, row_to_add, -scaling_factor, new)
else:
self.scale_and_combine_operation(matrix_num, row_to_scale, row_to_add, scaling_factor, new)
return True
def echelon_form(self,matrix_num,new=False):
matrix_title, matrix = self.matrices[matrix_num]
if new:
new_matrix = matrix.echelon_form()
self.matrices.append([get_name(f"{matrix_title}_\"echelon_form\""), new_matrix])
else:
self.matrices[matrix_num][1] = matrix.echelon_form()
return True
def rref(self,matrix_num,new=False):
matrix_title, matrix = self.matrices[matrix_num]
if new:
new_matrix = matrix.rref(pivots=False)
self.matrices.append([get_name(f"{matrix_title}_\"rref\""), new_matrix])
else:
self.matrices[matrix_num][1] = matrix.rref(pivots=False)
return True
def invert_matrix(self, matrix_num,new=False):
matrix_title, matrix = self.matrices[matrix_num]
# Check if the matrix is square
if matrix.shape[0] != matrix.shape[1]:
print("Error: Only square matrices can be inverted.")
input("Enter to continue")
return False
# Check if the matrix is invertible
if matrix.det() == 0:
print("Error: Matrix is singular (not invertible).")
input("Enter to continue")
return False
try:
# Invert the matrix
inverted_matrix = matrix.inv()
# Append the inverted matrix to the matrices list
if new:
self.matrices.append([get_name(f"{matrix_title}^-1"), inverted_matrix])
else:
self.matrices[matrix_num][1] = inverted_matrix
return True
except ValueError as e:
print("Error: ", e)
input("Enter to continue")
return False
def cofactor_matrix(self, matrix_num, new=False):
matrix_title, matrix = self.matrices[matrix_num]
# Check if the matrix is square
if matrix.shape[0] != matrix.shape[1]:
print("Error: Only square matrices have cofactors.")
input("Enter to continue")
return False
try:
# Compute the cofactor matrix of the matrix
cofactor_matrix = sympy.Matrix(matrix.shape[0], matrix.shape[1], lambda i, j: matrix.cofactor(i, j))
# Append the cofactor matrix to the matrices list
if new:
self.matrices.append([get_name(f"{matrix_title}_\"cofactor\""), cofactor_matrix])
else:
self.matrices[matrix_num][1] = cofactor_matrix
return True
except ValueError as e:
print("Error: ", e)
input("Enter to continue")
return False
def adjugate_matrix(self, matrix_num, new=False):
matrix_title, matrix = self.matrices[matrix_num]
# Check if the matrix is square
if matrix.shape[0] != matrix.shape[1]:
print("Error: Only square matrices can be adjugated.")
input("Enter to continue")
return False
try:
# Compute the adjugate of the matrix
adjugated_matrix = matrix.adjugate()
# Append the adjugated matrix to the matrices list
if new:
self.matrices.append([get_name(f"{matrix_title}_\"adjugated\""), adjugated_matrix])
else:
self.matrices[matrix_num][1] = adjugated_matrix
return True
except ValueError as e:
print("Error: ", e)
input("Enter to continue")