-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAugmentedMatrixToRREF.py
228 lines (209 loc) · 7.54 KB
/
AugmentedMatrixToRREF.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
# Joshua Allum, 28th January 2016
# RREF matrix solver
# Outputs every step in LaTeX format to be compiled
# Import fractions
from fractions import Fraction
# Initialize Matrix
matrix = []
def is_number(s):
try:
Fraction(s)
return True
except ValueError:
return False
#------------------------------------------------------------#
# Import augmented matrix from matrix.txt
print("Hello, getting matrix data...")
with open("matrix.txt", "r") as f:
for line in f:
row_string = line.rstrip('\n').split(' ')
row = []
for i in row_string:
try:
row.append(Fraction(i))
except ValueError:
row.append(i)
matrix.append(row)
print("Matrix data loaded.")
#------------------------------------------------------------#
# Prints matrix in its current state to terminal and to file
printed = 0
def print_matrix(m):
global printed
print("=============================")
if printed % 2 == 0 and printed != 0:
f.write('\\\\')
f.write('&\\begin{amatrix}{' + str(len(m[0]) - 1) + '}')
for i in m:
contains_fraction = False
for k in range (len(i) - 1):
if not (i[k] is str) and i[k].denominator != 1:
f.write('\\frac{'+str(i[k].numerator)+ \
'}{'+str(i[k].denominator)+'}&')
contains_fraction = True
else:
f.write(str(i[k]) + '&')
print(i[k], end=' ')
f.write(str(i[len(i) - 1]) + '\\\\')
if contains_fraction:
f.write('[0.25em]')
print(i[len(i) - 1])
f.write('\\end{amatrix}\n')
print("=============================")
printed += 1
return
#------------------------------------------------------------#
# Subtracts row, r2, from row, r1, enough times to make
# row, r1, column, lead_pos, equal 0
def row_subtract(r1, r2, lead_pos):
mult, contains_fraction = matrix[r1][lead_pos], False
if mult == 0:
f.write('\\\\')
return
elif mult == 1:
factor = '-R_'+str(r2+1)
sfactor = '-'
elif mult == -1:
factor = '+R_'+str(r2+1)
sfactor = '+'
elif mult < 0:
if mult.denominator != 1:
sfactor = '+\\frac{'+str(abs(mult.numerator))+ \
'}{'+str(mult.denominator)+'}'
contains_fraction = True
else:
sfactor = '+'+str(abs(mult))
factor = '+'+str(abs(mult))+'R_'+str(r2+1)
else:
if mult.denominator != 1:
sfactor = '-\\frac{'+str(mult.numerator)+ \
'}{'+str(mult.denominator)+'}'
contains_fraction = True
else:
sfactor = '-'+str(mult)
factor = '-'+str(mult)+'R_'+str(r2+1)
for i in range (len(matrix[r1])):
if type(matrix[r1][i]) is str:
if len(matrix[r1][i]) > 3:
matrix[r1][i] += sfactor+'('+str(matrix[r2][i])+')'
else:
matrix[r1][i] += sfactor+str(matrix[r2][i])
else:
matrix[r1][i] -= mult * matrix[r2][i]
f.write('R_'+str(r1+1)+factor+'\\\\')
if contains_fraction:
f.write('[0.25em]')
print('R_'+str(r1+1)+factor)
return
#------------------------------------------------------------#
# Performs row subtraction on all rows except the row, row_num
# and prints the steps taken to terminal and to file
def subtract_all_rows(row_num):
f.write('\\begin{array}{c}')
for r in range (len(matrix)):
if r != row_num:
row_subtract(r, row_num, lead_pos)
else:
f.write('\\\\')
f.write('\\end{array}')
if printed % 2 == 1:
f.write('&')
f.write('\n\sim\n')
#------------------------------------------------------------#
# Swaps row, row_num, to the end of the matrix
def swap_row(row_num, empty_rows):
last_nonzero_row = len(matrix)-1-empty_rows
temp = matrix[last_nonzero_row]
matrix[last_nonzero_row] = matrix[row_num]
matrix[row_num] = temp
del temp
f.write('\\begin{array}{c}')
for r in range (len(matrix)):
if r == last_nonzero_row:
f.write('R_'+str(row_num+1)+'\\leftrightarrow R_' \
+str(last_nonzero_row+1)+'\\\\')
print('R_'+str(row_num+1)+'<-->R_'+str(last_nonzero_row+1))
else:
f.write('\\\\')
f.write('\\end{array}')
if printed % 2 == 1:
f.write('&')
f.write('\n\sim\n')
return
#------------------------------------------------------------#
# Returns the position of the leading number of the row
def get_lead_pos(row_num):
for col_num in range (len(matrix[row_num])):
if matrix[row_num][col_num] != 0:
return col_num
return 0
#------------------------------------------------------------#
# Divides every element of the row, row_num by lead and prints
# the step taking to the terminal and to file
def divide_row(row_num, lead):
for i in range (len(matrix[row_num])):
if type(matrix[row_num][i]) is str:
prev = matrix[row_num][i]
recc = Fraction(1, lead)
if recc.denominator != 1:
matrix[row_num][i] = '\\frac{'+str(recc.numerator)+'}{' \
+str(recc.denominator)+'}'
if len(prev) > 3:
matrix[row_num][i] += '('+prev+')'
else:
matrix[row_num][i] += prev
else:
if len(prev) > 3:
matrix[row_num][i] = str(recc)+'('+prev+')'
else:
matrix[row_num][i] = str(recc)+prev
else:
matrix[row_num][i] /= lead
print(str(Fraction(1, lead))+'R_'+str(row_num+1))
f.write('\\begin{array}{c}')
for r in range(len(matrix)):
if r == row_num:
recc = Fraction(1, lead)
if recc.denominator != 1:
f.write('\\frac{'+str(recc.numerator)+'}{' \
+str(recc.denominator)+'}R_'+str(row_num+1)+'\\\\[0.25em]')
else:
f.write(str(recc)+'R_'+str(row_num+1)+'\\\\')
else:
f.write('\\\\')
f.write('\\end{array}')
if printed % 2 == 1:
f.write('&')
f.write('\n\sim\n')
#------------------------------------------------------------#
# Produces the row-reduced echelon form of the augmented
# matrix inputted and prints all the steps that were
# required to the terminal and to RREF.txt as compilable
# LaTeX code
with open('RREF.txt', 'w') as f:
f.write('$\\begin{aligned}[t]\n')
row_num, empty_rows, lead_pos = 0, 0, 0
print_matrix(matrix)
while row_num + empty_rows < len(matrix) and \
lead_pos < len(matrix[row_num]):
lead = matrix[row_num][lead_pos]
if lead == 0:
r = row_num
while r < (len(matrix)):
if matrix[r][lead_pos] != 0:
swap_row(row_num, r)
break
r += 1
lead = matrix[row_num][lead_pos]
if lead == 0:
lead_pos += 1
continue
else:
if lead == 1:
subtract_all_rows(row_num)
row_num += 1
lead_pos += 1
else:
divide_row(row_num, lead)
print_matrix(matrix)
f.write('\\end{aligned}$\n')