def generate_splitting_matrix_first(degree, splitpoint): matrix_form = generate_matrix_form(degree) _, M, P = matrix_form.args Z = sp.Matrix(degree + 1, degree + 1, lambda i, j: splitpoint**i if i == j else 0) Q = sp.MatMul(M.inverse(), Z, M).doit().simplify() return sp.MatMul(Q, P)
def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) if lh.is_Matrix or rh.is_Matrix: return sympy.MatMul(lh, rh, evaluate=False) else: return sympy.Mul(lh, rh, evaluate=False) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) if lh.is_Matrix or rh.is_Matrix: return sympy.MatMul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: return Div(lh, rh, in_parsing=True, evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc())
def state_equations(self): """System of first-order differential state equations: dotx = A x + B u where x is the state vector and u is the input vector. """ return expr(sym.Eq(self.dotx, sym.MatAdd(sym.MatMul(self.A, self.x), sym.MatMul(self.B, self.u)), evaluate=False))
def state_equations(self): """System of first-order differential state equations: x[n + 1] = A x[n] + B u[n] where x is the state vector and u is the input vector. """ return expr(sym.Eq(self.xnext, sym.MatAdd(sym.MatMul(self._A, self.x), sym.MatMul(self._B, self.u)), evaluate=False))
def state_equations(self): """System of first-order differential state equations: dotx(t) = A x(t) + B u(t) where x is the state vector and u is the input vector. """ return expr( sym.Eq(self.dotx, sym.MatAdd(sym.MatMul(self._A.sympy, self.x.sympy), sym.MatMul(self._B.sympy, self.u.sympy)), evaluate=False))
def output_equations(self): """System of output equations: y = C x + D u where y is the output vector, x is the state vector and u is the input vector. """ return expr(sym.Eq(self.y, sym.MatAdd(sym.MatMul(self.C, self.x), sym.MatMul(self.D, self.u)), evaluate=False))
def mat_mul_flat(lh, rh): if hasattr(lh, 'is_MatMul') and lh.is_MatMul or hasattr( rh, 'is_MatMul') and rh.is_MatMul: args = [] if hasattr(lh, 'is_MatMul') and lh.is_MatMul: args += list(lh.args) else: args += [lh] if hasattr(rh, 'is_MatMul') and rh.is_MatMul: args = args + list(rh.args) else: args += [rh] return sympy.MatMul(*args, evaluate=False) else: return sympy.MatMul(lh, rh, evaluate=False)
def output_equations(self): """System of output equations: y(t) = C x(t) + D u(t) where y is the output vector, x is the state vector and u is the input vector. """ return expr( sym.Eq(self.y, sym.MatAdd(sym.MatMul(self._C.sympy, self.x.sympy), sym.MatMul(self._D.sympy, self.u.sympy)), evaluate=False))
def map_lin_acc_in_world(self): r_mat = sp.Matrix([[(sp.cos(self.q_z)*sp.cos(self.q_y)) - (sp.sin(self.q_x)*sp.sin(self.q_z)*sp.sin(self.q_y)), -(sp.cos(self.q_x)*sp.cos(self.q_z)), (sp.cos(self.q_z)*sp.sin(self.q_y)) + (sp.cos(self.q_y)*sp.sin(self.q_x)*sp.sin(self.q_z))], [(sp.cos(self.q_y)*sp.sin(self.q_z)) - (sp.cos(self.q_z)*sp.sin(self.q_x)*sp.sin(self.q_y)), (sp.cos(self.q_x)*sp.cos(self.q_z)), (sp.sin(self.q_z)*sp.sin(self.q_y)) + (sp.cos(self.q_z)*sp.cos(self.q_y)*sp.sin(self.q_x))], [-sp.cos(self.q_x)*sp.sin(self.q_y), sp.sin(self.q_x), sp.cos(self.q_x)*sp.cos(self.q_y)]]) a = sp.MatMul(r_mat, sp.Matrix([[self.a_x - self.ba_x - self.na_x], [self.a_y - self.ba_y - self.na_y], [self.a_z - self.ba_z - self.na_z]])) lin_acc_in_world = sp.Matrix([[0],[0],[-9.81]]) + a return lin_acc_in_world # if __name__ == "__main__": # state = State() # f1 = state.x**2 # f2 = state.y**2 # f3 = state.z**2 # f4 = state.q_x**2 # x = sp.Matrix([state.x,state.y,state.z, state.q_x]) # f_x = sp.Matrix([f1,f2,f3, f4]) # state.jacobian(f_x, x)
def convert_add(add): if add.ADD(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) if lh.is_Matrix or rh.is_Matrix: return sympy.MatAdd(lh, rh, evaluate=False) else: return sympy.Add(lh, rh, evaluate=False) elif add.SUB(): lh = convert_add(add.additive(0)) rh = convert_add(add.additive(1)) if lh.is_Matrix or rh.is_Matrix: return sympy.MatAdd(lh, sympy.MatMul(-1, rh, evaluate=False), evaluate=False) else: # If we want to force ordering for variables this should be: # return Sub(lh, rh, evaluate=False) if not rh.is_Matrix and rh.func.is_Number: rh = -rh else: rh = sympy.Mul(-1, rh, evaluate=False) return sympy.Add(lh, rh, evaluate=False) else: return convert_mp(add.mp())
def __buildProp(self, variables): diffs = [_sp.diff(self.__func, symb) for symb in self.__variables] tmp = diffs[0]**2 for diff, deltas in zip(diffs, self.__errorSymbs): tmp = _sp.Add(tmp, _sp.MatMul(diff**2, deltas**2)) return (tmp - diffs[0]**2)**( 1 / 2) # propagation assuming no correlations between errors
def express_func(frame1, frame2, tree): """ Static Method of the class the serves as a helper to the self.express(other) method definition and the reference_frame class express method. Parameters ---------- frame1, frame_2 : reference_frame_like An instance of `global_frame` or `reference_frame` classes. tree : nx.DiGraph The directed reference tree that stores the information of the relation between the given references. Returns ------- mat : sympy.MatMul A sequence of matrix multiplications that represents the transformation between the given frame. """ child_name = frame1.name parent_name = frame2.name graph = tree path_nodes = nx.algorithms.shortest_path(graph, child_name, parent_name) path_matrices = [] for i in range(len(path_nodes) - 1): path_matrices.append(graph.edges[path_nodes[-i - 2], path_nodes[-i - 1]]['mat']) mat = sm.MatMul(*path_matrices) return mat
def convert_unary(unary): if hasattr(unary, 'unary'): nested_unary = unary.unary() else: nested_unary = unary.unary_nofunc() if hasattr(unary, 'postfix_nofunc'): first = unary.postfix() tail = unary.postfix_nofunc() postfix = [first] + tail else: postfix = unary.postfix() if unary.ADD(): return convert_unary(nested_unary) elif unary.SUB(): tmp_convert_nested_unary = convert_unary(nested_unary) if tmp_convert_nested_unary.is_Matrix: return sympy.MatMul(-1, tmp_convert_nested_unary, evaluate=False) else: if tmp_convert_nested_unary.func.is_Number: return -tmp_convert_nested_unary else: return sympy.Mul(-1, tmp_convert_nested_unary, evaluate=False) elif postfix: return convert_postfix_list(postfix)
def matmul(other, hold=True): if hold: new = sympy.MatMul(mat, other) else: new = mat.multiply(other) custom_sympy_attrs(new) return new
def equations(self, inverse=False): """System of equations used to find the unknowns. If inverse is True, evaluate the Matrix inverse.""" self._analyse() if inverse: return expr( sym.Eq(self.X, sym.MatMul(self._A.inv(), self._Z), evaluate=False)) return expr( sym.Eq(self.X, sym.MatMul(sym.Pow(self._A, -1), self._Z), evaluate=False))
def generate_matrix_form(degree): # See https://pomax.github.io/bezierinfo/#matrix bezier_without_points = eq_r_bezier.rhs.replace(s_p[s_i, s_k], 1) expanded = bezier_without_points.subs(s_K, degree).doit() coeffs = [sp.Poly(arg).coeffs() for arg in expanded.args] coeffs = sorted(coeffs, key=len) coeffs = [coeff + [0] * (len(coeffs) - len(coeff)) for coeff in coeffs] coeff_matrix = sp.Matrix(coeffs) t_matrix = sp.Matrix([s_t**i for i in range(degree + 1)]).T p_matrix = sp.Matrix([s_p[s_i, i] for i in range(degree + 1)]) return sp.MatMul(t_matrix, coeff_matrix, p_matrix)
def generate_splitting_matrix_second(degree, splitpoint): Q, P = generate_splitting_matrix_first(degree, splitpoint).args Q = Q.tolist() def rotate(l, n): return l[-n:] + l[:-n] Q = [rotate(r, len(r) - 1 - i) for i, r in enumerate(Q)] Q.reverse() Q = sp.Matrix(Q) return sp.MatMul(Q, P)
def format(self, form='A y = b', invert=False): """Forms can be: A y = b b = A y Ainv b = y y = Ainv b If `invert` is True, the A matrix is inverted.""" if form == 'A y = b': return expr(sym.Eq(sym.MatMul(self.A, self.y), self.b), evaluate=False) elif form == 'b = A y': return expr(sym.Eq(self.b, sym.MatMul(self.A, self.y)), evaluate=False) elif form in ('y = Ainv b', 'default'): if invert: return expr(sym.Eq(self.y, sym.MatMul(self.Ainv, self.b), evaluate=False)) return expr(sym.Eq(self.y, sym.MatMul(sym.Pow(self.A, -1), self.b), evaluate=False)) elif form == 'Ainv b = y': if invert: return expr(sym.Eq(sym.MatMul(self.Ainv, self.b), self.y, evaluate=False)) return expr(sym.Eq(sym.MatMul(sym.Pow(self.A, -1), self.b), self.y, evaluate=False)) else: raise ValueError('Unknown form %s' % form)
def mat_mul_flat(lh, rh): if hasattr(lh, 'is_MatMul') and lh.is_MatMul or hasattr( rh, 'is_MatMul') and rh.is_MatMul: args = [] if hasattr(lh, 'is_MatMul') and lh.is_MatMul: args += list(lh.args) else: args += [lh] if hasattr(rh, 'is_MatMul') and rh.is_MatMul: args = args + list(rh.args) else: args += [rh] return sympy.MatMul(*[arg.doit() for arg in args], evaluate=False) else: if hasattr(lh, 'doit') and hasattr(rh, 'doit'): return sympy.MatMul(lh.doit(), rh.doit(), evaluate=False) elif hasattr(lh, 'doit') and not hasattr(rh, 'doit'): return sympy.MatMul(lh.doit(), rh, evaluate=False) elif not hasattr(lh, 'doit') and hasattr(rh, 'doit'): return sympy.MatMul(lh, rh.doit(), evaluate=False) else: return sympy.MatMul(lh, rh, evaluate=False)
def hill(text, k): key = sy.Matrix([[k[0], k[1]], [k[2], k[3]]]) key_adjugate = key.T.adjugate().applyfunc(mod) key_mod_inverse = (MMI(key.det() % MOD, MOD) * key_adjugate).applyfunc(mod) plaintext = '' for i, j in zip(text[0::2], text[1::2]): pair = sy.MatMul(key_mod_inverse, sy.Matrix([[abc.index(i)], [abc.index(j)]])) plaintext += abc[pair[0, 0] % MOD] + abc[pair[1, 0] % MOD] return plaintext
def map_ang_vel_in_world(self): g_mat = sp.Matrix([[sp.cos(self.q_y), 0, -(sp.cos(self.q_x)*sp.sin(self.q_y))], [0, 1, sp.sin(self.q_x) ], [sp.sin(self.q_y),0, (sp.cos(self.q_x)*sp.cos(self.q_y))]]) inverse_g = g_mat.T ang_vel_in_world = sp.MatMul(inverse_g, sp.Matrix([[self.w_x - self.bg_x - self.ng_x], [self.w_y - self.bg_y - self.ng_y], [self.w_z - self.bg_z - self.ng_z]])) ang_vel_in_world = sp.Matrix(ang_vel_in_world) # print(ang_vel_in_world.shape) # a = ang_vel_in_world[0,:] # b = ang_vel_in_world[1,:] # c = sp.Matrix([a,b]) # print(a.shape, b.shape, c.shape) return ang_vel_in_world
def convert_frac(frac): diff_op = False partial_op = False lower_itv = frac.lower.getSourceInterval() lower_itv_len = lower_itv[1] - lower_itv[0] + 1 if (frac.lower.start == frac.lower.stop and frac.lower.start.type == PSLexer.DIFFERENTIAL): wrt = get_differential_var_str(frac.lower.start.text) diff_op = True elif (lower_itv_len == 2 and frac.lower.start.type == PSLexer.SYMBOL and frac.lower.start.text == '\\partial' and (frac.lower.stop.type == PSLexer.LETTER_NO_E or frac.lower.stop.type == PSLexer.SYMBOL)): partial_op = True wrt = frac.lower.stop.text if frac.lower.stop.type == PSLexer.SYMBOL: wrt = wrt[1:] if diff_op or partial_op: wrt = sympy.Symbol(wrt, real=True, positive=True) if (diff_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == PSLexer.LETTER_NO_E and frac.upper.start.text == 'd'): return [wrt] elif (partial_op and frac.upper.start == frac.upper.stop and frac.upper.start.type == PSLexer.SYMBOL and frac.upper.start.text == '\\partial'): return [wrt] upper_text = rule2text(frac.upper) expr_top = None if diff_op and upper_text.startswith('d'): expr_top = process_sympy(upper_text[1:]) elif partial_op and frac.upper.start.text == '\\partial': expr_top = process_sympy(upper_text[len('\\partial'):]) if expr_top: return sympy.Derivative(expr_top, wrt) expr_top = convert_expr(frac.upper) expr_bot = convert_expr(frac.lower) if expr_top.is_Matrix or expr_bot.is_Matrix: return sympy.MatMul(expr_top, sympy.Pow(expr_bot, -1, evaluate=False), evaluate=False) else: return sympy.Mul(expr_top, sympy.Pow(expr_bot, -1, evaluate=False), evaluate=False)
def convert_mp(mp): if hasattr(mp, 'mp'): mp_left = mp.mp(0) mp_right = mp.mp(1) else: mp_left = mp.mp_nofunc(0) mp_right = mp.mp_nofunc(1) if mp.MUL() or mp.CMD_TIMES() or mp.CMD_CDOT(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) if lh.is_Matrix or rh.is_Matrix: return mat_mul_flat(lh, rh) else: return mul_flat(lh, rh) elif mp.DIV() or mp.CMD_DIV() or mp.COLON(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) if lh.is_Matrix or rh.is_Matrix: return sympy.MatMul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) else: return sympy.Mul(lh, sympy.Pow(rh, -1, evaluate=False), evaluate=False) elif mp.CMD_MOD(): lh = convert_mp(mp_left) rh = convert_mp(mp_right) if rh.is_Matrix: raise Exception( "Cannot perform modulo operation with a matrix as an operand") else: return sympy.Mod(lh, rh, evaluate=False) else: if hasattr(mp, 'unary'): return convert_unary(mp.unary()) else: return convert_unary(mp.unary_nofunc())
def convert_postfix_list(arr, i=0): if i >= len(arr): raise Exception("Index out of bounds") res = convert_postfix(arr[i]) if isinstance(res, sympy.Expr) or isinstance(res, sympy.Matrix): if i == len(arr) - 1: return res # nothing to multiply by else: # multiply by next rh = convert_postfix_list(arr, i + 1) if res.is_Matrix or rh.is_Matrix: return sympy.MatMul(res, rh, evaluate=False) else: return sympy.Mul(res, rh, evaluate=False) else: # must be derivative wrt = res[0] if i == len(arr) - 1: raise Exception("Expected expression for derivative") else: expr = convert_postfix_list(arr, i + 1) return sympy.Derivative(expr, wrt)
def matmuldiff(expr, symbol, order): if order > 1: # recursively reduce to order 1: tmp = matmuldiff(expr, symbol, order - 1) # last deriv step return matrix_time_deriv(tmp, func_symbols, t_symbol, prov_deriv_symbols, order=1) args = expr.args res = 0 * expr for i, a in enumerate(args): first_factors = args[:i] last_factors = args[i + 1:] diff_factor = time_deriv(a, func_symbols, t_symbol=symbol) product_args = first_factors + (diff_factor, ) + last_factors res = res + sp.MatMul(*product_args) return res
# %% Programa para obtener K y f correspondientes al elemento de barra de # % 2 nodos unidimensional, utilizando funciones de forma globales import sympy as sp from sympy.matrices import Matrix sp.init_printing(pretty_print=True) # Defino las variables simbolicas x, L, E, A, b = sp.symbols('x L E A b') N1 = sp.Function('N1') N2 = sp.Function('N2') N3 = sp.Function('N3') N4 = sp.Function('N4') # Defino las funciones de forma N = Matrix([[N1(x), N2(x), N3(x), N4(x)]]) # matriz de funciones de forma B = sp.diff(N,x) # matriz de deformación D = E*A # matriz constitutiva # Matriz de rigidez (ecuación 2.83) fc = A*E # factor común K = sp.simplify(sp.integrate(B.T*D*B, (x, 0, L))) K = sp.MatMul(fc, K/fc, evaluate = False) print('K = '); sp.pprint(K, num_columns=150); print() # Vector de fuerzas nodales equivalentes (ecuación 2.83) fc = b f = sp.simplify(sp.integrate(N.T*b, (x, 0, L))) f = sp.MatMul(fc, f/fc, evaluate = False) print('f = '); sp.pprint(f)
x_n = sp.MatrixSymbol('x_n', 2, 1) hessian = sp.MatrixSymbol('hessian', 2, 2) d = sp.MatrixSymbol('d', 2, 1) lamda = sp.symbols("lamda") gamma = 100 f = -9 * x[0] - 10 * x[1] + \ gamma * (-sp.log(100 - x[0] - x[1]) - sp.log(x[0]) - sp.log(x[1]) - sp.log(50 - x[0] + x[1])) # function # Gradient f_grad = sp.Matrix([f.diff(var) for var in x]) # Hessian f_hess = sp.Matrix([diff_rows(j, x) for j in f_grad]) dk = sp.MatMul(-1 * hessian * f_grad) x00 = sp.Matrix([[8], [90]]) x01 = sp.Matrix([[1], [40]]) x02 = sp.Matrix([[15], [68.69]]) x03 = sp.Matrix([[10], [20]]) for x0 in [x00, x01, x02, x03]: k = 0 while True: h = f_hess.subs({x: x0}).evalf() h = h.inv('LU') d_ = sp.Matrix(dk.subs({x: x0, hessian: h})) if k > 100 or d_ == 0: break
def equations(self): """Return the equations in matrix form.""" return expr(equation(sym.MatMul(self.A, self.y), self.b))
def fitCij(crystSys, arguments): print "\n------------------------------------Fitted Results-------------------------------------" def fit(i, j): from scipy import stats, sqrt, square stress_fit = np.array(stress[i, j]) slope, intercept, r, p, stderr = stats.linregress(delta, stress_fit) print '\n' print 'Fitted result ', Stress_string[i, j], ' : ', slope print 'Error : ', stderr if abs(r) > 0.9: print 'Correlation coefficient (r) : ', r else: print 'Correlation coefficient (r) : ', r, ' <----- WARNING: BAD FIT' return slope, stderr def createCij(): CijMatrix = np.zeros((6, 6)) CijErrorMatrix = np.zeros((6, 6)) c = np.array(get_cij_pattern(crystSys)) for i in range(0, 6): for j in range(0, 6): index = int(c[i, j]) if index > 0: CijMatrix[i, j] = Cij_list[index - 1] CijErrorMatrix[i, j] = abs(Cij_errors_list[index - 1]) elif index < 0: CijMatrix[i, j] = -Cij_list[-index - 1] CijErrorMatrix[i, j] = abs(Cij_errors_list[-index - 1]) return CijMatrix, CijErrorMatrix # get stress from OUTCAR command = ( "grep 'in kB' outcar.2 | tail -1 | awk '{print -$3/10.0, -$4/10.0, -$5/10.0, -$7/10.0, -$8/10.0, -$6/10.0}'" ) stress = [] strain = [] delta_list = [] str_list = os.listdir("./") str_list = [int(elem[3:]) for elem in str_list if "str" in elem] str_list.sort() os.chdir("./rlx") process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) stress0 = [float(elem) for elem in process.stdout.read().strip().split()] os.chdir("../") for this_stress in str_list: stress_str = [] delta_list_in = [] os.chdir("./str" + str(this_stress)) delta_string = os.listdir("./") delta = [float(elem[1:]) for elem in delta_string if "d" in elem] delta.sort() for this_delta in delta: delta_list_in.append(this_delta) os.chdir("./d" + str(this_delta)) process = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True) stress_str.append([ float(elem) for elem in process.stdout.read().strip().split() ]) os.chdir("../") os.chdir("../") stress.append(stress_str) delta_list.append(delta_list_in) strain.append(get_strain_pattern(crystSys)) delta = np.array(delta) stress = (np.array(stress) - np.array(stress0)).tolist() c = np.zeros((6, 6)) re_stress = np.zeros((6, 6)) r_value = np.zeros((6, 6)) p_value = np.zeros((6, 6)) std_err = np.zeros((6, 6)) stress = np.array([np.array(stress_elem).T for stress_elem in stress]) # Start fitting Cijs Stress_string = np.chararray((6, 6), itemsize=15) Cij_list = np.zeros(21) Cij_errors_list = np.zeros(21) print "This code is trying to evaluate: " sympy.init_printing() stress_sym = (get_stress_pattern_sym(arguments.crystSys) / d) strain_sym = get_strain_pattern_sym(arguments.crystSys) cij_sym = get_cij_pattern_sym(arguments.crystSys) sympy.pprint( sympy.relational.Eq((stress_sym * d).T, sympy.MatMul(cij_sym, strain_sym.T))) # Initialize string for Stresses using symbolic notation e.g. C11+C12 stress_sym = np.array(stress_sym) for i in range(stress_sym.shape[0]): for j in range(stress_sym.shape[1]): Stress_string[i][j] = stress_sym[i][j] # Fitting results stored in Fit_results and error in Fit_errors Fit_results = np.zeros((stress_sym.shape)) Fit_errors = np.zeros((stress_sym.shape)) for i in range(stress_sym.shape[0]): for j in range(stress_sym.shape[1]): if stress_sym[i][j] != 0: Fit_results[i][j], Fit_errors[i][j] = fit(i, j) # Solve symbolic equations to get values for each Cijs # if crystSys == 1: # cubic # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C12" # Stress_string[0, 3] = "C44" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # Cij_list[3], Cij_errors_list[3] = fit(0, 3) # c44 # fit01, error01 = fit(0, 1) # 12 # fit02, error02 = fit(0, 2) # 12 # Cij_list[6] = (fit01+fit02)/2 # c12 # Cij_errors_list[6] = (error01+error02)/2 # elif crystSys == 2: # tetragonal high 4mm,-42m,422,4/mmm e1+e4, e3+e6 # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C44" # Stress_string[1, 0] = "C13" # Stress_string[1, 1] = "C13" # Stress_string[1, 2] = "C33" # Stress_string[1, 5] = "C66" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # Cij_list[6], Cij_errors_list[6] = fit(0, 1) # c12 # fit02, error02 = fit(0, 2) # 13 # Cij_list[3], Cij_errors_list[3] = fit(0, 3) # c44 # fit10, error10 = fit(1, 0) # 13 # fit11, error11 = fit(1, 1) # 13 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # Cij_list[5], Cij_errors_list[5] = fit(1, 5) # c66 # Cij_list[7] = (fit02+fit10+fit11)/3 # c13 # Cij_errors_list[7] = (error02+error10+error11)/3 # elif crystSys == 21: # tetragonal low 4, -4, 4/m e1+e4, e3+e6 # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C44" # Stress_string[0, 5] = "C16" # Stress_string[1, 0] = "C13 + C16" # Stress_string[1, 1] = "C13 - C16" # Stress_string[1, 2] = "C33" # Stress_string[1, 5] = "C66" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # Cij_list[6], Cij_errors_list[6] = fit(0, 1) # c12 # fit02, error02 = fit(0, 2) # 13 # Cij_list[3], Cij_errors_list[3] = fit(0, 3) # c44 # fit05, error05 = fit(0, 5) # 16 # fit10, error10 = fit(1, 0) # 13+16 # fit11, error11 = fit(1, 1) # 13-16 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # Cij_list[5], Cij_errors_list[5] = fit(1, 5) # c66 # Cij_list[7] = (fit02+fit10+fit11)/3 # c13 # Cij_errors_list[7] = (error02+error10+error11)/3 # Cij_list[10] = (fit10-fit11+fit05)/3 # c16 # Cij_errors_list[10] = (error10-error11+error05)/3 # elif crystSys == 3: # orthohombic # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C44" # Stress_string[1, 0] = "C12" # Stress_string[1, 1] = "C22" # Stress_string[1, 2] = "C23" # Stress_string[1, 4] = "C55" # Stress_string[2, 0] = "C13" # Stress_string[2, 1] = "C23" # Stress_string[2, 2] = "C33" # Stress_string[2, 5] = "C66" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # fit01, error01 = fit(0, 1) # 12 # fit02, error02 = fit(0, 2) # 13 # Cij_list[3], Cij_errors_list[3] = fit(0, 3) # c44 # fit10, error10 = fit(1, 0) # 12 # Cij_list[1], Cij_errors_list[1] = fit(1, 1) # c22 # fit12, error12 = fit(1, 2) # 23 # Cij_list[4], Cij_errors_list[4] = fit(1, 4) # c55 # fit20, error20 = fit(2, 0) # 13 # fit21, error21 = fit(2, 1) # 23 # Cij_list[2], Cij_errors_list[2] = fit(2, 2) # c33 # Cij_list[5], Cij_errors_list[5] = fit(2, 5) # c66 # Cij_list[6] = (fit10+fit01)/2 # c12 # Cij_errors_list[6] = (error10+error01)/2 # Cij_list[7] = (fit02+fit20)/2 # c13 # Cij_errors_list[7] = (error02+error20)/2 # Cij_list[11] = (fit12+fit21)/2 # c23 # Cij_errors_list[11] = (error12+error21)/2 # elif crystSys == 4: # monoclinic # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C44" # Stress_string[0, 4] = "C15" # Stress_string[0, 5] = "C46" # Stress_string[1, 0] = "C13" # Stress_string[1, 1] = "C23" # Stress_string[1, 2] = "C33" # Stress_string[1, 3] = "C46" # Stress_string[1, 4] = "C53" # Stress_string[1, 5] = "C66" # Stress_string[2, 0] = "C12" # Stress_string[2, 1] = "C22" # Stress_string[2, 2] = "C23" # Stress_string[2, 4] = "C25" # Stress_string[3, 0] = "C15" # Stress_string[3, 1] = "C25" # Stress_string[3, 2] = "C35" # Stress_string[3, 4] = "C55" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # fit01, error01 = fit(0, 1) # 12 # fit02, error02 = fit(0, 2) # 13 # Cij_list[3], Cij_errors_list[3] = fit(0, 3) # c44 # fit04, error04 = fit(0, 4) # 15 # fit05, error05 = fit(0, 5) # 46 # fit10, error10 = fit(1, 0) # 13 # fit11, error11 = fit(1, 1) # 23 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # fit13, error13 = fit(1, 3) # 46 # fit14, error14 = fit(1, 4) # 35 # Cij_list[5], Cij_errors_list[5] = fit(1, 5) # c66 # fit20, error20 = fit(2, 0) # 12 # Cij_list[1], Cij_errors_list[1] = fit(2, 1) # c22 # fit22, error22 = fit(2, 2) # 23 # fit24, error24 = fit(2, 4) # 25 # fit30, error30 = fit(3, 0) # 15 # fit31, error31 = fit(3, 1) # 25 # fit32, error32 = fit(3, 2) # 35 # Cij_list[4], Cij_errors_list[4] = fit(3, 4) # c55 # Cij_list[6] = (fit20+fit01)/2 # c12 # Cij_errors_list[6] = (error20+error01)/2 # Cij_list[7] = (fit02+fit10)/2 # c13 # Cij_errors_list[7] = (error02+error10)/2 # Cij_list[11] = (fit11+fit22)/2 # c23 # Cij_errors_list[11] = (error11+error22)/2 # Cij_list[9] = (fit04+fit30)/2 # c15 # Cij_errors_list[9] = (error04+error30)/2 # Cij_list[13] = (fit24+fit31)/2 # c25 # Cij_errors_list[13] = (error24+error31)/2 # Cij_list[16] = (fit14+fit32)/2 # c35 # Cij_errors_list[16] = (error14+error32)/2 # Cij_list[19] = (fit13+fit05)/2 # c46 # Cij_errors_list[19] = (error13+error05)/2 # elif crystSys == 41: # monoclinic # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C44" # Stress_string[0, 4] = "C45" # Stress_string[0, 5] = "C16" # Stress_string[1, 0] = "C13" # Stress_string[1, 1] = "C23" # Stress_string[1, 2] = "C33" # Stress_string[1, 3] = "C45" # Stress_string[1, 4] = "C55" # Stress_string[1, 5] = "C36" # Stress_string[2, 0] = "C12" # Stress_string[2, 1] = "C22" # Stress_string[2, 2] = "C23" # Stress_string[2, 5] = "C26" # Stress_string[3, 0] = "C16" # Stress_string[3, 1] = "C26" # Stress_string[3, 2] = "C36" # Stress_string[3, 5] = "C66" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # fit01, error01 = fit(0, 1) # 12 # fit02, error02 = fit(0, 2) # 13 # Cij_list[3], Cij_errors_list[3] = fit(0, 3) # c44 # fit04, error04 = fit(0, 4) # 45 # fit05, error05 = fit(0, 5) # 16 # fit10, error10 = fit(1, 0) # 13 # fit11, error11 = fit(1, 1) # 23 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # fit13, error13 = fit(1, 3) # 45 # Cij_list[4], Cij_errors_list[4] = fit(1, 4) # c55 # fit15, error15 = fit(1, 5) # 36 # fit20, error20 = fit(2, 0) # 12 # Cij_list[1], Cij_errors_list[1] = fit(2, 1) # c22 # fit22, error22 = fit(2, 2) # 23 # fit25, error25 = fit(2, 5) # 26 # fit30, error30 = fit(3, 0) # 16 # fit31, error31 = fit(3, 1) # 26 # fit32, error32 = fit(3, 2) # 36 # Cij_list[5], Cij_errors_list[5] = fit(3, 5) # c66 # Cij_list[6] = (fit20+fit01)/2 # c12 # Cij_errors_list[6] = (error20+error01)/2 # Cij_list[7] = (fit02+fit10)/2 # c13 # Cij_errors_list[7] = (error02+error10)/2 # Cij_list[11] = (fit22+fit11)/2 # c23 # Cij_errors_list[11] = (error22+error11)/2 # Cij_list[10] = (fit05+fit30)/2 # c16 # Cij_errors_list[10] = (error05+error30)/2 # Cij_list[14] = (fit25+fit31)/2 # c26 # Cij_errors_list[14] = (error25+error31)/2 # Cij_list[17] = (fit15+fit15)/2 # c36 # Cij_errors_list[17] = (error32+error32)/2 # Cij_list[18] = (fit13+fit04)/2 # c45 # Cij_errors_list[18] = (error13+error04)/2 # elif crystSys == 5: # triclinic # index = 0 # c = np.array(get_cij_pattern(crystSys)) # temp = np.zeros((6, 6)) # temp_err = np.zeros((6, 6)) # for i in range(6): # for j in range(6): # Stress_string[i, j] = "C"+str(i+1)+str(j+1) # temp[i, j], temp_err[i, j] = fit(i, j) # temp = (temp+temp.T)/2 # temp_err = (temp_err+temp_err.T)/2 # for i in range(6): # for j in range(i, 6): # Cij_list[c[i, j]-1] = temp[i, j] # Cij_errors_list[c[i, j]-1] = temp_err[i, j] # index += 1 # elif crystSys == 6: # hexagonal # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[1, 0] = "C13" # Stress_string[1, 1] = "C13" # Stress_string[1, 2] = "C33" # Stress_string[1, 3] = "C44" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # Cij_list[6], Cij_errors_list[6] = fit(0, 1) # c12 # fit02, error02 = fit(0, 2) # 13 # fit10, error10 = fit(1, 0) # 13 # fit11, error11 = fit(1, 1) # 13 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # Cij_list[3], Cij_errors_list[3] = fit(1, 3) # c44 # Cij_list[7] = (fit02+fit10+fit11)/3 # c13 # Cij_errors_list[7] = (error02+error10+error11)/3 # Cij_list[5] = 0.5*(Cij_list[0]-Cij_list[6]) # c66 # Cij_errors_list[5] = 0.5*(Cij_errors_list[0]-Cij_errors_list[6]) # elif crystSys == 7: # trignoal high # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C14" # Stress_string[1, 0] = "C13 + C14" # Stress_string[1, 1] = "C13 - C14" # Stress_string[1, 2] = "C33" # Stress_string[1, 3] = "C44" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # Cij_list[6], Cij_errors_list[6] = fit(0, 1) # c12 # fit02, error02 = fit(0, 2) # 13 # fit03, error03 = fit(0, 3) # 14 # fit10, error10 = fit(1, 0) # 13+14 # fit11, error11 = fit(1, 1) # 13-14 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # Cij_list[3], Cij_errors_list[3] = fit(1, 3) # c44 # Cij_list[7] = (fit02+fit10+fit11)/3 # c13 # Cij_errors_list[7] = (error02+error10+error11)/3 # Cij_list[8] = (fit03+fit10-fit11)/3 # c14 # Cij_errors_list[8] = (error03+error10-error11)/3 # Cij_list[5] = 0.5*(Cij_list[0]-Cij_list[6]) # c66 # Cij_errors_list[5] = 0.5*(Cij_errors_list[0]-Cij_errors_list[6]) # elif crystSys == 71: # trignoal low # Stress_string[0, 0] = "C11" # Stress_string[0, 1] = "C12" # Stress_string[0, 2] = "C13" # Stress_string[0, 3] = "C14" # Stress_string[0, 4] = "-C25" # Stress_string[1, 0] = "C13 + C14" # Stress_string[1, 1] = "C13 - C14" # Stress_string[1, 2] = "C33" # Stress_string[1, 3] = "C44" # Stress_string[1, 5] = "C25" # Cij_list[0], Cij_errors_list[0] = fit(0, 0) # c11 # Cij_list[6], Cij_errors_list[6] = fit(0, 1) # c12 # fit02, error02 = fit(0, 2) # 13 # fit03, error03 = fit(0, 3) # 14 # fit04, error04 = fit(0, 4) # -25 # fit10, error10 = fit(1, 0) # 13+14 # fit11, error11 = fit(1, 1) # 13-14 # Cij_list[2], Cij_errors_list[2] = fit(1, 2) # c33 # Cij_list[3], Cij_errors_list[3] = fit(1, 3) # c44 # fit15, error15 = fit(1, 5) # 25 # Cij_list[7] = (fit02+fit10+fit11)/3 # c13 # Cij_errors_list[7] = (error02+error10+error11)/3 # Cij_list[8] = (fit03+fit10-fit11)/3 # c14 # Cij_errors_list[8] = (error03+error10-error11)/3 # Cij_list[13] = (-fit04+fit15)/2 # c25 # Cij_errors_list[13] = (-error04+error15)/2 # Cij_list[5] = 0.5*(Cij_list[0]-Cij_list[6]) # c66 # Cij_errors_list[5] = 0.5*(Cij_errors_list[0]-Cij_errors_list[6]) c, std_err = createCij() return c, std_err
def LMDI_expression(self): """Calculate the LMDI equation in symbolic Matrix terms Returns: expressions (Symbolic Matrix): Matrix where each element contains a symbolic expression representing the appropriate calculation of the value TODO: - describe the expression more accurately """ print('self.variables:', self.variables) num_years = self.end_year - self.base_year num_columns = self.subscripts['i']['count'] # variable_dict = {var: # self.create_symbolic_var(var, # num_years, # num_columns) # for var in self.variables} activity = pd.read_csv('C:/Users/irabidea/Desktop/yamls/residential_activity.csv', index_col=0) activity = activity.loc[self.base_year:self.end_year, :] activity = sp.Matrix(activity.values) # sp.pprint(activity) # print(type(activity)) # exit() energy = pd.read_csv('C:/Users/irabidea/Desktop/yamls/residential_energy.csv', index_col=0) energy = energy.loc[self.base_year:self.end_year, :] energy = sp.Matrix(energy.values) variable_dict = {'A_i': activity, 'E_i': energy} print('input data A:\n', variable_dict['A_i']) for t, s in self.totals.items(): to_sum = variable_dict[s] variable_dict[t] = to_sum * sp.ones(to_sum.shape[1], 1) lhs_matrix = variable_dict[self.LHS_var] # lhs_matrix = self.eval_expression(lhs_matrix) print('lhs_matrix done') # lhs_matrix = lhs_matrix.as_explicit() print('lhs_matrix term literal') sp.pprint(lhs_matrix) print('type(lhs_matrix):', type(lhs_matrix)) weights = self.calc_weights(lhs_matrix, num_columns) sp.pprint(weights) print('type(weights):', type(weights)) symbolic_terms = [] for term in self.terms: print('term:', term) if '/' in term: parts = term.split('/') numerator = parts[0] numerator = variable_dict[numerator] denominator = parts[1] denominator = variable_dict[denominator] matrix_term = self.create_symbolic_term(numerator, denominator) else: matrix_term = variable_dict[term] # matrix_term = self.eval_expression(matrix_term) print('matrix_term done') # matrix_term = matrix_term.as_explicit() print('matrix term literal') weighted_term = self.weighted_term(weights, matrix_term) symbolic_terms.append(weighted_term) decomposition_pieces = self.decomposition.split('*') not_weighted = [t for t in decomposition_pieces if t not in self.terms] for n in not_weighted: # need to add capability for more complicated unweighted terms symbolic_terms.append(variable_dict[n]) # symbolic_terms = [self.eval_expression(s) for s in symbolic_terms] # print('done') # symbolic_terms = [s.as_explicit() for s in symbolic_terms] # print('well done') print("symbolic_terms:\n", symbolic_terms) if self.model == 'additive': expression = sp.MatAdd(*symbolic_terms).doit().as_explicit() elif self.model == 'multiplicative': expression = sp.MatMul(*symbolic_terms).doit().as_explicit() print('expression done') # expression = expression.as_explicit() print('expression literal') sp.pprint(expression) return expression