예제 #1
0
def test_py2tex_wordoutput(verbose=True, **kwargs):
    """Convert Python expression to Word readable output"""

    # Tests
    expr_py = [
        r"2*sqrt(2*pi*k*T_e/m_e)*(DeltaE/(k*T_e))**2*a_0**2",
    ]

    expr_docx = [
        r"2\sqrt((2\pi\cdotk\cdotT_(e)/m_(e)))\cdot(((\Delta E/k\cdotT_(e))))^(2)\cdot(a_(0))^(2)"
    ]

    for i, expr in enumerate(expr_py):
        if verbose:
            uprint("")
            uprint("ˆ")
            uprint("Python formula to convert: {0}".format(expr))
            s = py2tex(expr, output="word")
            uprint("Got:")
            b = expr_docx[i] == s
            print(s)
            #            uprint('.. correct =', b)
            if not b:
                uprint("Expected Word-readable output:\n", expr_docx[i])
                uprint("\n" * 3)
            assert b
        else:
            s = py2tex(expr,
                       output="word",
                       print_latex=False,
                       print_formula=False)
            assert expr_docx[i] == s
예제 #2
0
def test_py2tex_py3only(verbose=True, **kwargs):
    """ Some tests valid with Python 3 syntax only (Ex: unicodes: ˆ)"""

    if sys.version_info[0] != 3:
        if verbose:
            print("Not Python 3. Ignoring test_py2tex_py3only")
        return

    # Tests
    expr_py = [
        r"k_i__1_i__2ˆj__1ˆj__2",
    ]

    expr_tex = [
        r"$$k_{i_1,i_2}^{j_1,j_2}$$",
    ]

    for i, expr in enumerate(expr_py):
        if verbose:
            uprint("")
            uprint("ˆ")
            uprint("Python formula to convert: {0}".format(expr))
            s = py2tex(expr)
            uprint("Got:")
            b = expr_tex[i] == s
            print(s)
            #            uprint('.. correct =', b)
            if not b:
                uprint("Expected:\n", expr_tex[i])
                uprint("\n" * 3)
            assert b
        else:
            s = py2tex(expr, print_latex=False, print_formula=False)
            assert expr_tex[i] == s
예제 #3
0
def test_py2tex_wordoutput(verbose=True, **kwargs):
    '''  Convert Python expression to Word readable output
    '''

    # Tests
    expr_py = [
        r'2*sqrt(2*pi*k*T_e/m_e)*(DeltaE/(k*T_e))**2*a_0**2',
    ]

    expr_docx = [
        r'2\sqrt((2\pi\cdotk\cdotT_(e)/m_(e)))\cdot(((\Delta E/k\cdotT_(e))))^(2)\cdot(a_(0))^(2)'
    ]

    for i, expr in enumerate(expr_py):
        if verbose:
            uprint('')
            uprint(u'ˆ')
            uprint(u'Python formula to convert: {0}'.format(expr))
            s = py2tex(expr, output='word')
            uprint('Got:')
            b = (expr_docx[i] == s)
            print(s)
            #            uprint('.. correct =', b)
            if not b:
                uprint('Expected Word-readable output:\n', expr_docx[i])
                uprint('\n' * 3)
            assert b
        else:
            s = py2tex(expr,
                       output='word',
                       print_latex=False,
                       print_formula=False)
            assert expr_docx[i] == s
예제 #4
0
def test_py2tex_py3only(verbose=True, **kwargs):
    ''' Some tests valid with Python 3 syntax only (Ex: unicodes: ˆ)'''

    if sys.version_info[0] != 3:
        if verbose: print('Not Python 3. Ignoring test_py2tex_py3only')
        return

    # Tests
    expr_py = [
        r'k_i__1_i__2ˆj__1ˆj__2',
    ]

    expr_tex = [
        r'$$k_{i_1,i_2}^{j_1,j_2}$$',
    ]

    for i, expr in enumerate(expr_py):
        if verbose:
            uprint('')
            uprint(u'ˆ')
            uprint(u'Python formula to convert: {0}'.format(expr))
            s = py2tex(expr)
            uprint('Got:')
            b = (expr_tex[i] == s)
            print(s)
            #            uprint('.. correct =', b)
            if not b:
                uprint('Expected:\n', expr_tex[i])
                uprint('\n' * 3)
            assert b
        else:
            s = py2tex(expr, print_latex=False, print_formula=False)
            assert expr_tex[i] == s
예제 #5
0
def test_py2tex(verbose=True, **kwargs):
    """
    Note : for debugging use
        pt = ast.parse(expr)
        print(ast.dump(pt))
    """

    # Tests
    expr_py = [
        r"Re_x=(rho*v*x)/mu",
        r"2*sqrt(2*pi*k*T_e/m_e)*(DeltaE/(k*T_e))**2*a_0**2",
        r"f(x**2/y**3)",
        r"arctanh(x/sqrt(x))",
        r"quad(f,0,np.inf)",
        # ------------------
        r"1<2<a<=5",
        r"np.std([f(i) for i in range(21)])",
        r"np.sum([i**2 for i in range(1,101)])==338350",
        r"(a**b)**c",
        r"-x**2",
        r"-(x**2+y**2)",
        r"-(x+y)**2",
    ]

    expr_tex = [
        r"$$Re_x=\frac{\rho v x}{\mu}$$",
        r"$$2\sqrt{\frac{2\pi k T_e}{m_e}} \left(\frac{\Delta E}{k T_e}\right)^2 {a_0}^2$$",
        r"$$f{\left(\frac{x^2}{y^3}\right)}$$",
        r"$$\tanh^{-1}\left(\frac{x}{\sqrt{x}}\right)$$",
        r"$$\int_{0}^{\infty} f\left(u\right) du$$",
        # -------------------
        r"$$1<2<a<=5$$",
        r"$$\operatorname{std}\left(f{\left(i\right)}, i=0..20\right)$$",
        r"$$\sum_{i=1}^{100} i^2=338350$$",
        r"$$\left(a^b\right)^c$$",
        r"$$-x^2$$",
        r"$$-\left(x^2+y^2\right)$$",
        r"$$-\left(x+y\right)^2$$",
    ]

    for i, expr in enumerate(expr_py):
        if verbose:
            uprint("")
            uprint("ˆ")
            uprint("Python formula to convert: {0}".format(expr))
            s = py2tex(expr)
            uprint("Got:")
            b = expr_tex[i] == s
            print(s)
            #            uprint('.. correct =', b)
            if not b:
                uprint("Expected:\n", expr_tex[i])
                uprint("\n" * 3)
            assert expr_tex[i] == s
        else:
            s = py2tex(expr, print_latex=False, print_formula=False)
            assert expr_tex[i] == s

    return True
예제 #6
0
def test_py2tex(verbose=True, **kwargs):
    ''' 
    Note : for debugging use 
        pt = ast.parse(expr)
        print(ast.dump(pt))
    '''

    # Tests
    expr_py = [
        r'Re_x=(rho*v*x)/mu',
        r'2*sqrt(2*pi*k*T_e/m_e)*(DeltaE/(k*T_e))**2*a_0**2',
        r'f(x**2/y**3)',
        r'arctanh(x/sqrt(x))',
        r'quad(f,0,np.inf)',
        # ------------------
        r'1<2<a<=5',
        r'np.std([f(i) for i in range(21)])',
        r'np.sum([i**2 for i in range(1,101)])==338350',
        r'(a**b)**c',
    ]

    expr_tex = [
        r'$$Re_x=\frac{\rho v x}{\mu}$$',
        r"$$2\sqrt{\frac{2\pi k T_e}{m_e}} {\left(\frac{\Delta E}{k T_e}\right)}^2 {a_0}^2$$",
        r"$$f{\left(\frac{x^2}{y^3}\right)}$$",
        r"$$\tanh^{-1}(\frac{x}{\sqrt{x}})$$",
        r"$$\int_{0}^{\infty} f(u) du$$",
        # -------------------
        r'$$1<2<a<=5$$',
        r'$$\operatorname{std}\left(f{\left(i\right)}, i=0..20\right)$$',
        r'$$\sum_{i=1}^{100} i^2=338350$$',
        r'$${\left(a^b\right)}^c$$',
    ]

    for i, expr in enumerate(expr_py):
        if verbose:
            uprint('')
            uprint(u'ˆ')
            uprint(u'Python formula to convert: {0}'.format(expr))
            s = py2tex(expr)
            uprint('Got:')
            b = (expr_tex[i] == s)
            print(s)
            #            uprint('.. correct =', b)
            if not b:
                uprint('Expected:\n', expr_tex[i])
                uprint('\n' * 3)
            assert expr_tex[i] == s
        else:
            s = py2tex(expr, print_latex=False, print_formula=False)
            assert expr_tex[i] == s

    return True
예제 #7
0
def test_simplify_parser(verbose=True, **kwargs):
    ''' Test simplifications during Parsing. 
    
    simplify_ints and simplify_fractions implemented by alexhagen 
    See PR 7: https://github.com/erwanp/pytexit/pull/7
    '''

    # Test simplify_ints:
    assert py2tex('1./5.2', simplify_ints=True,
                  print_latex=False) == '$$\\frac{1}{5.2}$$'
    assert py2tex('1./5.2', simplify_ints=False,
                  print_latex=False) == '$$\\frac{1.0}{5.2}$$'

    # Test simplify_fractions:
    assert py2tex('0.5', simplify_fractions=False,
                  print_latex=False) == '$$0.5$$'
    assert py2tex('0.5', simplify_fractions=True,
                  print_latex=False) == '$$\\frac{1}{2}$$'

    # Test simplify_multpliers
    assert py2tex('2*4', print_latex=False) == '$$2\\times4$$'
    assert py2tex('-2*3', print_latex=False) == '$$-2\\times3$$'
    assert py2tex('a*-2', simplify_multipliers=True,
                  print_latex=False) == '$$-2a$$'
    assert py2tex('a*-2', simplify_multipliers=False,
                  print_latex=False) == '$$a\\times-2$$'
예제 #8
0
def test_simplify_parser(verbose=True, **kwargs):
    """Test simplifications during Parsing.

    simplify_ints and simplify_fractions implemented by alexhagen
    See PR 7: https://github.com/erwanp/pytexit/pull/7
    """

    # Test simplify_ints:
    assert (py2tex("1./5.2", simplify_ints=True,
                   print_latex=False) == "$$\\frac{1}{5.2}$$")
    assert (py2tex("1./5.2", simplify_ints=False,
                   print_latex=False) == "$$\\frac{1.0}{5.2}$$")

    # Test simplify_fractions:
    assert py2tex("0.5", simplify_fractions=False,
                  print_latex=False) == "$$0.5$$"
    assert (py2tex("0.5", simplify_fractions=True,
                   print_latex=False) == "$$\\frac{1}{2}$$")

    # Test simplify_multpliers
    assert py2tex("2*4", print_latex=False) == "$$2\\times4$$"
    assert py2tex("-2*3", print_latex=False) == "$$-2\\times3$$"
    assert py2tex("a*-2", simplify_multipliers=True,
                  print_latex=False) == "$$-2a$$"
    assert (py2tex("a*-2", simplify_multipliers=False,
                   print_latex=False) == "$$a\\times-2$$")
예제 #9
0
def for2tex(a, **kwargs):
    """Converts FORTRAN formula to Python Formula

    Parameters
    ----------

    a: str
        FORTRAN formula

    Other Parameters
    ----------------

    kwargs: dict
        forwarded to :func:`~pytexit.py2tex` function. See :func:`~pytexit.py2tex`
        doc.

    Examples
    --------

    convert FORTRAN formula to LaTeX with for2tex::

        for2tex(r'2.8d-11 * exp(-(26500 - 0.5 * 1.97 * 11600 )/Tgas)')

    See Also
    --------

    :func:`~pytexit.core.fortran.for2py`, :func:`~pytexit.pytexit.py2tex`

    """

    from pytexit import py2tex

    return py2tex(for2py(a), **kwargs)
예제 #10
0
파일: __init__.py 프로젝트: haavahk/adapy
def equation_compiler(f, print_latex=False, print_formula=False):
    from inspect import getsourcelines

    import pytexit

    lines = getsourcelines(f)
    final_line = lines[0][-1]
    return pytexit.py2tex(final_line.replace("return ", ""),
                          print_latex=print_latex,
                          print_formula=print_formula)
예제 #11
0
def get_normal_curve_label():
    C = '1/(sigma*sqrt(2*pi))'
    E = '-(1/2)*(((X-mu)/sigma)**2)'
    pdf_latex = py2tex('(' + C + ')*(e)**(' + E + ')',
                       print_latex=False,
                       print_formula=False)[1:-1]
    #pdf_latex = pdf_latex.replace('$','') # strip to insert some more
    #pdf_latex = '$\\fontsize{30pt}{3em}\\mu$'
    #print(pdf_latex)
    return pdf_latex
예제 #12
0
    def readable_odes(self, reaction_model, kind):
        """Converts the ODEs to LaTeX
        
        :param ReactionModel reaction_model: A solved/simulated ReactionModel instance
        :param str kind: odes or daes
        
        :return odes_new: Dictionary of equations as latex strings
        :rtype: dict
        
        """
        numeric_const_pattern = '[-+]? (?: (?: \d* \. \d+ ) | (?: \d+ \.? ) )(?: [Ee] [+-]? \d+ ) ?'
        rx = re.compile(numeric_const_pattern, re.VERBOSE)

        odes = {
            k: v.expression
            for k, v in getattr(reaction_model, kind).items()
        }
        odes_new = {}

        for k, v in odes.items():

            if kind == 'odes':
                try:
                    odes_new[f'{k}'] = self.remove(v.to_string())
                except:
                    odes_new[f'{k}'] = str(v)
            else:
                try:
                    odes_new[f'{k}'] = self.remove(v.to_string())
                except:
                    odes_new[f'{k}'] = str(v)

            # floats = rx.findall(odes_new[k])

            # text = odes_new[k]
            # #print(text)
            # for num in floats:
            #     find_it = num
            #     if int(float(num)) == float(num):
            #         continue
            #     elif len(num) < 5:
            #         continue
            #     else:
            #         repl_it = f'{float(find_it):.4f}'
            #         text = text.replace(find_it, repl_it)

            odes_new[k] = py2tex(odes_new[k],
                                 print_latex=False,
                                 print_formula=False)

        ode_list = []
        for k, v in odes_new.items():
            ode_list.append(f'{k} = {v}')

        return odes_new
예제 #13
0
def index():
    errors = []
    results = None
    if request.method == "POST":
        try:
            exp = request.form['data']
            results = py2tex(str(integrate(exp, x)))
        except:
            errors.append("Unable to reach client")
            print(errors)
    return render_template('index.html', errors=errors, results=results)
예제 #14
0
def make_table_of_symbols(symbols: List[str], units: List[str],
                          descriptions: List[str]):
    table_symbols_content = LongTable("l l l")
    table_symbols_content.add_hline()
    table_symbols_content.add_row(["Symbol", "Unit", "Description"])
    table_symbols_content.add_hline()
    table_symbols_content.end_table_header()
    table_symbols_content.add_hline()
    table_symbols_content.add_row(
        (MultiColumn(3, align='r', data='Continued on Next Page'), ))
    table_symbols_content.add_hline()
    table_symbols_content.end_table_footer()
    table_symbols_content.add_hline()
    table_symbols_content.add_row((MultiColumn(3, align='r', data='***End'), ))
    table_symbols_content.add_hline()
    table_symbols_content.end_table_last_footer()

    for i in range(len(symbols)):
        try:
            symbol = py2tex(symbols[i], print_latex=False,
                            print_formula=False).replace('$', '')
        except:
            symbol = symbols[i]
        try:
            unit = py2tex(units[i],
                          print_latex=False,
                          print_formula=False,
                          simplify_fractions=True).replace('$', '')
        except:
            unit = units[i]
        table_symbols_content.add_row([
            NoEscape(f'${symbol}$'),
            NoEscape(f'${unit}$'),
            NoEscape(descriptions[i])
        ])

    table_symbols_content.add_hline()

    return table_symbols_content
예제 #15
0
def py2tex_silent(python_expression):
    expr_str = str(python_expression)
    result = (py2tex(
        expr_str,
        print_latex=False,
        print_formula=False,
    ).replace("$$", ""))

    # matrices (also diagonal ones) are handled by sympify only
    # they are not implemented in py2tex, even though
    # diag does not raise an error
    if r'\operatorname{diag}\left(' in result: raise (TypeError)
    return result
예제 #16
0
def expression_decoder_latex_equation(data, variables):
    """
    Преобразование формулы из формата EXCEL в LaTex(mathjax) выражение.
    :param data: Строка, которую надо преобразовать.
    :param variables: Набор переменных, из которых будет составляться выражение.
    :return: строка в синтаксисе LaTex(mathjax)
    """
    done = ""
    to_replace = {"\\times": "\\times ", "$": ""}
    tok = Tokenizer(data)

    for t in tok.items:
        if t.value in "()":
            done += t.value
        elif t.type == "OPERATOR-INFIX":
            done += t.value.replace("^", "**").replace(",", ".")

        elif t.type == "FUNC":
            value = t.value
            if t.subtype == "OPEN":
                to_repl = {"LN": "LOG", "TREND": "trend"}
                for key, val in to_repl.items():
                    value = value.replace(key, val)
                done += value
            else:
                done += value

        elif t.type == "OPERAND" and t.subtype == "RANGE":
            t.value = t.value.replace("$", "")
            n = int("".join(filter(str.isdigit, t.value)))
            if ":" in t.value:
                v = t.value.split(":")
                n = int("".join(filter(str.isdigit, v[0])))
                done += "{}".format(n)
                to_replace[n] = variables[n]["latex_symbol"]

            elif t.value in ["ИСТИНА", "TRUE", "FALSE", "ЛОЖЬ"]:
                continue
            else:
                done += "{}".format(n)
                to_replace[n] = variables[n]["latex_symbol"]

        elif t.type == "OPERAND" and t.subtype == "NUMBER":
            done += str(t.value)
    if not done:
        return ""
    done = py2tex(done, print_latex=False, print_formula=False)
    for k, v in to_replace.items():
        done = done.replace(str(k), str(v))
    return done
예제 #17
0
def equation_compiler(f, print_latex=False, print_formula=False):
    from inspect import getsourcelines

    try:
        import pytexit
    except ModuleNotFoundError as e:
        raise ModuleNotFoundError(
            "To use the equation compiler you will need to install pytexit first.\n"
            'Use "pip install pytexit"\n\n'
            f'Original error message: "{e}"')

    lines = getsourcelines(f)
    final_line = lines[0][-1]
    return pytexit.py2tex(final_line.replace("return ", ""),
                          print_latex=print_latex,
                          print_formula=print_formula)
예제 #18
0
def slack_loop_botex(**payload):
    data = payload['data']
    web_client = payload['web_client']
    rtm_client = payload['rtm_client']

    if DEBUG:
        print("[DEBUG] def slack_loop_botex()")

    if 'text' in data and 'tex' in data.get('text', []):
        channel_id = data['channel']
        thread_ts = data['ts']
        user = data['user']
        latexreq = data['text'].split("tex ", 1)[1]

        filename = time.strftime("%Y%m%d-%H%M%S-{}-output.png".format(user))

        if DEBUG:
            print("[DEBUG] received text={} latexreq={}".format(
                data['text'], latexreq))

        try:
            latex = py2tex(latexreq)
            if DEBUG:
                print("[DEBUG] latex={}".format(latex))
            if DEBUG:
                print("[DEBUG] Generating png file")
            sympy.preview(latex,
                          viewer='file',
                          filename='/var/tmp/' + filename)
            if DEBUG:
                print("[DEBUG] Uploading to S3")
            reply = file2s3_getlink(filename)
        except:
            reply = "Cannot transform this expression, invalid syntax?"
        try:
            response = web_client.chat_postMessage(channel=channel_id,
                                                   text=f"Hi <@{user}>! " +
                                                   reply,
                                                   thread_ts=thread_ts)
        except SlackApiError as e:
            # You will get a SlackApiError if "ok" is False
            assert e.response["ok"] is False
            assert e.response[
                "error"]  # str like 'invalid_auth', 'channel_not_found'
            print(f"Got an error: {e.response['error']}")
예제 #19
0
    async def tex_command(self, ctx: Kaantext, *, expression: str) -> None:
        """
        turn python math expression into latex image in an embed
        ex: !tex x = 2 * sqrt(2 * pi * k * T_e / m_e) * (DeltaE / (k * T_e))**2 * a_0**2
        """

        # strip any whitespace and backticks
        expression = expression.strip().strip('`').strip()

        # converts python math expression to latex string
        try:
            tex = py2tex(
                expression,
                print_latex=False,
                print_formula=False,
            )
        except (TypeError, SyntaxError):
            return await ctx.send_error_msg('Expression could not be processed'
                                            )

        # convert latex to png and save to buffer
        buffer = io.BytesIO()
        sympy.preview(
            tex,
            viewer='BytesIO',
            outputbuffer=buffer,
            euler=False,
            dvioptions=[
                '-T',
                'tight',
                '-z',
                '0',
                '--truecolor',
                '-D 400',
                '-bg',
                'Transparent',
                '-fg',
                'White',
            ],
        )

        # open buffer as PIL.Image
        img = Image.open(buffer)

        # if the image width is higher than width
        width = 400
        if img.width > width:

            # resize image to width preserving aspect ratio
            img.thumbnail(size=(width, 1000))

        # add padding to the image
        pad_h = 20
        pad_v = 20
        w = img.width + pad_h * 2
        h = img.height + pad_v * 2
        padded_img = Image.new('RGBA', (w, h), (0, 0, 0, 0))
        padded_img.paste(img, (pad_h, pad_v))

        # clear the buffer
        buffer.seek(0)
        buffer.truncate(0)

        # write the resized/padded image to the cleared buffer
        padded_img.save(buffer, format='PNG')

        # seek to the beginning of the buffer
        buffer.seek(0)

        # use it to initialize a discord.File object
        file = discord.File(fp=buffer, filename='tex.png')

        # create embed for the latex image to be sent in
        embed = discord.Embed(
            title='Your expression as LaTeX',
            color=Colors.kaa,
        )
        embed.set_image(url="attachment://tex.png")

        # send the embed and the image as an attachment
        await ctx.send(file=file, embed=embed)
예제 #20
0
formula_1 = [
    "(tf*(td / to))*(ei)",
    "((tf*2)*(td / to*3))*(ei)",
    "(tf*(td / to))*((ei)**0.5)",
    "((tf**0.5)*(td / to))*(ei)",
    "tf*(td / (to))*((ei)**2)",
    "tf*(2*td / (to))*((ei))",
    "(tf*(td / to**2))*(ei)",
    "((tf**0.5)*(td / to))*((ei)**2)",
    "((tf*3)*(td / to))*((ei)**0.5)",
    "(tf*(td / (to**0.5)))*(ei)",
]
formula_2 = [
    "tt * speed * fe",
    "(tt ** 2) * speed * fe",
    "tt * (speed ** 2) * fe",
    "tt * speed * (fe ** 2)",
    "(tt ** 0.5) * speed * fe",
    "tt * (speed ** 0.5) * fe",
    "tt * speed * (fe ** 0.5)",
]

# for idx, val in enumerate(formula_1):
#     print(py2tex(val, output="word", print_formula=False).replace("\cdot", "\cdot "))

for idx, val in enumerate(formula_2):
    print(
        py2tex(val, output="word",
               print_formula=False).replace("\cdot", "\cdot "))
예제 #21
0
def main():
    equation = 'x = 2*sqrt(2*pi*k*T_e/m_e)*(DeltaE/(k*T_e))**2*a_0**2'
    sth = py2tex(equation)
    print("The old equation is: %s" % equation)
    print("The new one is: %s" % sth)
예제 #22
0
def plot_bi_nor_2(df, outcomes, n_events, fontsize=10, ax1=None, ax2=None, 
    C='1/(sigma*sqrt(2*pi))', E='-(((X-mu)/sigma)**2)/2', 
    xstepsize=10, n_shift=False, n_mu=0,
    xlabel = 'X', ylabel1='n (X)', ylabel2='p (X)'):
    """
    Given the dataframe with x, n(x), p(x) this provides two plots:
    x vs n(x) along with normal approx curve
    x vs p(x) along with normal approx curve

    n_shift - theoretical n(x) is probability neutral, so use this switch to shift its normal approx.curve
    when you have unequal probabilities between outcomes.Do not forget to provide new mu value if u enable this.
    """
    mu = 0
    sigma = 1
    mu, var, sigma = get_metrics(df)
    total_outcomes = sum(outcomes)
    p = round(mu/(n_events*total_outcomes),4)
    #print(p)
    #print('Mean: {}  SD: {}'.format(mu, sigma))

    if ax1 == None or ax2 == None:
        fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14,5))
    
    X = df['x'].tolist()
    N = df['n(x)'].tolist()    
    P = df['p(x)'].tolist()    

    # FREQUENCY GRAPH    

    ax1.bar(X, N, color="C0")    
    autoformat(ax1, xlabel, ylabel1, fontsize+3)  


    # PROBABILITY GRAPH    
    
    ax2.bar(X, P)    
    autoformat(ax2, xlabel, ylabel2, fontsize+3)      

    # standard normal continuous distribution approxmiation for frequency graph
    X = np.linspace(-max(X),max(X),10*len(X))
    #C = eval(C)
    Cf = df['n(x)'].max()  # max frequency
    if n_shift == True:     # disabling mu influence
        mu_temp = mu
        mu = n_mu
        Ef = eval(E)
        p_temp = round(mu/(n_events*total_outcomes),4)        
        metrics_text = '$\mu_x:{}$ \n$\sigma_x:{}$ \n$p_y:{}$'.format(mu, sigma,p_temp)
        #metrics_text = '$\mu:{}$ \n$\sigma:{}$'.format(mu, sigma)
        font_color='blue'
        mu = mu_temp
    else:
        Ef = eval(E)
        #p = round(mu/(n_events*total_outcomes),4)
        metrics_text = '$\mu_x:{}$ \n$\sigma_x:{}$ \n$p_y:{}$'.format(mu, sigma,p)
        #metrics_text = '$\mu:{}$ \n$\sigma:{}$'.format(mu, sigma)
        font_color='red'
    G = Cf*np.exp(Ef)
    ax1.plot(X,G, color='red')

    ax1.text(0.025,0.98,metrics_text, ha='left', va='top',transform = ax1.transAxes,fontsize=fontsize+3,color=font_color)

    pdf_latex = py2tex('max(n(x))'+ '*(e)**(' + E + ')', print_latex=False, print_formula=False)[1:-1]
    ax1.text(0.97, 0.98,pdf_latex,ha='right', va='top',transform = ax1.transAxes,fontsize=fontsize+5,color='red')    


    # standard normal continuous distribution apprxomation for probability graph
    #X = np.linspace(-max(X),max(X),100)
    Cp = eval(C)
    Ep = eval(E)
    G = Cp*np.exp(Ep)
    ax2.plot(X,G, color='red')


    metrics_text = '$\mu_x:{}$ \n$\sigma_x:{}$ \n$p_y:{}$'.format(mu, sigma,p)
    #metrics_text = '$\mu:{}$ \n$\sigma:{}$'.format(mu, sigma)
    ax2.text(0.025,0.98,metrics_text, ha='left', va='top',transform = ax2.transAxes,fontsize=fontsize+3,color='red')
    pdf_latex = py2tex('(' + C + ')*(e)**(' + E + ')', print_latex=False, print_formula=False)[1:-1]
    ax2.text(0.97, 0.98,pdf_latex,ha='right', va='top',transform = ax2.transAxes,fontsize=fontsize+5,color='red')

    
    # BOTH GRAPHS

    # fix x axis steps and limits for both graphs
    pend = mu + 5*sigma
    pstart = mu - 5*sigma
    if n_shift == True:
        nend = n_mu + 5*sigma
        nstart = n_mu - 5*sigma
        ax1.set_xlim([nstart,nend])
        ax1.xaxis.set_ticks(np.arange(int(nstart), int(nend), xstepsize))    
    else:
        ax1.set_xlim([pstart,pend])
        ax1.xaxis.set_ticks(np.arange(int(pstart), int(pend), xstepsize))    

    ax2.set_xlim([pstart,pend])
    ax2.xaxis.set_ticks(np.arange(int(pstart), int(pend), xstepsize))    

    if ax1 == None or ax2 == None:
        plt.tight_layout()
        plt.subplots_adjust(wspace=0.45)    
        plt.show()  
예제 #23
0
파일: app.py 프로젝트: kushalpoddar/matxt
	def post(self):
		#Handling the file upload of PDB
		parse = reqparse.RequestParser()
		parse.add_argument('fileimg', type=werkzeug.datastructures.FileStorage, location='files')
		
		args = parse.parse_args()

		image_file = args['fileimg']
		random_hash = md5(str(localtime()).encode('utf-8')).hexdigest()
		filepath = "temp/" + random_hash + ".png"
		image_file.save(filepath)

		image = cv2.imread(filepath);
		gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
		cv2.imwrite(filepath, gray)

		image = cv2.imread(filepath);
		rect, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)
		ctrs, hier = cv2.findContours(binary.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
		cnt=sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0])


		rects=[]
		for c in cnt :
		    x,y,w,h= cv2.boundingRect(c)
		    rect=[x,y,w,h]
		    rects.append(rect)

		i=0
		imgurls = []

		text_str = ''
		for r in rects:
			x=r[0]
			y=r[1]
			w=r[2]
			h=r[3]
			im_crop =binary[y:y+h+5,x:x+w+5]

			# img_not = cv2.bitwise_not(im_resize)

			#Size of the image
			height, width = im_crop.shape
			img_area = height*width

			val_type = 'char'
			#Checking if the area of this image is half the area of previous image
			if len(imgurls) and img_area < imgurls[i-1]['area']/1.5 and (y+h) < 50:
				val_type = 'power'

			img_not = cv2.resize(im_crop, (28, 28),  
			       interpolation = cv2.INTER_NEAREST)

			
			img_not = cv2.copyMakeBorder(img_not.copy(),5,5,5,5,cv2.BORDER_CONSTANT,value=[0,0,0])

			img_not = cv2.resize(img_not, (28, 28),  
			       interpolation = cv2.INTER_NEAREST)
			
			# cv2.imshow("Invert1",result)
			# cv2.waitKey(0)

			# im_resize = cv2.resize(im_crop,(28,28))
			filename_small = 'temp_save/'+random_hash + '_' + str(i)+'.png'
			cv2.imwrite(filename_small, img_not)


			img_model = img_not.reshape(-1, 28, 28, 1)
			result = loaded_model.predict_classes(img_model)

			prediction = int(result[0])


			if prediction == 10:
				prediction = '+'
			elif prediction == 11:
				prediction = '-'
			elif prediction == 12:
				prediction = '*'
			else:
				prediction = str(prediction)

			if val_type == 'char':
				text_str = text_str + prediction
			else:
				text_str = text_str + '**' +prediction

			imgurls.append({ 'name' : filename_small, 'prediction' : prediction, 'area' : img_area, 'type' : val_type })

			i = i+1

		evaluation = eval(text_str)
		latex = py2tex(text_str)
		latex = latex[2:len(latex)-2]
		
		return jsonify({ 'text' : text_str, 'eval' : evaluation, 'latex' : latex, 'pred' : imgurls })
예제 #24
0
from pytexit import py2tex

a = ['Dconst = (E*h**3)/(12*(1-ne**2))', 'k_ = (k*b**4)/(Dconst*np.pi**4)', 
'del_T = (T*alfa*Dconst*(1+ne)*np.pi**2)/b**2', 
'Wmn = (b**4)/(Dconst*np.pi**4)*(qmn + del_T*(m**2 * s**2 + n**2))/((m**2 * s**2 + n**2)**2 + k_)', 
'w0 = w0 + Wmn*np.sin(m*np.pi*x/a)*np.sin(n*np.pi*y/b)', 
'sigma_max = (6*qmn*2*b**2)/(np.pi**2*h**2*(s**2+1)**2)*(s**2+ne)']

for i in range(len(a)):
	py2tex(a[i])
	print('\n')

예제 #25
0
def central():

###differantiation order
    dd=input("order of differentiation:", type=NUMBER)
    put_text('order of differentiation',(dd))
    put_html('<hr>')
###hex of smal step h is 
    hs=dd

#### order of error
    err=input("order of error must be even number 2 or 4 only:", type=NUMBER)
    put_text('order of error',(err))
    put_html('<hr>')
#total number of points in cosideration    
    put_text('please provide only integer number ')
    put_text('for error order result if its greter than this please relod web and try max limit integer number is equal or less than (in central diff scheme) in between ',int(-1*(dd+err-1)/2),'and ',int((dd+err-1)/2))
    put_html('<hr>') 
    put_text('if for example -3.5 to 3.5 is shown limit then take max_limit and min_limit as -3 to 3 only neglect 0.5') 
    put_text('take limits from -3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 total n is 7')
    
    n = input("number of points in cosideration:", type=NUMBER)
    put_text('stencil number',(n))    
#take limits from -3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 total n is 7

    
    put_text('-3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 so min_limit as -3')
    min_limit = input("Input your minimum limit:", type=NUMBER)
    put_text('yor stencils max limit is ',(min_limit))
    put_html('<hr>')
    

#max limit 
    put_text('-3 to 3 for example ,so points in cosiderations are -3,-2,-1,0,1,2,3 so max_limit as 3')   
    max_limit = input("Input your max_limit:", type=NUMBER)
    put_text('yor stencils max limit is ',(max_limit))
    put_html('<hr>')   



  
####makiuing array
    a0 = np.linspace(min_limit,max_limit,n)
    a0= np. array(a0)

# making n*n matrix
    a=np.tile(a0, (n,1))
#print(a)
    a=np.array(a) 

### making indices 
    b=np.linspace(0,n-1)
    b=np.arange(0, n).reshape(n,1) 

    it = np.nditer([a, b, None], flags=['external_loop'])
    
    with it:
        for x, y, z in it:
            z[...] = x**y
        result = it.operands[2]

#result
    bb=result

########Inserting whre one is going to come
    az=np.zeros(n-1) 
    yy=np.insert(az,dd, 1) 

#output capture from print
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout

    for i in np.nditer(a0):
            print(sp.symbols('f(x+({}*h))'.format(i)))
    
    output = new_stdout.getvalue()

    sys.stdout = old_stdout

    j=output 

############solving matrix
    hh = np.linalg.solve(bb, yy)

    a = hh*np.math.factorial(dd)
#print(a) 


############ symbols manupalation and list to symbols conversion
##print(type(j))
    d = [x.replace('\n', '  ') for x in j]
# Original Array
    array = np.array(j, dtype=np.str)

#print(array)
  
# Split the element of the said array 
# with spaces
    sparr = np.char.split(array)      # imp step str to array numpy

#print(sparr)                        

    d=np.asarray(sparr,dtype=object)

    d = d.tolist()                    # convert to list
#print(d)

    d=sp.symbols(d)
    d=np.array(d)
#print(d)


######multiplyer
    B=np.array(a)
#B=B.astype(str)
#c = B.tolist()
    c=B.astype(object)
#print(c)



    re.sub(r' *\n *', '\t',np.array_str(np.c_[c,d]).replace('[', '(').replace(']', ')').strip())
             

    res = "\t".join("({}*{})+".format(x, y) for x, y in zip(c, d))


    name = res.rstrip(res[-1])



#print('(',name,')','*','*1/h**',hs)

######captiring print
    old_stdout = sys.stdout
    new_stdout = io.StringIO()
    sys.stdout = new_stdout

    print('(',name,')','*','1/h**',hs)

    kj = new_stdout.getvalue()

    sys.stdout = old_stdout

    def remove(string):
        pattern = re.compile(r'\s+')
        return re.sub(pattern, '', string)
      
# Driver Program
    string = kj
#remove will remove all spaces 
    yy=remove(string)


    #put_text('%s' % (remove(string)))
    
#making variable to latex plote    
    y=py2tex(yy,print_latex=False, print_formula=False)
    o=y.replace('+-','-')
    #put_text('%s' % o)
    def org(o):
        w=o
        p=w
        pp=p.replace('$$',' ')
        tt=" ' "
        #string="r"
        #pg=string+pp
        #tg=" ' "
        pg=tt+pp+tt
        return pg

    t=org(o)


                                                                  
###matplotlib
                                         
    lat = t                                                            

# #add text                                 
#     ax = plt.axes([1,0,0.1,0.1]) #left,bottom,width,height
#     ax.set_xticks([])
#     ax.set_yticks([])
#     ax.axis('off')
#     plt.text(0.2,0.2,r'$%s$' % lat ,size=500,color="red",fontsize=100)
# #hide axes 
#     fig = plt.gca()                                                                 
#     fig.axes.get_xaxis().set_visible(False)                                         
#     fig.axes.get_yaxis().set_visible(False)                                         
#     plt.savefig('images/out.jpeg', bbox_inches='tight', pad_inches=0)                                                                                                                                                                                
#     plt.close()
    
#save image

    # img = open('images/out.jpeg', 'rb').read()  
    # put_image(img, width='500000000px')
    
    put_html('<hr>')
    put_text('this is python output  %s'  % yy)
    

    
    put_html('<hr>')
    
    #visualize equation
    tpl = '''<!DOCTYPE html><html><head>  <meta charset="utf-8">  <meta name="viewport" content="width=device-width">  <title>MathJax example</title>  <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>  <script id="MathJax-script" async          src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">  </script></head><body><p>{{#contents}}{{& pywebio_output_parse}}{{/contents}}</p></body></html>'''
    # tpl = '''<!DOCTYPE html>
    # <html><head>  <meta charset="utf-8">  
    # <meta name="viewport" content="width=device-width"> 
    # <title> </title>  
    # <script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script> 
    # <script id="MathJax-script" async          src="https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-mml-chtml.js">  </script>
    # </head>
    # <body>
    # <p>{{#contents}}{{& pywebio_output_parse}}{{/contents}}
    #      </p>
    #      </body>
    #      </html>'''    
    put_widget(tpl, {"contents": [put_text((lat))]})
    
    #for latex output
    put_html('<hr>')
    put_text('upper is latex out put %s'   % o)
예제 #26
0
def test_hardcoded_names(verbose=True, **kwargs):
    ''' Test special numpy functions, greek letters (unicode), and hardcoded 
    conventions (ex: eps for \\epsilon)
    '''

    # Operators
    assert py2tex('a>2', print_latex=False) == '$$a>2$$'
    assert py2tex('a>=2', print_latex=False) == '$$a>=2$$'
    assert py2tex('3%2', print_latex=False) == '$$3\\bmod2$$'
    assert py2tex('a & b', print_latex=False) == '$$a\\operatorname{and}b$$'
    assert py2tex('a | b', print_latex=False) == '$$a\\operatorname{or}b$$'
    assert py2tex('a ^ b', print_latex=False) == '$$a\\operatorname{xor}b$$'
    assert py2tex('4 << 5',
                  print_latex=False) == '$$4\\operatorname{shiftLeft}5$$'
    assert py2tex('4 >> 5',
                  print_latex=False) == '$$4\\operatorname{shiftRight}5$$'
    assert py2tex('~n == -n - 1',
                  print_latex=False) == '$$\\operatorname{invert}n=-n-1$$'

    # Python syntax
    assert py2tex('sum([k for k in range(1, N)])',
                  print_latex=False) == '$$\sum_{k=1}^{N-1} k$$'
    assert py2tex('sum([k for k in range(1, N+1)])',
                  print_latex=False) == '$$\sum_{k=1}^{N} k$$'
    assert py2tex('sum([k for k in range(1, 11)])',
                  print_latex=False) == '$$\sum_{k=1}^{10} k$$'

    # Math Functions
    assert py2tex('log(x)', print_latex=False) == '$$\\ln(x)$$'
    assert py2tex('np.log10(x)', print_latex=False) == '$$\\log(x)$$'
    assert py2tex('numpy.arccos(x)', print_latex=False) == '$$\\arccos(x)$$'
    # the test below uses unicode symbol, which is valid only in Python2
    if sys.version_info[0] != 3:
        assert py2tex('arcsin(α)',
                      print_latex=False) == '$$\\arcsin(\\alpha)$$'
        assert py2tex('arctan(α)',
                      print_latex=False) == '$$\\arctan(\\alpha)$$'
    else:
        assert py2tex('arcsin(alpha)',
                      print_latex=False) == '$$\\arcsin(\\alpha)$$'
        assert py2tex('arctan(alpha)',
                      print_latex=False) == '$$\\arctan(\\alpha)$$'
    assert py2tex('arcsinh(x)', print_latex=False) == '$$\sinh^{-1}(x)$$'
    assert py2tex('arccosh(x)', print_latex=False) == '$$\\cosh^{-1}(x)$$'

    assert py2tex('np.power(2, 10)', print_latex=False) == '$${2}^{ 10}$$'
    # Additional function (conventions)
    assert py2tex('kron(i, j)', print_latex=False) == '$$\\delta_{i, j}$$'
    # unknown function:
    assert py2tex('myFunc()') == '$$\\operatorname{myFunc}\\left(\\right)$$'

    # Special characters (conventions):
    assert py2tex('eps*lbd+Lbd',
                  print_latex=False) == '$$\\epsilon \\lambda+\\Lambda$$'
예제 #27
0
from pytexit import py2tex

py2tex("x = 2*sqrt(2*pi*k*T_e/m_e)*(DeltaE/(k*T_e))**2*a_0**2")
# py2tex("2*x + 5*y = -1")
py2tex("a = 2*x + 5*y")
예제 #28
0
def test_hardcoded_names(verbose=True, **kwargs):
    """Test special numpy functions, greek letters (unicode), and hardcoded
    conventions (ex: eps for \\epsilon)
    """

    # Operators
    assert py2tex("a>2", print_latex=False) == "$$a>2$$"
    assert py2tex("a>=2", print_latex=False) == "$$a>=2$$"
    assert py2tex("3%2", print_latex=False) == "$$3\\bmod2$$"
    assert py2tex("a & b", print_latex=False) == "$$a\\operatorname{and}b$$"
    assert py2tex("a | b", print_latex=False) == "$$a\\operatorname{or}b$$"
    assert py2tex("a ^ b", print_latex=False) == "$$a\\operatorname{xor}b$$"
    assert py2tex("4 << 5",
                  print_latex=False) == "$$4\\operatorname{shiftLeft}5$$"
    assert py2tex("4 >> 5",
                  print_latex=False) == "$$4\\operatorname{shiftRight}5$$"
    assert (py2tex("~n == -n - 1",
                   print_latex=False) == "$$\\operatorname{invert}n=-n-1$$")

    # Python syntax
    assert (py2tex("sum([k for k in range(1, N)])",
                   print_latex=False) == "$$\sum_{k=1}^{N-1} k$$")
    assert (py2tex("sum([k for k in range(1, N+1)])",
                   print_latex=False) == "$$\sum_{k=1}^{N} k$$")
    assert (py2tex("sum([k for k in range(1, 11)])",
                   print_latex=False) == "$$\sum_{k=1}^{10} k$$")

    # Math Functions
    assert py2tex("log(x)", print_latex=False) == "$$\\ln\\left(x\\right)$$"
    assert py2tex("np.log10(x)",
                  print_latex=False) == "$$\\log\\left(x\\right)$$"
    assert (py2tex("numpy.arccos(x)",
                   print_latex=False) == "$$\\arccos\\left(x\\right)$$")
    # the test below uses unicode symbol, which is valid only in Python2
    if sys.version_info[0] != 3:
        assert (py2tex(
            "arcsin(α)",
            print_latex=False) == "$$\\arcsin\\left(\\alpha\\right)$$")
        assert (py2tex(
            "arctan(α)",
            print_latex=False) == "$$\\arctan\\left(\\alpha\\right)$$")
    else:
        assert (py2tex(
            "arcsin(alpha)",
            print_latex=False) == "$$\\arcsin\\left(\\alpha\\right)$$")
        assert (py2tex(
            "arctan(alpha)",
            print_latex=False) == "$$\\arctan\\left(\\alpha\\right)$$")
    assert py2tex("arcsinh(x)",
                  print_latex=False) == "$$\sinh^{-1}\\left(x\\right)$$"
    assert py2tex("arccosh(x)",
                  print_latex=False) == "$$\\cosh^{-1}\\left(x\\right)$$"

    assert py2tex("np.power(2, 10)", print_latex=False) == "$${2}^{ 10}$$"
    # Additional function (conventions)
    assert py2tex("kron(i, j)", print_latex=False) == "$$\\delta_{i, j}$$"
    # unknown function:
    assert py2tex("myFunc()") == "$$\\operatorname{myFunc}\\left(\\right)$$"

    # Special characters (conventions):
    assert py2tex("eps*lbd+Lbd",
                  print_latex=False) == "$$\\epsilon \\lambda+\\Lambda$$"
예제 #29
0
 def get_latex_equation(self, equation_string):
     latex_string = py2tex(equation_string,
                           print_latex=False,
                           print_formula=False)
     # print("{}".format(latex_string))
     return latex_string
예제 #30
0
def generate_latex(expression: str):
    return py2tex(expression)