Beispiel #1
0
def table_to_printstream(species, table, fmt='rst'):
    """Given species table and reaction table get properly formatted output.

    Arguments:
        species: table of species as output by gen_table
        table: rxn table as returned by gen_table

    Returns:
        string formatted output
    """
    model_name = table["model"][0]
    table = table.sort_values("model")[[
        "schema", "fwd_rate", "rev_rate", "kd"
    ]]

    printstream_info = [
        tb.tabulate(np.expand_dims(t[1].transpose(), axis=1), tablefmt=fmt)
        for t in table.iterrows()
    ]

    if fmt == 'latex':
        return "\n".join(["\documentclass{article}",
                             r"\usepackage[utf8]{inputenc}",
                             r"\usepackage{amsmath}",
                             "\\begin{document}",
                            "\def\\arraystretch{2}",
                            model_name,
                          "\n".join(["%s: %s" % (latex(r[1]), latex(r[0])) for r in species])] + \
                          printstream_info + \
                          ["\end{document}"])
    elif fmt == 'plain':
        return "\n============================\n".join([
            "", model_name, "\n".join(
                ["%s: %s" % (r[1], r[0]) for r in species])
        ] + printstream_info) + "\n"
def test_deprecated_print_cyclic():
    p = Permutation(0, 1, 2)
    try:
        Permutation.print_cyclic = True
        with warns_deprecated_sympy():
            assert sstr(p) == '(0 1 2)'
        with warns_deprecated_sympy():
            assert srepr(p) == 'Permutation(0, 1, 2)'
        with warns_deprecated_sympy():
            assert pretty(p) == '(0 1 2)'
        with warns_deprecated_sympy():
            assert latex(p) == r'\left( 0\; 1\; 2\right)'

        Permutation.print_cyclic = False
        with warns_deprecated_sympy():
            assert sstr(p) == 'Permutation([1, 2, 0])'
        with warns_deprecated_sympy():
            assert srepr(p) == 'Permutation([1, 2, 0])'
        with warns_deprecated_sympy():
            assert pretty(p, use_unicode=False) == '/0 1 2\\\n\\1 2 0/'
        with warns_deprecated_sympy():
            assert latex(p) == \
                r'\begin{pmatrix} 0 & 1 & 2 \\ 1 & 2 & 0 \end{pmatrix}'
    finally:
        Permutation.print_cyclic = None
Beispiel #3
0
def print_mat(xs):
    from sympy.printing import latex
    rv = "\\begin{pmatrix} "
    for row in xrange(0, len(xs)):
        s = latex(xs[row, 0])
        for col in xrange(1, len(xs)):
            s += " & " + latex(xs[row, col])
        rv += s + " \\\\ "
    return rv[:-3] + " \\end{pmatrix}"
Beispiel #4
0
def print_mat(xs):
    from sympy.printing import latex
    rv = "\\begin{pmatrix} "
    for row in xrange(0, len(xs)):
        s = latex(xs[row, 0])
        for col in xrange(1, len(xs)):
            s += " & " + latex(xs[row, col])
        rv += s + " \\\\ "
    return rv[:-3] + " \\end{pmatrix}"
def create_linear_system(symbol, superscript, sym_group='622', tdim=2):
    sg = RedSgSymOps()
    print(sg.symops['6parZ3'])
    symops = sg(sym_group)
    symop = symops[0]
    R = Matrix(symop)
    Rsym = Matrix([[Symbol('R_{{{},{}}}'.format(i, j)) for j in range(1, 4)]
                   for i in range(1, 4)])
    print('Rsym=\n', latex(Rsym))
    print('R=\n', latex(R))
    print(symop)
    ivm, vm = SymbolicTensor.voigt_map(2)
    print(ivm)
    print(vm)
    indices0 = list(product(range(3), repeat=tdim))
    indices1 = list(product(range(1, 4), repeat=tdim))
    print(indices0)
    print(indices1)

    lhs = Matrix([[Rsym[I, i] * Rsym[J, j] for (i, j) in indices0]
                  for (I, J) in indices0])
    print(latex(lhs))
    vec = Matrix([[Symbol('c_{{{},{}}}'.format(i, j))] for (i, j) in indices1])
    print(latex(vec))
    vvec = Matrix([[Symbol('c_{{{}}}'.format(vm[k] + 1))] for k in indices0])
    print(latex(vvec))
    lines = []
    frac_lines = []
    redfrac_lines = []
    symbol += '^{{{}}}'.format(superscript)
    for (I, J) in indices:
        line = '&'.join([
            "{}_{{{}{}}} {}_{{{}{}}}".format(symbol, I, i, symbol, J, j)
            for (i, j) in indices
        ])
        lines.append(line)
        Iint = int(I) - 1
        Jint = int(J) - 1
        frac_line = '&'.join([
            "{} \cdot {}".format(symop[Iint, int(i) - 1], symop[Jint,
                                                                int(j) - 1])
            for (i, j) in indices
        ])
        frac_line = frac_line.replace('sqrt(3)', '\\sqrt{3}')
        frac_lines.append(frac_line)
        redfrac_line = '&'.join([
            "{}".format(4 * symop[Iint, int(i) - 1] *
                        symop[Jint, int(j) - 1]) for (i, j) in indices
        ])
        redfrac_line = redfrac_line.replace('sqrt(3)', '\\sqrt{3}')
        redfrac_lines.append(redfrac_line)
    print('\\\\'.join(lines))
    print('\\\\'.join(frac_lines))
    print('\\\\'.join(redfrac_lines))
Beispiel #6
0
    def latex(self, variable):
        funs = self.funs
        seps = self.seps
        s = r"""\begin{{cases}}
 {} & {} \in (-\infty,{})\\
""".format(latex(funs[0]), variable, seps[0])
        for (sup, inf, fun) in zip(seps[1:], seps[:-1], funs[1:]):
            s += r"""{} & {} \in [{},{})\\
""".format(latex(fun), variable, inf, sup)
        s += r""" {} & {} \in [{}, +\infty )
 \end{{cases}}""".format(latex(funs[-1]), variable, seps[-1])
        return s
Beispiel #7
0
    def _repr_html_(self):
        '''
        Returns a string formatted in RST.
        '''
        rows = [
            f'<p><b>{self.__class__.__name__}</b></p>',
            '',
            '<p><i>Quantities</i></p>',
            '',
            '<ul>'
        ]
        for name, _, doc in self._q:
            rows.append(f'<li><i>{name}</i>: {doc}</li>')
        rows.extend(['</ul>', '', '<p><i>Constants</i></p>', '', '<ul>'])
        for name, _, doc in self._c:
            rows.append(f'<li><i>{name}</i>: {doc}</li>')
        rows.extend(['</ul>', '', '<p><i>Parameters</i></p>', '', '<ul>'])
        for name, _, doc in self._p:
            rows.append(f'<li><i>{name}</i>: {doc}</li>')
        if self._eq is not None:
            rows.extend(['</ul>', '', '<p><i>Equations</i></p>', '', '<ul>'])
            for i, (k, v) in enumerate(sorted(self._eq.items())):
                lats = "\\frac{d%s}{dt} = %s" % (k, printing.latex(v))
                lat = latex(lats, mode='equation')
                line = "".join(["<li>", str(lat), '</li>'])
                rows.append(line)
            rows.append("</ul>")

        return '\n'.join(rows)
Beispiel #8
0
def print_pygame(st):
    try:
        import pygame
    except ImportError:
        print "Pygame is not installed. In Debian, install the " "python-pygame package."
        return

    from pygame import QUIT, KEYDOWN, K_ESCAPE, K_q

    st = latex(st)
    pygame.font.init()
    size = 640, 240
    screen = pygame.display.set_mode(size)
    screen.fill((255, 255, 255))
    font = pygame.font.Font(None, 24)
    text = font.render(st, True, (0, 0, 0))
    textpos = text.get_rect(centerx=screen.get_width() / 2)
    screen.blit(text, textpos)
    pygame.display.flip()

    image = tex2png(st, pygame)
    imagepos = image.get_rect(centerx=screen.get_width() / 2).move((0, 30))
    screen.blit(image, imagepos)
    pygame.display.flip()

    while 1:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            elif event.type == KEYDOWN and event.key == K_ESCAPE:
                return
            elif event.type == KEYDOWN and event.key == K_q:
                return
def fmt_rct(r, species_dict, fmt='plain'):
    """Formats a given reaction from pysb to a given output format.
    
    Arguments:
        r : collections.namedtuple reaction object
        species_dict : mapping of pysb species names present in expressions to the actual species eg __s0 --> B(...)
        fmt: string format to output. current options are
                'plain': plaintext
                'latex': latex
        TODO: implement the species_dict mapping
    
    Returns:
        List of strings [reaction_name, reaction_schema, k_f, k_r, k_d]
    """
    arrow = {'latex': " $\longleftrightarrow$ ", 'plain': "<-->"}[fmt]
    fmt_fct = {
        'latex':
        lambda x: "$%s$" % latex(x).replace("__", "").replace(" % ", ""),
        'plain': lambda x: str(x).replace(" % ", "")
    }[fmt]
    r_schema = " + ".join(map(fmt_fct, r.reactants)) + arrow + "".join(
        map(fmt_fct, r.products))
    return [
        r.name.replace("_", "-"), r_schema,
        fmt_fct(r.fwd_rate),
        fmt_fct(r.rev_rate),
        fmt_fct(r.kd)
    ]
Beispiel #10
0
 def _repr_latex_(self):
     """Latex repr hook for IPython."""
     if self.DEFAULT_REPR_LATEX == "dim_dict":
         expr_dim = expand_dict_to_expr(self.dim_dict)
         return "$" + latex(expr_dim) + "$"
     else:  # self.DEFAULT_REPR_LATEX == "SI_unit":
         return self.latex_SI_unit()
Beispiel #11
0
 def fmt_fct(x):
     if type(x) is ComplexPattern:
         x = species_dict[str(x)]
     return {
         'latex': "$%s$" % latex(x).replace("__", "").replace(" % ", ""),
         'plain': str(x).replace(" % ", "")
     }[fmt]
Beispiel #12
0
 def out(self, expr):
     """
     expr: A sympy expression
     """
     if type(expr) == str: return expr
     l = latex(expr, symbol_names=self.symbol_names)
     return l
Beispiel #13
0
    def to_rst(self):
        '''
        Returns a string formatted in RST.
        '''
        rows = [
            f'*{self.__class__.__name__}*',
            '',
            '*Quantities*',
            ''
        ]
        for name, _, doc in self._q:
            rows.append(f'* *{name}*: {doc}')
        rows.extend(['', '*Constants*', ''])
        for name, _, doc in self._c:
            rows.append(f'* *{name}*: {doc}')
        rows.extend(['', '*Parameters*', ''])
        for name, _, doc in self._p:
            rows.append(f'* *{name}*: {doc}')
        if self._eq is not None:
            rows.extend(['', '*Equations*', '', '.. math::',
                         '', '    \\begin{array}{l}'])
            for i, (k, v) in enumerate(sorted(self._eq.items())):
                line = "".join(
                    ["    ", "\\frac{d%s}{dt} = " % k, printing.latex(v)])
                if i < len(self._eq) - 1:
                    line += " \\\\"
                rows.append(line)
            rows.append("    \\end{array}")

        return '\n'.join(rows)
Beispiel #14
0
    def write_problems(self, valid_combos):
        """Takes variable values and returns problem / answer pairs as LaTeX."""

        # To be used when converting the equation to sympy
        transformations = standard_transformations + (
            implicit_multiplication_application, )

        # To preserve the order of the expression, may need to sub each arg separately and then reconstruct the whole equation (sympy can identify each term as an arg)
        for combo in valid_combos:

            # Sympy doesn't like equations, so this allows it to evaluate
            # the left and right side independently
            subbed_left_side = self.equation[:self.equation.find('=')]
            subbed_right_side = self.equation[self.equation.find('=') + 1:]

            for i, var in enumerate(self.variables):
                variable = var['variable']
                # Replace non-answer variables with values
                if i < len(self.variables) - 1:
                    subbed_left_side = subbed_left_side.replace(
                        variable, str(combo['values'][variable]))
                    subbed_right_side = subbed_right_side.replace(
                        variable, str(combo['values'][variable]))

                # Store the answer(s)
                else:
                    if len(combo['values'][variable]) == 1:
                        combo[
                            'answer'] = f"{variable} = {combo['values'][variable][0]}"
                    else:
                        combo[
                            'answer'] = f"{variable} = {combo['values'][variable]}"

            # Latexify each side of the equation, then concatenate
            latex_left_side = latex(
                parse_expr(subbed_left_side,
                           transformations=transformations,
                           evaluate=False))
            latex_right_side = latex(
                parse_expr(subbed_right_side,
                           transformations=transformations,
                           evaluate=False))
            latex_problem = str(latex_left_side) + ' = ' + str(
                latex_right_side)

            combo['problem'] = str(latex_problem)
Beispiel #15
0
 def latex(self, request=None, raw=False):
     self.latex = latex(self.expression, mode='plain')
     obj = {'string':self.expressionString, 
         'javascript': self.javascript, 'latex':self.latex}
     if (raw):
         return obj
     else:
         return JsonResponse(obj)
Beispiel #16
0
def draw_plot(f, lower=-10, upper=-10, num=1000):
    y = parse_expr(f)
    xvals = linspace(lower, upper, num=num)
    vals = [y.evalf(subs={'x': x}) for x in xvals]
    plot(xvals, vals)
    title('$%s$' % latex(y))
    grid()
    savefig('/tmp/plot.png')
    show()
Beispiel #17
0
    def _plot_bradford(self, std, proteins, p, r_sq):
        '''
        plot bradford standard curve and sample absorbance data points
        '''

        # plot
        fig, ax = plt.subplots(figsize=(6, 5))

        # standard curve and labeled points
        xra = np.linspace(std['abs_595'].min(), std['abs_595'].max(), 100)
        plt.plot(xra, p(xra), lw=2.5, color='orange', zorder=0)
        plt.scatter(std['abs_595'],
                    std['Sample'],
                    edgecolor='k',
                    alpha=0.5,
                    label='BSA standards',
                    marker='s')

        # plot replicates of each sample abs
        for samp in proteins['Sample'].unique():
            temp = proteins[proteins['Sample'] == samp]
            plt.scatter(temp['abs_595'],
                        p(temp['abs_595']),
                        label=samp,
                        edgecolor='k',
                        alpha=0.8)

        plt.grid(alpha=0.2)
        plt.legend(loc='center left',
                   bbox_to_anchor=(1, 0.5),
                   fontsize='large')
        ax.set_axisbelow(True)

        # setup poly equation to pretty print
        x = symbols("x")

        # extract coefficients and reverse so order is decreasing powers
        poly = sum(
            S("{:6.1f}".format(v)) * x**i for i, v in enumerate(p.c[::-1]))
        eq_latex = printing.latex(poly)

        annotation_str = '${}$'.format(eq_latex)
        annotation_str += '\n'
        annotation_str += r'$R^2$ = {:.3f}'.format(r_sq)

        plt.text(0.05,
                 0.8,
                 annotation_str,
                 transform=ax.transAxes,
                 fontsize='large')
        plt.xlabel('OD595')
        plt.ylabel('Concentration (ug/mL)')
        plt.title('Bradford Assay Standard Curve')

        plt.savefig(Path(cwd, 'tmp', f'{self.filename}_std_curve.png'),
                    bbox_inches='tight',
                    dpi=300)
Beispiel #18
0
def get_foc():
    jData = request.get_json()
    retData = {}
    c_points = []
    x = Symbol('x')
    Xt = jData['init_func']
    retData['init_func'] = Xt
    derivative_data = []
    try:
        d1 = Derivative(Xt, x).doit()
        retData['d1'] = printing.latex(d1)
        d2 = Derivative(Xt, x, 2).doit()
        retData['d2'] = printing.latex(d2)
        # critical_points = solve(d1)
        # print(critical_points)
        # for idx,c in enumerate(critical_points):
        # 	retData['critical_points_'+str(idx)] = str(round(d2.subs({x:c}).evalf(),3))
        # print('found max mins')
        for c in range(-100, 100, 1):
            new_row = []
            new_row.append((c / 20))
            new_row.append((round((sympify(Xt)).subs({x: c / 20}).evalf(), 4)))
            new_row.append((round(d1.subs({x: c / 20}).evalf(), 4)))
            new_row.append((round(d2.subs({x: c / 20}).evalf(), 4)))
            if c / 20 == 3 or c / 20 == -3:
                new_row.append((round((sympify(Xt)).subs({
                    x: c / 20
                }).evalf(), 4)))

            else:
                new_row.append(None)
            derivative_data.append(new_row)
        print('created data')
        retData['forViz'] = str(derivative_data)
    except SympifyError:
        print('Parsing error')
        error_msg = {'error': "Incorrect function. Please rectify."}
        return jsonify(success=False, data=error_msg)
    except:
        print('Doesn\' t exist')
        error_msg = {'error': 'Doesn\' t exist'}
        return jsonify(success=False, data=error_msg)

    return jsonify(success=True, data=retData)
Beispiel #19
0
def test_logic_printing():
   from sympy import symbols, pretty
   from sympy.printing import latex
   
   syms = symbols('a:f')
   expr = And(*syms)

   assert latex(expr) == 'a \\wedge b \\wedge c \\wedge d \\wedge e \\wedge f'
   assert pretty(expr) == 'And(a, b, c, d, e, f)'
   assert str(expr) == 'And(a, b, c, d, e, f)'
Beispiel #20
0
def calc(s: str) -> LatexResult:
    global sympy_dict

    if (m := assignment_pattern.match(s)) is not None:
        name = m.group(1)
        value = parse_expr(m.group(2),
                           local_dict=sympy_dict,
                           transformations=TRANSFORMATIONS)
        sympy_dict[name] = value
        return LatexResult(latex(value))
def eval_math(obj):
    if 'func' not in obj:
        raise ValueError('must provide func')
    func = obj['func']
    if func not in FUNC_WHITELIST:
        raise ValueError('func must be eval, latex, or literal')

    if 'expr' not in obj:
        raise ValueError('must provide expr')
    expr = obj['expr']

    if func == 'eval':
        kwargs = {'ln_notation': 'True', 'inv_trig_style': 'power'}
        return latex(eval(expr), **kwargs)
    elif func == 'latex':
        return latex(sympify(expr, evaluate=False))
    elif func == 'literal':
        return expr
    return 'error'
Beispiel #22
0
 def latex_equation(eq_string):
     """ 
     Helper function to convert the right hand side of an equation string
     `eq_string` to a LaTeX expression (not a full equation in LaTeX terms)
     using `sympy`.
     """   
     # convert equation to latex
     latex_eq = latex(DocumentWriter.to_sympy_expression(eq_string),
                      mode='plain')
 
     return latex_eq
Beispiel #23
0
 def latex(self, request=None, raw=False):
     self.latex = latex(self.expression, mode='plain')
     obj = {
         'string': self.expressionString,
         'javascript': self.javascript,
         'latex': self.latex
     }
     if (raw):
         return obj
     else:
         return JsonResponse(obj)
Beispiel #24
0
    def latex_equation(eq_string):
        """ 
        Helper function to convert the right hand side of an equation string
        `eq_string` to a LaTeX expression (not a full equation in LaTeX terms)
        using `sympy`.
        """
        # convert equation to latex
        latex_eq = latex(DocumentWriter.to_sympy_expression(eq_string),
                         mode='plain')

        return latex_eq
Beispiel #25
0
 def _repr_markdown_(self):
     """ Return markdown representation for IPython notebook
     """
     if self.ptformatter is not None and self.format is '' and isinstance(self.value, float):
         # %precision magic only works for floats
         fmt = self.ptformatter.float_format
         return u"%s %s" % (fmt % self.value, self.unit._repr_markdown_())
     if str(type(self.value)).find('sympy') > 0:
         # sympy
         return '${0}$ {1}'.format(printing.latex(self.value), self.unit.markdown)
     return '{0:{format}} {1}'.format(self.value, self.unit.markdown, format=self.format)
Beispiel #26
0
def sympy2latex(sp_object, symbol_names):
    """
    print latex code from sympy object
    """
    if isinstance(sp_object, types.matrix_types) and any(el == 0
                                                   for el in
                                                   sp_object.shape):
        return r'\left(\right)'
    else:
        return latex(sp_object, fold_short_frac=fold_short_frac,
                     mat_str=mat_str, mat_delim=mat_delim,
                     mul_symbol=mul_symbol, symbol_names=symbol_names)
Beispiel #27
0
    def format_TeX_mat(self):
        tex_mat = deepcopy(self.original_mat)
        for c, i in enumerate(tex_mat):
            tex_mat[c] = format_matrix_element(i)

        tex_form = UnevaluatedExpr(
            self.ket_row) * UnevaluatedExpr(tex_mat) * UnevaluatedExpr(
                self.bra_col)
        tex_formatted_form = R'$\hat{H}=' + printing.latex(
            tex_form, mat_delim='(', mat_str='matrix') + '$'

        return tex_formatted_form
Beispiel #28
0
 def latex_SI_unit(self):
     """Latex repr of SI unit form.
     
     Leverage sympy's latex function to compute the latex expression equivalent to
     the SI-unit string representation of the Dimension.
     
     See also
     --------
     Dimension.siunit_dict
     """
     expr_SI = expand_dict_to_expr(self.siunit_dict())
     return "$" + latex(expr_SI) + "$"
Beispiel #29
0
def sympy2latex(sp_object, symbol_names):
    """
    print latex code from sympy object
    """
    if isinstance(sp_object, types.matrix_types) and any(el == 0
                                                   for el in
                                                   sp_object.shape):
        return r'\left(\right)'
    else:
        return latex(sp_object, fold_short_frac=fold_short_frac,
                     mat_str=mat_str, mat_delim=mat_delim,
                     mul_symbol=mul_symbol, symbol_names=symbol_names)
Beispiel #30
0
    def render_expression(self, expression, differential=False):
        """
        Function to render mathematical expression using
        `sympy.printing.latex`

        Parameters
        ----------

        expression : str, Quantity
            Expression that has to rendered

        differential : bool, optional
            Whether should be treated as variable in differential equation
        
        Returns
        -------

        rend_exp : str
            Markdown text for the expression
        """
        # change to str
        if isinstance(expression, Quantity):
            expression = str(expression)
        else:
            if not isinstance(expression, str):
                expression = str(expression)
            # convert to sympy expression
            expression = str_to_sympy(expression)
        # check to be treated as differential variable
        if differential:
            # independent variable is always 't'
            t = symbols('t')
            expression = Derivative(expression, 't')
        # render expression
        rend_exp = latex(expression,
                         mode='equation',
                         itex=True,
                         mul_symbol='.')
        # horrible way to remove _placeholder_{arg} inside brackets
        rend_exp = rend_exp.replace('_placeholder_{arg}', '-')
        rend_exp = rend_exp.replace('\operatorname', '')
        # check GitHub based markdown rendering
        if self.github_md:
            # to remove `$$`
            rend_exp = rend_exp[2:][:-2]
            # link to render as image
            git_rend_exp = (
                '<img src="https://render.githubusercontent.com/render/math?math='
                + rend_exp + '">')
            return git_rend_exp
        # to remove `$` (in most md compiler single $ is used)
        return rend_exp[1:][:-1]
Beispiel #31
0
    def model(self, u, var, returnlatex=False):
        from sympy.tensor.array import derive_by_array, tensorproduct
        m = len(var)
        gradient = Matrix(derive_by_array(u, var))
        length = sqrt(trace(Matrix(tensorproduct(gradient, gradient)).reshape(m, m)))
        n = gradient/length
        div = Matrix(derive_by_array(n, var)).reshape(m, m)
        div_n = trace(div)
#        div_n = sym.simplify(div_n)
        hessian = Matrix(derive_by_array(gradient, var)).reshape(m, m)
        laplace = trace(hessian)
        laplace = sym.simplify(laplace)
        val = {'grad': gradient, 'Hessian': hessian, 'Laplace': laplace,
                'unit_normal':n, 'div_unit_normal':div_n}
        if returnlatex is False:
            return val
        else:
            print('grad:\n', printing.latex(val['grad']))
            print('Hessian:\n', printing.latex(val['Hessian']))
            print('Laplace:\n', printing.latex(val['Laplace']))
            print('unit_normal:\n', printing.latex(val['unit_normal']))
            print('div_unit_normal:\n', printing.latex(val['div_unit_normal']))
Beispiel #32
0
 def _repr_markdown_(self):
     """ Return markdown representation for IPython notebook
     """
     if self.ptformatter is not None and self.format is '' and isinstance(
             self.value, float):  # pragma: no cover
         # %precision magic only works for floats
         fmt = self.ptformatter.float_format
         return u"%s %s" % (fmt % self.value, self.unit._repr_markdown_())
     if str(type(self.value)).find('sympy') > 0:
         # sympy
         return '${0}$ {1}'.format(printing.latex(self.value),
                                   self.unit.markdown)
     return '{0:{format}} {1}'.format(self.value,
                                      self.unit.markdown,
                                      format=self.format)
Beispiel #33
0
def printable(num, digits=3, return_zero=False, return_one=True):
    if num == 0:
        if return_zero: return '0'
        else: return ''
    elif num == 1 and return_one == False:
        return ''
    elif num == -1 and return_one == False:
        return '-'
    # Surprisingly, sympy does not handle these cases
    elif num == np.inf:
        return r'\infty'
    elif num == -np.inf:
        return r'-\infty'
    if isinstance(num, float):
        return '%.3f' % num
    else:
        from sympy.printing import latex
        return latex(num)
Beispiel #34
0
def printable(num,digits=3,return_zero=False,return_one=True):
    if num==0:
        if return_zero: return '0'
        else: return ''
    elif num==1 and return_one==False:
        return ''
    elif num==-1 and return_one==False:
        return '-'
    # Surprisingly, sympy does not handle these cases
    elif num == np.inf:
        return r'\infty'
    elif num == -np.inf:
        return r'-\infty'
    if isinstance(num,float):
        return '%.3f' % num
    else:
        from sympy.printing import latex
        return latex(num)
Beispiel #35
0
    def test_generated_cases(self):

        failed_tests = []
        n_tests = 20
        print 'Generating', n_tests, 'test_cases\n'
        for _ in np.arange(n_tests):
            n_terms = np.random.randint(1, high=5)
            expr = generate_term()
            for _ in np.arange(n_terms - 1):
                term = generate_term()
                op = np.random.choice(ops)
                if op == '+':
                    expr = expr + term
                elif op == '-':
                    expr = expr - term
                elif op == '*':
                    expr = expr * term
                elif op == '/':
                    expr = expr / term
                elif op == '^':
                    expr = expr**term
                else:
                    assert False
            s_l_expr = latex(expr)
            try:
                l_expr = process_sympy(s_l_expr)
                equiv = equivalent(expr, l_expr)
                e = None
            except Exception as e:
                # Parsing failed
                l_expr = None
                equiv = False
            if not equiv:
                print '%s %s' % (s_l_expr, 'PASSED' if equiv else 'FAILED')
                failed_tests.append((s_l_expr, l_expr))
                print 'sympy: %s\nlatex: %s' % (expr, l_expr)
                if e is not None:
                    print e
                print

        if failed_tests:
            print len(failed_tests), 'failed test cases'
        assert len(failed_tests) == 0
Beispiel #36
0
    def out(self, expr):
        """
        expr: A sympy expression
        _l = _latex()
        _p = _l.out
        _d = _l.symbol_names
        from sympy import MatrixSymbol
        from sympy import Symbol
        from sympy import Matrix
        X = MatrixSymbol('X', 3, 3)
        _d[X]=r'\Phi_W'
        _p(Matrix([[X], [X]]))
        k = Symbol('k')
        _d[k]=r'\k_W'
        _p(Sum(X * k, (k, 1, 10)))
        """
	l = latex(expr, symbol_names=self.symbol_names)
        print(l)
	return l
 def write_results(self, filename):
     '''
     Write the model reduction results in a file given by filename. 
     The symbolic data is written in LaTeX.
     '''
     from sympy.printing import latex
     f1 = open(filename, 'w')
     f1.write('Model reduction results.\n')
     for key, value in self.results_dict.items():
         f1.write('A possible reduced model: \n \n')
         f1.write('\n$x_{hat} = ')
         f1.write(str(key.x))
         f1.write('$\n\n\n\n')
         for k in range(len(key.f)):
             f1.write('\n$f_{hat}(' + str(k + 1) + ') = ')
             f1.write(latex(key.f[k]))
             f1.write('$\n\n')
         f1.write('\n\n\n')
         f1.write('\nError metric:')
         f1.write(str(value[0]))
         f1.write('\n\n\n')
         f1.write('\nRobustness metric:')
         f1.write(str(value[1]))
         f1.write('\n\n\n')
         f1.write('Other properties')
         f1.write('\n\n\n')
         f1.write('\n C = ')
         f1.write(str(key.C))
         f1.write('\n$ g = ')
         f1.write(str(key.g))
         f1.write('$\n h = ')
         f1.write(str(key.h))
         f1.write('\n$h = ')
         f1.write(str(key.h))
         f1.write('$\n Solutions : \n')
         f1.write(str(key.x_sol))
         f1.write('\n\n\n\n')
         f1.write('\n Sensitivity Solutions : \n')
         f1.write(str(key.S))
         f1.write('\n\n\n\n')
     f1.close()
Beispiel #38
0
def print_tex(data):
    return '''
\\title{A Very Simple \\LaTeXe{} Template}
\\author{
        Vitaly Surazhsky \\\\
                Department of Computer Science\\\\
        Technion---Israel Institute of Technology\\\\
        Technion City, Haifa 32000, \\underline{Israel}
            \\and
        Yossi Gil\\\\
        Department of Computer Science\\\\
        Technion---Israel Institute of Technology\\\\
        Technion City, Haifa 32000, \\underline{Israel}
}
\\date{\\today}

\\documentclass[12pt]{article}

\\begin{document}
$$%s$$
\\end{document}
''' % str(printing.latex(data))
    def latex(self):
    	"""A laTeX representation of the compact form."""
    	from sympy.printing import latex

        d       = self.d
        A       = self.A
        Ahat    = self.Ahat
        b       = self.b
        bhat    = self.bhat
        theta   = self.theta

        s= r'\begin{align}'
        s+='\n'
        s+=r'  \begin{array}{c|'
        s+='c'*(len(self)) +'|'
        s+='c'*(len(self)) 
        s+='}\n'
        for i in range(len(self)):
            s+='  '+latex(d[i])
            
            for j in range(len(self)):
                s+=' & '+latex(Ahat[i,j])
            
            for j in range(len(self)):
                s+=' & '+latex(A[i,j])
            
            s+=r'\\'
            s+='\n'
        s+=r'  \hline'
        s+='\n'
        s+= '  '+latex(theta)
        for j in range(len(self)):
            s+=' & '+latex(bhat[j])
        for j in range(len(self)):
            s+=' & '+latex(b[j])
        s+='\n'
        s+=r'  \end{array}'
        s+='\n'
        s+=r'\end{align}'
        s=s.replace('- -','')
    	return s
    def latex(self):
        """A laTeX representation of the compact form."""
        from sympy.printing import latex

        d = self.d
        A = self.A
        Ahat = self.Ahat
        b = self.b
        bhat = self.bhat
        theta = self.theta

        s = r'\begin{align}'
        s += '\n'
        s += r'  \begin{array}{c|'
        s += 'c' * (len(self)) + '|'
        s += 'c' * (len(self))
        s += '}\n'
        for i in range(len(self)):
            s += '  ' + latex(d[i])

            for j in range(len(self)):
                s += ' & ' + latex(Ahat[i, j])

            for j in range(len(self)):
                s += ' & ' + latex(A[i, j])

            s += r'\\'
            s += '\n'
        s += r'  \hline'
        s += '\n'
        s += '  ' + latex(theta)
        for j in range(len(self)):
            s += ' & ' + latex(bhat[j])
        for j in range(len(self)):
            s += ' & ' + latex(b[j])
        s += '\n'
        s += r'  \end{array}'
        s += '\n'
        s += r'\end{align}'
        s = s.replace('- -', '')
        return s
from sympy import *

#u_i_n = Symbol("u_i^{n}")
u_i_n = Symbol("u_i^n")
pprint(u_i_n)

import sympy.printing as printing

delta__y_l = symbols("Delta__y_l")
print(printing.latex(delta__y_l))

u_i_np1 = symbols("u_i__n+1")
print(printing.latex(u_i_np1))

u_ip1_np1 = symbols("u_i+1__n+1")
print(printing.latex(u_ip1_np1))

u_ip1j_np1 = symbols("u_{i+1,j}__n+1")
print(printing.latex(u_ip1j_np1))
pprint(u_ip1j_np1)
Beispiel #42
0
def a_matrix(theta, alpha, l, d):
    return Matrix([[cos(theta), -1*(sin(theta)*cos(alpha)), sin(theta)*sin(alpha), l*cos(theta)],
                   [sin(theta), cos(theta)*cos(alpha), -1*cos(theta)*sin(alpha), l*sin(theta)],
                   [0, sin(alpha), cos(alpha), d],
                   [0, 0, 0, 1]])

output = eye(4)
a_matrices = [a_matrix(t_1, np.deg2rad(config['theta_1']['alpha']), config['theta_1']['l'], config['theta_1']['d']),
              a_matrix(t_2, np.deg2rad(config['theta_2']['alpha']), config['theta_2']['l'], config['theta_2']['d']),
              a_matrix(t_3, np.deg2rad(config['theta_3']['alpha']), config['theta_3']['l'], config['theta_3']['d']),
              a_matrix(t_4, np.deg2rad(config['theta_4']['alpha']), config['theta_4']['l'], config['theta_4']['d']),
              a_matrix(t_5, np.deg2rad(config['theta_5']['alpha']), config['theta_5']['l'], config['theta_5']['d'])]

for matrix in a_matrices:
    output = output*matrix
print(latex(simplify(trigsimp(output[0,0]))) +'\n')
print(latex(simplify(trigsimp(output[0,1]))) +'\n')
print(latex(simplify(trigsimp(output[0,2]))) +'\n')
print(latex(simplify(trigsimp(output[0,3]))) +'\n')
print(latex(simplify(trigsimp(output[1,0]))) +'\n')
print(latex(simplify(trigsimp(output[1,1]))) +'\n')
print(latex(simplify(trigsimp(output[1,2]))) +'\n')
print(latex(simplify(trigsimp(output[1,3]))) +'\n')
print(latex(simplify(trigsimp(output[2,0]))) +'\n')
print(latex(simplify(trigsimp(output[2,1]))) +'\n')
print(latex(simplify(trigsimp(output[2,2]))) +'\n')
print(latex(simplify(trigsimp(output[2,3]))) +'\n')
#q1
q_1 = asin(((q_24-d_5*q_23-((l_3*q_23))/sin(t_3+t_4))-(l_2*q_23/sin(t_3+t_4)))/l_1)

q_2 = asin((q_23)/(sin(t_3+t_4)))-t_1