def logarithmic_average(self, x, y): """[summary] Args: x ([type]): [description] y ([type]): [description] Returns: [type]: [description] """ if x != y: negative_y = y * -1 log_x = x.applyfunc(sp.log) log_y = y.applyfunc(sp.log) negative_log_y = log_y * -1 numerator = sp.MatAdd(x, negative_y) print('numerator shape', numerator.shape) denominator = sp.MatAdd(log_x, negative_log_y) print('denominator shape', denominator.shape) logarithmic_average = self.hadamard_division(numerator, denominator) elif x == y: logarithmic_average = x return logarithmic_average
def _assemble_forces_equations(self): node = 'ground' nrows = 2 F_applied = sm.MutableSparseMatrix(nrows, 1, None) in_edges = self.forces_graph.in_edges([node], data='obj') if len(in_edges) == 0: Q_in_R = zero_matrix(3, 1) Q_in_P = zero_matrix(4, 1) else: Q_in_R = sm.MatAdd(*[e[-1].Qj.blocks[0] for e in in_edges]) Q_in_P = sm.MatAdd(*[e[-1].Qj.blocks[1] for e in in_edges]) out_edges = self.forces_graph.out_edges([node], data='obj') if len(out_edges) == 0: Q_out_R = zero_matrix(3, 1) Q_out_P = zero_matrix(4, 1) else: Q_out_R = sm.MatAdd(*[e[-1].Qi.blocks[0] for e in out_edges]) Q_out_P = sm.MatAdd(*[e[-1].Qi.blocks[1] for e in out_edges]) Q_t_R = Q_in_R + Q_out_R Q_t_P = Q_in_P + Q_out_P F_applied[0] = Q_t_R F_applied[1] = Q_t_P self.frc_equations = F_applied
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 _assemble_forces_equations(self): graph = self.forces_graph nodes = self.bodies nrows = 2 * len(nodes) F_applied = sm.MutableSparseMatrix(nrows, 1, None) for i, n in enumerate(nodes): if self._is_virtual_node(n): continue in_edges = graph.in_edges([n], data='obj') if len(in_edges) == 0: Q_in_R = zero_matrix(3, 1) Q_in_P = zero_matrix(4, 1) else: Q_in_R = sm.MatAdd(*[e[-1].Qj.blocks[0] for e in in_edges]) Q_in_P = sm.MatAdd(*[e[-1].Qj.blocks[1] for e in in_edges]) out_edges = graph.out_edges([n], data='obj') if len(out_edges) == 0: Q_out_R = zero_matrix(3, 1) Q_out_P = zero_matrix(4, 1) else: Q_out_R = sm.MatAdd(*[e[-1].Qi.blocks[0] for e in out_edges]) Q_out_P = sm.MatAdd(*[e[-1].Qi.blocks[1] for e in out_edges]) Q_t_R = Q_in_R + Q_out_R Q_t_P = Q_in_P + Q_out_P F_applied[i * 2] = Q_t_R F_applied[i * 2 + 1] = Q_t_P self.frc_equations = F_applied
def mat_add_flat(lh, rh): if hasattr(lh, 'is_MatAdd') and lh.is_MatAdd or hasattr( rh, 'is_MatAdd') and rh.is_MatAdd: args = [] if hasattr(lh, 'is_MatAdd') and lh.is_MatAdd: args += list(lh.args) else: args += [lh] if hasattr(rh, 'is_MatAdd') and rh.is_MatAdd: args = args + list(rh.args) else: args += [rh] return sympy.MatAdd(*args, evaluate=False) else: return sympy.MatAdd(lh, rh, evaluate=False)
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 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 tosympy(self, nsimplify=False): """Return sympy representation of the Model. If nsimplify=True, attempt to rewrite numerical coefficients as exact formulas.""" if not nsimplify: result = sympy.sympify(sum(key * val for key, val in self.toarray().items())) else: # Vectorize nsimplify vnsimplify = np.vectorize(sympy.nsimplify, otypes=[object]) result = sympy.MatAdd(*[key * sympy.Matrix(vnsimplify(val)) for key, val in self.toarray().items()]).doit() if isinstance(result, (sympy.MatrixBase, sympy.ImmutableDenseMatrix, sympy.ImmutableDenseNDimArray)): result = sympy.Matrix(result).reshape(*result.shape) return result
def _build_hamiltonian(self): # return foreman(self._parameter_coords, self.components, self.bands) if self._parameter_coords is not None: self._parameter_coords = validate_coords(self._parameter_coords) str_coords = "({})".format(", ".join(self._parameter_coords)) subs = {v: v + str_coords for v in self._varied_parameters} else: subs = {} hamiltonian_components = [ kwant.continuum.sympify(_models_cache[c], locals=subs) for c in self.components ] hamiltonian = sympy.ImmutableMatrix( sympy.MatAdd(*hamiltonian_components)) indices = [] for band in self.bands: indices += self._band_indices[band] return hamiltonian[:, indices][indices, :]
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