コード例 #1
0
ファイル: session.py プロジェクト: ArchKaine/sympy
def init_session(ipython=None, pretty_print=True, order=None,
        use_unicode=None, quiet=False, argv=[]):
    """Initialize an embedded IPython or Python session. """
    import sys

    in_ipython = False

    if ipython is False:
        ip = _init_python_session()
        mainloop = ip.interact
    else:
        try:
            import IPython
        except ImportError:
            if ipython is not True:
                if not quiet:
                    print no_ipython
                ip = _init_python_session()
                mainloop = ip.interact
            else:
                raise RuntimeError("IPython is not available on this system")
        else:
            ipython = True
            if IPython.__version__ >= '0.11':
                try:
                    ip = get_ipython()
                except NameError:
                    ip = None
            else:
                ip = IPython.ipapi.get()
                if ip:
                    ip = ip.IP

            if ip is not None:
                in_ipython = True
            else:
                ip = _init_ipython_session(argv)

            if IPython.__version__ >= '0.11':
                # runsource is gone, use run_cell instead, which doesn't
                # take a symbol arg.  The second arg is `store_history`,
                # and False means don't add the line to IPython's history.
                ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)
                mainloop = ip.mainloop
            else:
                mainloop = ip.interact

    _preexec_source = preexec_source

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode, ip=ip)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        mainloop(message)
        sys.exit('Exiting ...')
    else:
        ip.write(message)
        ip.set_hook('shutdown_hook', lambda ip: ip.write("Exiting ...\n"))
コード例 #2
0
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    # Since Python filters deprecation warnings by default,
    # we add a filter to make sure this message will be shown.
    warnings.simplefilter("once", SymPyDeprecationWarning)
    SymPyDeprecationWarning(
        feature="using %load_ext sympy.interactive.ipythonprinting",
        useinstead="from sympy import init_printing ; init_printing()",
        deprecated_since_version="0.7.3",
        issue=3914
    ).warn()
    init_printing(ip=ip)
コード例 #3
0
ファイル: ipythonprinting.py プロジェクト: dyao-vu/meta-core
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    import IPython

    global _loaded
    # Use extension manager to track loaded status if available
    # This is currently in IPython 0.14.dev
    if hasattr(ip.extension_manager, 'loaded'):
        loaded = 'sympy.interactive.ipythonprinting' not in ip.extension_manager.loaded
    else:
        loaded = _loaded

    if not loaded:
        init_printing(ip=ip)
        _loaded = True
コード例 #4
0
ファイル: session.py プロジェクト: haz/sympy
def init_session(ipython=None, pretty_print=True, order=None,
        use_unicode=None, quiet=False, keep_sign=False, argv=[]):
    """Initialize an embedded IPython or Python session. """
    import sys

    in_ipython = False

    if ipython is False:
        ip = _init_python_session()
    else:
        try:
            import IPython
        except ImportError:
            if ipython is not True:
                print no_ipython
                ip = _init_python_session()
            else:
                raise RuntimeError("IPython is not available on this system")
        else:
            ip = IPython.ipapi.get()
            ipython = True

            if ip is not None:
                ip, in_ipython = ip.IP, True
            else:
                ip = _init_ipython_session(argv)

    _preexec_source = preexec_source

    if keep_sign:
        _preexec_source += "Basic.keep_sign = True\n"

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        ip.interact(message)
        sys.exit('Exiting ...')
    else:
        ip.write(message)
        ip.set_hook('shutdown_hook', lambda ip: ip.write("Exiting ...\n"))
コード例 #5
0
ファイル: printing.py プロジェクト: pducks32/intergrala
def init_vprinting(**kwargs):
    """Initializes time derivative printing for all SymPy objects, i.e. any
    functions of time will be displayed in a more compact notation. The main
    benefit of this is for printing of time derivatives; instead of
    displaying as ``Derivative(f(t),t)``, it will display ``f'``. This is
    only actually needed for when derivatives are present and are not in a
    physics.vector.Vector or physics.vector.Dyadic object. This function is a
    light wrapper to `sympy.interactive.init_printing`. Any keyword
    arguments for it are valid here.

    {0}

    Examples
    ========

    >>> from sympy import Function, symbols
    >>> from sympy.physics.vector import init_vprinting
    >>> t, x = symbols('t, x')
    >>> omega = Function('omega')
    >>> omega(x).diff()
    Derivative(omega(x), x)
    >>> omega(t).diff()
    Derivative(omega(t), t)

    Now use the string printer:

    >>> init_vprinting(pretty_print=False)
    >>> omega(x).diff()
    Derivative(omega(x), x)
    >>> omega(t).diff()
    omega'

    """
    kwargs['str_printer'] = vsstrrepr
    kwargs['pretty_printer'] = vpprint
    kwargs['latex_printer'] = vlatex
    init_printing(**kwargs)
コード例 #6
0
ファイル: printing.py プロジェクト: AkshaySiramdas/sympy
def init_vprinting(**kwargs):
    """Initializes time derivative printing for all SymPy objects, i.e. any
    functions of time will be displayed in a more compact notation. The main
    benefit of this is for printing of time derivatives; instead of
    displaying as ``Derivative(f(t),t)``, it will display ``f'``. This is
    only actually needed for when derivatives are present and are not in a
    physics.vector.Vector or physics.vector.Dyadic object. This function is a
    light wrapper to `sympy.interactive.init_printing`. Any keyword
    arguments for it are valid here.

    {0}

    Examples
    ========

    >>> from sympy import Function, symbols
    >>> from sympy.physics.vector import init_vprinting
    >>> t, x = symbols('t, x')
    >>> omega = Function('omega')
    >>> omega(x).diff()
    Derivative(omega(x), x)
    >>> omega(t).diff()
    Derivative(omega(t), t)

    Now use the string printer:

    >>> init_vprinting(pretty_print=False)
    >>> omega(x).diff()
    Derivative(omega(x), x)
    >>> omega(t).diff()
    omega'

    """
    kwargs['str_printer'] = vsstrrepr
    kwargs['pretty_printer'] = vpprint
    kwargs['latex_printer'] = vlatex
    init_printing(**kwargs)
コード例 #7
0
#!/usr/bin/python
# -*- coding: utf-8 -*-

from sympy import *
from sympy.abc import *
from sympy.matrices import *
from sympy.interactive.printing import init_printing
init_printing(use_unicode=False, wrap_line=False, no_global=True)

m11, m12, m13 = symbols('m11,m12,m13')
m21, m22, m23 = symbols('m21,m22,m23')
m31, m32, m33 = symbols('m31,m32,m33')

# compute det(M) * M^{-T} = det(M) * inv^T = det(M) * 1/det * cof^TT = cof
# compute inverse of M
M = Matrix([[m11, m12, m13], [m21, m22, m23], [m31, m32, m33]])
print "matrix:"
print M
print ""
print "inv:", simplify(M.inv())
# inv = 1/det * adj = 1/det * cof^T

print "det:", simplify(M.det())
print ""
print "adj:", simplify(M.adjugate())
print ""
print "cof:", simplify(M.cofactorMatrix())
コード例 #8
0
def calculate_Integral(expression,var1,var2,var3,varSup1,varSup2,varSup3,varInf1,varInf2,varInf3,\
                       typeIntegral,numDimensions,numColumns,\
                       showIntegral,showTime,numDigText,numerTypeIntegral,simplifyResult,outputResult):
    global nonCalculatedIntegral, nonCalculatedIntegralOutput, resultIntegral, resultIntegralSimp, resultOutput, timeIntegral

    init_printing(use_unicode=True, num_columns=numColumns)
    timet1=time.time()

    integrand = expression
    diffvar1 = var1.strip()
    diffvar2 = var2.strip()
    diffvar3 = var3.strip()
    limSup1 = varSup1.strip()
    limSup2 = varSup2.strip()
    limSup3 = varSup3.strip()
    limInf1 = varInf1.strip()
    limInf2 = varInf2.strip()
    limInf3 = varInf3.strip()

    integrateExpr = '('+integrand+','
    if typeIntegral == integralType['indefinite']:
        integrateExpr += diffvar1
        if numDimensions > 1:
            integrateExpr += ','+diffvar2
        if numDimensions > 2:
            integrateExpr += ','+diffvar3
        integrateExpr += ')'
        try:
            nonCalculatedIntegral = sympify('Integral'+integrateExpr)
        except:
            nonCalculatedIntegral = 'Integral'+integrateExpr
        try:
            resultIntegral = sympify('integrate'+integrateExpr)
        except:
            resultIntegral = integralErrorMessage
    else:
        integrateExpr += '('+diffvar1+','+limInf1+','+limSup1+')'
        if numDimensions > 1:
            integrateExpr += ',('+diffvar2+','+limInf2+','+limSup2+')'
        if numDimensions > 2:
            integrateExpr += ',('+diffvar3+','+limInf3+','+limSup3+')'
        integrateExpr += ')'
        try:
            nonCalculatedIntegral = sympify('Integral'+integrateExpr)
        except:
            nonCalculatedIntegral = 'Integral'+integrateExpr
        if typeIntegral == integralType['definite']:
            try:
                resultIntegral = sympify('integrate'+integrateExpr)
            except:
                resultIntegral = integralErrorMessage
        else:
            if numerTypeIntegral == numerIntegralType['approx']:
                try:
                    resultIntegral = sympify('N(integrate'+integrateExpr+','+numDigText+')')
                except:
                    resultIntegral = integralErrorMessage
            else:
                mp.dps=int(numDigText)
                integrateExpr = "(lambda "
                if numDimensions > 2:
                    integrateExpr += diffvar3+","
                if numDimensions > 1:
                    integrateExpr += diffvar2+","
                integrand = fixMPMathText(integrand)
                integrateExpr += diffvar1+": "+integrand
                if numDimensions > 2:
                    limInf3 = fixMPMathText(limInf3)
                    limSup3 = fixMPMathText(limSup3)
                    integrateExpr += ',['+limInf3+','+limSup3+']'
                if numDimensions > 1:
                    limInf2 = fixMPMathText(limInf2)
                    limSup2 = fixMPMathText(limSup2)
                    integrateExpr += ',['+limInf2+','+limSup2+']'
                limInf1 = fixMPMathText(limInf1)
                limSup1 = fixMPMathText(limSup1)
                integrateExpr += ",["+limInf1+","+limSup1+"])"
                try:
                    if numerTypeIntegral == numerIntegralType['infinities']:
                        resultIntegral = eval("quadts"+integrateExpr)
                    else:
                        resultIntegral = eval("quadgl"+integrateExpr)
                    resultIntegral = sympify('N('+fixMPMathOutput(str(resultIntegral))+','+numDigText+')')
                except:
                    resultIntegral = integralNumerErrorMessage

    if (resultIntegral) and (type(resultIntegral) != str) and (typeIntegral != integralType['numerical']):
        if simplifyResult == simplifyType['none']:
            resultIntegralSimp = sympify(resultIntegral)
        elif simplifyResult == simplifyType['expandterms']:
            resultIntegralSimp = sympify(mapexpr(resultIntegral,expand))
        elif simplifyResult == simplifyType['simplifyterms']:
            resultIntegralSimp = sympify(mapexpr(resultIntegral,simplify))
        elif simplifyResult == simplifyType['expandall']:
            resultIntegralSimp = sympify(expand(resultIntegral))
        elif simplifyResult == simplifyType['simplifyall']:
            resultIntegralSimp = sympify(simplify(resultIntegral))
    else:
        resultIntegralSimp = resultIntegral

    timet2=time.time()
    timeIntegral = timet2-timet1

    nonCalculatedIntegralOutput = str(nonCalculatedIntegral)
    resultOutput = str(resultIntegralSimp)
    if outputResult == outputType['bidimensional']:
        if (type(nonCalculatedIntegral) != str):
            nonCalculatedIntegralOutput = fixUnicodeText(printing.pretty(nonCalculatedIntegral))
        if (type(resultIntegralSimp) != str):
            resultOutput = fixUnicodeText(printing.pretty(resultIntegralSimp))
    elif outputResult == outputType['latex']:
        if (type(nonCalculatedIntegral) != str):
            nonCalculatedIntegralOutput = latex(nonCalculatedIntegral)
        if (type(resultIntegralSimp) != str):
            resultOutput = latex(resultIntegralSimp)
    elif outputResult == outputType['c']:
        if (type(resultIntegralSimp) != str):
            resultOutput = ccode(resultIntegralSimp)
    elif outputResult == outputType['fortran']:
        if (type(resultIntegralSimp) != str):
            resultOutput = fcode(resultIntegralSimp)
    elif outputResult == outputType['javascript']:
        if (type(resultIntegralSimp) != str):
            resultOutput = jscode(resultIntegralSimp)
    elif outputResult == outputType['python']:
        if (type(resultIntegralSimp) != str):
            resultOutput = python(resultIntegralSimp)

    if showTime and (timeIntegral > 0.0):
        result = '<FONT COLOR="LightGreen">'+("Calculated after %f s :" % timeIntegral)+'</FONT><br>'
    else:
        result = u""
    if showIntegral and nonCalculatedIntegralOutput:
        result += u'<FONT COLOR="LightBlue">'+(nonCalculatedIntegralOutput.replace(' ','&nbsp;')).replace("\n","<br>")+'<br>=</FONT><br>'
    if (type(resultIntegralSimp) != str):
        result += (resultOutput.replace(' ','&nbsp;')).replace("\n","<br>")
    else:
        result += u'<FONT COLOR="Red">'+((resultOutput.replace(' ','&nbsp;')).replace("\n","<br>"))+'</FONT>'
    return result
コード例 #9
0
ファイル: limit.py プロジェクト: rcolistete/limit-sailfish
def calculate_Limit(
    expression,
    variable,
    point,
    direction,
    flagPortrait,
    showLimit,
    showTime,
    numerApprox,
    numDigText,
    simplifyResult,
    outputResult,
):
    global nonCalculatedLimit, nonCalculatedLimitOutput, resultLimit, resultLimitSimp, resultOutput, timeLimit

    if flagPortrait:
        init_printing(use_unicode=True, num_columns=35)
    else:
        init_printing(use_unicode=True, num_columns=60)
    timet1 = time.time()

    expressionLimit = expression
    variableLimit = variable.strip()
    pointLimit = point.strip()
    limitExpr = u"(" + expressionLimit + u"," + variableLimit + u"," + pointLimit
    if direction != "Bilateral":
        limitExpr += u',dir="'
        if direction == "Left":
            limitExpr += u'-"'
        elif direction == "Right":
            limitExpr += u'+"'
    limitExpr += u")"

    if direction == "Bilateral":
        try:
            nonCalculatedLimit = sympify(u"Limit" + limitExpr)
        except:
            nonCalculatedLimit = u"Limit" + limitExpr
    else:
        # "Limit" has a bug not showing the "+" and "-" above the point value.
        nonCalculatedLimit = u"Limit" + limitExpr
    if direction == "Bilateral":
        try:
            if (sympify(u"limit" + limitExpr)) == (sympify(u"limit" + limitExpr[:-1] + u',dir="-")')):
                resultLimit = sympify(u"limit" + limitExpr)
            else:
                resultLimit = (
                    u"Bilateral limit does not exist because the limits from the left and right are different."
                )
        except:
            resultLimit = limitErrorMessage
    else:
        try:
            resultLimit = sympify(u"limit" + limitExpr)
        except:
            resultLimit = limitErrorMessage
    if (type(resultLimit) != str) and numerApprox:
        try:
            resultLimit = sympify("N(" + str(resultLimit) + "," + numDigText + ")")
        except:
            resultLimit = limitErrorMessage

    if (resultLimit) and (type(resultLimit) != str) and (not numerApprox):
        if simplifyResult == simplifyType["none"]:
            resultLimitSimp = sympify(resultLimit)
        elif simplifyResult == simplifyType["expandterms"]:
            resultLimitSimp = sympify(mapexpr(resultLimit, expand))
        elif simplifyResult == simplifyType["simplifyterms"]:
            resultLimitSimp = sympify(mapexpr(resultLimit, simplify))
        elif simplifyResult == simplifyType["expandall"]:
            resultLimitSimp = sympify(expand(resultLimit))
        elif simplifyResult == simplifyType["simplifyall"]:
            resultLimitSimp = sympify(simplify(resultLimit))
    else:
        resultLimitSimp = resultLimit

    timet2 = time.time()
    timeLimit = timet2 - timet1

    if direction == "Bilateral":
        nonCalculatedLimitOutput = fixUnicodeText(printing.pretty(nonCalculatedLimit))
    if type(resultLimitSimp) != str:
        resultOutput = fixUnicodeText(printing.pretty(resultLimitSimp))

    nonCalculatedLimitOutput = str(nonCalculatedLimit)
    resultOutput = str(resultLimitSimp)
    if outputResult == outputType["bidimensional"]:
        if (direction == "Bilateral") and (type(nonCalculatedLimit) != str):
            nonCalculatedLimitOutput = fixUnicodeText(printing.pretty(nonCalculatedLimit))
        if type(resultLimitSimp) != str:
            resultOutput = fixUnicodeText(printing.pretty(resultLimitSimp))
    elif outputResult == outputType["latex"]:
        if (direction == "Bilateral") and (type(nonCalculatedLimit) != str):
            nonCalculatedLimitOutput = latex(nonCalculatedLimit)
        if type(resultLimitSimp) != str:
            resultOutput = latex(resultLimitSimp)
    elif outputResult == outputType["c"]:
        if type(resultLimitSimp) != str:
            resultOutput = ccode(resultLimitSimp)
    elif outputResult == outputType["fortran"]:
        if type(resultLimitSimp) != str:
            resultOutput = fcode(resultLimitSimp)
    elif outputResult == outputType["javascript"]:
        if type(resultLimitSimp) != str:
            resultOutput = jscode(resultLimitSimp)
    elif outputResult == outputType["python"]:
        if type(resultLimitSimp) != str:
            resultOutput = python(resultLimitSimp)

    if showTime and (timeLimit > 0.0):
        result = '<FONT COLOR="LightGreen">' + ("Calculated after %f s :" % timeLimit) + "</FONT><br>"
    else:
        result = u""
    if showLimit and nonCalculatedLimitOutput:
        result += (
            u'<FONT COLOR="LightBlue">'
            + (nonCalculatedLimitOutput.replace(" ", "&nbsp;")).replace("\n", "<br>")
            + "<br>=</FONT><br>"
        )
    if type(resultLimitSimp) != str:
        result += (resultOutput.replace(" ", "&nbsp;")).replace("\n", "<br>")
    else:
        result += u'<FONT COLOR="Red">' + ((resultOutput.replace(" ", "&nbsp;")).replace("\n", "<br>")) + "</FONT>"
    return result
コード例 #10
0
import sympy as sp
from sympy.interactive.printing import init_printing


if __name__ == '__main__':
    init_printing(pretty_print=False, use_unicode=False, wrap_line=False, use_latex=True)

    f, g = sp.symbols('f g', cls=sp.Function)
    x = sp.symbols("x")

    edo_g = sp.Eq(3*g(x).diff(x) + x, 6)
    print(sp.pretty(edo_g))

    edo_g_solved = sp.dsolve(edo_g, g(x))
    print(sp.pretty(edo_g_solved))

    print('-' * 175)

    v = sp.Symbol("v", reel=True, positive=True)
    bessel_edo = sp.Eq((x**2)*f(x).diff(x, x) + x*f(x).diff(x) + (x**2 - v**2)*f(x), 0)
    print(sp.pretty(bessel_edo))

    bessel_edo_solved = sp.dsolve(bessel_edo, f(x))
    print(sp.pretty(bessel_edo_solved))

    print('-' * 175)

    psi = sp.symbols("psi", cls=sp.Function)
    t = sp.Symbol("t", reel=True, positive=True)
    omega0 = sp.Symbol("omega_0", reel=True)
    osc_hrm_edo = sp.Eq(psi(t).diff(t, t) + (omega0**2)*psi(t), 0)
コード例 #11
0
import sympy as s
from sympy.interactive.printing import init_printing
from sympy.matrices import Matrix
import numpy as np

init_printing(use_unicode=False, wrap_line=False, no_global=True)

# In [1]: %load_ext autoreload
#
# In [2]: %autoreload 2

class GradientDescentState(object):
    """holds the state for gradient descent"""

    def __init__(self, size, symbols, fn, initalGuess, grad):
        self.numberOfVariables = size
        self.x = symbols
        self.fn = fn
        self.initalGuess = initalGuess
        self.grad = grad

        self.currentIterValue = Matrix(initalGuess)

    # compute the gradient at point
    def atPoint(self, subs):
        if len(subs) != self.numberOfVariables:
            raise Exception('airity mismatch: atPoint')

        res = self.grad
        for idx in range(0, self.numberOfVariables):
            res = res.subs(self.x[idx], subs[idx]);
コード例 #12
0
ファイル: strplus.py プロジェクト: worldmaker18349276/magicpy
def init_mprinting():
    init_printing(pretty_print=False, str_printer=mstr)
コード例 #13
0
ファイル: hmm.py プロジェクト: fmlab-iis/dp-pomdp
# to execute: do
# $ PYTHONPATH=<path to python Z3> python hmm.py

from sympy.interactive.printing import init_printing
init_printing()
from sympy.matrices import Matrix
from sympy import Rational, N
from z3 import *

TR = Matrix([[Rational(2, 3), Rational(1, 6),
              Rational(1,
                       6)], [Rational(1, 3),
                             Rational(1, 3),
                             Rational(1, 3)],
             [Rational(1, 6), Rational(1, 6),
              Rational(2, 3)]])

# prior knowledge: family member, contagious disease

p0 = Matrix([[1, 0, 0]])
p1 = Matrix([[0, 0, 1]])

r0 = p0 * TR
r1 = p1 * TR

print(r0)
print(r1)

# prior knowledge: disease contraction rate is p, independent

rate = Real('rate')
コード例 #14
0
#print(R, R.shape)

sv = 0.5  #过程噪声
G = np.matrix([
    [0.5 * dt**2],  #G矩阵-过程噪声协方差系数
    [0.5 * dt**2],
    [dt],
    [dt]
])
Q = G * G.T * sv**2  #过程噪声协方差矩阵
#SymPy是符号数学的Python库。它的目标是成为一个全功能的计算机代数系统,同时保持代码简洁、易于理解和扩展。
#Symbol 是一种基本数据类型
# Matrix矩阵运算库
from sympy import Symbol, Matrix
from sympy.interactive import printing
printing.init_printing()  #根据环境选择输出方式
dts = Symbol('dt')  #定义变量,此变量不是程序中认为的变量,而是数学公式里面的变量
Qs = Matrix([[0.5 * dts**2], [0.5 * dts**2], [dts], [dts]])
Qs * Qs.T
#-----------------------------------------------------------------------
# 初始化一个单位矩阵
I = np.eye(4)
print(I, I.shape)
#--------------------------------------------------------------------------------

m = 200  # 测量数
vx = 20  # in X
vy = 10  # in Y

mx = np.array(vx + np.random.randn(m))  #生成200个X方向测量值
my = np.array(vy + np.random.randn(m))  #生成200个Y方向测量值
コード例 #15
0
ファイル: Sympa Example.py プロジェクト: pombredanne/sympa
# coding: utf-8

# In[1]:

from sympy import *
from sympy.interactive.printing import init_printing
init_printing()


# In[2]:

from sympa import domath


# In[3]:

import pandas as pd


# In[4]:

df = pd.DataFrame({'x' : range(7)})
df['x'] = df.x * 10
df['y'] = df.x * 0.05
df['r'] = pi * df['y'] / 2
df


# In[5]:
コード例 #16
0
#!/usr/bin/env python
# coding: utf-8

# In[47]:


import numpy as np
from sympy import*
from sympy.interactive import printing;
printing.init_printing(use_latex=true);
from IPython.display import display, Latex 

#test 1q13
# usar pandas y numpy

def nombre(3):
    contador=1;
<<<<<<< HEAD
# Correcto
>>>>>>>>> Temporary merge branch 2


def Newton_algoritmo(F, J, x, eps):
    """
    Resuelve un sistema no linear Rn-Rn F(x)=0, ambos F y J deben ser funciones de x
    x es el valor de las coordenadas iniciales, y sigue hasta que ||F|| < eps que es una tolerancia
    """
    F_value = F(x)
    #display(Latex('$$ F(x) = '+ latex(simplify(F_value)) + '$$'))
    F_norm = np.linalg.norm(F_value, ord=2)  # l2 norm of vector
    contador_iteraciones = 0
コード例 #17
0
See [O'Reilly Book](https://www.safaribooksonline.com/blog/2014/02/11/altering-display-existing-classes-ipython/)
for minimal guidance if you're interested.'''

# I should implement this as an extension module
# https://mindtrove.info/4-ways-to-extend-jupyter-notebook/
# {{{ this allows me to skip if I called from sphinx
from .general_functions import inside_sphinx
if inside_sphinx():
    pass  # called from sphinx
else:
    get_ipython().magic('pylab inline')
# }}}
import numpy
import sympy
from sympy.interactive import printing
printing.init_printing(use_latex=True, wrap_line=False, num_columns=10000)
if not inside_sphinx():
    from .core import image as pyspec_image
    from .core import plot as pyspec_plot
    from .core import nddata as pyspec_nddata
    from .core import gca

import re
from IPython.display import Math


def load_ipython_extension(ip):
    list(ip.display_formatter.formatters.keys())

    tex_formatters = ip.display_formatter.formatters['text/latex']
    plain_formatters = ip.display_formatter.formatters['text/plain']
コード例 #18
0
def calculate_Derivative(expression,var1,numvar1,var2,numvar2,var3,numvar3,\
                         flagPortrait,showDerivative,showTime,numerApprox,numDigText,\
                         simplifyResult,outputResult):
    global nonCalculatedDerivative, nonCalculatedDerivativeOutput, resultDerivative, \
           resultDerivativeSimp, resultOutput, timeDerivative

    if flagPortrait:
        init_printing(use_unicode=True, num_columns=35)
    else:
        init_printing(use_unicode=True, num_columns=60)
    timet1=time.time()

    expressionDerivative = expression
    variable1Derivative = var1.strip()
    numVar1Derivative = numvar1.strip()
    if not numVar1Derivative:
        numVar1Derivative = '0'
    variable2Derivative = var2.strip()
    numVar2Derivative = numvar2.strip()
    if not numVar2Derivative:
        numVar2Derivative = '0'
    variable3Derivative = var3.strip()
    numVar3Derivative = numvar3.strip()
    if not numVar3Derivative:
        numVar3Derivative = '0'

    derivativeExpr = '('+expressionDerivative
    if variable1Derivative and (eval(numVar1Derivative) > 0):
        derivativeExpr += ','+variable1Derivative+','+numVar1Derivative
    if variable2Derivative and (eval(numVar2Derivative) > 0):
        derivativeExpr += ','+variable2Derivative+','+numVar2Derivative
    if variable3Derivative and (eval(numVar3Derivative) > 0):
        derivativeExpr += ','+variable3Derivative+','+numVar3Derivative
    derivativeExpr += u')'
    try:
        nonCalculatedDerivative = sympify('Derivative'+derivativeExpr)
    except:
        nonCalculatedDerivative = 'Derivative'+derivativeExpr
    try:
        if numerApprox:
            resultDerivative = sympify('N(diff'+derivativeExpr+','+numDigText+')')
        else:
            resultDerivative = sympify('diff'+derivativeExpr)
    except:
        resultDerivative = derivativeErrorMessage

    if (resultDerivative) and (type(resultDerivative) != str):
        if (simplifyResult == simplifyType['none']) or (numerApprox):
            resultDerivativeSimp = sympify(resultDerivative)
        elif simplifyResult == simplifyType['expandterms']:
            resultDerivativeSimp = sympify(mapexpr(resultDerivative,expand))
        elif simplifyResult == simplifyType['simplifyterms']:
            resultDerivativeSimp = sympify(mapexpr(resultDerivative,simplify))
        elif simplifyResult == simplifyType['expandall']:
            resultDerivativeSimp = sympify(expand(resultDerivative))
        elif simplifyResult == simplifyType['simplifyall']:
            resultDerivativeSimp = sympify(simplify(resultDerivative))
    else:
        resultDerivativeSimp = resultDerivative

    timet2=time.time()
    timeDerivative = timet2-timet1

    nonCalculatedDerivativeOutput = str(nonCalculatedDerivative)
    resultOutput = str(resultDerivativeSimp)
    if outputResult == outputType['bidimensional']:
        if (type(nonCalculatedDerivative) != str):
            nonCalculatedDerivativeOutput = fixUnicodeText(printing.pretty(nonCalculatedDerivative))
        if (type(resultDerivativeSimp) != str):
            resultOutput = fixUnicodeText(printing.pretty(resultDerivativeSimp))
    elif outputResult == outputType['latex']:
        if (type(nonCalculatedDerivative) != str):
            nonCalculatedDerivativeOutput = latex(nonCalculatedDerivative)
        if (type(resultDerivativeSimp) != str):
            resultOutput = latex(resultDerivativeSimp)
#    elif outputResult == outputType['mathml']:
#        if (type(nonCalculatedDerivative) != str):
#            nonCalculatedDerivativeOutput = str(mathml(nonCalculatedDerivative))
#        if (type(resultDerivativeSimp) != str):
#            resultOutput = str(print_mathml(resultDerivativeSimp))
    elif outputResult == outputType['c']:
        if (type(resultDerivativeSimp) != str):
            resultOutput = ccode(resultDerivativeSimp)
    elif outputResult == outputType['fortran']:
        if (type(resultDerivativeSimp) != str):
            resultOutput = fcode(resultDerivativeSimp)
    elif outputResult == outputType['javascript']:
        if (type(resultDerivativeSimp) != str):
            resultOutput = jscode(resultDerivativeSimp)
    elif outputResult == outputType['python']:
        if (type(resultDerivativeSimp) != str):
            resultOutput = python(resultDerivativeSimp)

    if showTime and (timeDerivative > 0.0):
        result = '<FONT COLOR="LightGreen">'+("Calculated after %f s :" % timeDerivative)+'</FONT><br>'
    else:
        result = u""
    if showDerivative and nonCalculatedDerivativeOutput:
        result += u'<FONT COLOR="LightBlue">'+(nonCalculatedDerivativeOutput.replace(' ','&nbsp;')).replace("\n","<br>")+'<br>=</FONT><br>'
    if (type(resultDerivativeSimp) != str):
        result += (resultOutput.replace(' ','&nbsp;')).replace("\n","<br>")
    else:
        result += u'<FONT COLOR="Red">'+((resultOutput.replace(' ','&nbsp;')).replace("\n","<br>"))+'</FONT>'
    return result
コード例 #19
0
ファイル: session.py プロジェクト: alexako/sympy
def init_session(ipython=None, pretty_print=True, order=None,
        use_unicode=None, use_latex=None, quiet=False, auto_symbols=False,
        auto_int_to_Integer=False, str_printer=None, pretty_printer=None,
        latex_printer=None, argv=[]):
    """
    Initialize an embedded IPython or Python session. The IPython session is
    initiated with the --pylab option, without the numpy imports, so that
    matplotlib plotting can be interactive.

    Parameters
    ==========

    pretty_print: boolean
        If True, use pretty_print to stringify;
        if False, use sstrrepr to stringify.
    order: string or None
        There are a few different settings for this parameter:
        lex (default), which is lexographic order;
        grlex, which is graded lexographic order;
        grevlex, which is reversed graded lexographic order;
        old, which is used for compatibility reasons and for long expressions;
        None, which sets it to lex.
    use_unicode: boolean or None
        If True, use unicode characters;
        if False, do not use unicode characters.
    use_latex: boolean or None
        If True, use latex rendering if IPython GUI's;
        if False, do not use latex rendering.
    quiet: boolean
        If True, init_session will not print messages regarding its status;
        if False, init_session will print messages regarding its status.
    auto_symbols: boolean
        If True, IPython will automatically create symbols for you.
        If False, it will not.
        The default is False.
    auto_int_to_Integer: boolean
        If True, IPython will automatically wrap int literals with Integer, so
        that things like 1/2 give Rational(1, 2).
        If False, it will not.
        The default is False.
    ipython: boolean or None
        If True, printing will initialize for an IPython console;
        if False, printing will initialize for a normal console;
        The default is None, which automatically determines whether we are in
        an ipython instance or not.
    str_printer: function, optional, default=None
        A custom string printer function. This should mimic
        sympy.printing.sstrrepr().
    pretty_printer: function, optional, default=None
        A custom pretty printer. This should mimic sympy.printing.pretty().
    latex_printer: function, optional, default=None
        A custom LaTeX printer. This should mimic sympy.printing.latex()
        This should mimic sympy.printing.latex().
    argv: list of arguments for IPython
        See sympy.bin.isympy for options that can be used to initialize IPython.

    See Also
    ========

    sympy.interactive.printing.init_printing: for examples and the rest of the parameters.


    Examples
    ========

    >>> from sympy import init_session, Symbol, sin, sqrt
    >>> sin(x) #doctest: +SKIP
    NameError: name 'x' is not defined
    >>> init_session() #doctest: +SKIP
    >>> sin(x) #doctest: +SKIP
    sin(x)
    >>> sqrt(5) #doctest: +SKIP
      ___
    \/ 5
    >>> init_session(pretty_print=False) #doctest: +SKIP
    >>> sqrt(5) #doctest: +SKIP
    sqrt(5)
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_session(order='grlex') #doctest: +SKIP
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + y**2 + x + y
    >>> init_session(order='grevlex') #doctest: +SKIP
    >>> y * x**2 + x * y**2 #doctest: +SKIP
    x**2*y + x*y**2
    >>> init_session(order='old') #doctest: +SKIP
    >>> x**2 + y**2 + x + y #doctest: +SKIP
    x + y + x**2 + y**2
    >>> theta = Symbol('theta') #doctest: +SKIP
    >>> theta #doctest: +SKIP
    theta
    >>> init_session(use_unicode=True) #doctest: +SKIP
    >>> theta # doctest: +SKIP
    \u03b8
    """
    import sys

    in_ipython = False

    if ipython is not False:
        try:
            import IPython
        except ImportError:
            if ipython is True:
                raise RuntimeError("IPython is not available on this system")
            ip = None
        else:
            try:
                from IPython import get_ipython
                ip = get_ipython()
            except ImportError:
                ip = None
        in_ipython = bool(ip)
        if ipython is None:
            ipython = in_ipython

    if ipython is False:
        ip = init_python_session()
        mainloop = ip.interact
    else:
        if ip is None:
            ip = init_ipython_session(argv=argv, auto_symbols=auto_symbols,
                auto_int_to_Integer=auto_int_to_Integer)

        if V(IPython.__version__) >= '0.11':
            # runsource is gone, use run_cell instead, which doesn't
            # take a symbol arg.  The second arg is `store_history`,
            # and False means don't add the line to IPython's history.
            ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)

            #Enable interactive plotting using pylab.
            try:
                ip.enable_pylab(import_all=False)
            except Exception:
                # Causes an import error if matplotlib is not installed.
                # Causes other errors (depending on the backend) if there
                # is no display, or if there is some problem in the
                # backend, so we have a bare "except Exception" here
                pass
        if not in_ipython:
            mainloop = ip.mainloop

    readline = import_module("readline")
    if auto_symbols and (not ipython or V(IPython.__version__) < '0.11' or not readline):
        raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above with readline support")
    if auto_int_to_Integer and (not ipython or V(IPython.__version__) < '0.11'):
        raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above")

    _preexec_source = preexec_source

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print, order=order,
                  use_unicode=use_unicode, use_latex=use_latex, ip=ip,
                  str_printer=str_printer, pretty_printer=pretty_printer,
                  latex_printer=latex_printer)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        print(message)
        mainloop()
        sys.exit('Exiting ...')
    else:
        print(message)
        import atexit
        atexit.register(lambda: print("Exiting ...\n"))
コード例 #20
0
ファイル: session.py プロジェクト: devs1991/test_edx_docmode
def init_session(ipython=None,
                 pretty_print=True,
                 order=None,
                 use_unicode=None,
                 quiet=False,
                 argv=[]):
    """Initialize an embedded IPython or Python session. """
    import sys

    in_ipython = False

    if ipython is False:
        ip = _init_python_session()
        mainloop = ip.interact
    else:
        try:
            import IPython
        except ImportError:
            if ipython is not True:
                print no_ipython
                ip = _init_python_session()
                mainloop = ip.interact
            else:
                raise RuntimeError("IPython is not available on this system")
        else:
            ipython = True
            if IPython.__version__ >= '0.11':
                try:
                    ip = get_ipython()
                except NameError:
                    ip = None
            else:
                ip = IPython.ipapi.get()
                if ip:
                    ip = ip.IP

            if ip is not None:
                in_ipython = True
            else:
                ip = _init_ipython_session(argv)

            if IPython.__version__ >= '0.11':
                # runsource is gone, use run_cell instead, which doesn't
                # take a symbol arg.  The second arg is `store_history`,
                # and False means don't add the line to IPython's history.
                ip.runsource = lambda src, symbol='exec': ip.run_cell(
                    src, False)
                mainloop = ip.mainloop
            else:
                mainloop = ip.interact

    _preexec_source = preexec_source

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print,
                  order=order,
                  use_unicode=use_unicode,
                  ip=ip)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        mainloop(message)
        sys.exit('Exiting ...')
    else:
        ip.write(message)
        ip.set_hook('shutdown_hook', lambda ip: ip.write("Exiting ...\n"))
コード例 #21
0
ファイル: ipythonprinting.py プロジェクト: vchekan/sympy
def load_ipython_extension(ip):
    """Load the extension in IPython."""
    init_printing(ip=ip)
コード例 #22
0
def init_session(ipython=None,
                 pretty_print=True,
                 order=None,
                 use_unicode=None,
                 quiet=False,
                 auto=False,
                 argv=[]):
    """
    Initialize an embedded IPython or Python session.

    Parameters
    ==========

    pretty_print: boolean
        If True, use pretty_print to stringify;
        if False, use sstrrepr to stringify.
    order: string or None
        There are a few different settings for this parameter:
        lex (default), which is lexographic order;
        grlex, which is graded lexographic order;
        grevlex, which is reversed graded lexographic order;
        old, which is used for compatibility reasons and for long expressions;
        None, which sets it to lex.
    use_unicode: boolean or None
        If True, use unicode characters;
        if False, do not use unicode characters.
    quiet: boolean
        If True, init_session will not print messages regarding its status;
        if False, init_session will print messages regarding its status.
    auto: boolean
        If True, init_session will automatically create symbols for you;
        if False, it will not.
    ipython: boolean or None
        If True, printing will initialize for an IPython console;
        if False, printing will initialize for a normal console;
        The default is None, which does what False does.
    argv: list of arguments for IPython
        See sympy.bin.isympy for options that can be used to initialize IPython.

    See Also
    ========

    sympy.interactive.printing.init_printing: for examples and the rest of the parameters.


    Examples
    ========

    >>> from sympy import init_session, Symbol, sin, sqrt
    >>> sin(x) #doctest: +SKIP
    NameError: name 'x' is not defined
    >>> init_session() #doctest: +SKIP
    >>> sin(x) #doctest: +SKIP
    sin(x)
    >>> sqrt(5) #doctest: +SKIP
      ___
    \/ 5
    >>> init_session(pretty_print=False) #doctest: +SKIP
    >>> sqrt(5) #doctest: +SKIP
    sqrt(5)
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_session(order='grlex') #doctest: +SKIP
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + y**2 + x + y
    >>> init_session(order='grevlex') #doctest: +SKIP
    >>> y * x**2 + x * y**2 #doctest: +SKIP
    x**2*y + x*y**2
    >>> init_session(order='old') #doctest: +SKIP
    >>> x**2 + y**2 + x + y #doctest: +SKIP
    x + y + x**2 + y**2
    >>> theta = Symbol('theta') #doctest: +SKIP
    >>> theta #doctest: +SKIP
    theta
    >>> init_session(use_unicode=True) #doctest: +SKIP
    >>> theta # doctest: +SKIP
    \u03b8
    """
    import sys

    in_ipython = False

    if ipython is False:
        ip = init_python_session()
        mainloop = ip.interact
    else:
        try:
            import IPython
        except ImportError:
            if ipython is not True:
                if not quiet:
                    print no_ipython
                ip = init_python_session()
                mainloop = ip.interact
            else:
                raise RuntimeError("IPython is not available on this system")
        else:
            ipython = True

            if IPython.__version__ >= '0.11':
                try:
                    ip = get_ipython()
                except NameError:
                    ip = None
            else:
                ip = IPython.ipapi.get()
                if ip:
                    ip = ip.IP

            if ip is not None:
                in_ipython = True
            else:
                ip = init_ipython_session(argv=argv, auto=auto)

            if IPython.__version__ >= '0.11':
                # runsource is gone, use run_cell instead, which doesn't
                # take a symbol arg.  The second arg is `store_history`,
                # and False means don't add the line to IPython's history.
                ip.runsource = lambda src, symbol='exec': ip.run_cell(
                    src, False)
                mainloop = ip.mainloop
            else:
                mainloop = ip.interact

    if auto and (not ipython or IPython.__version__ < '0.11'):
        raise RuntimeError(
            "automatic construction of symbols is possible only in IPython 0.11 or above"
        )

    _preexec_source = preexec_source

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print,
                  order=order,
                  use_unicode=use_unicode,
                  ip=ip)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        mainloop(message)
        sys.exit('Exiting ...')
    else:
        ip.write(message)
        ip.set_hook('shutdown_hook', lambda ip: ip.write("Exiting ...\n"))
コード例 #23
0
ファイル: session.py プロジェクト: B-Rich/sympy
"""Tools for setting up interactive sessions. """

from __future__ import print_function, division

from sympy.external import import_module
from sympy.interactive.printing import init_printing

preexec_source = """\
from __future__ import division
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
init_printing()
"""

verbose_message = """\
These commands were executed:
%(source)s
Documentation can be found at http://www.sympy.org
"""

no_ipython = """\
Couldn't locate IPython. Having IPython installed is greatly recommended.
See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
just install the 'ipython' package and start isympy again.
"""


def _make_message(ipython=True, quiet=False, source=None):
    """Create a banner for an interactive session. """
コード例 #24
0
ファイル: main.py プロジェクト: Kiril94/Inverse_Problems
dldA, dldf, dldc = sympy.symbols("dLdA, dLdf, dLdc")
dgdA, dgdf, dgdc = sympy.symbols("dGdA,dGdf,dGdc")

# Define relation:
funcl = Al * cl**2 / ((d - fl)**2 + cl**2)
funcg = Ag / (sympy.sqrt(2 * sympy.pi) * cg) * sympy.exp(-(d - fg)**2 /
                                                         (2 * cg**2))
#compute derivatives
dldA = funcl.diff(Al)
dldf = funcl.diff(fl)
dldc = funcl.diff(cl)
dgdA = funcg.diff(Ag)
dgdf = funcg.diff(fg)
dgdc = funcg.diff(cg)
#Printing
init_printing(forecolor='White')
#display(sympy.Eq(sympy.symbols('dLdA'), dldA))
#display(sympy.Eq(sympy.symbols('dLdf'), dldf))
#display(sympy.Eq(sympy.symbols('dLdc'), dldc))

#display(sympy.Eq(sympy.symbols('dGdA'), dgdA))
#display(sympy.Eq(sympy.symbols('dGdf'), dgdf))
#display(sympy.Eq(sympy.symbols('dGdc'), dgdc))
display(sympy.Eq(sympy.symbols('L'), funcl))
display(latex(funcg))


# In[define functions]
def Lorentz(m):
    A = m[0:-1:3]
    f = m[1:-1:3]
コード例 #25
0
import os

from sympy.interactive import printing
printing.init_printing(use_latex=True)

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import matplotlib.ticker
# from sympy import Piecewise, log, ITE, piecewise_fold
# from sympy.abc import x, y

from data import data

FONT = {'family': 'DejaVu Sans', 'weight': 'bold', 'size': 20}

IMAGE_FILE = "Figura1.png"
IMAGES_DIRECTORY = os.path.normpath(os.path.join(os.getcwd(), "..", "assets"))
IMAGE_PATH = os.path.join(IMAGES_DIRECTORY, IMAGE_FILE)

print(data.slope_list[1].y)

data.coeff = np.array(data.coeff)

# count = data.points.x[0]
# funs = []
# conds = []
# for i in range(0,25):
#   limit = data.points.x[i+1]
#   while count <= limit:
#     fun = (data.coeff[i,3]*(x-data.points.x[i])**3)+(data.coeff[i,2]*(x-data.points.x[i])**2)+(data.coeff[i,1]*(x-data.points.x[i]))+(data.coeff[i,0])
コード例 #26
0
def init_session(ipython=None,
                 pretty_print=True,
                 order=None,
                 use_unicode=None,
                 use_latex=None,
                 quiet=False,
                 auto_symbols=False,
                 auto_int_to_Integer=False,
                 argv=[]):
    """
    Initialize an embedded IPython or Python session. The IPython session is
    initiated with the --pylab option, without the numpy imports, so that
    matplotlib plotting can be interactive.

    Parameters
    ==========

    pretty_print: boolean
        If True, use pretty_print to stringify;
        if False, use sstrrepr to stringify.
    order: string or None
        There are a few different settings for this parameter:
        lex (default), which is lexographic order;
        grlex, which is graded lexographic order;
        grevlex, which is reversed graded lexographic order;
        old, which is used for compatibility reasons and for long expressions;
        None, which sets it to lex.
    use_unicode: boolean or None
        If True, use unicode characters;
        if False, do not use unicode characters.
    use_latex: boolean or None
        If True, use latex rendering if IPython GUI's;
        if False, do not use latex rendering.
    quiet: boolean
        If True, init_session will not print messages regarding its status;
        if False, init_session will print messages regarding its status.
    auto_symbols: boolean
        If True, IPython will automatically create symbols for you.
        If False, it will not.
        The default is False.
    auto_int_to_Integer: boolean
        If True, IPython will automatically wrap int literals with Integer, so
        that things like 1/2 give Rational(1, 2).
        If False, it will not.
        The default is False.
    ipython: boolean or None
        If True, printing will initialize for an IPython console;
        if False, printing will initialize for a normal console;
        The default is None, which automatically determines whether we are in
        an ipython instance or not.
    argv: list of arguments for IPython
        See sympy.bin.isympy for options that can be used to initialize IPython.

    See Also
    ========

    sympy.interactive.printing.init_printing: for examples and the rest of the parameters.


    Examples
    ========

    >>> from sympy import init_session, Symbol, sin, sqrt
    >>> sin(x) #doctest: +SKIP
    NameError: name 'x' is not defined
    >>> init_session() #doctest: +SKIP
    >>> sin(x) #doctest: +SKIP
    sin(x)
    >>> sqrt(5) #doctest: +SKIP
      ___
    \/ 5
    >>> init_session(pretty_print=False) #doctest: +SKIP
    >>> sqrt(5) #doctest: +SKIP
    sqrt(5)
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_session(order='grlex') #doctest: +SKIP
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + y**2 + x + y
    >>> init_session(order='grevlex') #doctest: +SKIP
    >>> y * x**2 + x * y**2 #doctest: +SKIP
    x**2*y + x*y**2
    >>> init_session(order='old') #doctest: +SKIP
    >>> x**2 + y**2 + x + y #doctest: +SKIP
    x + y + x**2 + y**2
    >>> theta = Symbol('theta') #doctest: +SKIP
    >>> theta #doctest: +SKIP
    theta
    >>> init_session(use_unicode=True) #doctest: +SKIP
    >>> theta # doctest: +SKIP
    \u03b8
    """
    import sys

    in_ipython = False

    if ipython is not False:
        try:
            import IPython
        except ImportError:
            if ipython is True:
                raise RuntimeError("IPython is not available on this system")
            ip = None
        else:
            if V(IPython.__version__) >= '0.11':
                try:
                    ip = get_ipython()
                except NameError:
                    ip = None
            else:
                ip = IPython.ipapi.get()
                if ip:
                    ip = ip.IP
        in_ipython = bool(ip)
        if ipython is None:
            ipython = in_ipython

    if ipython is False:
        ip = init_python_session()
        mainloop = ip.interact
    else:
        if ip is None:
            ip = init_ipython_session(argv=argv,
                                      auto_symbols=auto_symbols,
                                      auto_int_to_Integer=auto_int_to_Integer)

        if V(IPython.__version__) >= '0.11':
            # runsource is gone, use run_cell instead, which doesn't
            # take a symbol arg.  The second arg is `store_history`,
            # and False means don't add the line to IPython's history.
            ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)

            #Enable interactive plotting using pylab.
            try:
                ip.enable_pylab(import_all=False)
            except Exception:
                # Causes an import error if matplotlib is not installed.
                # Causes other errors (depending on the backend) if there
                # is no display, or if there is some problem in the
                # backend, so we have a bare "except Exception" here
                pass
        if not in_ipython:
            mainloop = ip.mainloop

    readline = import_module("readline")
    if auto_symbols and (not ipython or V(IPython.__version__) < '0.11'
                         or not readline):
        raise RuntimeError(
            "automatic construction of symbols is possible only in IPython 0.11 or above with readline support"
        )
    if auto_int_to_Integer and (not ipython
                                or V(IPython.__version__) < '0.11'):
        raise RuntimeError(
            "automatic int to Integer transformation is possible only in IPython 0.11 or above"
        )

    _preexec_source = preexec_source

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print,
                  order=order,
                  use_unicode=use_unicode,
                  use_latex=use_latex,
                  ip=ip)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        mainloop(message)
        sys.exit('Exiting ...')
    else:
        ip.write(message)
        import atexit
        atexit.register(lambda ip: ip.write("Exiting ...\n"), ip)
コード例 #27
0
ファイル: session.py プロジェクト: sn6uv/sympy
def init_session(ipython=None, pretty_print=True, order=None,
        use_unicode=None, quiet=False, auto_symbols=False, auto_int_to_Integer=False, argv=[]):
    """
    Initialize an embedded IPython or Python session. The IPython session is
    initiated with the --pylab option, without the numpy imports, so that
    matplotlib plotting can be interactive.

    Parameters
    ==========

    pretty_print: boolean
        If True, use pretty_print to stringify;
        if False, use sstrrepr to stringify.
    order: string or None
        There are a few different settings for this parameter:
        lex (default), which is lexographic order;
        grlex, which is graded lexographic order;
        grevlex, which is reversed graded lexographic order;
        old, which is used for compatibility reasons and for long expressions;
        None, which sets it to lex.
    use_unicode: boolean or None
        If True, use unicode characters;
        if False, do not use unicode characters.
    quiet: boolean
        If True, init_session will not print messages regarding its status;
        if False, init_session will print messages regarding its status.
    auto_symbols: boolean
        If True, IPython will automatically create symbols for you.
        If False, it will not.
        The default is False.
    auto_int_to_Integer: boolean
        If True, IPython will automatically wrap int literals with Integer, so
        that things like 1/2 give Rational(1, 2).
        If False, it will not.
        The default is False.
    ipython: boolean or None
        If True, printing will initialize for an IPython console;
        if False, printing will initialize for a normal console;
        The default is None, which does what False does.
    argv: list of arguments for IPython
        See sympy.bin.isympy for options that can be used to initialize IPython.

    See Also
    ========

    sympy.interactive.printing.init_printing: for examples and the rest of the parameters.


    Examples
    ========

    >>> from sympy import init_session, Symbol, sin, sqrt
    >>> sin(x) #doctest: +SKIP
    NameError: name 'x' is not defined
    >>> init_session() #doctest: +SKIP
    >>> sin(x) #doctest: +SKIP
    sin(x)
    >>> sqrt(5) #doctest: +SKIP
      ___
    \/ 5
    >>> init_session(pretty_print=False) #doctest: +SKIP
    >>> sqrt(5) #doctest: +SKIP
    sqrt(5)
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + x + y**2 + y
    >>> init_session(order='grlex') #doctest: +SKIP
    >>> y + x + y**2 + x**2 #doctest: +SKIP
    x**2 + y**2 + x + y
    >>> init_session(order='grevlex') #doctest: +SKIP
    >>> y * x**2 + x * y**2 #doctest: +SKIP
    x**2*y + x*y**2
    >>> init_session(order='old') #doctest: +SKIP
    >>> x**2 + y**2 + x + y #doctest: +SKIP
    x + y + x**2 + y**2
    >>> theta = Symbol('theta') #doctest: +SKIP
    >>> theta #doctest: +SKIP
    theta
    >>> init_session(use_unicode=True) #doctest: +SKIP
    >>> theta # doctest: +SKIP
    \u03b8
    """
    import sys

    in_ipython = False

    if ipython is False:
        ip = init_python_session()
        mainloop = ip.interact
    else:
        try:
            import IPython
        except ImportError:
            if ipython is not True:
                if not quiet:
                    print no_ipython
                ip = init_python_session()
                mainloop = ip.interact
            else:
                raise RuntimeError("IPython is not available on this system")
        else:
            ipython = True

            if IPython.__version__ >= '0.11':
                try:
                    ip = get_ipython()
                except NameError:
                    ip = None
            else:
                ip = IPython.ipapi.get()
                if ip:
                    ip = ip.IP

            if ip is not None:
                in_ipython = True
            else:
                ip = init_ipython_session(argv=argv,
                    auto_symbols=auto_symbols, auto_int_to_Integer=auto_int_to_Integer)

            if IPython.__version__ >= '0.11':
                # runsource is gone, use run_cell instead, which doesn't
                # take a symbol arg.  The second arg is `store_history`,
                # and False means don't add the line to IPython's history.
                ip.runsource = lambda src, symbol='exec': ip.run_cell(src, False)

                #Enable interactive plotting using pylab.
                try:
                    ip.enable_pylab(import_all=False)
                except ImportError:
                    #Causes an import error if matplotlib is not installed.
                    pass
            if not in_ipython:
                mainloop = ip.mainloop

    if auto_symbols and (not ipython or IPython.__version__ < '0.11'):
        raise RuntimeError("automatic construction of symbols is possible only in IPython 0.11 or above")
    if auto_int_to_Integer and (not ipython or IPython.__version__ < '0.11'):
        raise RuntimeError("automatic int to Integer transformation is possible only in IPython 0.11 or above")

    _preexec_source = preexec_source

    ip.runsource(_preexec_source, symbol='exec')
    init_printing(pretty_print=pretty_print, order=order, use_unicode=use_unicode, ip=ip)

    message = _make_message(ipython, quiet, _preexec_source)

    if not in_ipython:
        mainloop(message)
        sys.exit('Exiting ...')
    else:
        ip.write(message)
        ip.set_hook('shutdown_hook', lambda ip: ip.write("Exiting ...\n"))
コード例 #28
0
plt.xticks(np.arange(3), ('$x$', '$y$', '$z$'), fontsize=22)

plt.xlim([-0.5, 2.5])
plt.ylim([2.5, -0.5])

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes("right", "5%", pad="3%")
plt.colorbar(im, cax=cax)

plt.tight_layout()

#Process Noise Covariance Matrix
from sympy import Symbol, Matrix
from sympy.interactive import printing
printing.init_printing()
dts = Symbol('\Delta t')
Qs = Matrix([[0.5 * dts**2], [0.5 * dts**2], [0.5 * dts**2], [dts], [dts],
             [dts], [1.0], [1.0], [1.0]])
Qs * Qs.T

sa = 0.1
G = np.matrix([[1 / 2.0 * dt**2], [1 / 2.0 * dt**2], [1 / 2.0 * dt**2], [dt],
               [dt], [dt], [1.0], [1.0], [1.0]])
Q = G * G.T * sa**2

fig = plt.figure(figsize=(6, 6))
im = plt.imshow(Q, interpolation="none", cmap=plt.get_cmap('binary'))
plt.title('Process Noise Covariance Matrix $Q$')
ylocs, ylabels = plt.yticks()
# set the locations of the yticks
コード例 #29
0
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>

# <codecell>

from IPython.display import display

from sympy.interactive import printing
printing.init_printing()

from __future__ import division
import sympy as sym
from sympy import *


import matplotlib
matplotlib.rc('font',**{'family':'serif'})

# <markdowncell>

# # Outline of the HTSE solution to second order

# <codecell>

z0, z, u, B, t , U= symbols(r"z_{0} z u \beta t U")
m=6.
grand = -sym.log( z0 ) / B - B * (t/z0)**2 * m * ( z + z**3 * u + 2*z**2 * (1-u) / (B*U))
grand

# <codecell>
コード例 #30
0
from sympy import Symbol, symbols, expand, factor
from sympy.interactive.printing import init_printing
from sympy.printing.pretty.pretty import pprint

# 심볼 선언
x = Symbol('x')

print('x에 대한 다항식:', x + x + 3)

x, y = symbols('x, y')
print('x,y에 대한 다항식', x * y + x * y + x * y)

print('전개식:', expand((x + 1) * (x + 2)))
print('인수분해:', factor(x**2 + 3 * x + 2))

# 오름차순 정렬
init_printing(order='rev-lex')

print('pprint:', end='')
pprint(expand((x + 1) * (x + 2)))

polynomial = 2 + 3 * x + x**2
print('polynomial:', end='')
pprint(polynomial)

polynomial = x**2 + 2 * x * y + y**2
print('다항식대입:', polynomial.subs({x: 2, y: 1}))
コード例 #31
0
"""Tools for setting up interactive sessions. """

from __future__ import print_function, division

from distutils.version import LooseVersion as V

from sympy.external import import_module
from sympy.interactive.printing import init_printing

preexec_source = """\
from __future__ import division
from sympy import *
x, y, z, t = symbols('x y z t')
k, m, n = symbols('k m n', integer=True)
f, g, h = symbols('f g h', cls=Function)
init_printing()
"""

verbose_message = """\
These commands were executed:
%(source)s
Documentation can be found at http://www.sympy.org
"""

no_ipython = """\
Couldn't locate IPython. Having IPython installed is greatly recommended.
See http://ipython.scipy.org for more details. If you use Debian/Ubuntu,
just install the 'ipython' package and start isympy again.
"""

from __future__ import division
from sympy.interactive import printing

printing.init_printing(use_latex="mathjax")


from IPython.display import display, Image, Latex
import numpy as np
import math
import scipy.constants as sc

import sympy as sym

# from sympy import *


class FlatPlate(object):
    """ Definition of boundary layer thickness, friction coefficient, Nusselt number (both local and average)
        as a function of the regime.
        import HT_external_convection_flat_plate.py as flatplate
        
        bl =flatplate.FlatPlate(regime,thermal_bc,U_infty,nu,alpha_f,L,xi,Re_xc)
        where 
        regime = 'laminar' or 'turbulent' or 'mixed', 
        thermal_bc = 'isothermal', 'heat flux', 'unheated starting length',
        U_infty is the free stream velocity,
        nu the fluid viscosity,
        alpha the fluid thermal diffusivity,
        L length of the plate
        xi unheated started length
        Re_xc critical Reynolds number for transition laminar to turbulence
コード例 #33
0
""" Object name 1: FlatPlate
    Object name 2: CircularCylinder
    Object name 3: NoncircularCylinder
    Object name 4: BankofTubes
"""
from __future__ import division
from sympy.interactive import printing
printing.init_printing(use_latex='mathjax')


from IPython.display import display,Image, Latex
import numpy as np
import math
import scipy.constants as sc

import sympy as sym
#from sympy import *

class FlatPlate(object):
    """ Definition of boundary layer thickness, friction coefficient, Nusselt number (both local and average)
        as a function of the regime.
        import HT_external_convection.py as extconv
        
        bl =extconv.FlatPlate(regime,thermal_bc,U_infty,nu,alpha_f,L,xi,Re_xc)
        where 
        regime = 'laminar' or 'turbulent' or 'mixed', 
        thermal_bc = 'isothermal', 'heat flux', 'unheated starting length',
        U_infty is the free stream velocity,
        nu the fluid viscosity,
        alpha the fluid thermal diffusivity,
        L length of the plate
コード例 #34
0
# coding: utf-8

# In[64]:

get_ipython().magic(u'matplotlib inline')
import matplotlib.pyplot as plt
import numpy as np
import mpld3
from IPython.display import Image
import numpy as np
from sympy.interactive import printing
printing.init_printing(use_latex=True)
Image(filename='afr_circuit.png')


# This code will compare simulation results for the Active Feedback Resonator (depicted above) with measurements.
# 
# The main output will be modeling the predicted behavior of the noise and snr vs Q in the case of coherent and incoherent noise.
# 
# Table of Contents:
# 
# [Theory](#theory)
# 
# [Simulations](#simulations)
# 
# [Measurements](#measurements)
# 
# [Comparison](#comparison)
# 
# [Literature Review](#literature)
コード例 #35
0
import math

import numpy as np

import sympy as sp
from sympy.interactive.printing import init_printing

init_printing(use_unicode=False, wrap_line=False)


def kalman_step(A, C, Q, R, y, x, V):
    # INPUTS:
    # A - the system matrix
    # C - the observation matrix
    # Q - the system covariance
    # R - the observation covariance
    # y(:)   - the observation at time t
    # x(:) - E[X | y(:, 1:t-1)] prior mean
    # V(:,:) - Cov[X | y(:, 1:t-1)] prior covariance
    # OUTPUTS (where X is the hidden state being estimated)
    # xnew(:) =   E[ X | y(:, 1:t) ]
    # Vnew(:,:) = Var[ X(t) | y(:, 1:t) ]
    # VVnew(:,:) = Cov[ X(t), X(t-1) | y(:, 1:t) ]
    # loglik = log P(y(:,t) | y(:,1:t-1)) log-likelihood of innovation

    xpred = np.matmul(A, x)
    Vpred = np.matmul(np.matmul(A, V), A.transpose()) + Q

    e = y - np.matmul(C, xpred)  # error (innovation)
    S = np.matmul(np.matmul(C, Vpred), C.transpose()) + R
    ss = max(V.shape)
コード例 #36
0
""" Object name 1: FlatPlate
    Object name 2: CircularCylinder
    Object name 3: NoncircularCylinder
    Object name 4: BankofTubes
"""

from sympy.interactive import printing
printing.init_printing(use_latex='mathjax')

from IPython.display import display, Image, Latex
import numpy as np
import math
import scipy.constants as sc
import sys
try:
    import thermodynamics as thermo
except ModuleNotFoundError:
    from Libraries import thermodynamics as thermo
import sympy as sym
#from sympy import *


class FlatPlate(object):
    """ Definition of boundary layer thickness, friction coefficient, Nusselt number (both local and average)
        as a function of the regime.
        import HT_external_convection.py as extconv
        
        bl =extconv.FlatPlate(regime,thermal_bc,U_infty,nu,alpha,L,xi=0.0,Re_xc=5e5)
            where regime = 'laminar' or 'turbulent' or 'mixed', 
            thermal_bc = 'isothermal', 'heat flux', 'unheated starting length',
            U_infty is the free stream velocity,