def test_cgs_gauss_convert_constants():

    assert (convert_to(speed_of_light, centimeter / second,
                       cgs_gauss) == 29979245800 * centimeter / second)

    assert convert_to(coulomb_constant, 1, cgs_gauss) == 1
    assert convert_to(
        coulomb_constant, newton * meter**2 / coulomb**2,
        cgs_gauss) == 22468879468420441 * meter**2 * newton / (25000000000 *
                                                               coulomb**2)
    assert convert_to(
        coulomb_constant, newton * meter**2 / coulomb**2,
        SI) == 22468879468420441 * meter**2 * newton / (2500000 * coulomb**2)
    assert (convert_to(coulomb_constant, dyne * centimeter**2 / statcoulomb**2,
                       cgs_gauss) == centimeter**2 * dyne / statcoulomb**2)
    assert convert_to(coulomb_constant, 1, SI) == coulomb_constant
    assert (NS(
        convert_to(coulomb_constant, newton * meter**2 / coulomb**2,
                   SI)) == "8987551787.36818*meter**2*newton/coulomb**2")

    assert convert_to(elementary_charge, statcoulomb, cgs_gauss)
    assert convert_to(gravitational_constant, dyne * centimeter**2 / gram**2,
                      cgs_gauss)
    assert (NS(convert_to(planck, erg * second,
                          cgs_gauss)) == "6.62607015e-27*erg*second")
Example #2
0
def test_deprecated_quantity_methods():
    step = Quantity("step")
    with warns_deprecated_sympy():
        step.set_dimension(length)
        step.set_scale_factor(2*meter)
        assert convert_to(step, centimeter) == 200*centimeter
        assert convert_to(1000*step/second, kilometer/second) == 2*kilometer/second
Example #3
0
    def __init__(self, val, dim=None, sigma=None, epsilon=None, symbol=None,
                 is_const=False):
        """
        Physical Quantity
        :param val: значение
        :param dim: размерность величины. Если указана, используется она. Если None, берётся размерность val.
        :param sigma: относительная погрешность
        :param epsilon:  абсолютная погрешность
            Стоит указывать только одну погрешность, другая посчитается сама.
        :param symbol: можно особо указать sympy символ (зачем?)
        :param is_const: позволяет сделать константу, у которой не будет погрешностей.
            Иначе же за погрешность надо брать последнюю цифру (не реализовано).
        """

        if isinstance(val, PQ):
            raise Exception("Не пытайтесь передать PQ как val или sigma. Явно пропишите к нему .val")

        self.dim = None
        if dim is not None:
            self.dim = dim
        else:
            if val != 0:
                self.dim = PQ.get_dim(val)
            elif sigma is not None:
                self.dim = PQ.get_dim(sigma)
            else:
                raise Exception('Impossible to deduce dim (note: zero is dimensionless)')

        self.val = u.convert_to(val, self.dim)

        if sigma is not None:
            self.sigma = u.convert_to(sigma, self.dim)
            self.epsilon = u.convert_to(self.sigma/self.val, sp.numbers.Integer(1))
            if self.epsilon == sp.zoo or self.epsilon == sp.oo or self.epsilon == sp.nan:
                self.epsilon = np.nan
            elif self.epsilon < 0:
                self.epsilon = sp.Abs(self.epsilon)
        elif epsilon is not None:
            self.epsilon = np.float64(u.convert_to(epsilon, sp.numbers.Integer(1)))
            if not np.isnan(self.epsilon) and self.epsilon < 0:
                self.epsilon = np.abs(self.epsilon)
            self.sigma = u.convert_to(self.val*self.epsilon, self.dim)
        else:
            if is_const:
                self.sigma = self.epsilon = 0
            else:
                pass  # TODO:last digit

        self.is_const = is_const

        if symbol is None:
            if not hasattr(PQ, 'symbol_counter'):
                PQ.symbol_counter = 0
            else:
                PQ.symbol_counter += 1
            self.symbol = sp.symbols('symbol' + str(PQ.symbol_counter))
        else:
            self.symbol = sp.symbols(symbol)
Example #4
0
 def repr_as(self, dim):
     """
     Конвертитует себя в размерность dim.
     :returns себя
     """
     self.dim = dim
     self.val = u.convert_to(self.val, dim).n()
     self.sigma = u.convert_to(self.sigma, dim).n()
     return self
Example #5
0
def convertTo(expr, unit):
    """Wraps units.convert_to for extra functionality.

    Extra features:
        Allows `unit` to be a string.
        If `expr` has no units, returns `expr * unit`.

    :param expr: sympy.Expr
    :param unit: str\\units.Quantity\\units.Dimension
    :return: sympy.Expr or None
    """
    logger.log(logging.DEBUG - 1, f'convertTo({expr}, {unit})')
    if expr is None:
        return None

    if isinstance(unit, str):
        try:
            unit = unitSubs[unit]
        except KeyError:
            unit = parseExpr(unit)
    u = unit

    logger.log(logging.DEBUG - 1, f'convertTo() expr {expr}, u {u}')
    dim = getDimension(expr)
    logger.log(logging.DEBUG - 1, f'convertTo() dim = {dim}')
    if dim is None:
        _ret = expr * u
    if dim is not None and dim.name == 1:
        _ret = expr * u
    else:
        _ret = units.convert_to(expr, u)

    logger.log(logging.DEBUG - 1, f'convertTo() -> {str(_ret)}')
    return _ret
Example #6
0
 def _convert_to_sec(self, val):
     if val is not None:
         try:
             # sympy >= 1.1
             return units.convert_to(val, units.seconds).args[0]
         except Exception:
             # sympy < 1.1
             return val / units.seconds
     return None
Example #7
0
 def _convert_to_sec(self, val):
     if val is not None:
         try:
             # sympy >= 1.1
             return units.convert_to(val, units.seconds).args[0]
         except:
             # sympy < 1.1
             return val / units.seconds
     return None
Example #8
0
    def __init__(self,
                 inlet=None,
                 outlet=None,
                 num_nodes=None,
                 teta=0,
                 length=None,
                 diameter=None,
                 epsilon=0,
                 ambient_t=None,
                 isotherm=True,
                 heat_transfer_coef=0):
        self.inlet_stream = inlet
        self.outlet_stream = outlet
        self.D = np.array(convert_to(diameter, U.m).args[0], dtype=np.float32)
        self.A = np.pi * self.D**2 / 4
        self.teta = teta
        self.epsilon = epsilon and np.array(convert_to(epsilon, U.m).args[0],
                                            dtype=np.float32)
        self.isotherm = isotherm
        self.ambient_T = ambient_t and np.array(
            convert_to(ambient_t, U.K).args[0], dtype=np.float32)
        self.U = heat_transfer_coef and np.array(convert_to(
            heat_transfer_coef, U.W / ((U.m**2) * U.K)).args[0],
                                                 dtype=np.float32)

        self.domain = Domain(
            np.array(convert_to(length, U.m).args[0], dtype=np.float32),
            num_nodes + 2)
        # define domain var and their boundry conditions
        DomainVar('P', self.domain, (0, self.inlet_stream.P))
        DomainVar('m', self.domain, (0, self.inlet_stream.m))
        DomainVar('T', self.domain, (0, self.inlet_stream.T))

        # intial conditions
        self.domain.P[:] = self.inlet_stream.P
        self.domain.m[:] = self.inlet_stream.m
        self.domain.T[:] = self.inlet_stream.T

        self.ps = PropertySet()
        self.ps.P = self.domain.P
        self.ps.T = self.domain.T
        self.ps.MW = inlet.MW
        self.pc = PipePropertyCalculator(self.ps, self)
Example #9
0
def get_expr_without_units(expr, to, units_map):
    """Converts an expression with units to one without, applying conversion factors where necessary"""
    expr = sympy_units.convert_to(expr, to)
    subs = []
    for s in units_map:
        if type(s) == str:
            subs.append((Symbol(s) * to, Symbol(s)))
        else:  #assume symbol
            subs.append((s * to, s))
    return expr.subs(subs)
Example #10
0
def test_binary_information():
    assert convert_to(kibibyte, byte) == 1024*byte
    assert convert_to(mebibyte, byte) == 1024**2*byte
    assert convert_to(gibibyte, byte) == 1024**3*byte
    assert convert_to(tebibyte, byte) == 1024**4*byte
    assert convert_to(pebibyte, byte) == 1024**5*byte
    assert convert_to(exbibyte, byte) == 1024**6*byte

    assert kibibyte.convert_to(bit) == 8*1024*bit
    assert byte.convert_to(bit) == 8*bit

    a = 10*kibibyte*hour

    assert convert_to(a, byte) == 10240*byte*hour
    assert convert_to(a, minute) == 600*kibibyte*minute
    assert convert_to(a, [byte, minute]) == 614400*byte*minute
Example #11
0
def eval(dim, lambd, *args, symbol=None):
    """
    Вычисляет новую PE по формуле и пересчитывает погрешности как надо.
    :param dim: Размерность желаемой величины.
    :param lambd: Функция, которая будет вычисляться. Обычно в виде лямбды.
    :param args: Параметры, которые надо передавать функции.
    :param symbol: можно особо указать sympy символ (зачем?)
    :return: Новое PQ.
    """
    args = list(args)
    log.debug('args: %s', args)

    log.debug("Initial args types: %s"%str([type(arg) for arg in args]))
    for i in range(len(args)):
        if issubclass(type(args[i]), np.ndarray):
            if type(args[i][0]) is not PQ:
                args[i] = pqarray([PQ(val, is_const=True) for val in args[i]])
        elif type(args[i]) is not PQ:
            args[i] = PQ(args[i], is_const=True)
    log.debug('args converted to PQ: %s', args)

    partdiffs = [sp.diff(lambd(*[arg.symbol for arg in args]), x.symbol) for x in args]
    log.debug('partdiffs %s', partdiffs)

    values = {(arg.symbol, arg.val) for arg in args}
    log.debug('values of partdiffs %s', values)

    summands = [sp.Abs(partdiff.subs(values).evalf()**2*pe.sigma**2) for
                (partdiff, pe) in zip(partdiffs, args)]
    summands = [u.convert_to(s, dim**2) for s in summands]
    log.debug('summands %s', summands)

    new_val = u.convert_to(lambd(*[arg.val for arg in args]), dim).n()

    log.debug('val %s', new_val)

    new_sigma = u.convert_to(sp.sqrt(sum(summands)), dim).n()
    log.debug('sigma %s', new_sigma)

    log.debug('dim %s', dim)

    return PQ(new_val, sigma=new_sigma, symbol=symbol, dim=dim)
Example #12
0
def test_units():
    assert convert_to((5*m/s * day) / km, 1) == 432
    assert convert_to(foot / meter, meter) == Rational(3048, 10000)
    # amu is a pure mass so mass/mass gives a number, not an amount (mol)
    # TODO: need better simplification routine:
    assert str(convert_to(grams/amu, grams).n(2)) == '6.0e+23'

    # Light from the sun needs about 8.3 minutes to reach earth
    t = (1*au / speed_of_light) / minute
    # TODO: need a better way to simplify expressions containing units:
    t = convert_to(convert_to(t, meter / minute), meter)
    assert t == S(49865956897)/5995849160

    # TODO: fix this, it should give `m` without `Abs`
    assert sqrt(m**2) == Abs(m)
    assert (sqrt(m))**2 == m

    t = Symbol('t')
    assert integrate(t*m/s, (t, 1*s, 5*s)) == 12*m*s
    assert (t * m/s).integrate((t, 1*s, 5*s)) == 12*m*s
Example #13
0
    def print_unit_base(self, unit):
        """
        Useless method.

        DO NOT USE, use instead ``convert_to``.

        Give the string expression of a unit in term of the basis.

        Units are displayed by decreasing power.
        """
        SymPyDeprecationWarning(
            deprecated_since_version="1.2",
            issue=13336,
            feature="print_unit_base",
            useinstead="convert_to",
        ).warn()
        from sympy.physics.units import convert_to
        return convert_to(unit, self._base_units)
Example #14
0
    def print_unit_base(self, unit):
        """
        Useless method.

        DO NOT USE, use instead ``convert_to``.

        Give the string expression of a unit in term of the basis.

        Units are displayed by decreasing power.
        """
        SymPyDeprecationWarning(
            deprecated_since_version="1.2",
            issue=13336,
            feature="print_unit_base",
            useinstead="convert_to",
        ).warn()
        from sympy.physics.units import convert_to
        return convert_to(unit, self._base_units)
Example #15
0
def test_convert_to():
    q = Quantity("q1")
    q.set_global_relative_scale_factor(S(5000), meter)

    assert q.convert_to(m) == 5000 * m

    assert speed_of_light.convert_to(m / s) == 299792458 * m / s
    # TODO: eventually support this kind of conversion:
    # assert (2*speed_of_light).convert_to(m / s) == 2 * 299792458 * m / s
    assert day.convert_to(s) == 86400 * s

    # Wrong dimension to convert:
    assert q.convert_to(s) == q
    assert speed_of_light.convert_to(m) == speed_of_light

    expr = joule * second
    conv = convert_to(expr, joule)
    assert conv == joule * second
Example #16
0
def canonicalize(expr, base=None):
    """Convert all units to given base units (default: SI base units)

    Parameters
    ----------
    expr :

    base :
        (Default value = None)

    Returns
    -------


    """
    if base is None:
        base = (spu.m, spu.kg, spu.s, spu.A, spu.K, spu.mol, spu.cd)
    return spu.convert_to(expr, base)
Example #17
0
def test_conversion_with_2_nonstandard_dimensions():
    good_grade = Quantity("good_grade")
    kilo_good_grade = Quantity("kilo_good_grade")
    centi_good_grade = Quantity("centi_good_grade")

    kilo_good_grade.set_global_relative_scale_factor(1000, good_grade)
    centi_good_grade.set_global_relative_scale_factor(S.One/10**5, kilo_good_grade)

    charity_points = Quantity("charity_points")
    milli_charity_points = Quantity("milli_charity_points")
    missions = Quantity("missions")

    milli_charity_points.set_global_relative_scale_factor(S.One/1000, charity_points)
    missions.set_global_relative_scale_factor(251, charity_points)

    assert convert_to(
        kilo_good_grade*milli_charity_points*millimeter,
        [centi_good_grade, missions, centimeter]
    ) == S.One * 10**5 / (251*1000) / 10 * centi_good_grade*missions*centimeter
Example #18
0
 def canonicalize(expr, base=None):
     """Convert all units to given base units (default: SI base units)"""
     if base is None:
         base = (spu.m, spu.kg, spu.s, spu.A, spu.K, spu.mol, spu.cd)
     return spu.convert_to(expr, base)
Example #19
0
    circuito, análisis_en_netlist)
resultados = ahkab.run(circuito, lista_de_análisis)

# %% [markdown]
# Imprimos los resultados del análisis `.op`:

# %%
print(resultados['op'])

# %% [markdown]
# Los cantidades `V1`, `V2` y `V3` hacen referencia a los distintos valores del potencial que se ha perdido en cada uno de los bornes que has elegido para describir el netlist (`1`, `2`, etc.). Por ejemplo, podemos calcular el *potencial consumido* por la resistencia `R1` y verás que coincide con el del punto `V2` devuelto por Ahkab.

# %%
r1 = 3E3 * u.ohms
intensidad_ahkab = resultados['op']['I(V1)'][0][0] * u.ampere
v2 = convert_to(intensidad_ahkab * r1, [u.volt])
pprint(v2)

# %% [markdown]
#  > **Pregunta**: reproduce el resto de los valores anteriores de manera *manual* mediante Sympy (es decir, aplicando la ley de Ohm, pero con tun *toque computacional*). Te pongo aquí un ejemplo del que puedes partir… En él sólo calculo la corriente que circula por el circuito (sí, justo la que antes Ahkab ha devuelto de manera automática). Para ello necesito previamente computar la resistencia total (`r_total`). Faltarían el resto de resultados y convertirlos a unidades más *vistosas* (mediante la orden `convert_to` y `.n()`).

# %%
v1 = 9 * u.volts
r1 = 3 * u.kilo * u.ohms
r2 = 10 * u.kilo * u.ohms
r3 = 5 * u.kilo * u.ohms
r_total = r1 + r2 + r3
intensidad = u.Quantity('i')
intensidad.set_dimension(u.current)
ley_ohm = Eq(v1, intensidad * r_total)
solucion_para_intensidad = solve(ley_ohm, intensidad)
Example #20
0
# Ejercicio basado en https://docs.sympy.org/latest/modules/physics/units/examples.html#equation-with-quantities
# Sobre Kepler https://en.wikipedia.org/wiki/Johannes_Kepler

from sympy import solve, symbols, pi, Eq  # Cargamos objetos directos de Sympy
# Unidades S.I.
from sympy.physics.units import meter, kilogram, second, kelvin, newton, day, year
# Cargamos la función convert_to para pasar de unas unidades a otras
from sympy.physics.units import convert_to
# Cargamos constantes
# La constante de gravitación universal https://www.google.com/search?q=gravitational+constant
from sympy.physics.units import gravitational_constant as G
from sympy.physics.units import speed_of_light as c

T = symbols("T")  # Incógnita: periodo de giro (T)
a = 108208000e3 * meter  # Dato conocido: semieje mayor de Venus
M0 = 1.9891e30 * kilogram  # Dato conocido: masa del Sol

eq_kepler = Eq(T**2 / a**3, 4 * pi**2 / G / M0)  # Ecuación de Kepler
# Despejamos T, el resultado acaba en otra variable llamada "solution"
solution = solve(eq_kepler, T)[1]

# print(solution)
print(convert_to(solution, [year]).n())

# Conversión entre unidades https://docs.sympy.org/latest/modules/physics/units/quantities.html
#print(convert_to(G, [newton, meter,  kilogram]))
Example #21
0
from sympy.functions import *
from sympy.interactive import init_printing
from sympy.physics.units import Quantity
from sympy.physics.units import convert_to
from utils import *

init_printing()

hp_to_watts = 745.7

W0 = Quantity("W0")
W = Quantity("W")
m = Quantity("m")
v = Quantity("v")
g = Quantity("g")
theta = symbols("theta")

set_quantity(W0, un.power, 85 * hp_to_watts * un.watts)
set_quantity(W, un.power, 20 * hp_to_watts * un.watts)
set_quantity(m, un.mass, 1200 * un.kg)
set_quantity(v, un.velocity, 48 * un.km / un.hour)
set_quantity(g, un.acceleration, 9.81 * un.m / un.s**2)

eq = Eq(sin(theta), (W0 - W) / (m * g * v))
pretty_print(eq)

theta = solve(eq, theta)[1]

theta = convert_to(theta, un.watts).n()
pretty_print(convert_to(theta, un.degrees).n())
Example #22
0
 def add_sigma(self, other_sigma):
     self.sigma = sp.sqrt(self.sigma**2 + other_sigma**2)
     self.epsilon = u.convert_to(self.sigma/self.val, sp.numbers.Integer(1))
     return self
Example #23
0
import sympy.physics.units as un
from sympy import symbols, Eq, pretty_print
from sympy.interactive import init_printing
from sympy.physics.units import Quantity
from sympy.physics.units import convert_to
from utils import *

init_printing()

E = Quantity("E")
c = Quantity("c")

set_quantity(E, un.energy, 2.15e12 * un.kilo * un.watts * un.hour)
set_quantity(c, un.speed, 3.00e8 * un.m / un.s)
E = convert_to(E, un.joule).n()

print('Heavy water:')
pretty_print(Eq(symbols('D2O'), 2 * symbols('D') + symbols('O')))

print('Let nucleosynthesis reaction be like below:')
pretty_print(Eq(symbols('D'), symbols('H_^2')))
pretty_print(Eq(symbols('H^2') + symbols('H^2'), symbols('He_^4')))

print('a).')
m = symbols('m')
pretty_print(Eq(m, symbols('E') / c**2))
m = E / c**2
m = convert_to(m, un.kg).n()

pretty_print("Energy to mass  : {}".format(m))
Example #24
0
from sympy.physics import units

# Convert 12 inches to meters
D = units.convert_to(12 * units.inch, units.meter)

# Convert 0.2 mg/L to kg/m3
C = units.convert_to(0.2 * units.mg / units.l, units.kg / units.m**3)

# Convert 30 psi to m (assuming density = 1000 kg/m3 and gravity = 9.81 m/s2)
P = 30 * units.psi
P = units.convert_to(P, units.Pa)  # convert psi to pascal
waterpressure = 9810 * units.Pa / units.m
H = P / waterpressure  # convert pascal to m

# Convert 200 gallons/day to m3/day
if not 'gallon' in units.find_unit('volume'):
    units.gallon = 4 * units.quart
R = units.convert_to(200 * units.gallon / units.day, units.m**3 / units.day)
Example #25
0
def test_conversion_to_from_si():

    assert convert_to(statcoulomb, coulomb,
                      cgs_gauss) == 5 * coulomb / 149896229
    assert convert_to(coulomb, statcoulomb,
                      cgs_gauss) == 149896229 * statcoulomb / 5
    assert convert_to(
        statcoulomb,
        sqrt(gram * centimeter**3) / second,
        cgs_gauss) == centimeter**(S(3) / 2) * sqrt(gram) / second
    assert convert_to(
        coulomb,
        sqrt(gram * centimeter**3) / second,
        cgs_gauss) == 149896229 * centimeter**(S(3) /
                                               2) * sqrt(gram) / (5 * second)

    # SI units have an additional base unit, no conversion in case of electromagnetism:
    assert convert_to(coulomb, statcoulomb, SI) == coulomb
    assert convert_to(statcoulomb, coulomb, SI) == statcoulomb

    # SI without electromagnetism:
    assert convert_to(erg, joule, SI) == joule / 10**7
    assert convert_to(erg, joule, cgs_gauss) == joule / 10**7
    assert convert_to(joule, erg, SI) == 10**7 * erg
    assert convert_to(joule, erg, cgs_gauss) == 10**7 * erg

    assert convert_to(dyne, newton, SI) == newton / 10**5
    assert convert_to(dyne, newton, cgs_gauss) == newton / 10**5
    assert convert_to(newton, dyne, SI) == 10**5 * dyne
    assert convert_to(newton, dyne, cgs_gauss) == 10**5 * dyne
Example #26
0
SI.set_quantity_dimension(s, length**2)
SI.set_quantity_scale_factor(s, 35.0 * un.cm**2)

SI.set_quantity_dimension(h1, length)
SI.set_quantity_scale_factor(h1, 2.4 * un.meters)

SI.set_quantity_dimension(h2, length)
SI.set_quantity_scale_factor(h2, 4.8 * un.meters)

SI.set_quantity_dimension(g, acceleration)
SI.set_quantity_scale_factor(g, 9.81 * un.m / un.s**2)

SI.set_quantity_dimension(etha, One)
SI.set_quantity_scale_factor(etha, 0.6)

SI.set_quantity_dimension(theta, One)
SI.set_quantity_scale_factor(theta, 30 * un.degrees)

eq1 = Eq(etha * Wo, rho * s * v * g * h1 + rho * s * v * v**2 / 2)
eq2 = Eq(v**2, 8 * g * h2)
# eq2 = Eq((v * sin(theta))**2, 2*g*h2)

pretty_print(eq1)
pretty_print(eq2)

res = solve((eq1, eq2), (v, Wo))[1][1]

pretty_print(res)
pretty_print(convert_to(res, un.watts).n())
Example #27
0
def check_unit_compatibility(rhs_units, lhs_units):
    try:
        assert sympy_units.convert_to(rhs_units + lhs_units, lhs_units)
    except:
        raise NameError('incompatible units:{} and {}'.format(
            lhs_units, rhs_units))
Example #28
0
 def set_epsilon(self, epsilon):
     self.epsilon = u.convert_to(epsilon, sp.numbers.Integer(1))
     self.sigma = u.convert_to(self.val*self.epsilon, self.dim)
     return self
Example #29
0
moments_of_inertia_slices = 8 / 15 * np.pi * moments_of_inertia_slices
pretty_print(moments_of_inertia_slices)

# sum slices up:
I_m5_g_per_cm3 = np.sum(moments_of_inertia_slices)
print('I_ns = {} m^5*g/cm^3'.format(I_m5_g_per_cm3))

# Moment of inertia of the Earth relative to NS axis
I_ns = get_quantity(
    Quantity("I_ns"),
    un.mass * un.length ** 2,
    I_m5_g_per_cm3 * un.m ** 5 * un.gram / un.cm ** 3
)

print("a)")
pretty_print(Eq(Symbol("I_ns"), convert_to(I_ns, un.kg * un.m ** 2).n()))

print("b)")
# angular speed of the Earth, rad/s:
omega = get_quantity(
    Quantity("omega"),
    np.angle / un.time, 2 * np.pi / (24 * 3600) * un.radians / un.second
)

# angular momentum of the Earth:
L = I_ns * omega
pretty_print(
    Eq(symbols("L"),
       convert_to(L, un.kg * un.m ** 2 / un.s).n())
)
Example #30
0
# %%
print(resultados['op'])

# %% [markdown]
# Los cantidades `V1`, `V2` y `V3` hacen referencia a los distintos valores del potencial que se ha perdido en cada uno de los bornes que has elegido para describir el netlist (`1`, `2`, etc.). Por ejemplo, podemos calcular el *potencial consumido* por la resistencia `R1` y verás que coincide con el del punto `V2` devuelto por Ahkab. **Ejercicio**: compruébalo tú mismo y refléjalo por escrito.
# %% [markdown]
# Cargamos primero todo lo relacionado con Sympy:

# %%


# %%
r1 = 3E3*ohms
intensidad_ahkab = resultados['op']['I(V1)'][0][0]*amperes
v2 = convert_to(intensidad_ahkab*r1, [volts])
v2

# %% [markdown]
#  > **Pregunta**: reproduce el resto de los valores anteriores de manera *manual* mediante Sympy (es decir, aplicando la ley de Ohm, pero con un *toque computacional*). Te pongo aquí un ejemplo del que puedes partir… En él sólo calculo la corriente que circula por el circuito (sí, justo la que antes Ahkab ha devuelto de manera automática). Para ello necesito previamente computar la resistencia total (`r_total`). Faltarían el resto de resultados y convertirlos a unidades más *vistosas* (mediante la orden `convert_to` y `.n()`).

# %%
v1 = 9*volts
r1 = 3*kilo*ohms
r2 = 10*kilo*ohms
r3 = 5*kilo*ohms
r_total = r1 + r2 + r3
intensidad = symbols('i')
ley_ohm = Eq(v1, intensidad*r_total)
solucion_para_intensidad = solve(ley_ohm, intensidad)
convert_to(solucion_para_intensidad[0], [amperes]).n(2)
Example #31
0
def test_issue_quart():
    assert convert_to(4 * quart / inch ** 3, meter) == 231
    assert convert_to(4 * quart / inch ** 3, millimeter) == 231
Example #32
0
from sympy import symbols, solve, Eq, pretty_print
from sympy.physics.units import Quantity, mass, acceleration, power, velocity
from sympy.physics.units import convert_to
from sympy.physics.units import kilo
from sympy.physics.units import km, hour, m, s, kg, W
from sympy.physics.units.systems import SI

a = symbols("a")
m_ = Quantity("m")
v = Quantity("v")
W_ = Quantity("W")

SI.set_quantity_dimension(a, acceleration)

SI.set_quantity_dimension(m_, mass)
SI.set_quantity_scale_factor(m_, 1000*kg)

SI.set_quantity_dimension(v, velocity)
SI.set_quantity_scale_factor(v, 60*km/hour)

SI.set_quantity_dimension(W_, power)
SI.set_quantity_scale_factor(W_, 120*kilo*W)

eq = Eq(W_, m_*a*v)
result = solve(eq, a)[0]
pretty_print(result)

pretty_print(convert_to(result, m / s ** 2).n())


Example #33
0
 def set_sigma(self, sigma):
     self.sigma = u.convert_to(sigma, self.dim)
     self.epsilon = u.convert_to(self.sigma/self.val, sp.numbers.Integer(1))
     return self
Example #34
0
 def __init__(self, P, T, m, MW):
     self.P = np.array(convert_to(P, U.pa).args[0], dtype=np.float32)
     self.T = np.array(convert_to(T, U.K).args[0], dtype=np.float32)
     self.m = np.array(convert_to(m, U.kg / U.s).args[0], dtype=np.float32)
     self.MW = np.array(convert_to(MW, U.kg / U.mol).args[0],
                        dtype=np.float32)