def check_basis(sol, prop): """ Checks if prop basis is equivalent to sol basis @param sol: verified basis, 2D numpy array, first dim: vector indexes, second dim: idx of element in a basis vect @param prop: proposed basis @return: boolean """ prop = np.array(prop, dtype=np.float64) # number of vector in basis n = len(sol) # Check dimension of proposed eigenspace if n != len(prop): display(Latex("Le nomber de vecteur(s) propre(s) donné(s) est incorrecte. " + "La dimension de l'espace propre est égale au nombre de variable(s) libre(s).")) return False else: # Check if the sol vector can be written as linear combination of prop vector # Do least squares to solve overdetermined system and check if sol is exact A = np.transpose(prop) lin_comb_ok = np.zeros(n, dtype=bool) for i in range(n): x, _, _, _ = np.linalg.lstsq(A, sol[i], rcond=None) res = np.sum((A @ x - sol[i]) ** 2) lin_comb_ok[i] = res < 10 ** -13 return np.all(lin_comb_ok)
def process_content(self, content, filename=None, latex=False, **kwargs): """Process the arguments into something LaTeX/word can handle. ``process_content`` checks the type of the content passed to it and will then process it into something that our exporter can handle. If ``content`` is a string, it will pull out any python variables and replace them with their output, and also process all markdown into LaTeX. If ``content`` is some graphics class, it will fill in the necessary graphics commands. :param content: the content that will be processed. Can be ``str``, ``pyg2d``, or an ``pygsvg`` object. :param str filename: filename for ``svg`` file, if applicable :param bool latex: if we need to output the content in LaTeX format, default ``False`` :returns: the content after processing """ if latex: return content if isinstance(content, str): content = self.process_markdown(content) latex_str = content return latex_str elif isinstance(content, pyg2d.pyg2d): lyx.latex() content.export(filename, force=True, sizes=['1']) string = content.show(need_string=True, **kwargs) return string elif isinstance(content, pyg2d.svg): lyx.latex() string = content.show(need_string=True, **kwargs) return Latex(string)
def show(self): # pragma: no cover """ Provide a pretty representation of the formula from within IPython. """ from IPython.display import Latex return Latex(self.latex_representation(mode="inline"))
def printEq(coeff, b, *args): """Method that prints the Latex string of a linear equation, given the values of the coefficients. If no coefficient value is provided, then a symbolic equation with `n` unknowns is plotted. In particular: * **SYMBOLIC EQUATION**: if the number of unknowns is either 1 or 2, then all the equation is displayed while, if the number of unknowns is higher than 2, only the first and last term of the equation are displayed * **NUMERICAL EQUATION**: whichever the number of unknowns, the whole equation is plotted. Numerical values of the coefficients are rounded to the third digit :param coeff: coefficients of the left-hand side of the linear equation :type: list[float] :param b: right-hand side coefficient of the linear equation :type b: float :param *args: optional; if passed, it contains the number of unknowns to be considered. If not passed, all the unknowns are considered, i.e. n equals the length of the coefficients list :type: *args: list """ if len(args) == 1: n = args[0] else: n = len(coeff) coeff = coeff + b texEq = '$' texEq = texEq + strEq(n, coeff) texEq = texEq + '$' display(Latex(texEq)) return
def printSyst(A, b, *args): """Method that prints a linear system of `n` unknowns and `m` equations. If `A` and `b` are empty, then a symbolic system is printed; otherwise a system containing the values of the coefficients stored in `A` and `b`, approximated up to their third digit is printed. :param A: left-hand side matrix. It must be [] if a symbolic system is desired :type: list[list[float]] :param b: right-hand side vector. It must be [] if a symbolic system is desired :type b: list[float] :param args: optional; if not empty, it is a list of two integers representing the number of equations of the linear system (i.e. `m`) and the number of unknowns of the system (i.e. `n`) :type: list """ if (len(args) == 2) or ( len(A) == len(b)): # ensures that MatCoeff has proper dimensions if len(args) == 2: m = args[0] n = args[1] else: m = len(A) n = len(A[0]) texSyst = '$\\begin{cases}' Eq_list = [] if len(A) and len(b): if type(b[0]) is list: b = np.array(b).astype(float) A = np.concatenate((A, b), axis=1) else: A = [A[i] + [b[i]] for i in range(0, m)] # becomes augmented matrix A = np.array(A) # just in case it's not for i in range(m): if not len(A) or not len(b): Eq_i = '' if n is 1: Eq_i = Eq_i + 'a_{' + str(i + 1) + '1}' + 'x_1 = b_' + str(i + 1) elif n is 2: Eq_i = Eq_i + 'a_{' + str( i + 1) + '1}' + 'x_1 + ' + 'a_{' + str( i + 1) + '2}' + 'x_2 = b_' + str(i + 1) else: Eq_i = Eq_i + 'a_{' + str( i + 1) + '1}' + 'x_1 + \ldots +' + 'a_{' + str( i + 1) + str(n) + '}' + 'x_' + str( n) + '= b_' + str(i + 1) else: Eq_i = strEq(n, A[i, :]) # attention A is (A|b) Eq_list.append(Eq_i) texSyst = texSyst + Eq_list[i] + '\\\\' texSyst = texSyst + '\\end{cases}$' display(Latex(texSyst)) else: print("La matrice des coefficients n'a pas les bonnes dimensions") return
def show_matrix_with_kernel_and_result(data, kernel, kernel_x, kernel_y, result): # Helper-method to show a matrix mark = set([(i, j) for i in range(kernel_x - 1, kernel_x + 2) for j in range(kernel_y - 1, kernel_y + 2)]) data = np.around(data).astype(int) result = np.around(result).astype(int) data = data.astype(str) for (x, y) in mark: data[x, y] = '%s\cdot %.2f' % (data[x, y], kernel[x - kernel_x + 1, y - kernel_y + 1]) return display( Latex( r'\[\scriptstyle \def\g{\color{lightgray}}\left(\begin{array}{%s}' % (r'r' * data.shape[0]) + r'\\'.join([ r' & '.join([ value if (x, y) in mark else r'\g{%s}' % value for (y, value) in enumerate(map(str, col)) ]) for (x, col) in enumerate(data) ]) + r'\end{array}\right)=\left(\begin{array}{%s}' % (r'r' * data.shape[0]) + r'\\'.join([ r' & '.join([ value if y == kernel_y - 1 and x == kernel_x - 1 else r'\g{%s}' % value for (y, value) in enumerate(map(str, col)) ]) for (x, col) in enumerate(result) ]) + r'\end{array}\right)\]'))
def printEquMatricesOLD(*args): # M=[M1, M2, ..., Mn] n>1 VERIFIED OK texEqu = '$' + texMatrix(args[0]) for i in range(1, len(args)): texEqu = texEqu + '\\quad \\sim \\quad' + texMatrix(args[i]) texEqu = texEqu + '$' display(Latex(texEqu)) return
def printEquMatricesOLD( listOfMatrices): #list of matrices is M=[M1, M2, ..., Mn] texEqu = '$' + texMatrix(listOfMatrices[0]) for i in range(1, len(listOfMatrices)): texEqu = texEqu + '\\quad \\sim \\quad' + texMatrix(listOfMatrices[i]) texEqu = texEqu + '$' display(Latex(texEqu))
def LT(text): """ Display latex in Jupyter notebook :param text: :return: """ display(Latex(text))
def wrapper(*args, **kwargs): line_args = { "override": override, "precision": precision, "sci_not": scientific_notation, } func_source = inspect.getsource(func) cell_source = _func_source_to_cell(func_source) # use innerscope to get the values of locals, closures, and globals when calling func scope = innerscope.call(func, *args, **kwargs) LatexRenderer.dec_sep = decimal_separator renderer = LatexRenderer(cell_source, scope, line_args) latex_code = renderer.render() if jupyter_display: try: from IPython.display import Latex, display except ModuleNotFoundError: ModuleNotFoundError( "jupyter_display option requires IPython.display to be installed." ) display(Latex(latex_code)) return scope.return_value # https://stackoverflow.com/questions/9943504/right-to-left-string-replace-in-python latex_code = "".join( latex_code.replace("\\[", "", 1).rsplit("\\]", 1)) return (left + latex_code + right, scope.return_value)
def pxfer( # pgf or pdf fig_name, filename, draft_mode=False, save_dir='.', graphics_dir='source', linewidth=1, height_fraction=.5, output_type='pgf', # or pdf figure=False, # if \begin{figure} caption='', label=None, **kwargs # keyword arguments for savefig ): if draft_mode: print('draft mode ... no figure saved') else: pxfer.counter += 1 if label is None: label = filename + f"_{pxfer.counter}" filename_sans = os.path.splitext(filename)[0] filename_counter = filename_sans + "_" + str( pxfer.counter) + '.' + output_type # if output_type is 'pgf': mpl.use("pgf") pgf_with_pdflatex = { "pgf.texsystem": "pdflatex", "pgf.preamble": [ r"\usepackage[T1]{fontenc}", r"\usepackage[utf8]{inputenc}", r"\DeclareUnicodeCharacter{2212}{\textendash}", r"\usepackage{cmbright}", ] } mpl.rcParams.update(pgf_with_pdflatex) elif output_type is 'pdf': mpl.use("module://ipykernel.pylab.backend_inline") else: error('output_type {output_type} not supported') # fig_name.savefig(save_dir + '/' + filename_counter, texsystem='pdflatex', **kwargs) mpl.use("module://ipykernel.pylab.backend_inline") if output_type is 'pgf': graphics_command = "\\input{" else: graphics_command = "\\includegraphics[width=" + f"{linewidth}" + "\\linewidth]{" if figure: wrapper_before = "\\begin{figure} \n" + "\\centering \n" wrapper_after = "\\caption{" + f"{caption}" + "} \n" + "\\label{" + f"{label}" + "} \n" + "\\end{figure}\n" else: # no figure environment wrapper_before = "\\begin{center} \n" + "\\resizebox{" + f"{linewidth}" + "\\linewidth}{!}{ \n" wrapper_after = "} \n" + "\\captionof{figure}{" + f"{caption}" + "} \n" + "\\label{" + f"{label}" + "}" + "\\end{center}" return Latex(wrapper_before + f"{graphics_command}" + f"{graphics_dir}/{filename_counter}" + "}\n" + f"{wrapper_after}")
def latex_annilators(annilators: List[List[Tuple["GbAlgMod2", str, int]]]): from IPython.display import Latex result = "\\begin{align*}\n" for a in annilators: s = "+".join(f"{name}{tex_parenthesis(coeff)}" for coeff, name, d in a) result += f"& {s}=0\\\\\n" result += "\\end{align*}" return Latex(result)
def ProblemInfo(options): if options['mode'] == separate_mode: print('SEPARATE SOLUTION') if options['lam_q'] == lam_q_fixed: print('System 1') display_J_mu() display( Latex(r'''$ {\bf A} = \begin{bmatrix} {\bf J}_{P~ok}^T & {\bf J}_S^{T} & {\bf J}_{\mu} \end{bmatrix}~~~ {\bf x} = \begin{bmatrix} \lambda_{ok}^P\\ \sigma\\ \mu \end{bmatrix}~~~ {\bf b} = - {\bf J}_Q^T\lambda^Q - {\bf J}_{P~form}^T\lambda_{form}^{P~new} $''')) print('System 2') display_C_gamma() display( Latex(r'''\begin{equation} {\bf B} = \begin{bmatrix} -{\bf I} & {\bf I} \end{bmatrix}~~~ {\bf y} = \begin{bmatrix} \gamma^{\max}[{\cal I}_\gamma]\\ \gamma^{\min}[{\cal I}_\gamma] \end{bmatrix}~~~ {\bf c} = {\bf C[{\cal I}_\gamma]} + {\rm sign}({\bf C[{\cal I}_\gamma]})\lambda^P[{\cal I}_\gamma] \end{equation}''')) else: pass else: print('SIMULTANEOUS SOLUTION') display_J_mu() display_C_gamma() display( Latex( r'''\lambda^P = -\gamma^{\max} + \gamma^{\min} - {\rm abs}({\bf C})''' ))
def StartFigure(caption='', label=''): """ Displays the LaTex formatting that goes before a figure with caption and label @param caption String of caption text @param label String of label text """ startstring = "\\begin{figure}[]\caption{%s}\label{%s}" % (caption, label) display(Latex(startstring))
def print_latex(str_list): """Display a comma-separated list of LaTeX strings in a Jupyter notebook. :param str_list: List of LaTeX string, e.g. ['$\\alpha$', '$\\beta$'] :return: None """ display(Latex('$, \\;\\;$'.join(str_list)))
def correction(a, b, c, d): if c and not (a) and not (d) and not (b): display( Latex( "C'est correct! Par exemple, si on applique le produit à la matrice ci-dessous" )) A = [[1, -1, 0, 0], [0, 0, 0, 1], [1, 2, 1, 2], [1, 0, 0, 1]] B = [[1, 0, 0, 0], [0, 1, 0, -6], [0, 0, 1, 0], [0, 0, 0, 1]] C = [[0, 0, 1, 0], [0, 1, 0, 0], [1, 0, 0, 0], [0, 0, 0, 1]] BCA = np.linalg.multi_dot([B, C, A]) texA = '$' + texMatrix(A) + '$' texBCA = '$' + texMatrix(BCA) + '$' display(Latex('$\qquad A = $' + texA)) display(Latex("on obtient")) display((Latex('$\qquad \hat{A} = $' + texBCA))) else: display(Latex("C'est faux."))
def _print_netlist_latex(netlist): """ Print each net in netlist in a Latex array """ from IPython.display import display, Latex # pylint: disable=import-error out = '\n\\begin{array}{ \\| c \\| c \\| l \\| }\n' out += '\n\\hline\n' out += '\\hline\n'.join(str(n) for n in netlist) out += '\\hline\n\\end{array}\n' display(Latex(out))
def latex(self, line, cell): """Render the cell as a block of LaTeX The subset of LaTeX which is supported depends on the implementation in the client. In the Jupyter Notebook, this magic only renders the subset of LaTeX defined by MathJax [here](https://docs.mathjax.org/en/v2.5-latest/tex.html).""" display(Latex(cell))
def printLTX( s: str, math: T.Union[str, bool] = False, equation: T.Union[str, bool] = False, matrix: T.Union[str, bool] = False, label: str = "", ): r"""Print in LaTeX. Parameters ---------- s : raw! str the s to print math : bool, str (default False) whether the whole string should be wrapped in $$ if str: wrap in that string equation: bool, None (default False) whether the whole string should be wrapped in $\equation$ if None: then '\equation*' matrix: bool, str (default False) whether the whole string should be wrapped in $\matrix$ if str, use that matrix type, like 'bmatrix' shortcuts) 'b' -> 'bmatrix' label: the label of the equation, etc. only used in equation or matrix Notes ----- .. todo:: optional PyLaTeX input """ if label == "": pass else: label = r"\label{" + label + "}" if isinstance(math, str): s = math + s + math elif math: # (True) s = "$" + s + "$" if equation: s = r"\begin{equation}" + label + s + r"\end{equation}" elif equation is None: s = r"\begin{equation*}" + label + s + r"\end{equation*}" if isinstance(matrix, str): if matrix == "b": matrix = "bmatrix" s = r"\begin{" + matrix + "}" + label + s + r"\end{" + matrix + "}" elif matrix: s = r"\begin{matrix}" + label + s + r"\end{matrix}" display(Latex(s)) return
def Exemples_calculs(): """Lance plusieurs exemples de calculs de coefficients directeurs""" while True: (xA, yA) = input_coord("A") while True: (xB, yB) = input_coord("B") if xB != xA or yB != yA: break else: display( "Il faut deux points distincts pour faire une droite ! Recommencez !" ) intro = Latex( """Nous allons calculer le coefficient directeur de la droite (AB) avec A( {} ; {} ) et B( {} ; {} )""".format(xA, yA, xB, yB)) if xA == xB: calcul = Latex( """Les droites parallèles à l'axe des ordonnées n'ont pas de coefficient directeur ! Il faut donc que vos points n'aient pas la même abscisse :""" ) else: frac = fractions.Fraction((yB - yA), (xB - xA)) if frac == int(frac): frac = str(int(frac)) else: frac = "\dfrac{{{numerator}}}{{{denominator}}}".format( numerator=frac.numerator, denominator=frac.denominator) calcul = Math( "m= \dfrac{{y_B-y_A}}{{x_B-x_A}}= \dfrac{{{yB}-{yA}}}{{{xB}-{xA}}}= \dfrac{{{yByA}}}{{{xBxA}}}={frac}" .format(xA=xA, yA=yA, xB=xB, yB=yB, yByA=yB - yA, xBxA=xB - xA, frac=frac)) Trace_droite(xA, yA, xB, yB) display(intro, calcul) s = input("Voulez-vous recommencer ?(o/n)") if s.lower() in ['n', 'non', 'no']: break else: clear_output()
def printEquMatricesAug( listOfMatrices, listOfRhS): # list of matrices is M=[M1, M2, ..., Mn] where Mi=(Mi|b) texEqu = '$' + texMatrix(listOfMatrices[0], listOfRhS[0]) for i in range(1, len(listOfMatrices)): texEqu = texEqu + '\\quad \\sim \\quad' + texMatrix( listOfMatrices[i], listOfRhS[i]) texEqu = texEqu + '$' display(Latex(texEqu))
def question7_2f(reponse): f = sp.Matrix([[4, -5, 8], [6, 10, 1], [-3, 15, -2]]) if np.abs(reponse - sp.det(f)) != 0: display("Dans ce cas, la deuxième rangée a été multiplié par cinq.") display("Après ça, c''est la transposée de la matrice.") display( Latex( "$ Soit: 5 \\times R_2 \\rightarrow R_2, \: et \: transposée $" )) display("Le déterminant est donc:") display( Latex( "$ det|f| = 5 \cdot det|A|^T = 5 \cdot det|A| = 5 \cdot 155 = 755 $" )) Determinant_3x3(f, step_by_step=True) else: display("Bravo! Vous avez trouvé la réponse.")
def question7_2e(reponse): e = sp.Matrix([[-1, 2, 3], [4, 6, -3], [0, -11, 4]]) if np.abs(reponse - sp.det(e)) != 0: display( "Dans ce cas, deux fois la première rangée a été ajouté à la troisième rangée." ) display("Aussi les premières deux rangées sont échangées.") display( Latex( "$ Soit: 2 \\times R_1 + R_3 \\rightarrow R_3, R_1 \\leftrightarrow R_2 $" )) display("Le déterminant est donc:") display( Latex("$ det|e| = (-1) \cdot det|A| = (-1) \cdot 155 = - 155 $")) Determinant_3x3(e, step_by_step=True) else: display("Bravo! Vous avez trouvé la réponse.")
def solution(e): out.clear_output() display( Latex("$" + "\det C" + "=" + "\det" + detA_s + "=" + "k \cdot" + "\det" + detAr_s + "= k \cdot" + "{}".format(Ar_det) + "=" + "{}".format(A_det) + "$")) display( Latex("Où $k$ est une constante qui n'est pas égale à zéro. ")) if sp.det(A) == 0: display( Latex( "$\det C$ est égal à zéro, donc la matrice $C$ est singulière." )) else: display( Latex( "$\det C $ n'est pas égal à zéro, donc la matrice $C$ est inversible." ))
def correlation(self, formula=False): """ Return correlation coefficient r. formula: Return formula. """ # assert isinstance(df, pd.core.frame.DataFrame), "df is not DataFrame!" # Display formula if formula is True: # r for sample display(Latex(r"$r_{xy} = \frac{S_{xy}}{S_{x}S_{y}}$")) # r for population display(Latex(r"$\rho_{xy} = \frac{\sigma_{xy}}{\sigma_{x}\sigma_{y}}$")) # Calculate correlation coefficient r r = np.mean(self.standard_x * self.standard_y) return r
def latex(self): string = "\\begin{bmatrix} \n " for row in self._data: for c in row: string += '{} & '.format(c) string = string.rstrip('& ') string += r" \\ " string += "\n\\end{bmatrix}" return Latex(string)
def generate_example(): s = random.randint(-30, 30) / 10 b = (random.randint(-10, 10) + 5)**2 / 10 g1 = function('quadratic') g2 = function(g1(x) + b) g = function( sp.Piecewise((g1(x), x < s), (g2(x), x > s), (g1(s) + 2 * b, True))) display(Latex("$\\text{New $g(x), s$ generated}$")) display(Latex("$s = " + str(s) + "$")) # display(Markdown('<br>')) display(Markdown("**Problem**: *Estimate the one-sided limits* ")) display( Latex( "$ \lim_{x \\to s^-} g(x) \\text{ and } \lim_{x \\to s^+} g(x)$")) return g, s
def Ex1Chapitre2_3(A, B, C): """Provides the correction to exercise 1 of notebook 2_3 :param A: original matrix :type A: list[list] or numpy.ndarray :param B: matrix such that A+B should be diagonal :type B: list[list] or numpy.ndarray :param C: matrix such that A+C should be symmetric and not diagonal :type C: list[list] or numpy.ndarray :return: :rtype: """ if not type(A) is np.ndarray: A = np.array(A) if not type(B) is np.ndarray: B = np.array(B) if not type(C) is np.ndarray: C = np.array(C) ans1 = isDiag(A + B) ans2 = isSym(A + C) and not isDiag(A + C) if ans1 and ans2: display(Latex('Correcte!')) else: display( Latex( 'Incorrect! Entrez des nouvelles valeurs pur le matrices B et C!\n' )) if ans1: display(Latex("A+B est bien diagonale!")) else: display(Latex("A+B est n'est pas diagonale!")) texAB = '$' + texMatrix(A + B) + '$' display(Latex(r"A+B=" + texAB)) if ans2: display(Latex("A+C est bien symétrique et non diagonale!")) elif isSym(A + C) and isDiag(A + C): display( Latex("A+C est bien symétrique mais elle est aussi diagonale!")) else: display(Latex("A + C n'est pas symétrique")) texAC = '$' + texMatrix(A + C) + '$' display(Latex(r"A+C=" + texAC)) return
def standardize(self, formula=False): """"Accept Pandas DataFrame object and return standardized units.""" # assert isinstance(df, pd.core.frame.DataFrame), "df is not DataFrame!" # Display formula if formula is True: display(Latex(r"$z = \frac{X - \mu}{\sigma}$")) # Convert any array of numbers to standardized units return (self.df - np.mean(self.df)) / np.std(self.df)
def question7_2c(reponse): c = sp.Matrix([[4, 6, -3], [-4, 8, 12], [-4, 5, -1]]) if np.abs(reponse - sp.det(c)) != 0: display( "Dans ce cas, la deuxième rangée a été multiplié par 4 et la troisième par -1" ) display( Latex( "$ Soit: 4 \\times R_2 \\rightarrow R_2, -1 \\times R_3 \\rightarrow R_3 $" )) display("Le déterminant est donc:") display( Latex( '$ det|c| = (-1) \cdot (4) \cdot det|A| = -4 \cdot 155 = - 620 $' )) Determinant_3x3(c, step_by_step=True) else: display("Bravo! Vous avez trouvé la réponse")