import math def ang(norm, phase): phase *= math.pi / 180. real = math.cos(phase) * norm imag = math.sin(phase) * norm return complex(real, imag) def readmat(lines): mat = [] pars = {} while lines: line = lines[0] lines = lines[1:] if '=' not in line: break left, right = line.split('=') left = left.strip() right = complex(eval(right)) pars[left] = right for key, val in pars.items(): print "%s = %s" % (key, str(val)) def myeval(part): for key, val in pars.items(): part = part.replace(key, str(val)) return complex(eval(part)) while lines: line = lines[0] lines = lines[1:] if line.strip() == '': continue if '\t' in line: parts = line.split('\t') else: parts = line.split(' ') parts = [myeval(p) for p in parts if p != ''] mat.append(parts) return mat def rowswap(mat, i, j): mat[i], mat[j] = mat[j], mat[i] def rowmult(mat, i, k): assert k != 0 mat[i] = [p * k for p in mat[i]] def rowdiv(mat, i, k): assert k != 0 mat[i] = [p / k for p in mat[i]] def rowadd(mat, i, j, k): assert i != j for col in xrange(len(mat[i])): mat[i][col] += mat[j][col] * k def solvematbycol(mat, col): mat.sort(key = lambda row, col = col: row[col] == 0) if col == 0: frow = 0 else: for i, line in enumerate(mat): if abs(line[col - 1]) < 0.00001: frow = i break else: raise Exception, "lol" for i in xrange(frow + 1, len(mat)): if mat[i][col] == 0: continue rowadd(mat, i, frow, - mat[i][col] / mat[frow][col]) def simplify(mat): for i, line in enumerate(mat): parts = [p.imag for p in line if p.imag != 0] parts += [p.real for p in line if p.real != 0] if parts: rowdiv(mat, i, min(parts)) def crepr(c): if c.imag == 0: return str(c.real) else: return str(c) def printmat(mat): print for line in mat: print ' '.join(["%8s" % crepr(i) for i in line]) def testdata(file): lines = [] for line in open(file, 'r'): line = line.strip('\n') if line == 'stop': break lines.append(line) return readmat(lines) if __name__ == '__main__': import sys a = testdata(sys.argv[1]) printmat(a) for col in range(len(a[0]) - 1): solvematbycol(a, col) printmat(a) simplify(a) printmat(a)