hash
stringlengths 64
64
| content
stringlengths 0
1.51M
|
---|---|
f34f1151dec6ef3b26841d50823dc8d60287a3889a9f09585648fc57f03f86a5 | from sympy.core.backend import Symbol, symbols
from sympy.physics.vector import Point, ReferenceFrame
from sympy.physics.mechanics import inertia, Body
from sympy.testing.pytest import raises
def test_default():
body = Body('body')
assert body.name == 'body'
assert body.loads == []
point = Point('body_masscenter')
point.set_vel(body.frame, 0)
com = body.masscenter
frame = body.frame
assert com.vel(frame) == point.vel(frame)
assert body.mass == Symbol('body_mass')
ixx, iyy, izz = symbols('body_ixx body_iyy body_izz')
ixy, iyz, izx = symbols('body_ixy body_iyz body_izx')
assert body.inertia == (inertia(body.frame, ixx, iyy, izz, ixy, iyz, izx),
body.masscenter)
def test_custom_rigid_body():
# Body with RigidBody.
rigidbody_masscenter = Point('rigidbody_masscenter')
rigidbody_mass = Symbol('rigidbody_mass')
rigidbody_frame = ReferenceFrame('rigidbody_frame')
body_inertia = inertia(rigidbody_frame, 1, 0, 0)
rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
rigidbody_frame, body_inertia)
com = rigid_body.masscenter
frame = rigid_body.frame
rigidbody_masscenter.set_vel(rigidbody_frame, 0)
assert com.vel(frame) == rigidbody_masscenter.vel(frame)
assert com.pos_from(com) == rigidbody_masscenter.pos_from(com)
assert rigid_body.mass == rigidbody_mass
assert rigid_body.inertia == (body_inertia, rigidbody_masscenter)
assert hasattr(rigid_body, 'masscenter')
assert hasattr(rigid_body, 'mass')
assert hasattr(rigid_body, 'frame')
assert hasattr(rigid_body, 'inertia')
def test_particle_body():
# Body with Particle
particle_masscenter = Point('particle_masscenter')
particle_mass = Symbol('particle_mass')
particle_frame = ReferenceFrame('particle_frame')
particle_body = Body('particle_body', particle_masscenter, particle_mass,
particle_frame)
com = particle_body.masscenter
frame = particle_body.frame
particle_masscenter.set_vel(particle_frame, 0)
assert com.vel(frame) == particle_masscenter.vel(frame)
assert com.pos_from(com) == particle_masscenter.pos_from(com)
assert particle_body.mass == particle_mass
assert not hasattr(particle_body, "_inertia")
assert hasattr(particle_body, 'frame')
assert hasattr(particle_body, 'masscenter')
assert hasattr(particle_body, 'mass')
def test_particle_body_add_force():
# Body with Particle
particle_masscenter = Point('particle_masscenter')
particle_mass = Symbol('particle_mass')
particle_frame = ReferenceFrame('particle_frame')
particle_body = Body('particle_body', particle_masscenter, particle_mass,
particle_frame)
a = Symbol('a')
force_vector = a * particle_body.frame.x
particle_body.apply_force(force_vector, particle_body.masscenter)
assert len(particle_body.loads) == 1
point = particle_body.masscenter.locatenew(
particle_body._name + '_point0', 0)
point.set_vel(particle_body.frame, 0)
force_point = particle_body.loads[0][0]
frame = particle_body.frame
assert force_point.vel(frame) == point.vel(frame)
assert force_point.pos_from(force_point) == point.pos_from(force_point)
assert particle_body.loads[0][1] == force_vector
def test_body_add_force():
# Body with RigidBody.
rigidbody_masscenter = Point('rigidbody_masscenter')
rigidbody_mass = Symbol('rigidbody_mass')
rigidbody_frame = ReferenceFrame('rigidbody_frame')
body_inertia = inertia(rigidbody_frame, 1, 0, 0)
rigid_body = Body('rigidbody_body', rigidbody_masscenter, rigidbody_mass,
rigidbody_frame, body_inertia)
l = Symbol('l')
Fa = Symbol('Fa')
point = rigid_body.masscenter.locatenew(
'rigidbody_body_point0',
l * rigid_body.frame.x)
point.set_vel(rigid_body.frame, 0)
force_vector = Fa * rigid_body.frame.z
# apply_force with point
rigid_body.apply_force(force_vector, point)
assert len(rigid_body.loads) == 1
force_point = rigid_body.loads[0][0]
frame = rigid_body.frame
assert force_point.vel(frame) == point.vel(frame)
assert force_point.pos_from(force_point) == point.pos_from(force_point)
assert rigid_body.loads[0][1] == force_vector
# apply_force without point
rigid_body.apply_force(force_vector)
assert len(rigid_body.loads) == 2
assert rigid_body.loads[1][1] == force_vector
# passing something else than point
raises(TypeError, lambda: rigid_body.apply_force(force_vector, 0))
raises(TypeError, lambda: rigid_body.apply_force(0))
def test_body_add_torque():
body = Body('body')
torque_vector = body.frame.x
body.apply_torque(torque_vector)
assert len(body.loads) == 1
assert body.loads[0] == (body.frame, torque_vector)
raises(TypeError, lambda: body.apply_torque(0))
|
f406364d2941f0b94e92392c9d9b59189390b046f6d65cf837fcd3ffb5b9df5d | from sympy.physics.units import Dimension
angle = Dimension(name="angle") # type: Dimension
# base dimensions (MKS)
length = Dimension(name="length", symbol="L")
mass = Dimension(name="mass", symbol="M")
time = Dimension(name="time", symbol="T")
# base dimensions (MKSA not in MKS)
current = Dimension(name='current', symbol='I') # type: Dimension
# other base dimensions:
temperature = Dimension("temperature", "T") # type: Dimension
amount_of_substance = Dimension("amount_of_substance") # type: Dimension
luminous_intensity = Dimension("luminous_intensity") # type: Dimension
# derived dimensions (MKS)
velocity = Dimension(name="velocity")
acceleration = Dimension(name="acceleration")
momentum = Dimension(name="momentum")
force = Dimension(name="force", symbol="F")
energy = Dimension(name="energy", symbol="E")
power = Dimension(name="power")
pressure = Dimension(name="pressure")
frequency = Dimension(name="frequency", symbol="f")
action = Dimension(name="action", symbol="A")
volume = Dimension("volume")
# derived dimensions (MKSA not in MKS)
voltage = Dimension(name='voltage', symbol='U') # type: Dimension
impedance = Dimension(name='impedance', symbol='Z') # type: Dimension
conductance = Dimension(name='conductance', symbol='G') # type: Dimension
capacitance = Dimension(name='capacitance') # type: Dimension
inductance = Dimension(name='inductance') # type: Dimension
charge = Dimension(name='charge', symbol='Q') # type: Dimension
magnetic_density = Dimension(name='magnetic_density', symbol='B') # type: Dimension
magnetic_flux = Dimension(name='magnetic_flux') # type: Dimension
# Dimensions in information theory:
information = Dimension(name='information') # type: Dimension
|
1a6381a684c4e9e85d2c38558462a4ec0586932b346c36a4b28035b8748bef81 | from sympy.physics.units.definitions.dimension_definitions import current, temperature, amount_of_substance, \
luminous_intensity, angle, charge, voltage, impedance, conductance, capacitance, inductance, magnetic_density, \
magnetic_flux, information
from sympy import Rational, pi, S as S_singleton
from sympy.physics.units.prefixes import kilo, milli, micro, deci, centi, nano, pico, kibi, mebi, gibi, tebi, pebi, exbi
from sympy.physics.units.quantities import Quantity
One = S_singleton.One
#### UNITS ####
# Dimensionless:
percent = percents = Quantity("percent", latex_repr=r"\%")
percent.set_global_relative_scale_factor(Rational(1, 100), One)
permille = Quantity("permille")
permille.set_global_relative_scale_factor(Rational(1, 1000), One)
# Angular units (dimensionless)
rad = radian = radians = Quantity("radian", abbrev="rad")
radian.set_global_dimension(angle)
deg = degree = degrees = Quantity("degree", abbrev="deg", latex_repr=r"^\circ")
degree.set_global_relative_scale_factor(pi/180, radian)
sr = steradian = steradians = Quantity("steradian", abbrev="sr")
mil = angular_mil = angular_mils = Quantity("angular_mil", abbrev="mil")
# Base units:
m = meter = meters = Quantity("meter", abbrev="m")
# gram; used to define its prefixed units
g = gram = grams = Quantity("gram", abbrev="g")
# NOTE: the `kilogram` has scale factor 1000. In SI, kg is a base unit, but
# nonetheless we are trying to be compatible with the `kilo` prefix. In a
# similar manner, people using CGS or gaussian units could argue that the
# `centimeter` rather than `meter` is the fundamental unit for length, but the
# scale factor of `centimeter` will be kept as 1/100 to be compatible with the
# `centi` prefix. The current state of the code assumes SI unit dimensions, in
# the future this module will be modified in order to be unit system-neutral
# (that is, support all kinds of unit systems).
kg = kilogram = kilograms = Quantity("kilogram", abbrev="kg")
kg.set_global_relative_scale_factor(kilo, gram)
s = second = seconds = Quantity("second", abbrev="s")
A = ampere = amperes = Quantity("ampere", abbrev='A')
ampere.set_global_dimension(current)
K = kelvin = kelvins = Quantity("kelvin", abbrev='K')
kelvin.set_global_dimension(temperature)
mol = mole = moles = Quantity("mole", abbrev="mol")
mole.set_global_dimension(amount_of_substance)
cd = candela = candelas = Quantity("candela", abbrev="cd")
candela.set_global_dimension(luminous_intensity)
mg = milligram = milligrams = Quantity("milligram", abbrev="mg")
mg.set_global_relative_scale_factor(milli, gram)
ug = microgram = micrograms = Quantity("microgram", abbrev="ug", latex_repr=r"\mu\text{g}")
ug.set_global_relative_scale_factor(micro, gram)
# derived units
newton = newtons = N = Quantity("newton", abbrev="N")
joule = joules = J = Quantity("joule", abbrev="J")
watt = watts = W = Quantity("watt", abbrev="W")
pascal = pascals = Pa = pa = Quantity("pascal", abbrev="Pa")
hertz = hz = Hz = Quantity("hertz", abbrev="Hz")
# CGS derived units:
dyne = Quantity("dyne")
dyne.set_global_relative_scale_factor(One/10**5, newton)
erg = Quantity("erg")
erg.set_global_relative_scale_factor(One/10**7, joule)
# MKSA extension to MKS: derived units
coulomb = coulombs = C = Quantity("coulomb", abbrev='C')
coulomb.set_global_dimension(charge)
volt = volts = v = V = Quantity("volt", abbrev='V')
volt.set_global_dimension(voltage)
ohm = ohms = Quantity("ohm", abbrev='ohm', latex_repr=r"\Omega")
ohm.set_global_dimension(impedance)
siemens = S = mho = mhos = Quantity("siemens", abbrev='S')
siemens.set_global_dimension(conductance)
farad = farads = F = Quantity("farad", abbrev='F')
farad.set_global_dimension(capacitance)
henry = henrys = H = Quantity("henry", abbrev='H')
henry.set_global_dimension(inductance)
tesla = teslas = T = Quantity("tesla", abbrev='T')
tesla.set_global_dimension(magnetic_density)
weber = webers = Wb = wb = Quantity("weber", abbrev='Wb')
weber.set_global_dimension(magnetic_flux)
# CGS units for electromagnetic quantities:
statampere = Quantity("statampere")
statcoulomb = statC = franklin = Quantity("statcoulomb", abbrev="statC")
statvolt = Quantity("statvolt")
gauss = Quantity("gauss")
maxwell = Quantity("maxwell")
debye = Quantity("debye")
oersted = Quantity("oersted")
# Other derived units:
optical_power = dioptre = diopter = D = Quantity("dioptre")
lux = lx = Quantity("lux", abbrev="lx")
# katal is the SI unit of catalytic activity
katal = kat = Quantity("katal", abbrev="kat")
# gray is the SI unit of absorbed dose
gray = Gy = Quantity("gray")
# becquerel is the SI unit of radioactivity
becquerel = Bq = Quantity("becquerel", abbrev="Bq")
# Common length units
km = kilometer = kilometers = Quantity("kilometer", abbrev="km")
km.set_global_relative_scale_factor(kilo, meter)
dm = decimeter = decimeters = Quantity("decimeter", abbrev="dm")
dm.set_global_relative_scale_factor(deci, meter)
cm = centimeter = centimeters = Quantity("centimeter", abbrev="cm")
cm.set_global_relative_scale_factor(centi, meter)
mm = millimeter = millimeters = Quantity("millimeter", abbrev="mm")
mm.set_global_relative_scale_factor(milli, meter)
um = micrometer = micrometers = micron = microns = \
Quantity("micrometer", abbrev="um", latex_repr=r'\mu\text{m}')
um.set_global_relative_scale_factor(micro, meter)
nm = nanometer = nanometers = Quantity("nanometer", abbrev="nm")
nm.set_global_relative_scale_factor(nano, meter)
pm = picometer = picometers = Quantity("picometer", abbrev="pm")
pm.set_global_relative_scale_factor(pico, meter)
ft = foot = feet = Quantity("foot", abbrev="ft")
ft.set_global_relative_scale_factor(Rational(3048, 10000), meter)
inch = inches = Quantity("inch")
inch.set_global_relative_scale_factor(Rational(1, 12), foot)
yd = yard = yards = Quantity("yard", abbrev="yd")
yd.set_global_relative_scale_factor(3, feet)
mi = mile = miles = Quantity("mile")
mi.set_global_relative_scale_factor(5280, feet)
nmi = nautical_mile = nautical_miles = Quantity("nautical_mile")
nmi.set_global_relative_scale_factor(6076, feet)
# Common volume and area units
l = liter = liters = Quantity("liter")
dl = deciliter = deciliters = Quantity("deciliter")
dl.set_global_relative_scale_factor(Rational(1, 10), liter)
cl = centiliter = centiliters = Quantity("centiliter")
cl.set_global_relative_scale_factor(Rational(1, 100), liter)
ml = milliliter = milliliters = Quantity("milliliter")
ml.set_global_relative_scale_factor(Rational(1, 1000), liter)
# Common time units
ms = millisecond = milliseconds = Quantity("millisecond", abbrev="ms")
millisecond.set_global_relative_scale_factor(milli, second)
us = microsecond = microseconds = Quantity("microsecond", abbrev="us", latex_repr=r'\mu\text{s}')
microsecond.set_global_relative_scale_factor(micro, second)
ns = nanosecond = nanoseconds = Quantity("nanosecond", abbrev="ns")
nanosecond.set_global_relative_scale_factor(nano, second)
ps = picosecond = picoseconds = Quantity("picosecond", abbrev="ps")
picosecond.set_global_relative_scale_factor(pico, second)
minute = minutes = Quantity("minute")
minute.set_global_relative_scale_factor(60, second)
h = hour = hours = Quantity("hour")
hour.set_global_relative_scale_factor(60, minute)
day = days = Quantity("day")
day.set_global_relative_scale_factor(24, hour)
anomalistic_year = anomalistic_years = Quantity("anomalistic_year")
anomalistic_year.set_global_relative_scale_factor(365.259636, day)
sidereal_year = sidereal_years = Quantity("sidereal_year")
sidereal_year.set_global_relative_scale_factor(31558149.540, seconds)
tropical_year = tropical_years = Quantity("tropical_year")
tropical_year.set_global_relative_scale_factor(365.24219, day)
common_year = common_years = Quantity("common_year")
common_year.set_global_relative_scale_factor(365, day)
julian_year = julian_years = Quantity("julian_year")
julian_year.set_global_relative_scale_factor((365 + One/4), day)
draconic_year = draconic_years = Quantity("draconic_year")
draconic_year.set_global_relative_scale_factor(346.62, day)
gaussian_year = gaussian_years = Quantity("gaussian_year")
gaussian_year.set_global_relative_scale_factor(365.2568983, day)
full_moon_cycle = full_moon_cycles = Quantity("full_moon_cycle")
full_moon_cycle.set_global_relative_scale_factor(411.78443029, day)
year = years = tropical_year
#### CONSTANTS ####
# Newton constant
G = gravitational_constant = Quantity("gravitational_constant", abbrev="G")
# speed of light
c = speed_of_light = Quantity("speed_of_light", abbrev="c")
# elementary charge
elementary_charge = Quantity("elementary_charge", abbrev="e")
# Planck constant
planck = Quantity("planck", abbrev="h")
# Reduced Planck constant
hbar = Quantity("hbar", abbrev="hbar")
# Electronvolt
eV = electronvolt = electronvolts = Quantity("electronvolt", abbrev="eV")
# Avogadro number
avogadro_number = Quantity("avogadro_number")
# Avogadro constant
avogadro = avogadro_constant = Quantity("avogadro_constant")
# Boltzmann constant
boltzmann = boltzmann_constant = Quantity("boltzmann_constant")
# Stefan-Boltzmann constant
stefan = stefan_boltzmann_constant = Quantity("stefan_boltzmann_constant")
# Atomic mass
amu = amus = atomic_mass_unit = atomic_mass_constant = Quantity("atomic_mass_constant")
# Molar gas constant
R = molar_gas_constant = Quantity("molar_gas_constant", abbrev="R")
# Faraday constant
faraday_constant = Quantity("faraday_constant")
# Josephson constant
josephson_constant = Quantity("josephson_constant", abbrev="K_j")
# Von Klitzing constant
von_klitzing_constant = Quantity("von_klitzing_constant", abbrev="R_k")
# Acceleration due to gravity (on the Earth surface)
gee = gees = acceleration_due_to_gravity = Quantity("acceleration_due_to_gravity", abbrev="g")
# magnetic constant:
u0 = magnetic_constant = vacuum_permeability = Quantity("magnetic_constant")
# electric constat:
e0 = electric_constant = vacuum_permittivity = Quantity("vacuum_permittivity")
# vacuum impedance:
Z0 = vacuum_impedance = Quantity("vacuum_impedance", abbrev='Z_0', latex_repr=r'Z_{0}')
# Coulomb's constant:
coulomb_constant = coulombs_constant = electric_force_constant = \
Quantity("coulomb_constant", abbrev="k_e")
atmosphere = atmospheres = atm = Quantity("atmosphere", abbrev="atm")
kPa = kilopascal = Quantity("kilopascal", abbrev="kPa")
kilopascal.set_global_relative_scale_factor(kilo, Pa)
bar = bars = Quantity("bar", abbrev="bar")
pound = pounds = Quantity("pound") # exact
psi = Quantity("psi")
dHg0 = 13.5951 # approx value at 0 C
mmHg = torr = Quantity("mmHg")
atmosphere.set_global_relative_scale_factor(101325, pascal)
bar.set_global_relative_scale_factor(100, kPa)
pound.set_global_relative_scale_factor(Rational(45359237, 100000000), kg)
mmu = mmus = milli_mass_unit = Quantity("milli_mass_unit")
quart = quarts = Quantity("quart")
# Other convenient units and magnitudes
ly = lightyear = lightyears = Quantity("lightyear", abbrev="ly")
au = astronomical_unit = astronomical_units = Quantity("astronomical_unit", abbrev="AU")
# Fundamental Planck units:
planck_mass = Quantity("planck_mass", abbrev="m_P", latex_repr=r'm_\text{P}')
planck_time = Quantity("planck_time", abbrev="t_P", latex_repr=r't_\text{P}')
planck_temperature = Quantity("planck_temperature", abbrev="T_P",
latex_repr=r'T_\text{P}')
planck_length = Quantity("planck_length", abbrev="l_P", latex_repr=r'l_\text{P}')
planck_charge = Quantity("planck_charge", abbrev="q_P", latex_repr=r'q_\text{P}')
# Derived Planck units:
planck_area = Quantity("planck_area")
planck_volume = Quantity("planck_volume")
planck_momentum = Quantity("planck_momentum")
planck_energy = Quantity("planck_energy", abbrev="E_P", latex_repr=r'E_\text{P}')
planck_force = Quantity("planck_force", abbrev="F_P", latex_repr=r'F_\text{P}')
planck_power = Quantity("planck_power", abbrev="P_P", latex_repr=r'P_\text{P}')
planck_density = Quantity("planck_density", abbrev="rho_P", latex_repr=r'\rho_\text{P}')
planck_energy_density = Quantity("planck_energy_density", abbrev="rho^E_P")
planck_intensity = Quantity("planck_intensity", abbrev="I_P", latex_repr=r'I_\text{P}')
planck_angular_frequency = Quantity("planck_angular_frequency", abbrev="omega_P",
latex_repr=r'\omega_\text{P}')
planck_pressure = Quantity("planck_pressure", abbrev="p_P", latex_repr=r'p_\text{P}')
planck_current = Quantity("planck_current", abbrev="I_P", latex_repr=r'I_\text{P}')
planck_voltage = Quantity("planck_voltage", abbrev="V_P", latex_repr=r'V_\text{P}')
planck_impedance = Quantity("planck_impedance", abbrev="Z_P", latex_repr=r'Z_\text{P}')
planck_acceleration = Quantity("planck_acceleration", abbrev="a_P",
latex_repr=r'a_\text{P}')
# Information theory units:
bit = bits = Quantity("bit")
bit.set_global_dimension(information)
byte = bytes = Quantity("byte")
kibibyte = kibibytes = Quantity("kibibyte")
mebibyte = mebibytes = Quantity("mebibyte")
gibibyte = gibibytes = Quantity("gibibyte")
tebibyte = tebibytes = Quantity("tebibyte")
pebibyte = pebibytes = Quantity("pebibyte")
exbibyte = exbibytes = Quantity("exbibyte")
byte.set_global_relative_scale_factor(8, bit)
kibibyte.set_global_relative_scale_factor(kibi, byte)
mebibyte.set_global_relative_scale_factor(mebi, byte)
gibibyte.set_global_relative_scale_factor(gibi, byte)
tebibyte.set_global_relative_scale_factor(tebi, byte)
pebibyte.set_global_relative_scale_factor(pebi, byte)
exbibyte.set_global_relative_scale_factor(exbi, byte)
# Older units for radioactivity
curie = Ci = Quantity("curie", abbrev="Ci")
rutherford = Rd = Quantity("rutherford", abbrev="Rd")
|
ec9b565fb63bd1f4a7e49aca3d475fee03f69c0e7e6ad48ae8d27691d7ae60e8 | """
MKS unit system.
MKS stands for "meter, kilogram, second, ampere".
"""
from __future__ import division
from typing import List
from sympy.physics.units.definitions import Z0, A, C, F, H, S, T, V, Wb, ohm
from sympy.physics.units.definitions.dimension_definitions import (
capacitance, charge, conductance, current, impedance, inductance,
magnetic_density, magnetic_flux, voltage)
from sympy.physics.units.prefixes import PREFIXES, prefix_unit
from sympy.physics.units.systems.mks import MKS, dimsys_length_weight_time
from sympy.physics.units.quantities import Quantity
dims = (voltage, impedance, conductance, current, capacitance, inductance, charge,
magnetic_density, magnetic_flux)
units = [A, V, ohm, S, F, H, C, T, Wb]
all_units = [] # type: List[Quantity]
for u in units:
all_units.extend(prefix_unit(u, PREFIXES))
all_units.extend([Z0])
dimsys_MKSA = dimsys_length_weight_time.extend([
# Dimensional dependencies for base dimensions (MKSA not in MKS)
current,
], new_dim_deps=dict(
# Dimensional dependencies for derived dimensions
voltage=dict(mass=1, length=2, current=-1, time=-3),
impedance=dict(mass=1, length=2, current=-2, time=-3),
conductance=dict(mass=-1, length=-2, current=2, time=3),
capacitance=dict(mass=-1, length=-2, current=2, time=4),
inductance=dict(mass=1, length=2, current=-2, time=-2),
charge=dict(current=1, time=1),
magnetic_density=dict(mass=1, current=-1, time=-2),
magnetic_flux=dict(length=2, mass=1, current=-1, time=-2),
))
MKSA = MKS.extend(base=(A,), units=all_units, name='MKSA', dimension_system=dimsys_MKSA)
|
9bb0165f90ecc75a89bc93124b2b55185bbb2acfe23d92a4f3f71e07aa280c05 | """
SI unit system.
Based on MKSA, which stands for "meter, kilogram, second, ampere".
Added kelvin, candela and mole.
"""
from __future__ import division
from typing import List
from sympy.physics.units import DimensionSystem, Dimension, dHg0
from sympy.physics.units.quantities import Quantity
from sympy import Rational, pi, sqrt, S
from sympy.physics.units.definitions.dimension_definitions import (
acceleration, action, current, impedance, length, mass, time, velocity,
amount_of_substance, temperature, information, frequency, force, pressure,
energy, power, charge, voltage, capacitance, conductance, magnetic_flux,
magnetic_density, inductance, luminous_intensity
)
from sympy.physics.units.definitions import (
kilogram, newton, second, meter, gram, cd, K, joule, watt, pascal, hertz,
coulomb, volt, ohm, siemens, farad, henry, tesla, weber, dioptre, lux,
katal, gray, becquerel, inch, liter, julian_year, gravitational_constant,
speed_of_light, elementary_charge, planck, hbar, electronvolt,
avogadro_number, avogadro_constant, boltzmann_constant,
stefan_boltzmann_constant, atomic_mass_constant, molar_gas_constant,
faraday_constant, josephson_constant, von_klitzing_constant,
acceleration_due_to_gravity, magnetic_constant, vacuum_permittivity,
vacuum_impedance, coulomb_constant, atmosphere, bar, pound, psi, mmHg,
milli_mass_unit, quart, lightyear, astronomical_unit, planck_mass,
planck_time, planck_temperature, planck_length, planck_charge, planck_area,
planck_volume, planck_momentum, planck_energy, planck_force, planck_power,
planck_density, planck_energy_density, planck_intensity,
planck_angular_frequency, planck_pressure, planck_current, planck_voltage,
planck_impedance, planck_acceleration, bit, byte, kibibyte, mebibyte,
gibibyte, tebibyte, pebibyte, exbibyte, curie, rutherford, radian, degree,
steradian, angular_mil, atomic_mass_unit, gee, kPa, ampere, u0, c, kelvin,
mol, mole, candela, m, kg, s, electric_constant, G, boltzmann
)
from sympy.physics.units.prefixes import PREFIXES, prefix_unit
from sympy.physics.units.systems.mksa import MKSA, dimsys_MKSA
derived_dims = (frequency, force, pressure, energy, power, charge, voltage,
capacitance, conductance, magnetic_flux,
magnetic_density, inductance, luminous_intensity)
base_dims = (amount_of_substance, luminous_intensity, temperature)
units = [mol, cd, K, lux, hertz, newton, pascal, joule, watt, coulomb, volt,
farad, ohm, siemens, weber, tesla, henry, candela, lux, becquerel,
gray, katal]
all_units = [] # type: List[Quantity]
for u in units:
all_units.extend(prefix_unit(u, PREFIXES))
all_units.extend([mol, cd, K, lux])
dimsys_SI = dimsys_MKSA.extend(
[
# Dimensional dependencies for other base dimensions:
temperature,
amount_of_substance,
luminous_intensity,
])
dimsys_default = dimsys_SI.extend(
[information],
)
SI = MKSA.extend(base=(mol, cd, K), units=all_units, name='SI', dimension_system=dimsys_SI)
One = S.One
SI.set_quantity_dimension(radian, One)
SI.set_quantity_scale_factor(ampere, One)
SI.set_quantity_scale_factor(kelvin, One)
SI.set_quantity_scale_factor(mole, One)
SI.set_quantity_scale_factor(candela, One)
# MKSA extension to MKS: derived units
SI.set_quantity_scale_factor(coulomb, One)
SI.set_quantity_scale_factor(volt, joule/coulomb)
SI.set_quantity_scale_factor(ohm, volt/ampere)
SI.set_quantity_scale_factor(siemens, ampere/volt)
SI.set_quantity_scale_factor(farad, coulomb/volt)
SI.set_quantity_scale_factor(henry, volt*second/ampere)
SI.set_quantity_scale_factor(tesla, volt*second/meter**2)
SI.set_quantity_scale_factor(weber, joule/ampere)
SI.set_quantity_dimension(lux, luminous_intensity / length ** 2)
SI.set_quantity_scale_factor(lux, steradian*candela/meter**2)
# katal is the SI unit of catalytic activity
SI.set_quantity_dimension(katal, amount_of_substance / time)
SI.set_quantity_scale_factor(katal, mol/second)
# gray is the SI unit of absorbed dose
SI.set_quantity_dimension(gray, energy / mass)
SI.set_quantity_scale_factor(gray, meter**2/second**2)
# becquerel is the SI unit of radioactivity
SI.set_quantity_dimension(becquerel, 1 / time)
SI.set_quantity_scale_factor(becquerel, 1/second)
#### CONSTANTS ####
# elementary charge
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(elementary_charge, charge)
SI.set_quantity_scale_factor(elementary_charge, 1.602176634e-19*coulomb)
# Electronvolt
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(electronvolt, energy)
SI.set_quantity_scale_factor(electronvolt, 1.602176634e-19*joule)
# Avogadro number
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(avogadro_number, One)
SI.set_quantity_scale_factor(avogadro_number, 6.02214076e23)
# Avogadro constant
SI.set_quantity_dimension(avogadro_constant, amount_of_substance ** -1)
SI.set_quantity_scale_factor(avogadro_constant, avogadro_number / mol)
# Boltzmann constant
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(boltzmann_constant, energy / temperature)
SI.set_quantity_scale_factor(boltzmann_constant, 1.380649e-23*joule/kelvin)
# Stefan-Boltzmann constant
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(stefan_boltzmann_constant, energy * time ** -1 * length ** -2 * temperature ** -4)
SI.set_quantity_scale_factor(stefan_boltzmann_constant, pi**2 * boltzmann_constant**4 / (60 * hbar**3 * speed_of_light ** 2))
# Atomic mass
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(atomic_mass_constant, mass)
SI.set_quantity_scale_factor(atomic_mass_constant, 1.66053906660e-24*gram)
# Molar gas constant
# REF: NIST SP 959 (June 2019)
SI.set_quantity_dimension(molar_gas_constant, energy / (temperature * amount_of_substance))
SI.set_quantity_scale_factor(molar_gas_constant, boltzmann_constant * avogadro_constant)
# Faraday constant
SI.set_quantity_dimension(faraday_constant, charge / amount_of_substance)
SI.set_quantity_scale_factor(faraday_constant, elementary_charge * avogadro_constant)
# Josephson constant
SI.set_quantity_dimension(josephson_constant, frequency / voltage)
SI.set_quantity_scale_factor(josephson_constant, 0.5 * planck / elementary_charge)
# Von Klitzing constant
SI.set_quantity_dimension(von_klitzing_constant, voltage / current)
SI.set_quantity_scale_factor(von_klitzing_constant, hbar / elementary_charge ** 2)
# Acceleration due to gravity (on the Earth surface)
SI.set_quantity_dimension(acceleration_due_to_gravity, acceleration)
SI.set_quantity_scale_factor(acceleration_due_to_gravity, 9.80665*meter/second**2)
# magnetic constant:
SI.set_quantity_dimension(magnetic_constant, force / current ** 2)
SI.set_quantity_scale_factor(magnetic_constant, 4*pi/10**7 * newton/ampere**2)
# electric constant:
SI.set_quantity_dimension(vacuum_permittivity, capacitance / length)
SI.set_quantity_scale_factor(vacuum_permittivity, 1/(u0 * c**2))
# vacuum impedance:
SI.set_quantity_dimension(vacuum_impedance, impedance)
SI.set_quantity_scale_factor(vacuum_impedance, u0 * c)
# Coulomb's constant:
SI.set_quantity_dimension(coulomb_constant, force * length ** 2 / charge ** 2)
SI.set_quantity_scale_factor(coulomb_constant, 1/(4*pi*vacuum_permittivity))
SI.set_quantity_dimension(psi, pressure)
SI.set_quantity_scale_factor(psi, pound * gee / inch ** 2)
SI.set_quantity_dimension(mmHg, pressure)
SI.set_quantity_scale_factor(mmHg, dHg0 * acceleration_due_to_gravity * kilogram / meter**2)
SI.set_quantity_dimension(milli_mass_unit, mass)
SI.set_quantity_scale_factor(milli_mass_unit, atomic_mass_unit/1000)
SI.set_quantity_dimension(quart, length ** 3)
SI.set_quantity_scale_factor(quart, Rational(231, 4) * inch**3)
# Other convenient units and magnitudes
SI.set_quantity_dimension(lightyear, length)
SI.set_quantity_scale_factor(lightyear, speed_of_light*julian_year)
SI.set_quantity_dimension(astronomical_unit, length)
SI.set_quantity_scale_factor(astronomical_unit, 149597870691*meter)
# Fundamental Planck units:
SI.set_quantity_dimension(planck_mass, mass)
SI.set_quantity_scale_factor(planck_mass, sqrt(hbar*speed_of_light/G))
SI.set_quantity_dimension(planck_time, time)
SI.set_quantity_scale_factor(planck_time, sqrt(hbar*G/speed_of_light**5))
SI.set_quantity_dimension(planck_temperature, temperature)
SI.set_quantity_scale_factor(planck_temperature, sqrt(hbar*speed_of_light**5/G/boltzmann**2))
SI.set_quantity_dimension(planck_length, length)
SI.set_quantity_scale_factor(planck_length, sqrt(hbar*G/speed_of_light**3))
SI.set_quantity_dimension(planck_charge, charge)
SI.set_quantity_scale_factor(planck_charge, sqrt(4*pi*electric_constant*hbar*speed_of_light))
# Derived Planck units:
SI.set_quantity_dimension(planck_area, length ** 2)
SI.set_quantity_scale_factor(planck_area, planck_length**2)
SI.set_quantity_dimension(planck_volume, length ** 3)
SI.set_quantity_scale_factor(planck_volume, planck_length**3)
SI.set_quantity_dimension(planck_momentum, mass * velocity)
SI.set_quantity_scale_factor(planck_momentum, planck_mass * speed_of_light)
SI.set_quantity_dimension(planck_energy, energy)
SI.set_quantity_scale_factor(planck_energy, planck_mass * speed_of_light**2)
SI.set_quantity_dimension(planck_force, force)
SI.set_quantity_scale_factor(planck_force, planck_energy / planck_length)
SI.set_quantity_dimension(planck_power, power)
SI.set_quantity_scale_factor(planck_power, planck_energy / planck_time)
SI.set_quantity_dimension(planck_density, mass / length ** 3)
SI.set_quantity_scale_factor(planck_density, planck_mass / planck_length**3)
SI.set_quantity_dimension(planck_energy_density, energy / length ** 3)
SI.set_quantity_scale_factor(planck_energy_density, planck_energy / planck_length**3)
SI.set_quantity_dimension(planck_intensity, mass * time ** (-3))
SI.set_quantity_scale_factor(planck_intensity, planck_energy_density * speed_of_light)
SI.set_quantity_dimension(planck_angular_frequency, 1 / time)
SI.set_quantity_scale_factor(planck_angular_frequency, 1 / planck_time)
SI.set_quantity_dimension(planck_pressure, pressure)
SI.set_quantity_scale_factor(planck_pressure, planck_force / planck_length**2)
SI.set_quantity_dimension(planck_current, current)
SI.set_quantity_scale_factor(planck_current, planck_charge / planck_time)
SI.set_quantity_dimension(planck_voltage, voltage)
SI.set_quantity_scale_factor(planck_voltage, planck_energy / planck_charge)
SI.set_quantity_dimension(planck_impedance, impedance)
SI.set_quantity_scale_factor(planck_impedance, planck_voltage / planck_current)
SI.set_quantity_dimension(planck_acceleration, acceleration)
SI.set_quantity_scale_factor(planck_acceleration, speed_of_light / planck_time)
# Older units for radioactivity
SI.set_quantity_dimension(curie, 1 / time)
SI.set_quantity_scale_factor(curie, 37000000000*becquerel)
SI.set_quantity_dimension(rutherford, 1 / time)
SI.set_quantity_scale_factor(rutherford, 1000000*becquerel)
# check that scale factors are the right SI dimensions:
for _scale_factor, _dimension in zip(
SI._quantity_scale_factors.values(),
SI._quantity_dimension_map.values()
):
dimex = SI.get_dimensional_expr(_scale_factor)
if dimex != 1:
# XXX: equivalent_dims is an instance method taking two arguments in
# addition to self so this can not work:
if not DimensionSystem.equivalent_dims(_dimension, Dimension(dimex)): # type: ignore
raise ValueError("quantity value and dimension mismatch")
del _scale_factor, _dimension
__all__ = [
'mmHg', 'atmosphere', 'inductance', 'newton', 'meter',
'vacuum_permittivity', 'pascal', 'magnetic_constant', 'voltage',
'angular_mil', 'luminous_intensity', 'all_units',
'julian_year', 'weber', 'division', 'exbibyte', 'liter',
'molar_gas_constant', 'faraday_constant', 'avogadro_constant',
'lightyear', 'planck_density', 'gee', 'mol', 'bit', 'gray',
'planck_momentum', 'bar', 'magnetic_density', 'prefix_unit', 'PREFIXES',
'planck_time', 'dimex', 'gram', 'candela', 'force', 'planck_intensity',
'energy', 'becquerel', 'planck_acceleration', 'speed_of_light',
'conductance', 'frequency', 'coulomb_constant', 'degree', 'lux', 'planck',
'current', 'planck_current', 'tebibyte', 'planck_power', 'MKSA', 'power',
'K', 'planck_volume', 'quart', 'pressure', 'amount_of_substance',
'joule', 'boltzmann_constant', 'Dimension', 'c', 'planck_force', 'length',
'watt', 'action', 'hbar', 'gibibyte', 'DimensionSystem', 'cd', 'volt',
'planck_charge', 'dioptre', 'vacuum_impedance', 'dimsys_default', 'farad',
'charge', 'gravitational_constant', 'temperature', 'u0', 'hertz',
'capacitance', 'tesla', 'steradian', 'planck_mass', 'josephson_constant',
'planck_area', 'stefan_boltzmann_constant', 'base_dims',
'astronomical_unit', 'radian', 'planck_voltage', 'impedance',
'planck_energy', 'atomic_mass_constant', 'rutherford', 'second', 'inch',
'elementary_charge', 'SI', 'electronvolt', 'dimsys_SI', 'henry',
'planck_angular_frequency', 'ohm', 'pound', 'planck_pressure', 'G', 'psi',
'dHg0', 'von_klitzing_constant', 'planck_length', 'avogadro_number',
'mole', 'acceleration', 'information', 'planck_energy_density',
'mebibyte', 's', 'acceleration_due_to_gravity',
'planck_temperature', 'units', 'mass', 'dimsys_MKSA', 'kelvin', 'kPa',
'boltzmann', 'milli_mass_unit', 'planck_impedance', 'electric_constant',
'derived_dims', 'kg', 'coulomb', 'siemens', 'byte', 'magnetic_flux',
'atomic_mass_unit', 'm', 'kibibyte', 'kilogram', 'One', 'curie', 'u',
'time', 'pebibyte', 'velocity', 'ampere', 'katal',
]
|
2052e9da1a1f30d2126be19f5b95b2821c9cb1d5c9c6f6167207cd62c4f513c4 | from sympy import (Abs, Add, Function, Number, Rational, S, Symbol,
diff, exp, integrate, log, sin, sqrt, symbols)
from sympy.physics.units import (amount_of_substance, convert_to, find_unit,
volume, kilometer)
from sympy.physics.units.definitions import (amu, au, centimeter, coulomb,
day, foot, grams, hour, inch, kg, km, m, meter, millimeter,
minute, quart, s, second, speed_of_light, bit,
byte, kibibyte, mebibyte, gibibyte, tebibyte, pebibyte, exbibyte,
kilogram, gravitational_constant)
from sympy.physics.units.definitions.dimension_definitions import (
Dimension, charge, length, time, temperature, pressure,
energy
)
from sympy.physics.units.prefixes import PREFIXES, kilo
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.systems import SI
from sympy.testing.pytest import XFAIL, raises, warns_deprecated_sympy
k = PREFIXES["k"]
def test_str_repr():
assert str(kg) == "kilogram"
def test_eq():
# simple test
assert 10*m == 10*m
assert 10*m != 10*s
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
def test_Quantity_definition():
q = Quantity("s10", abbrev="sabbr")
q.set_global_relative_scale_factor(10, second)
u = Quantity("u", abbrev="dam")
u.set_global_relative_scale_factor(10, meter)
km = Quantity("km")
km.set_global_relative_scale_factor(kilo, meter)
v = Quantity("u")
v.set_global_relative_scale_factor(5*kilo, meter)
assert q.scale_factor == 10
assert q.dimension == time
assert q.abbrev == Symbol("sabbr")
assert u.dimension == length
assert u.scale_factor == 10
assert u.abbrev == Symbol("dam")
assert km.scale_factor == 1000
assert km.func(*km.args) == km
assert km.func(*km.args).args == km.args
assert v.dimension == length
assert v.scale_factor == 5000
with warns_deprecated_sympy():
Quantity('invalid', 'dimension', 1)
with warns_deprecated_sympy():
Quantity('mismatch', dimension=length, scale_factor=kg)
def test_abbrev():
u = Quantity("u")
u.set_global_relative_scale_factor(S.One, meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("u")
u = Quantity("u", abbrev="om")
u.set_global_relative_scale_factor(S(2), meter)
assert u.name == Symbol("u")
assert u.abbrev == Symbol("om")
assert u.scale_factor == 2
assert isinstance(u.scale_factor, Number)
u = Quantity("u", abbrev="ikm")
u.set_global_relative_scale_factor(3*kilo, meter)
assert u.abbrev == Symbol("ikm")
assert u.scale_factor == 3000
def test_print():
u = Quantity("unitname", abbrev="dam")
assert repr(u) == "unitname"
assert str(u) == "unitname"
def test_Quantity_eq():
u = Quantity("u", abbrev="dam")
v = Quantity("v1")
assert u != v
v = Quantity("v2", abbrev="ds")
assert u != v
v = Quantity("v3", abbrev="dm")
assert u != v
def test_add_sub():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
assert isinstance(u + v, Add)
assert (u + v.convert_to(u)) == (1 + S.Half)*u
# TODO: eventually add this:
# assert (u + v).convert_to(u) == (1 + S.Half)*u
assert isinstance(u - v, Add)
assert (u - v.convert_to(u)) == S.Half*u
# TODO: eventually add this:
# assert (u - v).convert_to(u) == S.Half*u
def test_quantity_abs():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w3 = Quantity('v_w3')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
v_w3.set_global_relative_scale_factor(1, meter/second)
expr = v_w3 - Abs(v_w1 - v_w2)
assert SI.get_dimensional_expr(v_w1) == (length/time).name
Dq = Dimension(SI.get_dimensional_expr(expr))
with warns_deprecated_sympy():
Dq1 = Dimension(Quantity.get_dimensional_expr(expr))
assert Dq == Dq1
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
'length': 1,
'time': -1,
}
assert meter == sqrt(meter**2)
def test_check_unit_consistency():
u = Quantity("u")
v = Quantity("v")
w = Quantity("w")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
w.set_global_relative_scale_factor(S(2), second)
def check_unit_consistency(expr):
SI._collect_factor_and_dimension(expr)
raises(ValueError, lambda: check_unit_consistency(u + w))
raises(ValueError, lambda: check_unit_consistency(u - w))
raises(ValueError, lambda: check_unit_consistency(u + 1))
raises(ValueError, lambda: check_unit_consistency(u - 1))
raises(ValueError, lambda: check_unit_consistency(1 - exp(u / w)))
def test_mul_div():
u = Quantity("u")
v = Quantity("v")
t = Quantity("t")
ut = Quantity("ut")
v2 = Quantity("v")
u.set_global_relative_scale_factor(S(10), meter)
v.set_global_relative_scale_factor(S(5), meter)
t.set_global_relative_scale_factor(S(2), second)
ut.set_global_relative_scale_factor(S(20), meter*second)
v2.set_global_relative_scale_factor(S(5), meter/second)
assert 1 / u == u**(-1)
assert u / 1 == u
v1 = u / t
v2 = v
# Pow only supports structural equality:
assert v1 != v2
assert v1 == v2.convert_to(v1)
# TODO: decide whether to allow such expression in the future
# (requires somehow manipulating the core).
# assert u / Quantity('l2', dimension=length, scale_factor=2) == 5
assert u * 1 == u
ut1 = u * t
ut2 = ut
# Mul only supports structural equality:
assert ut1 != ut2
assert ut1 == ut2.convert_to(ut1)
# Mul only supports structural equality:
lp1 = Quantity("lp1")
lp1.set_global_relative_scale_factor(S(2), 1/meter)
assert u * lp1 != 20
assert u**0 == 1
assert u**1 == u
# TODO: Pow only support structural equality:
u2 = Quantity("u2")
u3 = Quantity("u3")
u2.set_global_relative_scale_factor(S(100), meter**2)
u3.set_global_relative_scale_factor(Rational(1, 10), 1/meter)
assert u ** 2 != u2
assert u ** -1 != u3
assert u ** 2 == u2.convert_to(u)
assert u ** -1 == u3.convert_to(u)
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.simplify() == Rational(49865956897, 5995849160)
# TODO: fix this, it should give `m` without `Abs`
assert sqrt(m**2) == 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
def test_issue_quart():
assert convert_to(4 * quart / inch ** 3, meter) == 231
assert convert_to(4 * quart / inch ** 3, millimeter) == 231
def test_issue_5565():
assert (m < s).is_Relational
def test_find_unit():
assert find_unit('coulomb') == ['coulomb', 'coulombs', 'coulomb_constant']
assert find_unit(coulomb) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(charge) == ['C', 'coulomb', 'coulombs', 'planck_charge', 'elementary_charge']
assert find_unit(inch) == [
'm', 'au', 'cm', 'dm', 'ft', 'km', 'ly', 'mi', 'mm', 'nm', 'pm', 'um',
'yd', 'nmi', 'feet', 'foot', 'inch', 'mile', 'yard', 'meter', 'miles',
'yards', 'inches', 'meters', 'micron', 'microns', 'decimeter',
'kilometer', 'lightyear', 'nanometer', 'picometer', 'centimeter',
'decimeters', 'kilometers', 'lightyears', 'micrometer', 'millimeter',
'nanometers', 'picometers', 'centimeters', 'micrometers',
'millimeters', 'nautical_mile', 'planck_length', 'nautical_miles', 'astronomical_unit',
'astronomical_units']
assert find_unit(inch**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(length**-1) == ['D', 'dioptre', 'optical_power']
assert find_unit(inch ** 3) == [
'l', 'cl', 'dl', 'ml', 'liter', 'quart', 'liters', 'quarts',
'deciliter', 'centiliter', 'deciliters', 'milliliter',
'centiliters', 'milliliters', 'planck_volume']
assert find_unit('voltage') == ['V', 'v', 'volt', 'volts', 'planck_voltage']
def test_Quantity_derivative():
x = symbols("x")
assert diff(x*meter, x) == meter
assert diff(x**3*meter**2, x) == 3*x**2*meter**2
assert diff(meter, meter) == 1
assert diff(meter**2, meter) == 2*meter
def test_quantity_postprocessing():
q1 = Quantity('q1')
q2 = Quantity('q2')
SI.set_quantity_dimension(q1, length*pressure**2*temperature/time)
SI.set_quantity_dimension(q2, energy*pressure*temperature/(length**2*time))
assert q1 + q2
q = q1 + q2
Dq = Dimension(SI.get_dimensional_expr(q))
assert SI.get_dimension_system().get_dimensional_dependencies(Dq) == {
'length': -1,
'mass': 2,
'temperature': 1,
'time': -5,
}
def test_factor_and_dimension():
assert (3000, Dimension(1)) == SI._collect_factor_and_dimension(3000)
assert (1001, length) == SI._collect_factor_and_dimension(meter + km)
assert (2, length/time) == SI._collect_factor_and_dimension(
meter/second + 36*km/(10*hour))
x, y = symbols('x y')
assert (x + y/100, length) == SI._collect_factor_and_dimension(
x*m + y*centimeter)
cH = Quantity('cH')
SI.set_quantity_dimension(cH, amount_of_substance/volume)
pH = -log(cH)
assert (1, volume/amount_of_substance) == SI._collect_factor_and_dimension(
exp(pH))
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
v_w2.set_global_relative_scale_factor(2, meter/second)
expr = Abs(v_w1/2 - v_w2)
assert (Rational(5, 4), length/time) == \
SI._collect_factor_and_dimension(expr)
expr = Rational(5, 2)*second/meter*v_w1 - 3000
assert (-(2996 + Rational(1, 4)), Dimension(1)) == \
SI._collect_factor_and_dimension(expr)
expr = v_w1**(v_w2/v_w1)
assert ((Rational(3, 2))**Rational(4, 3), (length/time)**Rational(4, 3)) == \
SI._collect_factor_and_dimension(expr)
with warns_deprecated_sympy():
assert (3000, Dimension(1)) == Quantity._collect_factor_and_dimension(3000)
@XFAIL
def test_factor_and_dimension_with_Abs():
with warns_deprecated_sympy():
v_w1 = Quantity('v_w1', length/time, Rational(3, 2)*meter/second)
v_w1.set_global_relative_scale_factor(Rational(3, 2), meter/second)
expr = v_w1 - Abs(v_w1)
assert (0, length/time) == Quantity._collect_factor_and_dimension(expr)
def test_dimensional_expr_of_derivative():
l = Quantity('l')
t = Quantity('t')
t1 = Quantity('t1')
l.set_global_relative_scale_factor(36, km)
t.set_global_relative_scale_factor(1, hour)
t1.set_global_relative_scale_factor(1, second)
x = Symbol('x')
y = Symbol('y')
f = Function('f')
dfdx = f(x, y).diff(x, y)
dl_dt = dfdx.subs({f(x, y): l, x: t, y: t1})
assert SI.get_dimensional_expr(dl_dt) ==\
SI.get_dimensional_expr(l / t / t1) ==\
Symbol("length")/Symbol("time")**2
assert SI._collect_factor_and_dimension(dl_dt) ==\
SI._collect_factor_and_dimension(l / t / t1) ==\
(10, length/time**2)
def test_get_dimensional_expr_with_function():
v_w1 = Quantity('v_w1')
v_w2 = Quantity('v_w2')
v_w1.set_global_relative_scale_factor(1, meter/second)
v_w2.set_global_relative_scale_factor(1, meter/second)
assert SI.get_dimensional_expr(sin(v_w1)) == \
sin(SI.get_dimensional_expr(v_w1))
assert SI.get_dimensional_expr(sin(v_w1/v_w2)) == 1
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
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
def test_eval_subs():
energy, mass, force = symbols('energy mass force')
expr1 = energy/mass
units = {energy: kilogram*meter**2/second**2, mass: kilogram}
assert expr1.subs(units) == meter**2/second**2
expr2 = force/mass
units = {force:gravitational_constant*kilogram**2/meter**2, mass:kilogram}
assert expr2.subs(units) == gravitational_constant*kilogram/meter**2
def test_issue_14932():
assert (log(inch) - log(2)).simplify() == log(inch/2)
assert (log(inch) - log(foot)).simplify() == -log(12)
p = symbols('p', positive=True)
assert (log(inch) - log(p)).simplify() == log(inch/p)
def test_issue_14547():
# the root issue is that an argument with dimensions should
# not raise an error when the the `arg - 1` calculation is
# performed in the assumptions system
from sympy.physics.units import foot, inch
from sympy import Eq
assert log(foot).is_zero is None
assert log(foot).is_positive is None
assert log(foot).is_nonnegative is None
assert log(foot).is_negative is None
assert log(foot).is_algebraic is None
assert log(foot).is_rational is None
# doesn't raise error
assert Eq(log(foot), log(inch)) is not None # might be False or unevaluated
x = Symbol('x')
e = foot + x
assert e.is_Add and set(e.args) == {foot, x}
e = foot + 1
assert e.is_Add and set(e.args) == {foot, 1}
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
|
2227945c1731566084ede657ec1073dbbd2cd157aec7d61d54023fc2ad36514b | from sympy.physics.units import DimensionSystem, joule, second, ampere
from sympy.testing.pytest import warns_deprecated_sympy
from sympy import Rational, S
from sympy.physics.units.definitions import c, kg, m, s
from sympy.physics.units.definitions.dimension_definitions import length, time
from sympy.physics.units.quantities import Quantity
from sympy.physics.units.unitsystem import UnitSystem
def test_definition():
# want to test if the system can have several units of the same dimension
dm = Quantity("dm")
base = (m, s)
# base_dim = (m.dimension, s.dimension)
ms = UnitSystem(base, (c, dm), "MS", "MS system")
ms.set_quantity_dimension(dm, length)
ms.set_quantity_scale_factor(dm, Rational(1, 10))
assert set(ms._base_units) == set(base)
assert set(ms._units) == {m, s, c, dm}
# assert ms._units == DimensionSystem._sort_dims(base + (velocity,))
assert ms.name == "MS"
assert ms.descr == "MS system"
def test_str_repr():
assert str(UnitSystem((m, s), name="MS")) == "MS"
assert str(UnitSystem((m, s))) == "UnitSystem((meter, second))"
assert repr(UnitSystem((m, s))) == "<UnitSystem: (%s, %s)>" % (m, s)
def test_print_unit_base():
A = Quantity("A")
A.set_global_relative_scale_factor(S.One, ampere)
Js = Quantity("Js")
Js.set_global_relative_scale_factor(S.One, joule*second)
mksa = UnitSystem((m, kg, s, A), (Js,))
with warns_deprecated_sympy():
assert mksa.print_unit_base(Js) == m**2*kg*s**-1/1000
def test_extend():
ms = UnitSystem((m, s), (c,))
Js = Quantity("Js")
Js.set_global_relative_scale_factor(1, joule*second)
mks = ms.extend((kg,), (Js,))
res = UnitSystem((m, s, kg), (c, Js))
assert set(mks._base_units) == set(res._base_units)
assert set(mks._units) == set(res._units)
def test_dim():
dimsys = UnitSystem((m, kg, s), (c,))
assert dimsys.dim == 3
def test_is_consistent():
dimension_system = DimensionSystem([length, time])
us = UnitSystem([m, s], dimension_system=dimension_system)
assert us.is_consistent == True
|
c3660546bc038488ef511326109fb081c3281db36015c014dea545bab46c603c | from sympy.physics.units.systems.si import dimsys_SI
from sympy import S, Symbol, sqrt
from sympy.physics.units.dimensions import Dimension
from sympy.physics.units.definitions.dimension_definitions import (
length, time
)
from sympy.physics.units import foot
from sympy.testing.pytest import raises
def test_Dimension_definition():
assert dimsys_SI.get_dimensional_dependencies(length) == {"length": 1}
assert length.name == Symbol("length")
assert length.symbol == Symbol("L")
halflength = sqrt(length)
assert dimsys_SI.get_dimensional_dependencies(halflength) == {"length": S.Half}
def test_Dimension_error_definition():
# tuple with more or less than two entries
raises(TypeError, lambda: Dimension(("length", 1, 2)))
raises(TypeError, lambda: Dimension(["length"]))
# non-number power
raises(TypeError, lambda: Dimension({"length": "a"}))
# non-number with named argument
raises(TypeError, lambda: Dimension({"length": (1, 2)}))
# symbol should by Symbol or str
raises(AssertionError, lambda: Dimension("length", symbol=1))
def test_str():
assert str(Dimension("length")) == "Dimension(length)"
assert str(Dimension("length", "L")) == "Dimension(length, L)"
def test_Dimension_properties():
assert dimsys_SI.is_dimensionless(length) is False
assert dimsys_SI.is_dimensionless(length/length) is True
assert dimsys_SI.is_dimensionless(Dimension("undefined")) is False
assert length.has_integer_powers(dimsys_SI) is True
assert (length**(-1)).has_integer_powers(dimsys_SI) is True
assert (length**1.5).has_integer_powers(dimsys_SI) is False
def test_Dimension_add_sub():
assert length + length == length
assert length - length == length
assert -length == length
raises(TypeError, lambda: length + foot)
raises(TypeError, lambda: foot + length)
raises(TypeError, lambda: length - foot)
raises(TypeError, lambda: foot - length)
# issue 14547 - only raise error for dimensional args; allow
# others to pass
x = Symbol('x')
e = length + x
assert e == x + length and e.is_Add and set(e.args) == {length, x}
e = length + 1
assert e == 1 + length == 1 - length and e.is_Add and set(e.args) == {length, 1}
def test_Dimension_mul_div_exp():
assert 2*length == length*2 == length/2 == length
assert 2/length == 1/length
x = Symbol('x')
m = x*length
assert m == length*x and m.is_Mul and set(m.args) == {x, length}
d = x/length
assert d == x*length**-1 and d.is_Mul and set(d.args) == {x, 1/length}
d = length/x
assert d == length*x**-1 and d.is_Mul and set(d.args) == {1/x, length}
velo = length / time
assert (length * length) == length ** 2
assert dimsys_SI.get_dimensional_dependencies(length * length) == {"length": 2}
assert dimsys_SI.get_dimensional_dependencies(length ** 2) == {"length": 2}
assert dimsys_SI.get_dimensional_dependencies(length * time) == { "length": 1, "time": 1}
assert dimsys_SI.get_dimensional_dependencies(velo) == { "length": 1, "time": -1}
assert dimsys_SI.get_dimensional_dependencies(velo ** 2) == {"length": 2, "time": -2}
assert dimsys_SI.get_dimensional_dependencies(length / length) == {}
assert dimsys_SI.get_dimensional_dependencies(velo / length * time) == {}
assert dimsys_SI.get_dimensional_dependencies(length ** -1) == {"length": -1}
assert dimsys_SI.get_dimensional_dependencies(velo ** -1.5) == {"length": -1.5, "time": 1.5}
length_a = length**"a"
assert dimsys_SI.get_dimensional_dependencies(length_a) == {"length": Symbol("a")}
assert length != 1
assert length / length != 1
length_0 = length ** 0
assert dimsys_SI.get_dimensional_dependencies(length_0) == {}
|
51620e7a3cc7712c7e51778a6b772201c7f024ae0bbf553f6c10d6d1ec3fa0ac | from sympy import Pow, Tuple, pi, sstr, sympify, symbols
from sympy.physics.units import (
G, centimeter, coulomb, day, degree, gram, hbar, hour, inch, joule, kelvin,
kilogram, kilometer, length, meter, mile, minute, newton, planck,
planck_length, planck_mass, planck_temperature, planck_time, radians,
second, speed_of_light, steradian, time, km)
from sympy.physics.units.util import convert_to, check_dimensions
from sympy.testing.pytest import raises
def NS(e, n=15, **options):
return sstr(sympify(e).evalf(n, **options), full_prec=True)
L = length
T = time
def test_dim_simplify_add():
# assert Add(L, L) == L
assert L + L == L
def test_dim_simplify_mul():
# assert Mul(L, T) == L*T
assert L*T == L*T
def test_dim_simplify_pow():
assert Pow(L, 2) == L**2
def test_dim_simplify_rec():
# assert Mul(Add(L, L), T) == L*T
assert (L + L) * T == L*T
def test_convert_to_quantities():
assert convert_to(3, meter) == 3
assert convert_to(mile, kilometer) == 25146*kilometer/15625
assert convert_to(meter/second, speed_of_light) == speed_of_light/299792458
assert convert_to(299792458*meter/second, speed_of_light) == speed_of_light
assert convert_to(2*299792458*meter/second, speed_of_light) == 2*speed_of_light
assert convert_to(speed_of_light, meter/second) == 299792458*meter/second
assert convert_to(2*speed_of_light, meter/second) == 599584916*meter/second
assert convert_to(day, second) == 86400*second
assert convert_to(2*hour, minute) == 120*minute
assert convert_to(mile, meter) == 201168*meter/125
assert convert_to(mile/hour, kilometer/hour) == 25146*kilometer/(15625*hour)
assert convert_to(3*newton, meter/second) == 3*newton
assert convert_to(3*newton, kilogram*meter/second**2) == 3*meter*kilogram/second**2
assert convert_to(kilometer + mile, meter) == 326168*meter/125
assert convert_to(2*kilometer + 3*mile, meter) == 853504*meter/125
assert convert_to(inch**2, meter**2) == 16129*meter**2/25000000
assert convert_to(3*inch**2, meter) == 48387*meter**2/25000000
assert convert_to(2*kilometer/hour + 3*mile/hour, meter/second) == 53344*meter/(28125*second)
assert convert_to(2*kilometer/hour + 3*mile/hour, centimeter/second) == 213376*centimeter/(1125*second)
assert convert_to(kilometer * (mile + kilometer), meter) == 2609344 * meter ** 2
assert convert_to(steradian, coulomb) == steradian
assert convert_to(radians, degree) == 180*degree/pi
assert convert_to(radians, [meter, degree]) == 180*degree/pi
assert convert_to(pi*radians, degree) == 180*degree
assert convert_to(pi, degree) == 180*degree
def test_convert_to_tuples_of_quantities():
assert convert_to(speed_of_light, [meter, second]) == 299792458 * meter / second
assert convert_to(speed_of_light, (meter, second)) == 299792458 * meter / second
assert convert_to(speed_of_light, Tuple(meter, second)) == 299792458 * meter / second
assert convert_to(joule, [meter, kilogram, second]) == kilogram*meter**2/second**2
assert convert_to(joule, [centimeter, gram, second]) == 10000000*centimeter**2*gram/second**2
assert convert_to(299792458*meter/second, [speed_of_light]) == speed_of_light
assert convert_to(speed_of_light / 2, [meter, second, kilogram]) == meter/second*299792458 / 2
# This doesn't make physically sense, but let's keep it as a conversion test:
assert convert_to(2 * speed_of_light, [meter, second, kilogram]) == 2 * 299792458 * meter / second
assert convert_to(G, [G, speed_of_light, planck]) == 1.0*G
assert NS(convert_to(meter, [G, speed_of_light, hbar]), n=7) == '6.187142e+34*gravitational_constant**0.5000000*hbar**0.5000000*speed_of_light**(-1.500000)'
assert NS(convert_to(planck_mass, kilogram), n=7) == '2.176434e-8*kilogram'
assert NS(convert_to(planck_length, meter), n=7) == '1.616255e-35*meter'
assert NS(convert_to(planck_time, second), n=6) == '5.39125e-44*second'
assert NS(convert_to(planck_temperature, kelvin), n=7) == '1.416784e+32*kelvin'
assert NS(convert_to(convert_to(meter, [G, speed_of_light, planck]), meter), n=10) == '1.000000000*meter'
def test_eval_simplify():
from sympy.physics.units import cm, mm, km, m, K, kilo
from sympy.core.symbol import symbols
x, y = symbols('x y')
assert (cm/mm).simplify() == 10
assert (km/m).simplify() == 1000
assert (km/cm).simplify() == 100000
assert (10*x*K*km**2/m/cm).simplify() == 1000000000*x*kelvin
assert (cm/km/m).simplify() == 1/(10000000*centimeter)
assert (3*kilo*meter).simplify() == 3000*meter
assert (4*kilo*meter/(2*kilometer)).simplify() == 2
assert (4*kilometer**2/(kilo*meter)**2).simplify() == 4
def test_quantity_simplify():
from sympy.physics.units.util import quantity_simplify
from sympy.physics.units import kilo, foot
from sympy.core.symbol import symbols
x, y = symbols('x y')
assert quantity_simplify(x*(8*kilo*newton*meter + y)) == x*(8000*meter*newton + y)
assert quantity_simplify(foot*inch*(foot + inch)) == foot**2*(foot + foot/12)/12
assert quantity_simplify(foot*inch*(foot*foot + inch*(foot + inch))) == foot**2*(foot**2 + foot/12*(foot + foot/12))/12
assert quantity_simplify(2**(foot/inch*kilo/1000)*inch) == 4096*foot/12
assert quantity_simplify(foot**2*inch + inch**2*foot) == 13*foot**3/144
def test_check_dimensions():
x = symbols('x')
assert check_dimensions(inch + x) == inch + x
assert check_dimensions(length + x) == length + x
# after subs we get 2*length; check will clear the constant
assert check_dimensions((length + x).subs(x, length)) == length
raises(ValueError, lambda: check_dimensions(inch + 1))
raises(ValueError, lambda: check_dimensions(length + 1))
raises(ValueError, lambda: check_dimensions(length + time))
raises(ValueError, lambda: check_dimensions(meter + second))
raises(ValueError, lambda: check_dimensions(2 * meter + second))
raises(ValueError, lambda: check_dimensions(2 * meter + 3 * second))
raises(ValueError, lambda: check_dimensions(1 / second + 1 / meter))
raises(ValueError, lambda: check_dimensions(2 * meter*(mile + centimeter) + km))
|
d8816647eb78f3a8652b25fb83bb885503fc6cc89fe0aa575487b51fa2641652 | from sympy.testing.pytest import warns_deprecated_sympy
from sympy import Matrix, eye, symbols
from sympy.physics.units.definitions.dimension_definitions import (
action, current, length, mass, time,
velocity)
from sympy.physics.units.dimensions import DimensionSystem
def test_call():
mksa = DimensionSystem((length, time, mass, current), (action,))
with warns_deprecated_sympy():
assert mksa(action) == mksa.print_dim_base(action)
def test_extend():
ms = DimensionSystem((length, time), (velocity,))
mks = ms.extend((mass,), (action,))
res = DimensionSystem((length, time, mass), (velocity, action))
assert mks.base_dims == res.base_dims
assert mks.derived_dims == res.derived_dims
def test_sort_dims():
with warns_deprecated_sympy():
assert (DimensionSystem.sort_dims((length, velocity, time))
== (length, time, velocity))
def test_list_dims():
dimsys = DimensionSystem((length, time, mass))
assert dimsys.list_can_dims == ("length", "mass", "time")
def test_dim_can_vector():
dimsys = DimensionSystem(
[length, mass, time],
[velocity, action],
{
velocity: {length: 1, time: -1}
}
)
assert dimsys.dim_can_vector(length) == Matrix([1, 0, 0])
assert dimsys.dim_can_vector(velocity) == Matrix([1, 0, -1])
dimsys = DimensionSystem(
(length, velocity, action),
(mass, time),
{
time: {length: 1, velocity: -1}
}
)
assert dimsys.dim_can_vector(length) == Matrix([0, 1, 0])
assert dimsys.dim_can_vector(velocity) == Matrix([0, 0, 1])
assert dimsys.dim_can_vector(time) == Matrix([0, 1, -1])
dimsys = DimensionSystem(
(length, mass, time),
(velocity, action),
{velocity: {length: 1, time: -1},
action: {mass: 1, length: 2, time: -1}})
assert dimsys.dim_vector(length) == Matrix([1, 0, 0])
assert dimsys.dim_vector(velocity) == Matrix([1, 0, -1])
def test_inv_can_transf_matrix():
dimsys = DimensionSystem((length, mass, time))
assert dimsys.inv_can_transf_matrix == eye(3)
def test_can_transf_matrix():
dimsys = DimensionSystem((length, mass, time))
assert dimsys.can_transf_matrix == eye(3)
dimsys = DimensionSystem((length, velocity, action))
assert dimsys.can_transf_matrix == eye(3)
dimsys = DimensionSystem((length, time), (velocity,), {velocity: {length: 1, time: -1}})
assert dimsys.can_transf_matrix == eye(2)
def test_is_consistent():
assert DimensionSystem((length, time)).is_consistent is True
def test_print_dim_base():
mksa = DimensionSystem(
(length, time, mass, current),
(action,),
{action: {mass: 1, length: 2, time: -1}})
L, M, T = symbols("L M T")
assert mksa.print_dim_base(action) == L**2*M/T
def test_dim():
dimsys = DimensionSystem(
(length, mass, time),
(velocity, action),
{velocity: {length: 1, time: -1},
action: {mass: 1, length: 2, time: -1}}
)
assert dimsys.dim == 3
|
6a29c79116f7f37029153e782111868b4905640ea00f91bdbeb43b2db4211bb0 | from sympy import S, Integral, sin, cos, pi, sqrt, symbols
from sympy.physics.vector import Dyadic, Point, ReferenceFrame, Vector
from sympy.physics.vector.functions import (cross, dot, express,
time_derivative,
kinematic_equations, outer,
partial_velocity,
get_motion_params, dynamicsymbols)
from sympy.testing.pytest import raises
Vector.simp = True
q1, q2, q3, q4, q5 = symbols('q1 q2 q3 q4 q5')
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q1, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
C = B.orientnew('C', 'Axis', [q3, B.y])
def test_dot():
assert dot(A.x, A.x) == 1
assert dot(A.x, A.y) == 0
assert dot(A.x, A.z) == 0
assert dot(A.y, A.x) == 0
assert dot(A.y, A.y) == 1
assert dot(A.y, A.z) == 0
assert dot(A.z, A.x) == 0
assert dot(A.z, A.y) == 0
assert dot(A.z, A.z) == 1
def test_dot_different_frames():
assert dot(N.x, A.x) == cos(q1)
assert dot(N.x, A.y) == -sin(q1)
assert dot(N.x, A.z) == 0
assert dot(N.y, A.x) == sin(q1)
assert dot(N.y, A.y) == cos(q1)
assert dot(N.y, A.z) == 0
assert dot(N.z, A.x) == 0
assert dot(N.z, A.y) == 0
assert dot(N.z, A.z) == 1
assert dot(N.x, A.x + A.y) == sqrt(2)*cos(q1 + pi/4) == dot(A.x + A.y, N.x)
assert dot(A.x, C.x) == cos(q3)
assert dot(A.x, C.y) == 0
assert dot(A.x, C.z) == sin(q3)
assert dot(A.y, C.x) == sin(q2)*sin(q3)
assert dot(A.y, C.y) == cos(q2)
assert dot(A.y, C.z) == -sin(q2)*cos(q3)
assert dot(A.z, C.x) == -cos(q2)*sin(q3)
assert dot(A.z, C.y) == sin(q2)
assert dot(A.z, C.z) == cos(q2)*cos(q3)
def test_cross():
assert cross(A.x, A.x) == 0
assert cross(A.x, A.y) == A.z
assert cross(A.x, A.z) == -A.y
assert cross(A.y, A.x) == -A.z
assert cross(A.y, A.y) == 0
assert cross(A.y, A.z) == A.x
assert cross(A.z, A.x) == A.y
assert cross(A.z, A.y) == -A.x
assert cross(A.z, A.z) == 0
def test_cross_different_frames():
assert cross(N.x, A.x) == sin(q1)*A.z
assert cross(N.x, A.y) == cos(q1)*A.z
assert cross(N.x, A.z) == -sin(q1)*A.x - cos(q1)*A.y
assert cross(N.y, A.x) == -cos(q1)*A.z
assert cross(N.y, A.y) == sin(q1)*A.z
assert cross(N.y, A.z) == cos(q1)*A.x - sin(q1)*A.y
assert cross(N.z, A.x) == A.y
assert cross(N.z, A.y) == -A.x
assert cross(N.z, A.z) == 0
assert cross(N.x, A.x) == sin(q1)*A.z
assert cross(N.x, A.y) == cos(q1)*A.z
assert cross(N.x, A.x + A.y) == sin(q1)*A.z + cos(q1)*A.z
assert cross(A.x + A.y, N.x) == -sin(q1)*A.z - cos(q1)*A.z
assert cross(A.x, C.x) == sin(q3)*C.y
assert cross(A.x, C.y) == -sin(q3)*C.x + cos(q3)*C.z
assert cross(A.x, C.z) == -cos(q3)*C.y
assert cross(C.x, A.x) == -sin(q3)*C.y
assert cross(C.y, A.x) == sin(q3)*C.x - cos(q3)*C.z
assert cross(C.z, A.x) == cos(q3)*C.y
def test_operator_match():
"""Test that the output of dot, cross, outer functions match
operator behavior.
"""
A = ReferenceFrame('A')
v = A.x + A.y
d = v | v
zerov = Vector(0)
zerod = Dyadic(0)
# dot products
assert d & d == dot(d, d)
assert d & zerod == dot(d, zerod)
assert zerod & d == dot(zerod, d)
assert d & v == dot(d, v)
assert v & d == dot(v, d)
assert d & zerov == dot(d, zerov)
assert zerov & d == dot(zerov, d)
raises(TypeError, lambda: dot(d, S.Zero))
raises(TypeError, lambda: dot(S.Zero, d))
raises(TypeError, lambda: dot(d, 0))
raises(TypeError, lambda: dot(0, d))
assert v & v == dot(v, v)
assert v & zerov == dot(v, zerov)
assert zerov & v == dot(zerov, v)
raises(TypeError, lambda: dot(v, S.Zero))
raises(TypeError, lambda: dot(S.Zero, v))
raises(TypeError, lambda: dot(v, 0))
raises(TypeError, lambda: dot(0, v))
# cross products
raises(TypeError, lambda: cross(d, d))
raises(TypeError, lambda: cross(d, zerod))
raises(TypeError, lambda: cross(zerod, d))
assert d ^ v == cross(d, v)
assert v ^ d == cross(v, d)
assert d ^ zerov == cross(d, zerov)
assert zerov ^ d == cross(zerov, d)
assert zerov ^ d == cross(zerov, d)
raises(TypeError, lambda: cross(d, S.Zero))
raises(TypeError, lambda: cross(S.Zero, d))
raises(TypeError, lambda: cross(d, 0))
raises(TypeError, lambda: cross(0, d))
assert v ^ v == cross(v, v)
assert v ^ zerov == cross(v, zerov)
assert zerov ^ v == cross(zerov, v)
raises(TypeError, lambda: cross(v, S.Zero))
raises(TypeError, lambda: cross(S.Zero, v))
raises(TypeError, lambda: cross(v, 0))
raises(TypeError, lambda: cross(0, v))
# outer products
raises(TypeError, lambda: outer(d, d))
raises(TypeError, lambda: outer(d, zerod))
raises(TypeError, lambda: outer(zerod, d))
raises(TypeError, lambda: outer(d, v))
raises(TypeError, lambda: outer(v, d))
raises(TypeError, lambda: outer(d, zerov))
raises(TypeError, lambda: outer(zerov, d))
raises(TypeError, lambda: outer(zerov, d))
raises(TypeError, lambda: outer(d, S.Zero))
raises(TypeError, lambda: outer(S.Zero, d))
raises(TypeError, lambda: outer(d, 0))
raises(TypeError, lambda: outer(0, d))
assert v | v == outer(v, v)
assert v | zerov == outer(v, zerov)
assert zerov | v == outer(zerov, v)
raises(TypeError, lambda: outer(v, S.Zero))
raises(TypeError, lambda: outer(S.Zero, v))
raises(TypeError, lambda: outer(v, 0))
raises(TypeError, lambda: outer(0, v))
def test_express():
assert express(Vector(0), N) == Vector(0)
assert express(S.Zero, N) is S.Zero
assert express(A.x, C) == cos(q3)*C.x + sin(q3)*C.z
assert express(A.y, C) == sin(q2)*sin(q3)*C.x + cos(q2)*C.y - \
sin(q2)*cos(q3)*C.z
assert express(A.z, C) == -sin(q3)*cos(q2)*C.x + sin(q2)*C.y + \
cos(q2)*cos(q3)*C.z
assert express(A.x, N) == cos(q1)*N.x + sin(q1)*N.y
assert express(A.y, N) == -sin(q1)*N.x + cos(q1)*N.y
assert express(A.z, N) == N.z
assert express(A.x, A) == A.x
assert express(A.y, A) == A.y
assert express(A.z, A) == A.z
assert express(A.x, B) == B.x
assert express(A.y, B) == cos(q2)*B.y - sin(q2)*B.z
assert express(A.z, B) == sin(q2)*B.y + cos(q2)*B.z
assert express(A.x, C) == cos(q3)*C.x + sin(q3)*C.z
assert express(A.y, C) == sin(q2)*sin(q3)*C.x + cos(q2)*C.y - \
sin(q2)*cos(q3)*C.z
assert express(A.z, C) == -sin(q3)*cos(q2)*C.x + sin(q2)*C.y + \
cos(q2)*cos(q3)*C.z
# Check to make sure UnitVectors get converted properly
assert express(N.x, N) == N.x
assert express(N.y, N) == N.y
assert express(N.z, N) == N.z
assert express(N.x, A) == (cos(q1)*A.x - sin(q1)*A.y)
assert express(N.y, A) == (sin(q1)*A.x + cos(q1)*A.y)
assert express(N.z, A) == A.z
assert express(N.x, B) == (cos(q1)*B.x - sin(q1)*cos(q2)*B.y +
sin(q1)*sin(q2)*B.z)
assert express(N.y, B) == (sin(q1)*B.x + cos(q1)*cos(q2)*B.y -
sin(q2)*cos(q1)*B.z)
assert express(N.z, B) == (sin(q2)*B.y + cos(q2)*B.z)
assert express(N.x, C) == (
(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*C.x -
sin(q1)*cos(q2)*C.y +
(sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*C.z)
assert express(N.y, C) == (
(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.x +
cos(q1)*cos(q2)*C.y +
(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.z)
assert express(N.z, C) == (-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z)
assert express(A.x, N) == (cos(q1)*N.x + sin(q1)*N.y)
assert express(A.y, N) == (-sin(q1)*N.x + cos(q1)*N.y)
assert express(A.z, N) == N.z
assert express(A.x, A) == A.x
assert express(A.y, A) == A.y
assert express(A.z, A) == A.z
assert express(A.x, B) == B.x
assert express(A.y, B) == (cos(q2)*B.y - sin(q2)*B.z)
assert express(A.z, B) == (sin(q2)*B.y + cos(q2)*B.z)
assert express(A.x, C) == (cos(q3)*C.x + sin(q3)*C.z)
assert express(A.y, C) == (sin(q2)*sin(q3)*C.x + cos(q2)*C.y -
sin(q2)*cos(q3)*C.z)
assert express(A.z, C) == (-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z)
assert express(B.x, N) == (cos(q1)*N.x + sin(q1)*N.y)
assert express(B.y, N) == (-sin(q1)*cos(q2)*N.x +
cos(q1)*cos(q2)*N.y + sin(q2)*N.z)
assert express(B.z, N) == (sin(q1)*sin(q2)*N.x -
sin(q2)*cos(q1)*N.y + cos(q2)*N.z)
assert express(B.x, A) == A.x
assert express(B.y, A) == (cos(q2)*A.y + sin(q2)*A.z)
assert express(B.z, A) == (-sin(q2)*A.y + cos(q2)*A.z)
assert express(B.x, B) == B.x
assert express(B.y, B) == B.y
assert express(B.z, B) == B.z
assert express(B.x, C) == (cos(q3)*C.x + sin(q3)*C.z)
assert express(B.y, C) == C.y
assert express(B.z, C) == (-sin(q3)*C.x + cos(q3)*C.z)
assert express(C.x, N) == (
(cos(q1)*cos(q3) - sin(q1)*sin(q2)*sin(q3))*N.x +
(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*N.y -
sin(q3)*cos(q2)*N.z)
assert express(C.y, N) == (
-sin(q1)*cos(q2)*N.x + cos(q1)*cos(q2)*N.y + sin(q2)*N.z)
assert express(C.z, N) == (
(sin(q3)*cos(q1) + sin(q1)*sin(q2)*cos(q3))*N.x +
(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*N.y +
cos(q2)*cos(q3)*N.z)
assert express(C.x, A) == (cos(q3)*A.x + sin(q2)*sin(q3)*A.y -
sin(q3)*cos(q2)*A.z)
assert express(C.y, A) == (cos(q2)*A.y + sin(q2)*A.z)
assert express(C.z, A) == (sin(q3)*A.x - sin(q2)*cos(q3)*A.y +
cos(q2)*cos(q3)*A.z)
assert express(C.x, B) == (cos(q3)*B.x - sin(q3)*B.z)
assert express(C.y, B) == B.y
assert express(C.z, B) == (sin(q3)*B.x + cos(q3)*B.z)
assert express(C.x, C) == C.x
assert express(C.y, C) == C.y
assert express(C.z, C) == C.z == (C.z)
# Check to make sure Vectors get converted back to UnitVectors
assert N.x == express((cos(q1)*A.x - sin(q1)*A.y), N)
assert N.y == express((sin(q1)*A.x + cos(q1)*A.y), N)
assert N.x == express((cos(q1)*B.x - sin(q1)*cos(q2)*B.y +
sin(q1)*sin(q2)*B.z), N)
assert N.y == express((sin(q1)*B.x + cos(q1)*cos(q2)*B.y -
sin(q2)*cos(q1)*B.z), N)
assert N.z == express((sin(q2)*B.y + cos(q2)*B.z), N)
"""
These don't really test our code, they instead test the auto simplification
(or lack thereof) of SymPy.
assert N.x == express((
(cos(q1)*cos(q3)-sin(q1)*sin(q2)*sin(q3))*C.x -
sin(q1)*cos(q2)*C.y +
(sin(q3)*cos(q1)+sin(q1)*sin(q2)*cos(q3))*C.z), N)
assert N.y == express((
(sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1))*C.x +
cos(q1)*cos(q2)*C.y +
(sin(q1)*sin(q3) - sin(q2)*cos(q1)*cos(q3))*C.z), N)
assert N.z == express((-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z), N)
"""
assert A.x == express((cos(q1)*N.x + sin(q1)*N.y), A)
assert A.y == express((-sin(q1)*N.x + cos(q1)*N.y), A)
assert A.y == express((cos(q2)*B.y - sin(q2)*B.z), A)
assert A.z == express((sin(q2)*B.y + cos(q2)*B.z), A)
assert A.x == express((cos(q3)*C.x + sin(q3)*C.z), A)
# Tripsimp messes up here too.
#print express((sin(q2)*sin(q3)*C.x + cos(q2)*C.y -
# sin(q2)*cos(q3)*C.z), A)
assert A.y == express((sin(q2)*sin(q3)*C.x + cos(q2)*C.y -
sin(q2)*cos(q3)*C.z), A)
assert A.z == express((-sin(q3)*cos(q2)*C.x + sin(q2)*C.y +
cos(q2)*cos(q3)*C.z), A)
assert B.x == express((cos(q1)*N.x + sin(q1)*N.y), B)
assert B.y == express((-sin(q1)*cos(q2)*N.x +
cos(q1)*cos(q2)*N.y + sin(q2)*N.z), B)
assert B.z == express((sin(q1)*sin(q2)*N.x -
sin(q2)*cos(q1)*N.y + cos(q2)*N.z), B)
assert B.y == express((cos(q2)*A.y + sin(q2)*A.z), B)
assert B.z == express((-sin(q2)*A.y + cos(q2)*A.z), B)
assert B.x == express((cos(q3)*C.x + sin(q3)*C.z), B)
assert B.z == express((-sin(q3)*C.x + cos(q3)*C.z), B)
"""
assert C.x == express((
(cos(q1)*cos(q3)-sin(q1)*sin(q2)*sin(q3))*N.x +
(sin(q1)*cos(q3)+sin(q2)*sin(q3)*cos(q1))*N.y -
sin(q3)*cos(q2)*N.z), C)
assert C.y == express((
-sin(q1)*cos(q2)*N.x + cos(q1)*cos(q2)*N.y + sin(q2)*N.z), C)
assert C.z == express((
(sin(q3)*cos(q1)+sin(q1)*sin(q2)*cos(q3))*N.x +
(sin(q1)*sin(q3)-sin(q2)*cos(q1)*cos(q3))*N.y +
cos(q2)*cos(q3)*N.z), C)
"""
assert C.x == express((cos(q3)*A.x + sin(q2)*sin(q3)*A.y -
sin(q3)*cos(q2)*A.z), C)
assert C.y == express((cos(q2)*A.y + sin(q2)*A.z), C)
assert C.z == express((sin(q3)*A.x - sin(q2)*cos(q3)*A.y +
cos(q2)*cos(q3)*A.z), C)
assert C.x == express((cos(q3)*B.x - sin(q3)*B.z), C)
assert C.z == express((sin(q3)*B.x + cos(q3)*B.z), C)
def test_time_derivative():
#The use of time_derivative for calculations pertaining to scalar
#fields has been tested in test_coordinate_vars in test_essential.py
A = ReferenceFrame('A')
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
B = A.orientnew('B', 'Axis', [q, A.z])
d = A.x | A.x
assert time_derivative(d, B) == (-qd) * (A.y | A.x) + \
(-qd) * (A.x | A.y)
d1 = A.x | B.y
assert time_derivative(d1, A) == - qd*(A.x|B.x)
assert time_derivative(d1, B) == - qd*(A.y|B.y)
d2 = A.x | B.x
assert time_derivative(d2, A) == qd*(A.x|B.y)
assert time_derivative(d2, B) == - qd*(A.y|B.x)
d3 = A.x | B.z
assert time_derivative(d3, A) == 0
assert time_derivative(d3, B) == - qd*(A.y|B.z)
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
q1dd, q2dd, q3dd, q4dd = dynamicsymbols('q1 q2 q3 q4', 2)
C = B.orientnew('C', 'Axis', [q4, B.x])
v1 = q1 * A.z
v2 = q2*A.x + q3*B.y
v3 = q1*A.x + q2*A.y + q3*A.z
assert time_derivative(B.x, C) == 0
assert time_derivative(B.y, C) == - q4d*B.z
assert time_derivative(B.z, C) == q4d*B.y
assert time_derivative(v1, B) == q1d*A.z
assert time_derivative(v1, C) == - q1*sin(q)*q4d*A.x + \
q1*cos(q)*q4d*A.y + q1d*A.z
assert time_derivative(v2, A) == q2d*A.x - q3*qd*B.x + q3d*B.y
assert time_derivative(v2, C) == q2d*A.x - q2*qd*A.y + \
q2*sin(q)*q4d*A.z + q3d*B.y - q3*q4d*B.z
assert time_derivative(v3, B) == (q2*qd + q1d)*A.x + \
(-q1*qd + q2d)*A.y + q3d*A.z
assert time_derivative(d, C) == - qd*(A.y|A.x) + \
sin(q)*q4d*(A.z|A.x) - qd*(A.x|A.y) + sin(q)*q4d*(A.x|A.z)
raises(ValueError, lambda: time_derivative(B.x, C, order=0.5))
raises(ValueError, lambda: time_derivative(B.x, C, order=-1))
def test_get_motion_methods():
#Initialization
t = dynamicsymbols._t
s1, s2, s3 = symbols('s1 s2 s3')
S1, S2, S3 = symbols('S1 S2 S3')
S4, S5, S6 = symbols('S4 S5 S6')
t1, t2 = symbols('t1 t2')
a, b, c = dynamicsymbols('a b c')
ad, bd, cd = dynamicsymbols('a b c', 1)
a2d, b2d, c2d = dynamicsymbols('a b c', 2)
v0 = S1*N.x + S2*N.y + S3*N.z
v01 = S4*N.x + S5*N.y + S6*N.z
v1 = s1*N.x + s2*N.y + s3*N.z
v2 = a*N.x + b*N.y + c*N.z
v2d = ad*N.x + bd*N.y + cd*N.z
v2dd = a2d*N.x + b2d*N.y + c2d*N.z
#Test position parameter
assert get_motion_params(frame = N) == (0, 0, 0)
assert get_motion_params(N, position=v1) == (0, 0, v1)
assert get_motion_params(N, position=v2) == (v2dd, v2d, v2)
#Test velocity parameter
assert get_motion_params(N, velocity=v1) == (0, v1, v1 * t)
assert get_motion_params(N, velocity=v1, position=v0, timevalue1=t1) == \
(0, v1, v0 + v1*(t - t1))
answer = get_motion_params(N, velocity=v1, position=v2, timevalue1=t1)
answer_expected = (0, v1, v1*t - v1*t1 + v2.subs(t, t1))
assert answer == answer_expected
answer = get_motion_params(N, velocity=v2, position=v0, timevalue1=t1)
integral_vector = Integral(a, (t, t1, t))*N.x + Integral(b, (t, t1, t))*N.y \
+ Integral(c, (t, t1, t))*N.z
answer_expected = (v2d, v2, v0 + integral_vector)
assert answer == answer_expected
#Test acceleration parameter
assert get_motion_params(N, acceleration=v1) == \
(v1, v1 * t, v1 * t**2/2)
assert get_motion_params(N, acceleration=v1, velocity=v0,
position=v2, timevalue1=t1, timevalue2=t2) == \
(v1, (v0 + v1*t - v1*t2),
-v0*t1 + v1*t**2/2 + v1*t2*t1 - \
v1*t1**2/2 + t*(v0 - v1*t2) + \
v2.subs(t, t1))
assert get_motion_params(N, acceleration=v1, velocity=v0,
position=v01, timevalue1=t1, timevalue2=t2) == \
(v1, v0 + v1*t - v1*t2,
-v0*t1 + v01 + v1*t**2/2 + \
v1*t2*t1 - v1*t1**2/2 + \
t*(v0 - v1*t2))
answer = get_motion_params(N, acceleration=a*N.x, velocity=S1*N.x,
position=S2*N.x, timevalue1=t1, timevalue2=t2)
i1 = Integral(a, (t, t2, t))
answer_expected = (a*N.x, (S1 + i1)*N.x, \
(S2 + Integral(S1 + i1, (t, t1, t)))*N.x)
assert answer == answer_expected
def test_kin_eqs():
q0, q1, q2, q3 = dynamicsymbols('q0 q1 q2 q3')
q0d, q1d, q2d, q3d = dynamicsymbols('q0 q1 q2 q3', 1)
u1, u2, u3 = dynamicsymbols('u1 u2 u3')
ke = kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', 313)
assert ke == kinematic_equations([u1,u2,u3], [q1,q2,q3], 'body', '313')
kds = kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'quaternion')
assert kds == [-0.5 * q0 * u1 - 0.5 * q2 * u3 + 0.5 * q3 * u2 + q1d,
-0.5 * q0 * u2 + 0.5 * q1 * u3 - 0.5 * q3 * u1 + q2d,
-0.5 * q0 * u3 - 0.5 * q1 * u2 + 0.5 * q2 * u1 + q3d,
0.5 * q1 * u1 + 0.5 * q2 * u2 + 0.5 * q3 * u3 + q0d]
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2], 'quaternion'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'quaternion', '123'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'foo'))
raises(TypeError, lambda: kinematic_equations(u1, [q0, q1, q2, q3], 'quaternion'))
raises(TypeError, lambda: kinematic_equations([u1], [q0, q1, q2, q3], 'quaternion'))
raises(TypeError, lambda: kinematic_equations([u1, u2, u3], q0, 'quaternion'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'body'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2, q3], 'space'))
raises(ValueError, lambda: kinematic_equations([u1, u2, u3], [q0, q1, q2], 'body', '222'))
assert kinematic_equations([0, 0, 0], [q0, q1, q2], 'space') == [S.Zero, S.Zero, S.Zero]
def test_partial_velocity():
q1, q2, q3, u1, u2, u3 = dynamicsymbols('q1 q2 q3 u1 u2 u3')
u4, u5 = dynamicsymbols('u4, u5')
r = symbols('r')
N = ReferenceFrame('N')
Y = N.orientnew('Y', 'Axis', [q1, N.z])
L = Y.orientnew('L', 'Axis', [q2, Y.x])
R = L.orientnew('R', 'Axis', [q3, L.y])
R.set_ang_vel(N, u1 * L.x + u2 * L.y + u3 * L.z)
C = Point('C')
C.set_vel(N, u4 * L.x + u5 * (Y.z ^ L.x))
Dmc = C.locatenew('Dmc', r * L.z)
Dmc.v2pt_theory(C, N, R)
vel_list = [Dmc.vel(N), C.vel(N), R.ang_vel_in(N)]
u_list = [u1, u2, u3, u4, u5]
assert (partial_velocity(vel_list, u_list, N) ==
[[- r*L.y, r*L.x, 0, L.x, cos(q2)*L.y - sin(q2)*L.z],
[0, 0, 0, L.x, cos(q2)*L.y - sin(q2)*L.z],
[L.x, L.y, L.z, 0, 0]])
# Make sure that partial velocities can be computed regardless if the
# orientation between frames is defined or not.
A = ReferenceFrame('A')
B = ReferenceFrame('B')
v = u4 * A.x + u5 * B.y
assert partial_velocity((v, ), (u4, u5), A) == [[A.x, B.y]]
raises(TypeError, lambda: partial_velocity(Dmc.vel(N), u_list, N))
raises(TypeError, lambda: partial_velocity(vel_list, u1, N))
def test_dynamicsymbols():
#Tests to check the assumptions applied to dynamicsymbols
f1 = dynamicsymbols('f1')
f2 = dynamicsymbols('f2', real=True)
f3 = dynamicsymbols('f3', positive=True)
f4, f5 = dynamicsymbols('f4,f5', commutative=False)
f6 = dynamicsymbols('f6', integer=True)
assert f1.is_real is None
assert f2.is_real
assert f3.is_positive
assert f4*f5 != f5*f4
assert f6.is_integer
|
2fa8e92d6e7b1574a6ca094a0f84451751646ded5efad419b6f313050574da21 | from sympy import symbols, pi, sin, cos, ImmutableMatrix as Matrix
from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols, dot
from sympy.abc import x, y, z
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_Vector():
assert A.x != A.y
assert A.y != A.z
assert A.z != A.x
assert A.x + 0 == A.x
v1 = x*A.x + y*A.y + z*A.z
v2 = x**2*A.x + y**2*A.y + z**2*A.z
v3 = v1 + v2
v4 = v1 - v2
assert isinstance(v1, Vector)
assert dot(v1, A.x) == x
assert dot(v1, A.y) == y
assert dot(v1, A.z) == z
assert isinstance(v2, Vector)
assert dot(v2, A.x) == x**2
assert dot(v2, A.y) == y**2
assert dot(v2, A.z) == z**2
assert isinstance(v3, Vector)
# We probably shouldn't be using simplify in dot...
assert dot(v3, A.x) == x**2 + x
assert dot(v3, A.y) == y**2 + y
assert dot(v3, A.z) == z**2 + z
assert isinstance(v4, Vector)
# We probably shouldn't be using simplify in dot...
assert dot(v4, A.x) == x - x**2
assert dot(v4, A.y) == y - y**2
assert dot(v4, A.z) == z - z**2
assert v1.to_matrix(A) == Matrix([[x], [y], [z]])
q = symbols('q')
B = A.orientnew('B', 'Axis', (q, A.x))
assert v1.to_matrix(B) == Matrix([[x],
[ y * cos(q) + z * sin(q)],
[-y * sin(q) + z * cos(q)]])
#Test the separate method
B = ReferenceFrame('B')
v5 = x*A.x + y*A.y + z*B.z
assert Vector(0).separate() == {}
assert v1.separate() == {A: v1}
assert v5.separate() == {A: x*A.x + y*A.y, B: z*B.z}
#Test the free_symbols property
v6 = x*A.x + y*A.y + z*A.z
assert v6.free_symbols(A) == {x,y,z}
raises(TypeError, lambda: v3.applyfunc(v1))
def test_Vector_diffs():
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
q1dd, q2dd, q3dd, q4dd = dynamicsymbols('q1 q2 q3 q4', 2)
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q3, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
v1 = q2 * A.x + q3 * N.y
v2 = q3 * B.x + v1
v3 = v1.dt(B)
v4 = v2.dt(B)
v5 = q1*A.x + q2*A.y + q3*A.z
assert v1.dt(N) == q2d * A.x + q2 * q3d * A.y + q3d * N.y
assert v1.dt(A) == q2d * A.x + q3 * q3d * N.x + q3d * N.y
assert v1.dt(B) == (q2d * A.x + q3 * q3d * N.x + q3d *\
N.y - q3 * cos(q3) * q2d * N.z)
assert v2.dt(N) == (q2d * A.x + (q2 + q3) * q3d * A.y + q3d * B.x + q3d *
N.y)
assert v2.dt(A) == q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y
assert v2.dt(B) == (q2d * A.x + q3d * B.x + q3 * q3d * N.x + q3d * N.y -
q3 * cos(q3) * q2d * N.z)
assert v3.dt(N) == (q2dd * A.x + q2d * q3d * A.y + (q3d**2 + q3 * q3dd) *
N.x + q3dd * N.y + (q3 * sin(q3) * q2d * q3d -
cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v3.dt(A) == (q2dd * A.x + (2 * q3d**2 + q3 * q3dd) * N.x + (q3dd -
q3 * q3d**2) * N.y + (q3 * sin(q3) * q2d * q3d -
cos(q3) * q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v3.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + (2 *
q3d**2 + q3 * q3dd) * N.x + (q3dd - q3 * q3d**2) *
N.y + (2 * q3 * sin(q3) * q2d * q3d - 2 * cos(q3) *
q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v4.dt(N) == (q2dd * A.x + q3d * (q2d + q3d) * A.y + q3dd * B.x +
(q3d**2 + q3 * q3dd) * N.x + q3dd * N.y + (q3 *
sin(q3) * q2d * q3d - cos(q3) * q2d * q3d - q3 *
cos(q3) * q2dd) * N.z)
assert v4.dt(A) == (q2dd * A.x + q3dd * B.x + (2 * q3d**2 + q3 * q3dd) *
N.x + (q3dd - q3 * q3d**2) * N.y + (q3 * sin(q3) *
q2d * q3d - cos(q3) * q2d * q3d - q3 * cos(q3) *
q2dd) * N.z)
assert v4.dt(B) == (q2dd * A.x - q3 * cos(q3) * q2d**2 * A.y + q3dd * B.x +
(2 * q3d**2 + q3 * q3dd) * N.x + (q3dd - q3 * q3d**2) *
N.y + (2 * q3 * sin(q3) * q2d * q3d - 2 * cos(q3) *
q2d * q3d - q3 * cos(q3) * q2dd) * N.z)
assert v5.dt(B) == q1d*A.x + (q3*q2d + q2d)*A.y + (-q2*q2d + q3d)*A.z
assert v5.dt(A) == q1d*A.x + q2d*A.y + q3d*A.z
assert v5.dt(N) == (-q2*q3d + q1d)*A.x + (q1*q3d + q2d)*A.y + q3d*A.z
assert v3.diff(q1d, N) == 0
assert v3.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, N) == q3 * N.x + N.y
assert v3.diff(q1d, A) == 0
assert v3.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, A) == q3 * N.x + N.y
assert v3.diff(q1d, B) == 0
assert v3.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
assert v3.diff(q3d, B) == q3 * N.x + N.y
assert v4.diff(q1d, N) == 0
assert v4.diff(q2d, N) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, N) == B.x + q3 * N.x + N.y
assert v4.diff(q1d, A) == 0
assert v4.diff(q2d, A) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, A) == B.x + q3 * N.x + N.y
assert v4.diff(q1d, B) == 0
assert v4.diff(q2d, B) == A.x - q3 * cos(q3) * N.z
assert v4.diff(q3d, B) == B.x + q3 * N.x + N.y
def test_vector_var_in_dcm():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
B = ReferenceFrame('B')
u1, u2, u3, u4 = dynamicsymbols('u1 u2 u3 u4')
v = u1 * u2 * A.x + u3 * N.y + u4**2 * N.z
assert v.diff(u1, N, var_in_dcm=False) == u2 * A.x
assert v.diff(u1, A, var_in_dcm=False) == u2 * A.x
assert v.diff(u3, N, var_in_dcm=False) == N.y
assert v.diff(u3, A, var_in_dcm=False) == N.y
assert v.diff(u3, B, var_in_dcm=False) == N.y
assert v.diff(u4, N, var_in_dcm=False) == 2 * u4 * N.z
raises(ValueError, lambda: v.diff(u1, N))
def test_vector_simplify():
x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A')
N = ReferenceFrame('N')
test1 = (1 / x + 1 / y) * N.x
assert (test1 & N.x) != (x + y) / (x * y)
test1 = test1.simplify()
assert (test1 & N.x) == (x + y) / (x * y)
test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * N.x
test2 = test2.simplify()
assert (test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3))
test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * N.x
test3 = test3.simplify()
assert (test3 & N.x) == 0
test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * N.x
test4 = test4.simplify()
assert (test4 & N.x) == -2 * y
|
74761f3877abb1f0afc772d97d02bbfc50b197f9294b5bf37b65c551004b3147 | from sympy import (symbols, sin, cos, pi, zeros, eye, simplify, ImmutableMatrix
as Matrix)
from sympy.physics.vector import (ReferenceFrame, Vector, CoordinateSym,
dynamicsymbols, time_derivative, express,
dot)
from sympy.physics.vector.frame import _check_frame
from sympy.physics.vector.vector import VectorTypeError
from sympy.testing.pytest import raises
Vector.simp = True
def test_coordinate_vars():
"""Tests the coordinate variables functionality"""
A = ReferenceFrame('A')
assert CoordinateSym('Ax', A, 0) == A[0]
assert CoordinateSym('Ax', A, 1) == A[1]
assert CoordinateSym('Ax', A, 2) == A[2]
raises(ValueError, lambda: CoordinateSym('Ax', A, 3))
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
assert isinstance(A[0], CoordinateSym) and \
isinstance(A[0], CoordinateSym) and \
isinstance(A[0], CoordinateSym)
assert A.variable_map(A) == {A[0]:A[0], A[1]:A[1], A[2]:A[2]}
assert A[0].frame == A
B = A.orientnew('B', 'Axis', [q, A.z])
assert B.variable_map(A) == {B[2]: A[2], B[1]: -A[0]*sin(q) + A[1]*cos(q),
B[0]: A[0]*cos(q) + A[1]*sin(q)}
assert A.variable_map(B) == {A[0]: B[0]*cos(q) - B[1]*sin(q),
A[1]: B[0]*sin(q) + B[1]*cos(q), A[2]: B[2]}
assert time_derivative(B[0], A) == -A[0]*sin(q)*qd + A[1]*cos(q)*qd
assert time_derivative(B[1], A) == -A[0]*cos(q)*qd - A[1]*sin(q)*qd
assert time_derivative(B[2], A) == 0
assert express(B[0], A, variables=True) == A[0]*cos(q) + A[1]*sin(q)
assert express(B[1], A, variables=True) == -A[0]*sin(q) + A[1]*cos(q)
assert express(B[2], A, variables=True) == A[2]
assert time_derivative(A[0]*A.x + A[1]*A.y + A[2]*A.z, B) == A[1]*qd*A.x - A[0]*qd*A.y
assert time_derivative(B[0]*B.x + B[1]*B.y + B[2]*B.z, A) == - B[1]*qd*B.x + B[0]*qd*B.y
assert express(B[0]*B[1]*B[2], A, variables=True) == \
A[2]*(-A[0]*sin(q) + A[1]*cos(q))*(A[0]*cos(q) + A[1]*sin(q))
assert (time_derivative(B[0]*B[1]*B[2], A) -
(A[2]*(-A[0]**2*cos(2*q) -
2*A[0]*A[1]*sin(2*q) +
A[1]**2*cos(2*q))*qd)).trigsimp() == 0
assert express(B[0]*B.x + B[1]*B.y + B[2]*B.z, A) == \
(B[0]*cos(q) - B[1]*sin(q))*A.x + (B[0]*sin(q) + \
B[1]*cos(q))*A.y + B[2]*A.z
assert express(B[0]*B.x + B[1]*B.y + B[2]*B.z, A, variables=True) == \
A[0]*A.x + A[1]*A.y + A[2]*A.z
assert express(A[0]*A.x + A[1]*A.y + A[2]*A.z, B) == \
(A[0]*cos(q) + A[1]*sin(q))*B.x + \
(-A[0]*sin(q) + A[1]*cos(q))*B.y + A[2]*B.z
assert express(A[0]*A.x + A[1]*A.y + A[2]*A.z, B, variables=True) == \
B[0]*B.x + B[1]*B.y + B[2]*B.z
N = B.orientnew('N', 'Axis', [-q, B.z])
assert N.variable_map(A) == {N[0]: A[0], N[2]: A[2], N[1]: A[1]}
C = A.orientnew('C', 'Axis', [q, A.x + A.y + A.z])
mapping = A.variable_map(C)
assert mapping[A[0]] == 2*C[0]*cos(q)/3 + C[0]/3 - 2*C[1]*sin(q + pi/6)/3 +\
C[1]/3 - 2*C[2]*cos(q + pi/3)/3 + C[2]/3
assert mapping[A[1]] == -2*C[0]*cos(q + pi/3)/3 + \
C[0]/3 + 2*C[1]*cos(q)/3 + C[1]/3 - 2*C[2]*sin(q + pi/6)/3 + C[2]/3
assert mapping[A[2]] == -2*C[0]*sin(q + pi/6)/3 + C[0]/3 - \
2*C[1]*cos(q + pi/3)/3 + C[1]/3 + 2*C[2]*cos(q)/3 + C[2]/3
def test_ang_vel():
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
q1d, q2d, q3d, q4d = dynamicsymbols('q1 q2 q3 q4', 1)
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q1, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
C = B.orientnew('C', 'Axis', [q3, B.y])
D = N.orientnew('D', 'Axis', [q4, N.y])
u1, u2, u3 = dynamicsymbols('u1 u2 u3')
assert A.ang_vel_in(N) == (q1d)*A.z
assert B.ang_vel_in(N) == (q2d)*B.x + (q1d)*A.z
assert C.ang_vel_in(N) == (q3d)*C.y + (q2d)*B.x + (q1d)*A.z
A2 = N.orientnew('A2', 'Axis', [q4, N.y])
assert N.ang_vel_in(N) == 0
assert N.ang_vel_in(A) == -q1d*N.z
assert N.ang_vel_in(B) == -q1d*A.z - q2d*B.x
assert N.ang_vel_in(C) == -q1d*A.z - q2d*B.x - q3d*B.y
assert N.ang_vel_in(A2) == -q4d*N.y
assert A.ang_vel_in(N) == q1d*N.z
assert A.ang_vel_in(A) == 0
assert A.ang_vel_in(B) == - q2d*B.x
assert A.ang_vel_in(C) == - q2d*B.x - q3d*B.y
assert A.ang_vel_in(A2) == q1d*N.z - q4d*N.y
assert B.ang_vel_in(N) == q1d*A.z + q2d*A.x
assert B.ang_vel_in(A) == q2d*A.x
assert B.ang_vel_in(B) == 0
assert B.ang_vel_in(C) == -q3d*B.y
assert B.ang_vel_in(A2) == q1d*A.z + q2d*A.x - q4d*N.y
assert C.ang_vel_in(N) == q1d*A.z + q2d*A.x + q3d*B.y
assert C.ang_vel_in(A) == q2d*A.x + q3d*C.y
assert C.ang_vel_in(B) == q3d*B.y
assert C.ang_vel_in(C) == 0
assert C.ang_vel_in(A2) == q1d*A.z + q2d*A.x + q3d*B.y - q4d*N.y
assert A2.ang_vel_in(N) == q4d*A2.y
assert A2.ang_vel_in(A) == q4d*A2.y - q1d*N.z
assert A2.ang_vel_in(B) == q4d*N.y - q1d*A.z - q2d*A.x
assert A2.ang_vel_in(C) == q4d*N.y - q1d*A.z - q2d*A.x - q3d*B.y
assert A2.ang_vel_in(A2) == 0
C.set_ang_vel(N, u1*C.x + u2*C.y + u3*C.z)
assert C.ang_vel_in(N) == (u1)*C.x + (u2)*C.y + (u3)*C.z
assert N.ang_vel_in(C) == (-u1)*C.x + (-u2)*C.y + (-u3)*C.z
assert C.ang_vel_in(D) == (u1)*C.x + (u2)*C.y + (u3)*C.z + (-q4d)*D.y
assert D.ang_vel_in(C) == (-u1)*C.x + (-u2)*C.y + (-u3)*C.z + (q4d)*D.y
q0 = dynamicsymbols('q0')
q0d = dynamicsymbols('q0', 1)
E = N.orientnew('E', 'Quaternion', (q0, q1, q2, q3))
assert E.ang_vel_in(N) == (
2 * (q1d * q0 + q2d * q3 - q3d * q2 - q0d * q1) * E.x +
2 * (q2d * q0 + q3d * q1 - q1d * q3 - q0d * q2) * E.y +
2 * (q3d * q0 + q1d * q2 - q2d * q1 - q0d * q3) * E.z)
F = N.orientnew('F', 'Body', (q1, q2, q3), 313)
assert F.ang_vel_in(N) == ((sin(q2)*sin(q3)*q1d + cos(q3)*q2d)*F.x +
(sin(q2)*cos(q3)*q1d - sin(q3)*q2d)*F.y + (cos(q2)*q1d + q3d)*F.z)
G = N.orientnew('G', 'Axis', (q1, N.x + N.y))
assert G.ang_vel_in(N) == q1d * (N.x + N.y).normalize()
assert N.ang_vel_in(G) == -q1d * (N.x + N.y).normalize()
def test_dcm():
q1, q2, q3, q4 = dynamicsymbols('q1 q2 q3 q4')
N = ReferenceFrame('N')
A = N.orientnew('A', 'Axis', [q1, N.z])
B = A.orientnew('B', 'Axis', [q2, A.x])
C = B.orientnew('C', 'Axis', [q3, B.y])
D = N.orientnew('D', 'Axis', [q4, N.y])
E = N.orientnew('E', 'Space', [q1, q2, q3], '123')
assert N.dcm(C) == Matrix([
[- sin(q1) * sin(q2) * sin(q3) + cos(q1) * cos(q3), - sin(q1) *
cos(q2), sin(q1) * sin(q2) * cos(q3) + sin(q3) * cos(q1)], [sin(q1) *
cos(q3) + sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) *
sin(q3) - sin(q2) * cos(q1) * cos(q3)], [- sin(q3) * cos(q2), sin(q2),
cos(q2) * cos(q3)]])
# This is a little touchy. Is it ok to use simplify in assert?
test_mat = D.dcm(C) - Matrix(
[[cos(q1) * cos(q3) * cos(q4) - sin(q3) * (- sin(q4) * cos(q2) +
sin(q1) * sin(q2) * cos(q4)), - sin(q2) * sin(q4) - sin(q1) *
cos(q2) * cos(q4), sin(q3) * cos(q1) * cos(q4) + cos(q3) * (- sin(q4) *
cos(q2) + sin(q1) * sin(q2) * cos(q4))], [sin(q1) * cos(q3) +
sin(q2) * sin(q3) * cos(q1), cos(q1) * cos(q2), sin(q1) * sin(q3) -
sin(q2) * cos(q1) * cos(q3)], [sin(q4) * cos(q1) * cos(q3) -
sin(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4)), sin(q2) *
cos(q4) - sin(q1) * sin(q4) * cos(q2), sin(q3) * sin(q4) * cos(q1) +
cos(q3) * (cos(q2) * cos(q4) + sin(q1) * sin(q2) * sin(q4))]])
assert test_mat.expand() == zeros(3, 3)
assert E.dcm(N) == Matrix(
[[cos(q2)*cos(q3), sin(q3)*cos(q2), -sin(q2)],
[sin(q1)*sin(q2)*cos(q3) - sin(q3)*cos(q1), sin(q1)*sin(q2)*sin(q3) +
cos(q1)*cos(q3), sin(q1)*cos(q2)], [sin(q1)*sin(q3) +
sin(q2)*cos(q1)*cos(q3), - sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1),
cos(q1)*cos(q2)]])
def test_w_diff_dcm1():
# Ref:
# Dynamics Theory and Applications, Kane 1985
# Sec. 2.1 ANGULAR VELOCITY
A = ReferenceFrame('A')
B = ReferenceFrame('B')
c11, c12, c13 = dynamicsymbols('C11 C12 C13')
c21, c22, c23 = dynamicsymbols('C21 C22 C23')
c31, c32, c33 = dynamicsymbols('C31 C32 C33')
c11d, c12d, c13d = dynamicsymbols('C11 C12 C13', level=1)
c21d, c22d, c23d = dynamicsymbols('C21 C22 C23', level=1)
c31d, c32d, c33d = dynamicsymbols('C31 C32 C33', level=1)
DCM = Matrix([
[c11, c12, c13],
[c21, c22, c23],
[c31, c32, c33]
])
B.orient(A, 'DCM', DCM)
b1a = (B.x).express(A)
b2a = (B.y).express(A)
b3a = (B.z).express(A)
# Equation (2.1.1)
B.set_ang_vel(A, B.x*(dot((b3a).dt(A), B.y))
+ B.y*(dot((b1a).dt(A), B.z))
+ B.z*(dot((b2a).dt(A), B.x)))
# Equation (2.1.21)
expr = ( (c12*c13d + c22*c23d + c32*c33d)*B.x
+ (c13*c11d + c23*c21d + c33*c31d)*B.y
+ (c11*c12d + c21*c22d + c31*c32d)*B.z)
assert B.ang_vel_in(A) - expr == 0
def test_w_diff_dcm2():
q1, q2, q3 = dynamicsymbols('q1:4')
N = ReferenceFrame('N')
A = N.orientnew('A', 'axis', [q1, N.x])
B = A.orientnew('B', 'axis', [q2, A.y])
C = B.orientnew('C', 'axis', [q3, B.z])
DCM = C.dcm(N).T
D = N.orientnew('D', 'DCM', DCM)
# Frames D and C are the same ReferenceFrame,
# since they have equal DCM respect to frame N.
# Therefore, D and C should have same angle velocity in N.
assert D.dcm(N) == C.dcm(N) == Matrix([
[cos(q2)*cos(q3), sin(q1)*sin(q2)*cos(q3) +
sin(q3)*cos(q1), sin(q1)*sin(q3) -
sin(q2)*cos(q1)*cos(q3)], [-sin(q3)*cos(q2),
-sin(q1)*sin(q2)*sin(q3) + cos(q1)*cos(q3),
sin(q1)*cos(q3) + sin(q2)*sin(q3)*cos(q1)],
[sin(q2), -sin(q1)*cos(q2), cos(q1)*cos(q2)]])
assert (D.ang_vel_in(N) - C.ang_vel_in(N)).express(N).simplify() == 0
def test_orientnew_respects_parent_class():
class MyReferenceFrame(ReferenceFrame):
pass
B = MyReferenceFrame('B')
C = B.orientnew('C', 'Axis', [0, B.x])
assert isinstance(C, MyReferenceFrame)
def test_orientnew_respects_input_indices():
N = ReferenceFrame('N')
q1 = dynamicsymbols('q1')
A = N.orientnew('a', 'Axis', [q1, N.z])
#modify default indices:
minds = [x+'1' for x in N.indices]
B = N.orientnew('b', 'Axis', [q1, N.z], indices=minds)
assert N.indices == A.indices
assert B.indices == minds
def test_orientnew_respects_input_latexs():
N = ReferenceFrame('N')
q1 = dynamicsymbols('q1')
A = N.orientnew('a', 'Axis', [q1, N.z])
#build default and alternate latex_vecs:
def_latex_vecs = [(r"\mathbf{\hat{%s}_%s}" % (A.name.lower(),
A.indices[0])), (r"\mathbf{\hat{%s}_%s}" %
(A.name.lower(), A.indices[1])),
(r"\mathbf{\hat{%s}_%s}" % (A.name.lower(),
A.indices[2]))]
name = 'b'
indices = [x+'1' for x in N.indices]
new_latex_vecs = [(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[0])), (r"\mathbf{\hat{%s}_{%s}}" %
(name.lower(), indices[1])),
(r"\mathbf{\hat{%s}_{%s}}" % (name.lower(),
indices[2]))]
B = N.orientnew(name, 'Axis', [q1, N.z], latexs=new_latex_vecs)
assert A.latex_vecs == def_latex_vecs
assert B.latex_vecs == new_latex_vecs
assert B.indices != indices
def test_orientnew_respects_input_variables():
N = ReferenceFrame('N')
q1 = dynamicsymbols('q1')
A = N.orientnew('a', 'Axis', [q1, N.z])
#build non-standard variable names
name = 'b'
new_variables = ['notb_'+x+'1' for x in N.indices]
B = N.orientnew(name, 'Axis', [q1, N.z], variables=new_variables)
for j,var in enumerate(A.varlist):
assert var.name == A.name + '_' + A.indices[j]
for j,var in enumerate(B.varlist):
assert var.name == new_variables[j]
def test_issue_10348():
u = dynamicsymbols('u:3')
I = ReferenceFrame('I')
I.orientnew('A', 'space', u, 'XYZ')
def test_issue_11503():
A = ReferenceFrame("A")
A.orientnew("B", "Axis", [35, A.y])
C = ReferenceFrame("C")
A.orient(C, "Axis", [70, C.z])
def test_partial_velocity():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
u1, u2 = dynamicsymbols('u1, u2')
A.set_ang_vel(N, u1 * A.x + u2 * N.y)
assert N.partial_velocity(A, u1) == -A.x
assert N.partial_velocity(A, u1, u2) == (-A.x, -N.y)
assert A.partial_velocity(N, u1) == A.x
assert A.partial_velocity(N, u1, u2) == (A.x, N.y)
assert N.partial_velocity(N, u1) == 0
assert A.partial_velocity(A, u1) == 0
def test_issue_11498():
A = ReferenceFrame('A')
B = ReferenceFrame('B')
# Identity transformation
A.orient(B, 'DCM', eye(3))
assert A.dcm(B) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
assert B.dcm(A) == Matrix([[1, 0, 0], [0, 1, 0], [0, 0, 1]])
# x -> y
# y -> -z
# z -> -x
A.orient(B, 'DCM', Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]]))
assert B.dcm(A) == Matrix([[0, 1, 0], [0, 0, -1], [-1, 0, 0]])
assert A.dcm(B) == Matrix([[0, 0, -1], [1, 0, 0], [0, -1, 0]])
assert B.dcm(A).T == A.dcm(B)
def test_reference_frame():
raises(TypeError, lambda: ReferenceFrame(0))
raises(TypeError, lambda: ReferenceFrame('N', 0))
raises(ValueError, lambda: ReferenceFrame('N', [0, 1]))
raises(TypeError, lambda: ReferenceFrame('N', [0, 1, 2]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], 0))
raises(ValueError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], [0, 1]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'], [0, 1, 2]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'],
['a', 'b', 'c'], 0))
raises(ValueError, lambda: ReferenceFrame('N', ['a', 'b', 'c'],
['a', 'b', 'c'], [0, 1]))
raises(TypeError, lambda: ReferenceFrame('N', ['a', 'b', 'c'],
['a', 'b', 'c'], [0, 1, 2]))
N = ReferenceFrame('N')
assert N[0] == CoordinateSym('N_x', N, 0)
assert N[1] == CoordinateSym('N_y', N, 1)
assert N[2] == CoordinateSym('N_z', N, 2)
raises(ValueError, lambda: N[3])
N = ReferenceFrame('N', ['a', 'b', 'c'])
assert N['a'] == N.x
assert N['b'] == N.y
assert N['c'] == N.z
raises(ValueError, lambda: N['d'])
assert str(N) == 'N'
A = ReferenceFrame('A')
B = ReferenceFrame('B')
q0, q1, q2, q3 = symbols('q0 q1 q2 q3')
raises(TypeError, lambda: A.orient(B, 'DCM', 0))
raises(TypeError, lambda: B.orient(N, 'Space', [q1, q2, q3], '222'))
raises(TypeError, lambda: B.orient(N, 'Axis', [q1, N.x + 2 * N.y], '222'))
raises(TypeError, lambda: B.orient(N, 'Axis', q1))
raises(TypeError, lambda: B.orient(N, 'Axis', [q1]))
raises(TypeError, lambda: B.orient(N, 'Quaternion', [q0, q1, q2, q3], '222'))
raises(TypeError, lambda: B.orient(N, 'Quaternion', q0))
raises(TypeError, lambda: B.orient(N, 'Quaternion', [q0, q1, q2]))
raises(NotImplementedError, lambda: B.orient(N, 'Foo', [q0, q1, q2]))
raises(TypeError, lambda: B.orient(N, 'Body', [q1, q2], '232'))
raises(TypeError, lambda: B.orient(N, 'Space', [q1, q2], '232'))
N.set_ang_acc(B, 0)
assert N.ang_acc_in(B) == Vector(0)
N.set_ang_vel(B, 0)
assert N.ang_vel_in(B) == Vector(0)
def test_check_frame():
raises(VectorTypeError, lambda: _check_frame(0))
def test_dcm_diff_16824():
# NOTE : This is a regression test for the bug introduced in PR 14758,
# identified in 16824, and solved by PR 16828.
# This is the solution to Problem 2.2 on page 264 in Kane & Lenvinson's
# 1985 book.
q1, q2, q3 = dynamicsymbols('q1:4')
s1 = sin(q1)
c1 = cos(q1)
s2 = sin(q2)
c2 = cos(q2)
s3 = sin(q3)
c3 = cos(q3)
dcm = Matrix([[c2*c3, s1*s2*c3 - s3*c1, c1*s2*c3 + s3*s1],
[c2*s3, s1*s2*s3 + c3*c1, c1*s2*s3 - c3*s1],
[-s2, s1*c2, c1*c2]])
A = ReferenceFrame('A')
B = ReferenceFrame('B')
B.orient(A, 'DCM', dcm)
AwB = B.ang_vel_in(A)
alpha2 = s3*c2*q1.diff() + c3*q2.diff()
beta2 = s1*c2*q3.diff() + c1*q2.diff()
assert simplify(AwB.dot(A.y) - alpha2) == 0
assert simplify(AwB.dot(B.y) - beta2) == 0
|
44d052ec0652b3b15b9f3878d31898ffa73ec403fb00922d613ffc1deba983da | from sympy import S, Symbol, sin, cos
from sympy.physics.vector import ReferenceFrame, Vector, Point, \
dynamicsymbols
from sympy.physics.vector.fieldfunctions import divergence, \
gradient, curl, is_conservative, is_solenoidal, \
scalar_potential, scalar_potential_difference
from sympy.testing.pytest import raises
R = ReferenceFrame('R')
q = dynamicsymbols('q')
P = R.orientnew('P', 'Axis', [q, R.z])
def test_curl():
assert curl(Vector(0), R) == Vector(0)
assert curl(R.x, R) == Vector(0)
assert curl(2*R[1]**2*R.y, R) == Vector(0)
assert curl(R[0]*R[1]*R.z, R) == R[0]*R.x - R[1]*R.y
assert curl(R[0]*R[1]*R[2] * (R.x+R.y+R.z), R) == \
(-R[0]*R[1] + R[0]*R[2])*R.x + (R[0]*R[1] - R[1]*R[2])*R.y + \
(-R[0]*R[2] + R[1]*R[2])*R.z
assert curl(2*R[0]**2*R.y, R) == 4*R[0]*R.z
assert curl(P[0]**2*R.x + P.y, R) == \
- 2*(R[0]*cos(q) + R[1]*sin(q))*sin(q)*R.z
assert curl(P[0]*R.y, P) == cos(q)*P.z
def test_divergence():
assert divergence(Vector(0), R) is S.Zero
assert divergence(R.x, R) is S.Zero
assert divergence(R[0]**2*R.x, R) == 2*R[0]
assert divergence(R[0]*R[1]*R[2] * (R.x+R.y+R.z), R) == \
R[0]*R[1] + R[0]*R[2] + R[1]*R[2]
assert divergence((1/(R[0]*R[1]*R[2])) * (R.x+R.y+R.z), R) == \
-1/(R[0]*R[1]*R[2]**2) - 1/(R[0]*R[1]**2*R[2]) - \
1/(R[0]**2*R[1]*R[2])
v = P[0]*P.x + P[1]*P.y + P[2]*P.z
assert divergence(v, P) == 3
assert divergence(v, R).simplify() == 3
assert divergence(P[0]*R.x + R[0]*P.x, R) == 2*cos(q)
def test_gradient():
a = Symbol('a')
assert gradient(0, R) == Vector(0)
assert gradient(R[0], R) == R.x
assert gradient(R[0]*R[1]*R[2], R) == \
R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z
assert gradient(2*R[0]**2, R) == 4*R[0]*R.x
assert gradient(a*sin(R[1])/R[0], R) == \
- a*sin(R[1])/R[0]**2*R.x + a*cos(R[1])/R[0]*R.y
assert gradient(P[0]*P[1], R) == \
((-R[0]*sin(q) + R[1]*cos(q))*cos(q) - (R[0]*cos(q) + R[1]*sin(q))*sin(q))*R.x + \
((-R[0]*sin(q) + R[1]*cos(q))*sin(q) + (R[0]*cos(q) + R[1]*sin(q))*cos(q))*R.y
assert gradient(P[0]*R[2], P) == P[2]*P.x + P[0]*P.z
scalar_field = 2*R[0]**2*R[1]*R[2]
grad_field = gradient(scalar_field, R)
vector_field = R[1]**2*R.x + 3*R[0]*R.y + 5*R[1]*R[2]*R.z
curl_field = curl(vector_field, R)
def test_conservative():
assert is_conservative(0) is True
assert is_conservative(R.x) is True
assert is_conservative(2 * R.x + 3 * R.y + 4 * R.z) is True
assert is_conservative(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) is \
True
assert is_conservative(R[0] * R.y) is False
assert is_conservative(grad_field) is True
assert is_conservative(curl_field) is False
assert is_conservative(4*R[0]*R[1]*R[2]*R.x + 2*R[0]**2*R[2]*R.y) is \
False
assert is_conservative(R[2]*P.x + P[0]*R.z) is True
def test_solenoidal():
assert is_solenoidal(0) is True
assert is_solenoidal(R.x) is True
assert is_solenoidal(2 * R.x + 3 * R.y + 4 * R.z) is True
assert is_solenoidal(R[1]*R[2]*R.x + R[0]*R[2]*R.y + R[0]*R[1]*R.z) is \
True
assert is_solenoidal(R[1] * R.y) is False
assert is_solenoidal(grad_field) is False
assert is_solenoidal(curl_field) is True
assert is_solenoidal((-2*R[1] + 3)*R.z) is True
assert is_solenoidal(cos(q)*R.x + sin(q)*R.y + cos(q)*P.z) is True
assert is_solenoidal(R[2]*P.x + P[0]*R.z) is True
def test_scalar_potential():
assert scalar_potential(0, R) == 0
assert scalar_potential(R.x, R) == R[0]
assert scalar_potential(R.y, R) == R[1]
assert scalar_potential(R.z, R) == R[2]
assert scalar_potential(R[1]*R[2]*R.x + R[0]*R[2]*R.y + \
R[0]*R[1]*R.z, R) == R[0]*R[1]*R[2]
assert scalar_potential(grad_field, R) == scalar_field
assert scalar_potential(R[2]*P.x + P[0]*R.z, R) == \
R[0]*R[2]*cos(q) + R[1]*R[2]*sin(q)
assert scalar_potential(R[2]*P.x + P[0]*R.z, P) == P[0]*P[2]
raises(ValueError, lambda: scalar_potential(R[0] * R.y, R))
def test_scalar_potential_difference():
origin = Point('O')
point1 = origin.locatenew('P1', 1*R.x + 2*R.y + 3*R.z)
point2 = origin.locatenew('P2', 4*R.x + 5*R.y + 6*R.z)
genericpointR = origin.locatenew('RP', R[0]*R.x + R[1]*R.y + R[2]*R.z)
genericpointP = origin.locatenew('PP', P[0]*P.x + P[1]*P.y + P[2]*P.z)
assert scalar_potential_difference(S.Zero, R, point1, point2, \
origin) == 0
assert scalar_potential_difference(scalar_field, R, origin, \
genericpointR, origin) == \
scalar_field
assert scalar_potential_difference(grad_field, R, origin, \
genericpointR, origin) == \
scalar_field
assert scalar_potential_difference(grad_field, R, point1, point2,
origin) == 948
assert scalar_potential_difference(R[1]*R[2]*R.x + R[0]*R[2]*R.y + \
R[0]*R[1]*R.z, R, point1,
genericpointR, origin) == \
R[0]*R[1]*R[2] - 6
potential_diff_P = 2*P[2]*(P[0]*sin(q) + P[1]*cos(q))*\
(P[0]*cos(q) - P[1]*sin(q))**2
assert scalar_potential_difference(grad_field, P, origin, \
genericpointP, \
origin).simplify() == \
potential_diff_P
|
b52799802f3df5230fae5f2d6c302db5e4e14fec030a34e2e7b1366bc5c3572f | from sympy import sin, cos, symbols, pi, ImmutableMatrix as Matrix
from sympy.physics.vector import ReferenceFrame, Vector, dynamicsymbols
from sympy.physics.vector.dyadic import _check_dyadic
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_dyadic():
d1 = A.x | A.x
d2 = A.y | A.y
d3 = A.x | A.y
assert d1 * 0 == 0
assert d1 != 0
assert d1 * 2 == 2 * A.x | A.x
assert d1 / 2. == 0.5 * d1
assert d1 & (0 * d1) == 0
assert d1 & d2 == 0
assert d1 & A.x == A.x
assert d1 ^ A.x == 0
assert d1 ^ A.y == A.x | A.z
assert d1 ^ A.z == - A.x | A.y
assert d2 ^ A.x == - A.y | A.z
assert A.x ^ d1 == 0
assert A.y ^ d1 == - A.z | A.x
assert A.z ^ d1 == A.y | A.x
assert A.x & d1 == A.x
assert A.y & d1 == 0
assert A.y & d2 == A.y
assert d1 & d3 == A.x | A.y
assert d3 & d1 == 0
assert d1.dt(A) == 0
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
B = A.orientnew('B', 'Axis', [q, A.z])
assert d1.express(B) == d1.express(B, B)
assert d1.express(B) == ((cos(q)**2) * (B.x | B.x) + (-sin(q) * cos(q)) *
(B.x | B.y) + (-sin(q) * cos(q)) * (B.y | B.x) + (sin(q)**2) *
(B.y | B.y))
assert d1.express(B, A) == (cos(q)) * (B.x | A.x) + (-sin(q)) * (B.y | A.x)
assert d1.express(A, B) == (cos(q)) * (A.x | B.x) + (-sin(q)) * (A.x | B.y)
assert d1.dt(B) == (-qd) * (A.y | A.x) + (-qd) * (A.x | A.y)
assert d1.to_matrix(A) == Matrix([[1, 0, 0], [0, 0, 0], [0, 0, 0]])
assert d1.to_matrix(A, B) == Matrix([[cos(q), -sin(q), 0],
[0, 0, 0],
[0, 0, 0]])
assert d3.to_matrix(A) == Matrix([[0, 1, 0], [0, 0, 0], [0, 0, 0]])
a, b, c, d, e, f = symbols('a, b, c, d, e, f')
v1 = a * A.x + b * A.y + c * A.z
v2 = d * A.x + e * A.y + f * A.z
d4 = v1.outer(v2)
assert d4.to_matrix(A) == Matrix([[a * d, a * e, a * f],
[b * d, b * e, b * f],
[c * d, c * e, c * f]])
d5 = v1.outer(v1)
C = A.orientnew('C', 'Axis', [q, A.x])
for expected, actual in zip(C.dcm(A) * d5.to_matrix(A) * C.dcm(A).T,
d5.to_matrix(C)):
assert (expected - actual).simplify() == 0
raises(TypeError, lambda: d1.applyfunc(0))
def test_dyadic_simplify():
x, y, z, k, n, m, w, f, s, A = symbols('x, y, z, k, n, m, w, f, s, A')
N = ReferenceFrame('N')
dy = N.x | N.x
test1 = (1 / x + 1 / y) * dy
assert (N.x & test1 & N.x) != (x + y) / (x * y)
test1 = test1.simplify()
assert (N.x & test1 & N.x) == (x + y) / (x * y)
test2 = (A**2 * s**4 / (4 * pi * k * m**3)) * dy
test2 = test2.simplify()
assert (N.x & test2 & N.x) == (A**2 * s**4 / (4 * pi * k * m**3))
test3 = ((4 + 4 * x - 2 * (2 + 2 * x)) / (2 + 2 * x)) * dy
test3 = test3.simplify()
assert (N.x & test3 & N.x) == 0
test4 = ((-4 * x * y**2 - 2 * y**3 - 2 * x**2 * y) / (x + y)**2) * dy
test4 = test4.simplify()
assert (N.x & test4 & N.x) == -2 * y
def test_dyadic_subs():
N = ReferenceFrame('N')
s = symbols('s')
a = s*(N.x | N.x)
assert a.subs({s: 2}) == 2*(N.x | N.x)
def test_check_dyadic():
raises(TypeError, lambda: _check_dyadic(0))
|
55b3c93317fa87abd8a051395991114567dacb6ce34c6b8e728d597bc95cca30 | from sympy.physics.vector import dynamicsymbols, Point, ReferenceFrame
from sympy.testing.pytest import raises
def test_point_v1pt_theorys():
q, q2 = dynamicsymbols('q q2')
qd, q2d = dynamicsymbols('q q2', 1)
qdd, q2dd = dynamicsymbols('q q2', 2)
N = ReferenceFrame('N')
B = ReferenceFrame('B')
B.set_ang_vel(N, qd * B.z)
O = Point('O')
P = O.locatenew('P', B.x)
P.set_vel(B, 0)
O.set_vel(N, 0)
assert P.v1pt_theory(O, N, B) == qd * B.y
O.set_vel(N, N.x)
assert P.v1pt_theory(O, N, B) == N.x + qd * B.y
P.set_vel(B, B.z)
assert P.v1pt_theory(O, N, B) == B.z + N.x + qd * B.y
def test_point_a1pt_theorys():
q, q2 = dynamicsymbols('q q2')
qd, q2d = dynamicsymbols('q q2', 1)
qdd, q2dd = dynamicsymbols('q q2', 2)
N = ReferenceFrame('N')
B = ReferenceFrame('B')
B.set_ang_vel(N, qd * B.z)
O = Point('O')
P = O.locatenew('P', B.x)
P.set_vel(B, 0)
O.set_vel(N, 0)
assert P.a1pt_theory(O, N, B) == -(qd**2) * B.x + qdd * B.y
P.set_vel(B, q2d * B.z)
assert P.a1pt_theory(O, N, B) == -(qd**2) * B.x + qdd * B.y + q2dd * B.z
O.set_vel(N, q2d * B.x)
assert P.a1pt_theory(O, N, B) == ((q2dd - qd**2) * B.x + (q2d * qd + qdd) * B.y +
q2dd * B.z)
def test_point_v2pt_theorys():
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
N = ReferenceFrame('N')
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 0)
O.set_vel(N, 0)
assert P.v2pt_theory(O, N, B) == 0
P = O.locatenew('P', B.x)
assert P.v2pt_theory(O, N, B) == (qd * B.z ^ B.x)
O.set_vel(N, N.x)
assert P.v2pt_theory(O, N, B) == N.x + qd * B.y
def test_point_a2pt_theorys():
q = dynamicsymbols('q')
qd = dynamicsymbols('q', 1)
qdd = dynamicsymbols('q', 2)
N = ReferenceFrame('N')
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 0)
O.set_vel(N, 0)
assert P.a2pt_theory(O, N, B) == 0
P.set_pos(O, B.x)
assert P.a2pt_theory(O, N, B) == (-qd**2) * B.x + (qdd) * B.y
def test_point_funcs():
q, q2 = dynamicsymbols('q q2')
qd, q2d = dynamicsymbols('q q2', 1)
qdd, q2dd = dynamicsymbols('q q2', 2)
N = ReferenceFrame('N')
B = ReferenceFrame('B')
B.set_ang_vel(N, 5 * B.y)
O = Point('O')
P = O.locatenew('P', q * B.x)
assert P.pos_from(O) == q * B.x
P.set_vel(B, qd * B.x + q2d * B.y)
assert P.vel(B) == qd * B.x + q2d * B.y
O.set_vel(N, 0)
assert O.vel(N) == 0
assert P.a1pt_theory(O, N, B) == ((-25 * q + qdd) * B.x + (q2dd) * B.y +
(-10 * qd) * B.z)
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 10 * B.x)
O.set_vel(N, 5 * N.x)
assert O.vel(N) == 5 * N.x
assert P.a2pt_theory(O, N, B) == (-10 * qd**2) * B.x + (10 * qdd) * B.y
B.set_ang_vel(N, 5 * B.y)
O = Point('O')
P = O.locatenew('P', q * B.x)
P.set_vel(B, qd * B.x + q2d * B.y)
O.set_vel(N, 0)
assert P.v1pt_theory(O, N, B) == qd * B.x + q2d * B.y - 5 * q * B.z
def test_point_pos():
q = dynamicsymbols('q')
N = ReferenceFrame('N')
B = N.orientnew('B', 'Axis', [q, N.z])
O = Point('O')
P = O.locatenew('P', 10 * N.x + 5 * B.x)
assert P.pos_from(O) == 10 * N.x + 5 * B.x
Q = P.locatenew('Q', 10 * N.y + 5 * B.y)
assert Q.pos_from(P) == 10 * N.y + 5 * B.y
assert Q.pos_from(O) == 10 * N.x + 10 * N.y + 5 * B.x + 5 * B.y
assert O.pos_from(Q) == -10 * N.x - 10 * N.y - 5 * B.x - 5 * B.y
def test_point_partial_velocity():
N = ReferenceFrame('N')
A = ReferenceFrame('A')
p = Point('p')
u1, u2 = dynamicsymbols('u1, u2')
p.set_vel(N, u1 * A.x + u2 * N.y)
assert p.partial_velocity(N, u1) == A.x
assert p.partial_velocity(N, u1, u2) == (A.x, N.y)
raises(ValueError, lambda: p.partial_velocity(A, u1))
|
18548dad6ba50095911d6415c422a2defdb70a1a26ecf96183349ed27192354c | from sympy import S
from sympy.physics.vector import Vector, ReferenceFrame, Dyadic
from sympy.testing.pytest import raises
Vector.simp = True
A = ReferenceFrame('A')
def test_output_type():
A = ReferenceFrame('A')
v = A.x + A.y
d = v | v
zerov = Vector(0)
zerod = Dyadic(0)
# dot products
assert isinstance(d & d, Dyadic)
assert isinstance(d & zerod, Dyadic)
assert isinstance(zerod & d, Dyadic)
assert isinstance(d & v, Vector)
assert isinstance(v & d, Vector)
assert isinstance(d & zerov, Vector)
assert isinstance(zerov & d, Vector)
raises(TypeError, lambda: d & S.Zero)
raises(TypeError, lambda: S.Zero & d)
raises(TypeError, lambda: d & 0)
raises(TypeError, lambda: 0 & d)
assert not isinstance(v & v, (Vector, Dyadic))
assert not isinstance(v & zerov, (Vector, Dyadic))
assert not isinstance(zerov & v, (Vector, Dyadic))
raises(TypeError, lambda: v & S.Zero)
raises(TypeError, lambda: S.Zero & v)
raises(TypeError, lambda: v & 0)
raises(TypeError, lambda: 0 & v)
# cross products
raises(TypeError, lambda: d ^ d)
raises(TypeError, lambda: d ^ zerod)
raises(TypeError, lambda: zerod ^ d)
assert isinstance(d ^ v, Dyadic)
assert isinstance(v ^ d, Dyadic)
assert isinstance(d ^ zerov, Dyadic)
assert isinstance(zerov ^ d, Dyadic)
assert isinstance(zerov ^ d, Dyadic)
raises(TypeError, lambda: d ^ S.Zero)
raises(TypeError, lambda: S.Zero ^ d)
raises(TypeError, lambda: d ^ 0)
raises(TypeError, lambda: 0 ^ d)
assert isinstance(v ^ v, Vector)
assert isinstance(v ^ zerov, Vector)
assert isinstance(zerov ^ v, Vector)
raises(TypeError, lambda: v ^ S.Zero)
raises(TypeError, lambda: S.Zero ^ v)
raises(TypeError, lambda: v ^ 0)
raises(TypeError, lambda: 0 ^ v)
# outer products
raises(TypeError, lambda: d | d)
raises(TypeError, lambda: d | zerod)
raises(TypeError, lambda: zerod | d)
raises(TypeError, lambda: d | v)
raises(TypeError, lambda: v | d)
raises(TypeError, lambda: d | zerov)
raises(TypeError, lambda: zerov | d)
raises(TypeError, lambda: zerov | d)
raises(TypeError, lambda: d | S.Zero)
raises(TypeError, lambda: S.Zero | d)
raises(TypeError, lambda: d | 0)
raises(TypeError, lambda: 0 | d)
assert isinstance(v | v, Dyadic)
assert isinstance(v | zerov, Dyadic)
assert isinstance(zerov | v, Dyadic)
raises(TypeError, lambda: v | S.Zero)
raises(TypeError, lambda: S.Zero | v)
raises(TypeError, lambda: v | 0)
raises(TypeError, lambda: 0 | v)
|
87bcae5a062a11a639ecbe5bce8a1d97cc46ab4ed4606c49d4d5442f047ba581 | from sympy import Symbol, symbols, S, Interval, pi, Rational, simplify
from sympy.physics.continuum_mechanics.beam import Beam
from sympy.functions import SingularityFunction, Piecewise, meijerg, Abs, log
from sympy.testing.pytest import raises
from sympy.physics.units import meter, newton, kilo, giga, milli
from sympy.physics.continuum_mechanics.beam import Beam3D
from sympy.geometry import Circle, Polygon, Point2D, Triangle
x = Symbol('x')
y = Symbol('y')
R1, R2 = symbols('R1, R2')
def test_Beam():
E = Symbol('E')
E_1 = Symbol('E_1')
I = Symbol('I')
I_1 = Symbol('I_1')
b = Beam(1, E, I)
assert b.length == 1
assert b.elastic_modulus == E
assert b.second_moment == I
assert b.variable == x
# Test the length setter
b.length = 4
assert b.length == 4
# Test the E setter
b.elastic_modulus = E_1
assert b.elastic_modulus == E_1
# Test the I setter
b.second_moment = I_1
assert b.second_moment is I_1
# Test the variable setter
b.variable = y
assert b.variable is y
# Test for all boundary conditions.
b.bc_deflection = [(0, 2)]
b.bc_slope = [(0, 1)]
assert b.boundary_conditions == {'deflection': [(0, 2)], 'slope': [(0, 1)]}
# Test for slope boundary condition method
b.bc_slope.extend([(4, 3), (5, 0)])
s_bcs = b.bc_slope
assert s_bcs == [(0, 1), (4, 3), (5, 0)]
# Test for deflection boundary condition method
b.bc_deflection.extend([(4, 3), (5, 0)])
d_bcs = b.bc_deflection
assert d_bcs == [(0, 2), (4, 3), (5, 0)]
# Test for updated boundary conditions
bcs_new = b.boundary_conditions
assert bcs_new == {
'deflection': [(0, 2), (4, 3), (5, 0)],
'slope': [(0, 1), (4, 3), (5, 0)]}
b1 = Beam(30, E, I)
b1.apply_load(-8, 0, -1)
b1.apply_load(R1, 10, -1)
b1.apply_load(R2, 30, -1)
b1.apply_load(120, 30, -2)
b1.bc_deflection = [(10, 0), (30, 0)]
b1.solve_for_reaction_loads(R1, R2)
# Test for finding reaction forces
p = b1.reaction_loads
q = {R1: 6, R2: 2}
assert p == q
# Test for load distribution function.
p = b1.load
q = -8*SingularityFunction(x, 0, -1) + 6*SingularityFunction(x, 10, -1) + 120*SingularityFunction(x, 30, -2) + 2*SingularityFunction(x, 30, -1)
assert p == q
# Test for shear force distribution function
p = b1.shear_force()
q = -8*SingularityFunction(x, 0, 0) + 6*SingularityFunction(x, 10, 0) + 120*SingularityFunction(x, 30, -1) + 2*SingularityFunction(x, 30, 0)
assert p == q
# Test for bending moment distribution function
p = b1.bending_moment()
q = -8*SingularityFunction(x, 0, 1) + 6*SingularityFunction(x, 10, 1) + 120*SingularityFunction(x, 30, 0) + 2*SingularityFunction(x, 30, 1)
assert p == q
# Test for slope distribution function
p = b1.slope()
q = -4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2) + 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + Rational(4000, 3)
assert p == q/(E*I)
# Test for deflection distribution function
p = b1.deflection()
q = x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3) + 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000
assert p == q/(E*I)
# Test using symbols
l = Symbol('l')
w0 = Symbol('w0')
w2 = Symbol('w2')
a1 = Symbol('a1')
c = Symbol('c')
c1 = Symbol('c1')
d = Symbol('d')
e = Symbol('e')
f = Symbol('f')
b2 = Beam(l, E, I)
b2.apply_load(w0, a1, 1)
b2.apply_load(w2, c1, -1)
b2.bc_deflection = [(c, d)]
b2.bc_slope = [(e, f)]
# Test for load distribution function.
p = b2.load
q = w0*SingularityFunction(x, a1, 1) + w2*SingularityFunction(x, c1, -1)
assert p == q
# Test for shear force distribution function
p = b2.shear_force()
q = w0*SingularityFunction(x, a1, 2)/2 + w2*SingularityFunction(x, c1, 0)
assert p == q
# Test for bending moment distribution function
p = b2.bending_moment()
q = w0*SingularityFunction(x, a1, 3)/6 + w2*SingularityFunction(x, c1, 1)
assert p == q
# Test for slope distribution function
p = b2.slope()
q = (w0*SingularityFunction(x, a1, 4)/24 + w2*SingularityFunction(x, c1, 2)/2)/(E*I) + (E*I*f - w0*SingularityFunction(e, a1, 4)/24 - w2*SingularityFunction(e, c1, 2)/2)/(E*I)
assert p == q
# Test for deflection distribution function
p = b2.deflection()
q = x*(E*I*f - w0*SingularityFunction(e, a1, 4)/24 - w2*SingularityFunction(e, c1, 2)/2)/(E*I) + (w0*SingularityFunction(x, a1, 5)/120 + w2*SingularityFunction(x, c1, 3)/6)/(E*I) + (E*I*(-c*f + d) + c*w0*SingularityFunction(e, a1, 4)/24 + c*w2*SingularityFunction(e, c1, 2)/2 - w0*SingularityFunction(c, a1, 5)/120 - w2*SingularityFunction(c, c1, 3)/6)/(E*I)
assert simplify(p - q) == 0
b3 = Beam(9, E, I)
b3.apply_load(value=-2, start=2, order=2, end=3)
b3.bc_slope.append((0, 2))
C3 = symbols('C3')
C4 = symbols('C4')
p = b3.load
q = -2*SingularityFunction(x, 2, 2) + 2*SingularityFunction(x, 3, 0) + 4*SingularityFunction(x, 3, 1) + 2*SingularityFunction(x, 3, 2)
assert p == q
p = b3.slope()
q = 2 + (-SingularityFunction(x, 2, 5)/30 + SingularityFunction(x, 3, 3)/3 + SingularityFunction(x, 3, 4)/6 + SingularityFunction(x, 3, 5)/30)/(E*I)
assert p == q
p = b3.deflection()
q = 2*x + (-SingularityFunction(x, 2, 6)/180 + SingularityFunction(x, 3, 4)/12 + SingularityFunction(x, 3, 5)/30 + SingularityFunction(x, 3, 6)/180)/(E*I)
assert p == q + C4
b4 = Beam(4, E, I)
b4.apply_load(-3, 0, 0, end=3)
p = b4.load
q = -3*SingularityFunction(x, 0, 0) + 3*SingularityFunction(x, 3, 0)
assert p == q
p = b4.slope()
q = -3*SingularityFunction(x, 0, 3)/6 + 3*SingularityFunction(x, 3, 3)/6
assert p == q/(E*I) + C3
p = b4.deflection()
q = -3*SingularityFunction(x, 0, 4)/24 + 3*SingularityFunction(x, 3, 4)/24
assert p == q/(E*I) + C3*x + C4
# can't use end with point loads
raises(ValueError, lambda: b4.apply_load(-3, 0, -1, end=3))
with raises(TypeError):
b4.variable = 1
def test_insufficient_bconditions():
# Test cases when required number of boundary conditions
# are not provided to solve the integration constants.
L = symbols('L', positive=True)
E, I, P, a3, a4 = symbols('E I P a3 a4')
b = Beam(L, E, I, base_char='a')
b.apply_load(R2, L, -1)
b.apply_load(R1, 0, -1)
b.apply_load(-P, L/2, -1)
b.solve_for_reaction_loads(R1, R2)
p = b.slope()
q = P*SingularityFunction(x, 0, 2)/4 - P*SingularityFunction(x, L/2, 2)/2 + P*SingularityFunction(x, L, 2)/4
assert p == q/(E*I) + a3
p = b.deflection()
q = P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
assert p == q/(E*I) + a3*x + a4
b.bc_deflection = [(0, 0)]
p = b.deflection()
q = a3*x + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
assert p == q/(E*I)
b.bc_deflection = [(0, 0), (L, 0)]
p = b.deflection()
q = -L**2*P*x/16 + P*SingularityFunction(x, 0, 3)/12 - P*SingularityFunction(x, L/2, 3)/6 + P*SingularityFunction(x, L, 3)/12
assert p == q/(E*I)
def test_statically_indeterminate():
E = Symbol('E')
I = Symbol('I')
M1, M2 = symbols('M1, M2')
F = Symbol('F')
l = Symbol('l', positive=True)
b5 = Beam(l, E, I)
b5.bc_deflection = [(0, 0),(l, 0)]
b5.bc_slope = [(0, 0),(l, 0)]
b5.apply_load(R1, 0, -1)
b5.apply_load(M1, 0, -2)
b5.apply_load(R2, l, -1)
b5.apply_load(M2, l, -2)
b5.apply_load(-F, l/2, -1)
b5.solve_for_reaction_loads(R1, R2, M1, M2)
p = b5.reaction_loads
q = {R1: F/2, R2: F/2, M1: -F*l/8, M2: F*l/8}
assert p == q
def test_beam_units():
E = Symbol('E')
I = Symbol('I')
R1, R2 = symbols('R1, R2')
b = Beam(8*meter, 200*giga*newton/meter**2, 400*1000000*(milli*meter)**4)
b.apply_load(5*kilo*newton, 2*meter, -1)
b.apply_load(R1, 0*meter, -1)
b.apply_load(R2, 8*meter, -1)
b.apply_load(10*kilo*newton/meter, 4*meter, 0, end=8*meter)
b.bc_deflection = [(0*meter, 0*meter), (8*meter, 0*meter)]
b.solve_for_reaction_loads(R1, R2)
assert b.reaction_loads == {R1: -13750*newton, R2: -31250*newton}
b = Beam(3*meter, E*newton/meter**2, I*meter**4)
b.apply_load(8*kilo*newton, 1*meter, -1)
b.apply_load(R1, 0*meter, -1)
b.apply_load(R2, 3*meter, -1)
b.apply_load(12*kilo*newton*meter, 2*meter, -2)
b.bc_deflection = [(0*meter, 0*meter), (3*meter, 0*meter)]
b.solve_for_reaction_loads(R1, R2)
assert b.reaction_loads == {R1: newton*Rational(-28000, 3), R2: newton*Rational(4000, 3)}
assert b.deflection().subs(x, 1*meter) == 62000*meter/(9*E*I)
def test_variable_moment():
E = Symbol('E')
I = Symbol('I')
b = Beam(4, E, 2*(4 - x))
b.apply_load(20, 4, -1)
R, M = symbols('R, M')
b.apply_load(R, 0, -1)
b.apply_load(M, 0, -2)
b.bc_deflection = [(0, 0)]
b.bc_slope = [(0, 0)]
b.solve_for_reaction_loads(R, M)
assert b.slope().expand() == ((10*x*SingularityFunction(x, 0, 0)
- 10*(x - 4)*SingularityFunction(x, 4, 0))/E).expand()
assert b.deflection().expand() == ((5*x**2*SingularityFunction(x, 0, 0)
- 10*Piecewise((0, Abs(x)/4 < 1), (16*meijerg(((3, 1), ()), ((), (2, 0)), x/4), True))
+ 40*SingularityFunction(x, 4, 1))/E).expand()
b = Beam(4, E - x, I)
b.apply_load(20, 4, -1)
R, M = symbols('R, M')
b.apply_load(R, 0, -1)
b.apply_load(M, 0, -2)
b.bc_deflection = [(0, 0)]
b.bc_slope = [(0, 0)]
b.solve_for_reaction_loads(R, M)
assert b.slope().expand() == ((-80*(-log(-E) + log(-E + x))*SingularityFunction(x, 0, 0)
+ 80*(-log(-E + 4) + log(-E + x))*SingularityFunction(x, 4, 0) + 20*(-E*log(-E)
+ E*log(-E + x) + x)*SingularityFunction(x, 0, 0) - 20*(-E*log(-E + 4) + E*log(-E + x)
+ x - 4)*SingularityFunction(x, 4, 0))/I).expand()
def test_composite_beam():
E = Symbol('E')
I = Symbol('I')
b1 = Beam(2, E, 1.5*I)
b2 = Beam(2, E, I)
b = b1.join(b2, "fixed")
b.apply_load(-20, 0, -1)
b.apply_load(80, 0, -2)
b.apply_load(20, 4, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0)]
assert b.length == 4
assert b.second_moment == Piecewise((1.5*I, x <= 2), (I, x <= 4))
assert b.slope().subs(x, 4) == 120.0/(E*I)
assert b.slope().subs(x, 2) == 80.0/(E*I)
assert int(b.deflection().subs(x, 4).args[0]) == 302 # Coefficient of 1/(E*I)
l = symbols('l', positive=True)
R1, M1, R2, R3, P = symbols('R1 M1 R2 R3 P')
b1 = Beam(2*l, E, I)
b2 = Beam(2*l, E, I)
b = b1.join(b2,"hinge")
b.apply_load(M1, 0, -2)
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(R3, 4*l, -1)
b.apply_load(P, 3*l, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0), (l, 0), (4*l, 0)]
b.solve_for_reaction_loads(M1, R1, R2, R3)
assert b.reaction_loads == {R3: -P/2, R2: P*Rational(-5, 4), M1: -P*l/4, R1: P*Rational(3, 4)}
assert b.slope().subs(x, 3*l) == -7*P*l**2/(48*E*I)
assert b.deflection().subs(x, 2*l) == 7*P*l**3/(24*E*I)
assert b.deflection().subs(x, 3*l) == 5*P*l**3/(16*E*I)
# When beams having same second moment are joined.
b1 = Beam(2, 500, 10)
b2 = Beam(2, 500, 10)
b = b1.join(b2, "fixed")
b.apply_load(M1, 0, -2)
b.apply_load(R1, 0, -1)
b.apply_load(R2, 1, -1)
b.apply_load(R3, 4, -1)
b.apply_load(10, 3, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0), (1, 0), (4, 0)]
b.solve_for_reaction_loads(M1, R1, R2, R3)
assert b.slope() == -2*SingularityFunction(x, 0, 1)/5625 + SingularityFunction(x, 0, 2)/1875\
- 133*SingularityFunction(x, 1, 2)/135000 + SingularityFunction(x, 3, 2)/1000\
- 37*SingularityFunction(x, 4, 2)/67500
assert b.deflection() == -SingularityFunction(x, 0, 2)/5625 + SingularityFunction(x, 0, 3)/5625\
- 133*SingularityFunction(x, 1, 3)/405000 + SingularityFunction(x, 3, 3)/3000\
- 37*SingularityFunction(x, 4, 3)/202500
def test_point_cflexure():
E = Symbol('E')
I = Symbol('I')
b = Beam(10, E, I)
b.apply_load(-4, 0, -1)
b.apply_load(-46, 6, -1)
b.apply_load(10, 2, -1)
b.apply_load(20, 4, -1)
b.apply_load(3, 6, 0)
assert b.point_cflexure() == [Rational(10, 3)]
def test_remove_load():
E = Symbol('E')
I = Symbol('I')
b = Beam(4, E, I)
try:
b.remove_load(2, 1, -1)
# As no load is applied on beam, ValueError should be returned.
except ValueError:
assert True
else:
assert False
b.apply_load(-3, 0, -2)
b.apply_load(4, 2, -1)
b.apply_load(-2, 2, 2, end = 3)
b.remove_load(-2, 2, 2, end = 3)
assert b.load == -3*SingularityFunction(x, 0, -2) + 4*SingularityFunction(x, 2, -1)
assert b.applied_loads == [(-3, 0, -2, None), (4, 2, -1, None)]
try:
b.remove_load(1, 2, -1)
# As load of this magnitude was never applied at
# this position, method should return a ValueError.
except ValueError:
assert True
else:
assert False
b.remove_load(-3, 0, -2)
b.remove_load(4, 2, -1)
assert b.load == 0
assert b.applied_loads == []
def test_apply_support():
E = Symbol('E')
I = Symbol('I')
b = Beam(4, E, I)
b.apply_support(0, "cantilever")
b.apply_load(20, 4, -1)
M_0, R_0 = symbols('M_0, R_0')
b.solve_for_reaction_loads(R_0, M_0)
assert b.slope() == (80*SingularityFunction(x, 0, 1) - 10*SingularityFunction(x, 0, 2)
+ 10*SingularityFunction(x, 4, 2))/(E*I)
assert b.deflection() == (40*SingularityFunction(x, 0, 2) - 10*SingularityFunction(x, 0, 3)/3
+ 10*SingularityFunction(x, 4, 3)/3)/(E*I)
b = Beam(30, E, I)
b.apply_support(10, "pin")
b.apply_support(30, "roller")
b.apply_load(-8, 0, -1)
b.apply_load(120, 30, -2)
R_10, R_30 = symbols('R_10, R_30')
b.solve_for_reaction_loads(R_10, R_30)
assert b.slope() == (-4*SingularityFunction(x, 0, 2) + 3*SingularityFunction(x, 10, 2)
+ 120*SingularityFunction(x, 30, 1) + SingularityFunction(x, 30, 2) + Rational(4000, 3))/(E*I)
assert b.deflection() == (x*Rational(4000, 3) - 4*SingularityFunction(x, 0, 3)/3 + SingularityFunction(x, 10, 3)
+ 60*SingularityFunction(x, 30, 2) + SingularityFunction(x, 30, 3)/3 - 12000)/(E*I)
P = Symbol('P', positive=True)
L = Symbol('L', positive=True)
b = Beam(L, E, I)
b.apply_support(0, type='fixed')
b.apply_support(L, type='fixed')
b.apply_load(-P, L/2, -1)
R_0, R_L, M_0, M_L = symbols('R_0, R_L, M_0, M_L')
b.solve_for_reaction_loads(R_0, R_L, M_0, M_L)
assert b.reaction_loads == {R_0: P/2, R_L: P/2, M_0: -L*P/8, M_L: L*P/8}
def test_max_shear_force():
E = Symbol('E')
I = Symbol('I')
b = Beam(3, E, I)
R, M = symbols('R, M')
b.apply_load(R, 0, -1)
b.apply_load(M, 0, -2)
b.apply_load(2, 3, -1)
b.apply_load(4, 2, -1)
b.apply_load(2, 2, 0, end=3)
b.solve_for_reaction_loads(R, M)
assert b.max_shear_force() == (Interval(0, 2), 8)
l = symbols('l', positive=True)
P = Symbol('P')
b = Beam(l, E, I)
R1, R2 = symbols('R1, R2')
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(P, 0, 0, end=l)
b.solve_for_reaction_loads(R1, R2)
assert b.max_shear_force() == (0, l*Abs(P)/2)
def test_max_bmoment():
E = Symbol('E')
I = Symbol('I')
l, P = symbols('l, P', positive=True)
b = Beam(l, E, I)
R1, R2 = symbols('R1, R2')
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(P, l/2, -1)
b.solve_for_reaction_loads(R1, R2)
b.reaction_loads
assert b.max_bmoment() == (l/2, P*l/4)
b = Beam(l, E, I)
R1, R2 = symbols('R1, R2')
b.apply_load(R1, 0, -1)
b.apply_load(R2, l, -1)
b.apply_load(P, 0, 0, end=l)
b.solve_for_reaction_loads(R1, R2)
assert b.max_bmoment() == (l/2, P*l**2/8)
def test_max_deflection():
E, I, l, F = symbols('E, I, l, F', positive=True)
b = Beam(l, E, I)
b.bc_deflection = [(0, 0),(l, 0)]
b.bc_slope = [(0, 0),(l, 0)]
b.apply_load(F/2, 0, -1)
b.apply_load(-F*l/8, 0, -2)
b.apply_load(F/2, l, -1)
b.apply_load(F*l/8, l, -2)
b.apply_load(-F, l/2, -1)
assert b.max_deflection() == (l/2, F*l**3/(192*E*I))
def test_Beam3D():
l, E, G, I, A = symbols('l, E, G, I, A')
R1, R2, R3, R4 = symbols('R1, R2, R3, R4')
b = Beam3D(l, E, G, I, A)
m, q = symbols('m, q')
b.apply_load(q, 0, 0, dir="y")
b.apply_moment_load(m, 0, 0, dir="z")
b.bc_slope = [(0, [0, 0, 0]), (l, [0, 0, 0])]
b.bc_deflection = [(0, [0, 0, 0]), (l, [0, 0, 0])]
b.solve_slope_deflection()
assert b.polar_moment() == 2*I
assert b.shear_force() == [0, -q*x, 0]
assert b.bending_moment() == [0, 0, -m*x + q*x**2/2]
expected_deflection = (x*(A*G*q*x**3/4 + A*G*x**2*(-l*(A*G*l*(l*q - 2*m) +
12*E*I*q)/(A*G*l**2 + 12*E*I)/2 - m) + 3*E*I*l*(A*G*l*(l*q - 2*m) +
12*E*I*q)/(A*G*l**2 + 12*E*I) + x*(-A*G*l**2*q/2 +
3*A*G*l**2*(A*G*l*(l*q - 2*m) + 12*E*I*q)/(A*G*l**2 + 12*E*I)/4 +
A*G*l*m*Rational(3, 2) - 3*E*I*q))/(6*A*E*G*I))
dx, dy, dz = b.deflection()
assert dx == dz == 0
assert simplify(dy - expected_deflection) == 0
b2 = Beam3D(30, E, G, I, A, x)
b2.apply_load(50, start=0, order=0, dir="y")
b2.bc_deflection = [(0, [0, 0, 0]), (30, [0, 0, 0])]
b2.apply_load(R1, start=0, order=-1, dir="y")
b2.apply_load(R2, start=30, order=-1, dir="y")
b2.solve_for_reaction_loads(R1, R2)
assert b2.reaction_loads == {R1: -750, R2: -750}
b2.solve_slope_deflection()
assert b2.slope() == [0, 0, x**2*(50*x - 2250)/(6*E*I) + 3750*x/(E*I)]
expected_deflection = (x*(25*A*G*x**3/2 - 750*A*G*x**2 + 4500*E*I +
15*x*(750*A*G - 10*E*I))/(6*A*E*G*I))
dx, dy, dz = b2.deflection()
assert dx == dz == 0
assert dy == expected_deflection
# Test for solve_for_reaction_loads
b3 = Beam3D(30, E, G, I, A, x)
b3.apply_load(8, start=0, order=0, dir="y")
b3.apply_load(9*x, start=0, order=0, dir="z")
b3.apply_load(R1, start=0, order=-1, dir="y")
b3.apply_load(R2, start=30, order=-1, dir="y")
b3.apply_load(R3, start=0, order=-1, dir="z")
b3.apply_load(R4, start=30, order=-1, dir="z")
b3.solve_for_reaction_loads(R1, R2, R3, R4)
assert b3.reaction_loads == {R1: -120, R2: -120, R3: -1350, R4: -2700}
def test_polar_moment_Beam3D():
l, E, G, A, I1, I2 = symbols('l, E, G, A, I1, I2')
I = [I1, I2]
b = Beam3D(l, E, G, I, A)
assert b.polar_moment() == I1 + I2
def test_parabolic_loads():
E, I, L = symbols('E, I, L', positive=True, real=True)
R, M, P = symbols('R, M, P', real=True)
# cantilever beam fixed at x=0 and parabolic distributed loading across
# length of beam
beam = Beam(L, E, I)
beam.bc_deflection.append((0, 0))
beam.bc_slope.append((0, 0))
beam.apply_load(R, 0, -1)
beam.apply_load(M, 0, -2)
# parabolic load
beam.apply_load(1, 0, 2)
beam.solve_for_reaction_loads(R, M)
assert beam.reaction_loads[R] == -L**3/3
# cantilever beam fixed at x=0 and parabolic distributed loading across
# first half of beam
beam = Beam(2*L, E, I)
beam.bc_deflection.append((0, 0))
beam.bc_slope.append((0, 0))
beam.apply_load(R, 0, -1)
beam.apply_load(M, 0, -2)
# parabolic load from x=0 to x=L
beam.apply_load(1, 0, 2, end=L)
beam.solve_for_reaction_loads(R, M)
# result should be the same as the prior example
assert beam.reaction_loads[R] == -L**3/3
# check constant load
beam = Beam(2*L, E, I)
beam.apply_load(P, 0, 0, end=L)
loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
assert loading.xreplace({x: 5}) == 40
assert loading.xreplace({x: 15}) == 0
# check ramp load
beam = Beam(2*L, E, I)
beam.apply_load(P, 0, 1, end=L)
assert beam.load == (P*SingularityFunction(x, 0, 1) -
P*SingularityFunction(x, L, 1) -
P*L*SingularityFunction(x, L, 0))
# check higher order load: x**8 load from x=0 to x=L
beam = Beam(2*L, E, I)
beam.apply_load(P, 0, 8, end=L)
loading = beam.load.xreplace({L: 10, E: 20, I: 30, P: 40})
assert loading.xreplace({x: 5}) == 40*5**8
assert loading.xreplace({x: 15}) == 0
def test_cross_section():
I = Symbol('I')
l = Symbol('l')
E = Symbol('E')
C3, C4 = symbols('C3, C4')
a, c, g, h, r, n = symbols('a, c, g, h, r, n')
# test for second_moment and cross_section setter
b0 = Beam(l, E, I)
assert b0.second_moment == I
assert b0.cross_section == None
b0.cross_section = Circle((0, 0), 5)
assert b0.second_moment == pi*Rational(625, 4)
assert b0.cross_section == Circle((0, 0), 5)
b0.second_moment = 2*n - 6
assert b0.second_moment == 2*n-6
assert b0.cross_section == None
with raises(ValueError):
b0.second_moment = Circle((0, 0), 5)
# beam with a circular cross-section
b1 = Beam(50, E, Circle((0, 0), r))
assert b1.cross_section == Circle((0, 0), r)
assert b1.second_moment == pi*r*Abs(r)**3/4
b1.apply_load(-10, 0, -1)
b1.apply_load(R1, 5, -1)
b1.apply_load(R2, 50, -1)
b1.apply_load(90, 45, -2)
b1.solve_for_reaction_loads(R1, R2)
assert b1.load == (-10*SingularityFunction(x, 0, -1) + 82*SingularityFunction(x, 5, -1)/S(9)
+ 90*SingularityFunction(x, 45, -2) + 8*SingularityFunction(x, 50, -1)/9)
assert b1.bending_moment() == (-10*SingularityFunction(x, 0, 1) + 82*SingularityFunction(x, 5, 1)/9
+ 90*SingularityFunction(x, 45, 0) + 8*SingularityFunction(x, 50, 1)/9)
q = (-5*SingularityFunction(x, 0, 2) + 41*SingularityFunction(x, 5, 2)/S(9)
+ 90*SingularityFunction(x, 45, 1) + 4*SingularityFunction(x, 50, 2)/S(9))/(pi*E*r*Abs(r)**3)
assert b1.slope() == C3 + 4*q
q = (-5*SingularityFunction(x, 0, 3)/3 + 41*SingularityFunction(x, 5, 3)/27 + 45*SingularityFunction(x, 45, 2)
+ 4*SingularityFunction(x, 50, 3)/27)/(pi*E*r*Abs(r)**3)
assert b1.deflection() == C3*x + C4 + 4*q
# beam with a recatangular cross-section
b2 = Beam(20, E, Polygon((0, 0), (a, 0), (a, c), (0, c)))
assert b2.cross_section == Polygon((0, 0), (a, 0), (a, c), (0, c))
assert b2.second_moment == a*c**3/12
# beam with a triangular cross-section
b3 = Beam(15, E, Triangle((0, 0), (g, 0), (g/2, h)))
assert b3.cross_section == Triangle(Point2D(0, 0), Point2D(g, 0), Point2D(g/2, h))
assert b3.second_moment == g*h**3/36
# composite beam
b = b2.join(b3, "fixed")
b.apply_load(-30, 0, -1)
b.apply_load(65, 0, -2)
b.apply_load(40, 0, -1)
b.bc_slope = [(0, 0)]
b.bc_deflection = [(0, 0)]
assert b.second_moment == Piecewise((a*c**3/12, x <= 20), (g*h**3/36, x <= 35))
assert b.cross_section == None
assert b.length == 35
assert b.slope().subs(x, 7) == 8400/(E*a*c**3)
assert b.slope().subs(x, 25) == 52200/(E*g*h**3) + 39600/(E*a*c**3)
assert b.deflection().subs(x, 30) == 537000/(E*g*h**3) + 712000/(E*a*c**3)
|
8e59387c037d557bdd2297ddd837d99accd6ec1a6544e3d71e0c84ed5702a05d | from sympy import (symbols, Symbol, pi, sqrt, cos, sin, Derivative,
Function, simplify, I, atan2)
from sympy.abc import epsilon, mu
from sympy.functions.elementary.exponential import exp
from sympy.physics.units import speed_of_light, m, s
from sympy.physics.optics import TWave
from sympy.testing.pytest import raises
c = speed_of_light.convert_to(m/s)
def test_twave():
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
n = Symbol('n') # Refractive index
t = Symbol('t') # Time
x = Symbol('x') # Spatial variable
E = Function('E')
w1 = TWave(A1, f, phi1)
w2 = TWave(A2, f, phi2)
assert w1.amplitude == A1
assert w1.frequency == f
assert w1.phase == phi1
assert w1.wavelength == c/(f*n)
assert w1.time_period == 1/f
assert w1.angular_velocity == 2*pi*f
assert w1.wavenumber == 2*pi*f*n/c
assert w1.speed == c/n
w3 = w1 + w2
assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
assert w3.frequency == f
assert w3.phase == atan2(A1*cos(phi1) + A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2))
assert w3.wavelength == c/(f*n)
assert w3.time_period == 1/f
assert w3.angular_velocity == 2*pi*f
assert w3.wavenumber == 2*pi*f*n/c
assert w3.speed == c/n
assert simplify(w3.rewrite(sin) - sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*sin(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*cos(phi1)
+ A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2)) + pi/2)) == 0
assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
assert w3.rewrite(cos) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*cos(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + atan2(A1*cos(phi1)
+ A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2)))
assert w3.rewrite(exp) == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+ A2**2)*exp(I*(pi*f*n*x*s/(149896229*m) - 2*pi*f*t
+ atan2(A1*cos(phi1) + A2*cos(phi2), A1*sin(phi1) + A2*sin(phi2))))
w4 = TWave(A1, None, 0, 1/f)
assert w4.frequency == f
raises(ValueError, lambda:TWave(A1))
raises(ValueError, lambda:TWave(A1, f, phi1, t))
|
c41399dd8ceaf6e329411949a9f0d0f768a5d16059e401ba2c382218e905a114 | from sympy import sqrt
from sympy.physics.optics import Medium
from sympy.abc import epsilon, mu, n
from sympy.physics.units import speed_of_light, u0, e0, m, kg, s, A
from sympy.testing.pytest import raises
c = speed_of_light.convert_to(m/s)
e0 = e0.convert_to(A**2*s**4/(kg*m**3))
u0 = u0.convert_to(m*kg/(A**2*s**2))
def test_medium():
m1 = Medium('m1')
assert m1.intrinsic_impedance == sqrt(u0/e0)
assert m1.speed == 1/sqrt(e0*u0)
assert m1.refractive_index == c*sqrt(e0*u0)
assert m1.permittivity == e0
assert m1.permeability == u0
m2 = Medium('m2', epsilon, mu)
assert m2.intrinsic_impedance == sqrt(mu/epsilon)
assert m2.speed == 1/sqrt(epsilon*mu)
assert m2.refractive_index == c*sqrt(epsilon*mu)
assert m2.permittivity == epsilon
assert m2.permeability == mu
# Increasing electric permittivity and magnetic permeability
# by small amount from its value in vacuum.
m3 = Medium('m3', 9.0*10**(-12)*s**4*A**2/(m**3*kg), 1.45*10**(-6)*kg*m/(A**2*s**2))
assert m3.refractive_index > m1.refractive_index
assert m3 > m1
assert m3 != m1
# Decreasing electric permittivity and magnetic permeability
# by small amount from its value in vacuum.
m4 = Medium('m4', 7.0*10**(-12)*s**4*A**2/(m**3*kg), 1.15*10**(-6)*kg*m/(A**2*s**2))
assert m4.refractive_index < m1.refractive_index
assert m4 < m1
m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
assert abs(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) \
< 1e-12*kg*m**2/(A**2*s**3)
assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
assert abs(m5.refractive_index - 1.33000000000000) < 1e-12
assert abs(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) \
< 1e-20*A**2*s**4/(kg*m**3)
assert abs(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) \
< 1e-20*kg*m/(A**2*s**2)
m6 = Medium('m6', None, mu, n)
assert m6.permittivity == n**2/(c**2*mu)
assert Medium('m7') == Medium('m8', e0, u0) # test for equality
raises(ValueError, lambda:Medium('m9', e0, u0, 2))
|
2f3f6b140e8c1f7f9e7da3ae247cb5f5a50a69a1ff115e2d37ffc1bdf0878f2b | from sympy.core.numbers import comp, Rational
from sympy.physics.optics.utils import (refraction_angle, fresnel_coefficients,
deviation, brewster_angle, critical_angle, lens_makers_formula,
mirror_formula, lens_formula, hyperfocal_distance,
transverse_magnification)
from sympy.physics.optics.medium import Medium
from sympy.physics.units import e0
from sympy import symbols, sqrt, Matrix, oo
from sympy.geometry.point import Point3D
from sympy.geometry.line import Ray3D
from sympy.geometry.plane import Plane
from sympy.testing.pytest import raises
ae = lambda a, b, n: comp(a, b, 10**-n)
def test_refraction_angle():
n1, n2 = symbols('n1, n2')
m1 = Medium('m1')
m2 = Medium('m2')
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
i = Matrix([1, 1, 1])
n = Matrix([0, 0, 1])
normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
assert refraction_angle(r1, 1, 1, n) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle([1, 1, 1], 1, 1, n) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle((1, 1, 1), 1, 1, n) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, [0, 0, 1]) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, (0, 0, 1)) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, normal_ray) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(i, 1, 1, plane=P) == Matrix([
[ 1],
[ 1],
[-1]])
assert refraction_angle(r1, 1, 1, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
assert refraction_angle(r1, m1, 1.33, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(Rational(100, 133), Rational(100, 133), -789378201649271*sqrt(3)/1000000000000000))
assert refraction_angle(r1, 1, m2, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
assert refraction_angle(r1, n1, n2, plane=P) == \
Ray3D(Point3D(0, 0, 0), Point3D(n1/n2, n1/n2, -sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)))
assert refraction_angle(r1, 1.33, 1, plane=P) == 0 # TIR
assert refraction_angle(r1, 1, 1, normal_ray) == \
Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
assert ae(refraction_angle(0.5, 1, 2), 0.24207, 5)
assert ae(refraction_angle(0.5, 2, 1), 1.28293, 5)
raises(ValueError, lambda: refraction_angle(r1, m1, m2, normal_ray, P))
raises(TypeError, lambda: refraction_angle(m1, m1, m2)) # can add other values for arg[0]
raises(TypeError, lambda: refraction_angle(r1, m1, m2, None, i))
raises(TypeError, lambda: refraction_angle(r1, m1, m2, m2))
def test_fresnel_coefficients():
assert all(ae(i, j, 5) for i, j in zip(
fresnel_coefficients(0.5, 1, 1.33),
[0.11163, -0.17138, 0.83581, 0.82862]))
assert all(ae(i, j, 5) for i, j in zip(
fresnel_coefficients(0.5, 1.33, 1),
[-0.07726, 0.20482, 1.22724, 1.20482]))
m1 = Medium('m1')
m2 = Medium('m2', n=2)
assert all(ae(i, j, 5) for i, j in zip(
fresnel_coefficients(0.3, m1, m2),
[0.31784, -0.34865, 0.65892, 0.65135]))
ans = [[-0.23563, -0.97184], [0.81648, -0.57738]]
got = fresnel_coefficients(0.6, m2, m1)
for i, j in zip(got, ans):
for a, b in zip(i.as_real_imag(), j):
assert ae(a, b, 5)
def test_deviation():
n1, n2 = symbols('n1, n2')
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
n = Matrix([0, 0, 1])
i = Matrix([-1, -1, -1])
normal_ray = Ray3D(Point3D(0, 0, 0), Point3D(0, 0, 1))
P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
assert deviation(r1, 1, 1, normal=n) == 0
assert deviation(r1, 1, 1, plane=P) == 0
assert deviation(r1, 1, 1.1, plane=P).evalf(3) + 0.119 < 1e-3
assert deviation(i, 1, 1.1, normal=normal_ray).evalf(3) + 0.119 < 1e-3
assert deviation(r1, 1.33, 1, plane=P) is None # TIR
assert deviation(r1, 1, 1, normal=[0, 0, 1]) == 0
assert deviation([-1, -1, -1], 1, 1, normal=[0, 0, 1]) == 0
assert ae(deviation(0.5, 1, 2), -0.25793, 5)
assert ae(deviation(0.5, 2, 1), 0.78293, 5)
def test_brewster_angle():
m1 = Medium('m1', n=1)
m2 = Medium('m2', n=1.33)
assert ae(brewster_angle(m1, m2), 0.93, 2)
m1 = Medium('m1', permittivity=e0, n=1)
m2 = Medium('m2', permittivity=e0, n=1.33)
assert ae(brewster_angle(m1, m2), 0.93, 2)
assert ae(brewster_angle(1, 1.33), 0.93, 2)
def test_critical_angle():
m1 = Medium('m1', n=1)
m2 = Medium('m2', n=1.33)
assert ae(critical_angle(m2, m1), 0.85, 2)
def test_lens_makers_formula():
n1, n2 = symbols('n1, n2')
m1 = Medium('m1', permittivity=e0, n=1)
m2 = Medium('m2', permittivity=e0, n=1.33)
assert lens_makers_formula(n1, n2, 10, -10) == 5*n2/(n1 - n2)
assert ae(lens_makers_formula(m1, m2, 10, -10), -20.15, 2)
assert ae(lens_makers_formula(1.33, 1, 10, -10), 15.15, 2)
def test_mirror_formula():
u, v, f = symbols('u, v, f')
assert mirror_formula(focal_length=f, u=u) == f*u/(-f + u)
assert mirror_formula(focal_length=f, v=v) == f*v/(-f + v)
assert mirror_formula(u=u, v=v) == u*v/(u + v)
assert mirror_formula(u=oo, v=v) == v
assert mirror_formula(u=oo, v=oo) is oo
assert mirror_formula(focal_length=oo, u=u) == -u
assert mirror_formula(u=u, v=oo) == u
assert mirror_formula(focal_length=oo, v=oo) is oo
assert mirror_formula(focal_length=f, v=oo) == f
assert mirror_formula(focal_length=oo, v=v) == -v
assert mirror_formula(focal_length=oo, u=oo) is oo
assert mirror_formula(focal_length=f, u=oo) == f
assert mirror_formula(focal_length=oo, u=u) == -u
raises(ValueError, lambda: mirror_formula(focal_length=f, u=u, v=v))
def test_lens_formula():
u, v, f = symbols('u, v, f')
assert lens_formula(focal_length=f, u=u) == f*u/(f + u)
assert lens_formula(focal_length=f, v=v) == f*v/(f - v)
assert lens_formula(u=u, v=v) == u*v/(u - v)
assert lens_formula(u=oo, v=v) == v
assert lens_formula(u=oo, v=oo) is oo
assert lens_formula(focal_length=oo, u=u) == u
assert lens_formula(u=u, v=oo) == -u
assert lens_formula(focal_length=oo, v=oo) is -oo
assert lens_formula(focal_length=oo, v=v) == v
assert lens_formula(focal_length=f, v=oo) == -f
assert lens_formula(focal_length=oo, u=oo) is oo
assert lens_formula(focal_length=oo, u=u) == u
assert lens_formula(focal_length=f, u=oo) == f
raises(ValueError, lambda: lens_formula(focal_length=f, u=u, v=v))
def test_hyperfocal_distance():
f, N, c = symbols('f, N, c')
assert hyperfocal_distance(f=f, N=N, c=c) == f**2/(N*c)
assert ae(hyperfocal_distance(f=0.5, N=8, c=0.0033), 9.47, 2)
def test_transverse_magnification():
si, so = symbols('si, so')
assert transverse_magnification(si, so) == -si/so
assert transverse_magnification(30, 15) == -2
|
657ed04ced42d13ff3249074b03f9e06712424b58fe045e754f57b26fe8a5d54 | from __future__ import print_function, division
from typing import Any
from sympy import Basic
from sympy import S
from sympy.core.expr import Expr
from sympy.core.numbers import Integer
from sympy.core.sympify import sympify
from sympy.core.compatibility import SYMPY_INTS, Iterable
import itertools
class NDimArray(object):
"""
Examples
========
Create an N-dim array of zeros:
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3, 4)
>>> a
[[[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]], [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]]
Create an N-dim array from a list;
>>> a = MutableDenseNDimArray([[2, 3], [4, 5]])
>>> a
[[2, 3], [4, 5]]
>>> b = MutableDenseNDimArray([[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]])
>>> b
[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11, 12]]]
Create an N-dim array from a flat list with dimension shape:
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a
[[1, 2, 3], [4, 5, 6]]
Create an N-dim array from a matrix:
>>> from sympy import Matrix
>>> a = Matrix([[1,2],[3,4]])
>>> a
Matrix([
[1, 2],
[3, 4]])
>>> b = MutableDenseNDimArray(a)
>>> b
[[1, 2], [3, 4]]
Arithmetic operations on N-dim arrays
>>> a = MutableDenseNDimArray([1, 1, 1, 1], (2, 2))
>>> b = MutableDenseNDimArray([4, 4, 4, 4], (2, 2))
>>> c = a + b
>>> c
[[5, 5], [5, 5]]
>>> a - b
[[-3, -3], [-3, -3]]
"""
_diff_wrt = True
def __new__(cls, iterable, shape=None, **kwargs):
from sympy.tensor.array import ImmutableDenseNDimArray
return ImmutableDenseNDimArray(iterable, shape, **kwargs)
def _parse_index(self, index):
if isinstance(index, (SYMPY_INTS, Integer)):
raise ValueError("Only a tuple index is accepted")
if self._loop_size == 0:
raise ValueError("Index not valide with an empty array")
if len(index) != self._rank:
raise ValueError('Wrong number of array axes')
real_index = 0
# check if input index can exist in current indexing
for i in range(self._rank):
if (index[i] >= self.shape[i]) or (index[i] < -self.shape[i]):
raise ValueError('Index ' + str(index) + ' out of border')
if index[i] < 0:
real_index += 1
real_index = real_index*self.shape[i] + index[i]
return real_index
def _get_tuple_index(self, integer_index):
index = []
for i, sh in enumerate(reversed(self.shape)):
index.append(integer_index % sh)
integer_index //= sh
index.reverse()
return tuple(index)
def _check_symbolic_index(self, index):
# Check if any index is symbolic:
tuple_index = (index if isinstance(index, tuple) else (index,))
if any([(isinstance(i, Expr) and (not i.is_number)) for i in tuple_index]):
for i, nth_dim in zip(tuple_index, self.shape):
if ((i < 0) == True) or ((i >= nth_dim) == True):
raise ValueError("index out of range")
from sympy.tensor import Indexed
return Indexed(self, *tuple_index)
return None
def _setter_iterable_check(self, value):
from sympy.matrices.matrices import MatrixBase
if isinstance(value, (Iterable, MatrixBase, NDimArray)):
raise NotImplementedError
@classmethod
def _scan_iterable_shape(cls, iterable):
def f(pointer):
if not isinstance(pointer, Iterable):
return [pointer], ()
result = []
elems, shapes = zip(*[f(i) for i in pointer])
if len(set(shapes)) != 1:
raise ValueError("could not determine shape unambiguously")
for i in elems:
result.extend(i)
return result, (len(shapes),)+shapes[0]
return f(iterable)
@classmethod
def _handle_ndarray_creation_inputs(cls, iterable=None, shape=None, **kwargs):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy import Dict, Tuple
if shape is None:
if iterable is None:
shape = ()
iterable = ()
# Construction of a sparse array from a sparse array
elif isinstance(iterable, SparseNDimArray):
return iterable._shape, iterable._sparse_array
# Construct N-dim array from an iterable (numpy arrays included):
elif isinstance(iterable, Iterable):
iterable, shape = cls._scan_iterable_shape(iterable)
# Construct N-dim array from a Matrix:
elif isinstance(iterable, MatrixBase):
shape = iterable.shape
# Construct N-dim array from another N-dim array:
elif isinstance(iterable, NDimArray):
shape = iterable.shape
else:
shape = ()
iterable = (iterable,)
if isinstance(iterable, (Dict, dict)) and shape is not None:
new_dict = iterable.copy()
for k, v in new_dict.items():
if isinstance(k, (tuple, Tuple)):
new_key = 0
for i, idx in enumerate(k):
new_key = new_key * shape[i] + idx
iterable[new_key] = iterable[k]
del iterable[k]
if isinstance(shape, (SYMPY_INTS, Integer)):
shape = (shape,)
if any([not isinstance(dim, (SYMPY_INTS, Integer)) for dim in shape]):
raise TypeError("Shape should contain integers only.")
return tuple(shape), iterable
def __len__(self):
"""Overload common function len(). Returns number of elements in array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a
[[0, 0, 0], [0, 0, 0], [0, 0, 0]]
>>> len(a)
9
"""
return self._loop_size
@property
def shape(self):
"""
Returns array shape (dimension).
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3, 3)
>>> a.shape
(3, 3)
"""
return self._shape
def rank(self):
"""
Returns rank of array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(3,4,5,6,3)
>>> a.rank()
5
"""
return self._rank
def diff(self, *args, **kwargs):
"""
Calculate the derivative of each element in the array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> from sympy.abc import x, y
>>> M = ImmutableDenseNDimArray([[x, y], [1, x*y]])
>>> M.diff(x)
[[1, 0], [0, y]]
"""
from sympy import Derivative
kwargs.setdefault('evaluate', True)
return Derivative(self.as_immutable(), *args, **kwargs)
def _accept_eval_derivative(self, s):
return s._visit_eval_derivative_array(self)
def _visit_eval_derivative_scalar(self, base):
# Types are (base: scalar, self: array)
return self.applyfunc(lambda x: base.diff(x))
def _visit_eval_derivative_array(self, base):
# Types are (base: array/matrix, self: array)
from sympy import derive_by_array
return derive_by_array(base, self)
def _eval_derivative_n_times(self, s, n):
return Basic._eval_derivative_n_times(self, s, n)
def _eval_derivative(self, arg):
return self.applyfunc(lambda x: x.diff(arg))
def _eval_derivative_array(self, arg):
from sympy import derive_by_array
from sympy import Tuple
from sympy.matrices.common import MatrixCommon
if isinstance(arg, (Iterable, Tuple, MatrixCommon, NDimArray)):
return derive_by_array(self, arg)
else:
return self.applyfunc(lambda x: x.diff(arg))
def applyfunc(self, f):
"""Apply a function to each element of the N-dim array.
Examples
========
>>> from sympy import ImmutableDenseNDimArray
>>> m = ImmutableDenseNDimArray([i*2+j for i in range(2) for j in range(2)], (2, 2))
>>> m
[[0, 1], [2, 3]]
>>> m.applyfunc(lambda i: 2*i)
[[0, 2], [4, 6]]
"""
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray) and f(S.Zero) == 0:
return type(self)({k: f(v) for k, v in self._sparse_array.items() if f(v) != 0}, self.shape)
return type(self)(map(f, Flatten(self)), self.shape)
def __str__(self):
"""Returns string, allows to use standard functions print() and str().
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 2)
>>> a
[[0, 0], [0, 0]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return "["+", ".join([str(self[self._get_tuple_index(e)]) for e in range(i, j)])+"]"
sh //= shape_left[0]
return "[" + ", ".join([f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh) for e in range(shape_left[0])]) + "]" # + "\n"*len(shape_left)
if self.rank() == 0:
return self[()].__str__()
return f(self._loop_size, self.shape, 0, self._loop_size)
def __repr__(self):
return self.__str__()
# We don't define _repr_png_ here because it would add a large amount of
# data to any notebook containing SymPy expressions, without adding
# anything useful to the notebook. It can still enabled manually, e.g.,
# for the qtconsole, with init_printing().
def _repr_latex_(self):
"""
IPython/Jupyter LaTeX printing
To change the behavior of this (e.g., pass in some settings to LaTeX),
use init_printing(). init_printing() will also enable LaTeX printing
for built in numeric types like ints and container types that contain
SymPy objects, like lists and dictionaries of expressions.
"""
from sympy.printing.latex import latex
s = latex(self, mode='plain')
return "$\\displaystyle %s$" % s
_repr_latex_orig = _repr_latex_ # type: Any
def tolist(self):
"""
Converting MutableDenseNDimArray to one-dim list
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
>>> a
[[1, 2], [3, 4]]
>>> b = a.tolist()
>>> b
[[1, 2], [3, 4]]
"""
def f(sh, shape_left, i, j):
if len(shape_left) == 1:
return [self[self._get_tuple_index(e)] for e in range(i, j)]
result = []
sh //= shape_left[0]
for e in range(shape_left[0]):
result.append(f(sh, shape_left[1:], i+e*sh, i+(e+1)*sh))
return result
return f(self._loop_size, self.shape, 0, self._loop_size)
def __add__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
raise TypeError(str(other))
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i+j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __sub__(self, other):
from sympy.tensor.array.arrayop import Flatten
if not isinstance(other, NDimArray):
raise TypeError(str(other))
if self.shape != other.shape:
raise ValueError("array shape mismatch")
result_list = [i-j for i,j in zip(Flatten(self), Flatten(other))]
return type(self)(result_list, self.shape)
def __mul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i*other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rmul__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected, use tensorproduct(...) for tensorial product")
other = sympify(other)
if isinstance(self, SparseNDimArray):
if other.is_zero:
return type(self)({}, self.shape)
return type(self)({k: other*v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [other*i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __div__(self, other):
from sympy.matrices.matrices import MatrixBase
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(other, (Iterable, NDimArray, MatrixBase)):
raise ValueError("scalar expected")
other = sympify(other)
if isinstance(self, SparseNDimArray) and other != S.Zero:
return type(self)({k: v/other for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [i/other for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __rdiv__(self, other):
raise NotImplementedError('unsupported operation on NDimArray')
def __neg__(self):
from sympy.tensor.array import SparseNDimArray
from sympy.tensor.array.arrayop import Flatten
if isinstance(self, SparseNDimArray):
return type(self)({k: -v for (k, v) in self._sparse_array.items()}, self.shape)
result_list = [-i for i in Flatten(self)]
return type(self)(result_list, self.shape)
def __iter__(self):
def iterator():
if self._shape:
for i in range(self._shape[0]):
yield self[i]
else:
yield self[()]
return iterator()
def __eq__(self, other):
"""
NDimArray instances can be compared to each other.
Instances equal if they have same shape and data.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 3)
>>> b = MutableDenseNDimArray.zeros(2, 3)
>>> a == b
True
>>> c = a.reshape(3, 2)
>>> c == b
False
>>> a[0,0] = 1
>>> b[0,0] = 2
>>> a == b
False
"""
from sympy.tensor.array import SparseNDimArray
if not isinstance(other, NDimArray):
return False
if not self.shape == other.shape:
return False
if isinstance(self, SparseNDimArray) and isinstance(other, SparseNDimArray):
return dict(self._sparse_array) == dict(other._sparse_array)
return list(self) == list(other)
def __ne__(self, other):
return not self == other
__truediv__ = __div__
__rtruediv__ = __rdiv__
def _eval_transpose(self):
if self.rank() != 2:
raise ValueError("array rank not 2")
from .arrayop import permutedims
return permutedims(self, (1, 0))
def transpose(self):
return self._eval_transpose()
def _eval_conjugate(self):
from sympy.tensor.array.arrayop import Flatten
return self.func([i.conjugate() for i in Flatten(self)], self.shape)
def conjugate(self):
return self._eval_conjugate()
def _eval_adjoint(self):
return self.transpose().conjugate()
def adjoint(self):
return self._eval_adjoint()
def _slice_expand(self, s, dim):
if not isinstance(s, slice):
return (s,)
start, stop, step = s.indices(dim)
return [start + i*step for i in range((stop-start)//step)]
def _get_slice_data_for_array_access(self, index):
sl_factors = [self._slice_expand(i, dim) for (i, dim) in zip(index, self.shape)]
eindices = itertools.product(*sl_factors)
return sl_factors, eindices
def _get_slice_data_for_array_assignment(self, index, value):
if not isinstance(value, NDimArray):
value = type(self)(value)
sl_factors, eindices = self._get_slice_data_for_array_access(index)
slice_offsets = [min(i) if isinstance(i, list) else None for i in sl_factors]
# TODO: add checks for dimensions for `value`?
return value, eindices, slice_offsets
@classmethod
def _check_special_bounds(cls, flat_list, shape):
if shape == () and len(flat_list) != 1:
raise ValueError("arrays without shape need one scalar value")
if shape == (0,) and len(flat_list) > 0:
raise ValueError("if array shape is (0,) there cannot be elements")
def _check_index_for_getitem(self, index):
if isinstance(index, (SYMPY_INTS, Integer, slice)):
index = (index, )
if len(index) < self.rank():
index = tuple([i for i in index] + \
[slice(None) for i in range(len(index), self.rank())])
if len(index) > self.rank():
raise ValueError('Dimension of index greater than rank of array')
return index
class ImmutableNDimArray(NDimArray, Basic):
_op_priority = 11.0
def __hash__(self):
return Basic.__hash__(self)
def as_immutable(self):
return self
def as_mutable(self):
raise NotImplementedError("abstract method")
|
7766d5c0c5a834d00a59804c644b5c4d3efd842e2ab3d670aeb72558e6ab61ee | from __future__ import print_function, division
import functools
from sympy import Basic, Tuple, S
from sympy.core.sympify import _sympify
from sympy.tensor.array.mutable_ndim_array import MutableNDimArray
from sympy.tensor.array.ndim_array import NDimArray, ImmutableNDimArray
from sympy.simplify import simplify
class DenseNDimArray(NDimArray):
def __new__(self, *args, **kwargs):
return ImmutableDenseNDimArray(*args, **kwargs)
def __getitem__(self, index):
"""
Allows to get items from N-dim array.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([0, 1, 2, 3], (2, 2))
>>> a
[[0, 1], [2, 3]]
>>> a[0, 0]
0
>>> a[1, 1]
3
>>> a[0]
[0, 1]
>>> a[1]
[2, 3]
Symbolic index:
>>> from sympy.abc import i, j
>>> a[i, j]
[[0, 1], [2, 3]][i, j]
Replace `i` and `j` to get element `(1, 1)`:
>>> a[i, j].subs({i: 1, j: 1})
3
"""
syindex = self._check_symbolic_index(index)
if syindex is not None:
return syindex
index = self._check_index_for_getitem(index)
if isinstance(index, tuple) and any([isinstance(i, slice) for i in index]):
sl_factors, eindices = self._get_slice_data_for_array_access(index)
array = [self._array[self._parse_index(i)] for i in eindices]
nshape = [len(el) for i, el in enumerate(sl_factors) if isinstance(index[i], slice)]
return type(self)(array, nshape)
else:
index = self._parse_index(index)
return self._array[index]
@classmethod
def zeros(cls, *shape):
list_length = functools.reduce(lambda x, y: x*y, shape, S.One)
return cls._new(([0]*list_length,), shape)
def tomatrix(self):
"""
Converts MutableDenseNDimArray to Matrix. Can convert only 2-dim array, else will raise error.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1 for i in range(9)], (3, 3))
>>> b = a.tomatrix()
>>> b
Matrix([
[1, 1, 1],
[1, 1, 1],
[1, 1, 1]])
"""
from sympy.matrices import Matrix
if self.rank() != 2:
raise ValueError('Dimensions must be of size of 2')
return Matrix(self.shape[0], self.shape[1], self._array)
def reshape(self, *newshape):
"""
Returns MutableDenseNDimArray instance with new shape. Elements number
must be suitable to new shape. The only argument of method sets
new shape.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray([1, 2, 3, 4, 5, 6], (2, 3))
>>> a.shape
(2, 3)
>>> a
[[1, 2, 3], [4, 5, 6]]
>>> b = a.reshape(3, 2)
>>> b.shape
(3, 2)
>>> b
[[1, 2], [3, 4], [5, 6]]
"""
new_total_size = functools.reduce(lambda x,y: x*y, newshape)
if new_total_size != self._loop_size:
raise ValueError("Invalid reshape parameters " + newshape)
# there is no `.func` as this class does not subtype `Basic`:
return type(self)(self._array, newshape)
class ImmutableDenseNDimArray(DenseNDimArray, ImmutableNDimArray):
"""
"""
def __new__(cls, iterable, shape=None, **kwargs):
return cls._new(iterable, shape, **kwargs)
@classmethod
def _new(cls, iterable, shape, **kwargs):
from sympy.utilities.iterables import flatten
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
shape = Tuple(*map(_sympify, shape))
cls._check_special_bounds(flat_list, shape)
flat_list = flatten(flat_list)
flat_list = Tuple(*flat_list)
self = Basic.__new__(cls, flat_list, shape, **kwargs)
self._shape = shape
self._array = list(flat_list)
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape, 1)
return self
def __setitem__(self, index, value):
raise TypeError('immutable N-dim array')
def as_mutable(self):
return MutableDenseNDimArray(self)
def _eval_simplify(self, **kwargs):
return self.applyfunc(simplify)
class MutableDenseNDimArray(DenseNDimArray, MutableNDimArray):
def __new__(cls, iterable=None, shape=None, **kwargs):
return cls._new(iterable, shape, **kwargs)
@classmethod
def _new(cls, iterable, shape, **kwargs):
from sympy.utilities.iterables import flatten
shape, flat_list = cls._handle_ndarray_creation_inputs(iterable, shape, **kwargs)
flat_list = flatten(flat_list)
self = object.__new__(cls)
self._shape = shape
self._array = list(flat_list)
self._rank = len(shape)
self._loop_size = functools.reduce(lambda x,y: x*y, shape) if shape else len(flat_list)
return self
def __setitem__(self, index, value):
"""Allows to set items to MutableDenseNDimArray.
Examples
========
>>> from sympy import MutableDenseNDimArray
>>> a = MutableDenseNDimArray.zeros(2, 2)
>>> a[0,0] = 1
>>> a[1,1] = 1
>>> a
[[1, 0], [0, 1]]
"""
if isinstance(index, tuple) and any([isinstance(i, slice) for i in index]):
value, eindices, slice_offsets = self._get_slice_data_for_array_assignment(index, value)
for i in eindices:
other_i = [ind - j for ind, j in zip(i, slice_offsets) if j is not None]
self._array[self._parse_index(i)] = value[other_i]
else:
index = self._parse_index(index)
self._setter_iterable_check(value)
value = _sympify(value)
self._array[index] = value
def as_immutable(self):
return ImmutableDenseNDimArray(self)
@property
def free_symbols(self):
return {i for j in self._array for i in j.free_symbols}
|
c3685e0f68be652a177950273746879e2c50aec4c0da5ef8bdd4ed5f50369249 | from sympy.testing.pytest import raises
from sympy.tensor.toperators import PartialDerivative
from sympy.tensor.tensor import (TensorIndexType,
tensor_indices,
TensorHead, tensor_heads)
from sympy import symbols, diag
from sympy import Array, Rational
from random import randint
L = TensorIndexType("L")
i, j, k, m, m1, m2, m3, m4 = tensor_indices("i j k m m1 m2 m3 m4", L)
i0 = tensor_indices("i0", L)
L_0, L_1 = tensor_indices("L_0 L_1", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
def test_invalid_partial_derivative_valence():
raises(ValueError, lambda: PartialDerivative(C(j), D(-j)))
raises(ValueError, lambda: PartialDerivative(C(-j), D(j)))
def test_tensor_partial_deriv():
# Test flatten:
expr = PartialDerivative(PartialDerivative(A(i), A(j)), A(i))
assert expr.expr == A(L_0)
assert expr.variables == (A(j), A(L_0))
expr1 = PartialDerivative(A(i), A(j))
assert expr1.expr == A(i)
assert expr1.variables == (A(j),)
expr2 = A(i)*PartialDerivative(H(k, -i), A(j))
assert expr2.get_indices() == [L_0, k, -L_0, -j]
expr2b = A(i)*PartialDerivative(H(k, -i), A(-j))
assert expr2b.get_indices() == [L_0, k, -L_0, j]
expr3 = A(i)*PartialDerivative(B(k)*C(-i) + 3*H(k, -i), A(j))
assert expr3.get_indices() == [L_0, k, -L_0, -j]
expr4 = (A(i) + B(i))*PartialDerivative(C(j), D(j))
assert expr4.get_indices() == [i, L_0, -L_0]
expr4b = (A(i) + B(i))*PartialDerivative(C(-j), D(-j))
assert expr4b.get_indices() == [i, -L_0, L_0]
expr5 = (A(i) + B(i))*PartialDerivative(C(-i), D(j))
assert expr5.get_indices() == [L_0, -L_0, -j]
def test_replace_arrays_partial_derivative():
x, y, z, t = symbols("x y z t")
# d(A^i)/d(A_j) = d(g^ik A_k)/d(A_j) = g^ik delta_jk
expr = PartialDerivative(A(i), A(-j))
assert expr.get_free_indices() == [i, j]
assert expr.get_indices() == [i, j]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [i, j]) == Array([[1, 0], [0, -1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [i, j]) == Array([[1, 0], [0, -1]])
expr = PartialDerivative(A(i), A(j))
assert expr.get_free_indices() == [i, -j]
assert expr.get_indices() == [i, -j]
assert expr.replace_with_arrays({A(i): [x, y]}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [i, -j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [i, -j]) == Array([[1, 0], [0, 1]])
expr = PartialDerivative(A(-i), A(-j))
expr.get_free_indices() == [-i, j]
expr.get_indices() == [-i, j]
assert expr.replace_with_arrays({A(-i): [x, y]}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, 1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(-i): [x, y], L: diag(1, -1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, [-i, j]) == Array([[1, 0], [0, 1]])
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, [-i, j]) == Array([[1, 0], [0, 1]])
expr = PartialDerivative(A(i), A(i))
assert expr.get_free_indices() == []
assert expr.get_indices() == [L_0, -L_0]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, []) == 2
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, []) == 2
expr = PartialDerivative(A(-i), A(-i))
assert expr.get_free_indices() == []
assert expr.get_indices() == [-L_0, L_0]
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, 1)}, []) == 2
assert expr.replace_with_arrays({A(i): [x, y], L: diag(1, -1)}, []) == 2
expr = PartialDerivative(H(i, j) + H(j, i), A(i))
assert expr.get_indices() == [L_0, j, -L_0]
assert expr.get_free_indices() == [j]
expr = PartialDerivative(H(i, j) + H(j, i), A(k))*B(-i)
assert expr.get_indices() == [L_0, j, -k, -L_0]
assert expr.get_free_indices() == [j, -k]
expr = PartialDerivative(A(i)*(H(-i, j) + H(j, -i)), A(j))
assert expr.get_indices() == [L_0, -L_0, L_1, -L_1]
assert expr.get_free_indices() == []
expr = A(j)*A(-j) + expr
assert expr.get_indices() == [L_0, -L_0, L_1, -L_1]
assert expr.get_free_indices() == []
expr = A(i)*(B(j)*PartialDerivative(C(-j), D(i)) + C(j)*PartialDerivative(D(-j), B(i)))
assert expr.get_indices() == [L_0, L_1, -L_1, -L_0]
assert expr.get_free_indices() == []
expr = A(i)*PartialDerivative(C(-j), D(i))
assert expr.get_indices() == [L_0, -j, -L_0]
assert expr.get_free_indices() == [-j]
def test_expand_partial_derivative_sum_rule():
tau = symbols("tau")
# check sum rule for D(tensor, symbol)
expr1aa = PartialDerivative(A(i), tau)
assert expr1aa._expand_partial_derivative() == PartialDerivative(A(i), tau)
expr1ab = PartialDerivative(A(i) + B(i), tau)
assert (expr1ab._expand_partial_derivative() ==
PartialDerivative(A(i), tau) +
PartialDerivative(B(i), tau))
expr1ac = PartialDerivative(A(i) + B(i) + C(i), tau)
assert (expr1ac._expand_partial_derivative() ==
PartialDerivative(A(i), tau) +
PartialDerivative(B(i), tau) +
PartialDerivative(C(i), tau))
# check sum rule for D(tensor, D(j))
expr1ba = PartialDerivative(A(i), D(j))
assert expr1ba._expand_partial_derivative() ==\
PartialDerivative(A(i), D(j))
expr1bb = PartialDerivative(A(i) + B(i), D(j))
assert (expr1bb._expand_partial_derivative() ==
PartialDerivative(A(i), D(j)) +
PartialDerivative(B(i), D(j)))
expr1bc = PartialDerivative(A(i) + B(i) + C(i), D(j))
assert expr1bc._expand_partial_derivative() ==\
PartialDerivative(A(i), D(j))\
+ PartialDerivative(B(i), D(j))\
+ PartialDerivative(C(i), D(j))
# check sum rule for D(tensor, H(j, k))
expr1ca = PartialDerivative(A(i), H(j, k))
assert expr1ca._expand_partial_derivative() ==\
PartialDerivative(A(i), H(j, k))
expr1cb = PartialDerivative(A(i) + B(i), H(j, k))
assert (expr1cb._expand_partial_derivative() ==
PartialDerivative(A(i), H(j, k))
+ PartialDerivative(B(i), H(j, k)))
expr1cc = PartialDerivative(A(i) + B(i) + C(i), H(j, k))
assert (expr1cc._expand_partial_derivative() ==
PartialDerivative(A(i), H(j, k))
+ PartialDerivative(B(i), H(j, k))
+ PartialDerivative(C(i), H(j, k)))
# check sum rule for D(D(tensor, D(j)), H(k, m))
expr1da = PartialDerivative(A(i), (D(j), H(k, m)))
assert expr1da._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))
expr1db = PartialDerivative(A(i) + B(i), (D(j), H(k, m)))
assert expr1db._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))\
+ PartialDerivative(B(i), (D(j), H(k, m)))
expr1dc = PartialDerivative(A(i) + B(i) + C(i), (D(j), H(k, m)))
assert expr1dc._expand_partial_derivative() ==\
PartialDerivative(A(i), (D(j), H(k, m)))\
+ PartialDerivative(B(i), (D(j), H(k, m)))\
+ PartialDerivative(C(i), (D(j), H(k, m)))
def test_expand_partial_derivative_constant_factor_rule():
nneg = randint(0, 1000)
pos = randint(1, 1000)
neg = -randint(1, 1000)
c1 = Rational(nneg, pos)
c2 = Rational(neg, pos)
c3 = Rational(nneg, neg)
expr2a = PartialDerivative(nneg*A(i), D(j))
assert expr2a._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))
expr2b = PartialDerivative(neg*A(i), D(j))
assert expr2b._expand_partial_derivative() ==\
neg*PartialDerivative(A(i), D(j))
expr2ca = PartialDerivative(c1*A(i), D(j))
assert expr2ca._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))
expr2cb = PartialDerivative(c2*A(i), D(j))
assert expr2cb._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))
expr2cc = PartialDerivative(c3*A(i), D(j))
assert expr2cc._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))
def test_expand_partial_derivative_full_linearity():
nneg = randint(0, 1000)
pos = randint(1, 1000)
neg = -randint(1, 1000)
c1 = Rational(nneg, pos)
c2 = Rational(neg, pos)
c3 = Rational(nneg, neg)
# check full linearity
p = PartialDerivative(42, D(j))
assert p and not p._expand_partial_derivative()
expr3a = PartialDerivative(nneg*A(i) + pos*B(i), D(j))
assert expr3a._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))\
+ pos*PartialDerivative(B(i), D(j))
expr3b = PartialDerivative(nneg*A(i) + neg*B(i), D(j))
assert expr3b._expand_partial_derivative() ==\
nneg*PartialDerivative(A(i), D(j))\
+ neg*PartialDerivative(B(i), D(j))
expr3c = PartialDerivative(neg*A(i) + pos*B(i), D(j))
assert expr3c._expand_partial_derivative() ==\
neg*PartialDerivative(A(i), D(j))\
+ pos*PartialDerivative(B(i), D(j))
expr3d = PartialDerivative(c1*A(i) + c2*B(i), D(j))
assert expr3d._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))\
+ c2*PartialDerivative(B(i), D(j))
expr3e = PartialDerivative(c2*A(i) + c1*B(i), D(j))
assert expr3e._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))\
+ c1*PartialDerivative(B(i), D(j))
expr3f = PartialDerivative(c2*A(i) + c3*B(i), D(j))
assert expr3f._expand_partial_derivative() ==\
c2*PartialDerivative(A(i), D(j))\
+ c3*PartialDerivative(B(i), D(j))
expr3g = PartialDerivative(c3*A(i) + c2*B(i), D(j))
assert expr3g._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))\
+ c2*PartialDerivative(B(i), D(j))
expr3h = PartialDerivative(c3*A(i) + c1*B(i), D(j))
assert expr3h._expand_partial_derivative() ==\
c3*PartialDerivative(A(i), D(j))\
+ c1*PartialDerivative(B(i), D(j))
expr3i = PartialDerivative(c1*A(i) + c3*B(i), D(j))
assert expr3i._expand_partial_derivative() ==\
c1*PartialDerivative(A(i), D(j))\
+ c3*PartialDerivative(B(i), D(j))
def test_expand_partial_derivative_product_rule():
# check product rule
expr4a = PartialDerivative(A(i)*B(j), D(k))
assert expr4a._expand_partial_derivative() == \
PartialDerivative(A(i), D(k))*B(j)\
+ A(i)*PartialDerivative(B(j), D(k))
expr4b = PartialDerivative(A(i)*B(j)*C(k), D(m))
assert expr4b._expand_partial_derivative() ==\
PartialDerivative(A(i), D(m))*B(j)*C(k)\
+ A(i)*PartialDerivative(B(j), D(m))*C(k)\
+ A(i)*B(j)*PartialDerivative(C(k), D(m))
expr4c = PartialDerivative(A(i)*B(j), C(k), D(m))
assert expr4c._expand_partial_derivative() ==\
PartialDerivative(A(i), C(k), D(m))*B(j) \
+ PartialDerivative(A(i), C(k))*PartialDerivative(B(j), D(m))\
+ PartialDerivative(A(i), D(m))*PartialDerivative(B(j), C(k))\
+ A(i)*PartialDerivative(B(j), C(k), D(m))
def test_eval_partial_derivative_expr_by_symbol():
tau, alpha = symbols("tau alpha")
expr1 = PartialDerivative(tau**alpha, tau)
assert expr1._perform_derivative() == alpha * 1 / tau * tau ** alpha
expr2 = PartialDerivative(2*tau + 3*tau**4, tau)
assert expr2._perform_derivative() == 2 + 12 * tau ** 3
expr3 = PartialDerivative(2*tau + 3*tau**4, alpha)
assert expr3._perform_derivative() == 0
def test_eval_partial_derivative_single_tensors_by_scalar():
tau, mu = symbols("tau mu")
expr = PartialDerivative(tau**mu, tau)
assert expr._perform_derivative() == mu*tau**mu/tau
expr1a = PartialDerivative(A(i), tau)
assert expr1a._perform_derivative() == 0
expr1b = PartialDerivative(A(-i), tau)
assert expr1b._perform_derivative() == 0
expr2a = PartialDerivative(H(i, j), tau)
assert expr2a._perform_derivative() == 0
expr2b = PartialDerivative(H(i, -j), tau)
assert expr2b._perform_derivative() == 0
expr2c = PartialDerivative(H(-i, j), tau)
assert expr2c._perform_derivative() == 0
expr2d = PartialDerivative(H(-i, -j), tau)
assert expr2d._perform_derivative() == 0
def test_eval_partial_derivative_single_1st_rank_tensors_by_tensor():
expr1 = PartialDerivative(A(i), A(j))
assert expr1._perform_derivative() - L.delta(i, -j) == 0
expr2 = PartialDerivative(A(i), A(-j))
assert expr2._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, j) == 0
expr3 = PartialDerivative(A(-i), A(-j))
assert expr3._perform_derivative() - L.delta(-i, j) == 0
expr4 = PartialDerivative(A(-i), A(j))
assert expr4._perform_derivative() - L.metric(-i, -L_0) * L.delta(L_0, -j) == 0
expr5 = PartialDerivative(A(i), B(j))
expr6 = PartialDerivative(A(i), C(j))
expr7 = PartialDerivative(A(i), D(j))
expr8 = PartialDerivative(A(i), H(j, k))
assert expr5._perform_derivative() == 0
assert expr6._perform_derivative() == 0
assert expr7._perform_derivative() == 0
assert expr8._perform_derivative() == 0
expr9 = PartialDerivative(A(i), A(i))
assert expr9._perform_derivative() - L.delta(L_0, -L_0) == 0
expr10 = PartialDerivative(A(-i), A(-i))
assert expr10._perform_derivative() - L.delta(-L_0, L_0) == 0
def test_eval_partial_derivative_single_2nd_rank_tensors_by_tensor():
expr1 = PartialDerivative(H(i, j), H(m, m1))
assert expr1._perform_derivative() - L.delta(i, -m) * L.delta(j, -m1) == 0
expr2 = PartialDerivative(H(i, j), H(-m, m1))
assert expr2._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, m) * L.delta(j, -m1) == 0
expr3 = PartialDerivative(H(i, j), H(m, -m1))
assert expr3._perform_derivative() - L.delta(i, -m) * L.metric(j, L_0) * L.delta(-L_0, m1) == 0
expr4 = PartialDerivative(H(i, j), H(-m, -m1))
assert expr4._perform_derivative() - L.metric(i, L_0) * L.delta(-L_0, m) * L.metric(j, L_1) * L.delta(-L_1, m1) == 0
def test_eval_partial_derivative_divergence_type():
expr1a = PartialDerivative(A(i), A(i))
expr1b = PartialDerivative(A(i), A(k))
expr1c = PartialDerivative(L.delta(-i, k) * A(i), A(k))
assert (expr1a._perform_derivative()
- (L.delta(-i, k) * expr1b._perform_derivative())).contract_delta(L.delta) == 0
assert (expr1a._perform_derivative()
- expr1c._perform_derivative()).contract_delta(L.delta) == 0
expr2a = PartialDerivative(H(i, j), H(i, j))
expr2b = PartialDerivative(H(i, j), H(k, m))
expr2c = PartialDerivative(L.delta(-i, k) * L.delta(-j, m) * H(i, j), H(k, m))
assert (expr2a._perform_derivative()
- (L.delta(-i, k) * L.delta(-j, m) * expr2b._perform_derivative())).contract_delta(L.delta) == 0
assert (expr2a._perform_derivative()
- expr2c._perform_derivative()).contract_delta(L.delta) == 0
def test_eval_partial_derivative_expr1():
tau, alpha = symbols("tau alpha")
# this is only some special expression
# tested: vector derivative
# tested: scalar derivative
# tested: tensor derivative
base_expr1 = A(i)*H(-i, j) + A(i)*A(-i)*A(j) + tau**alpha*A(j)
tensor_derivative = PartialDerivative(base_expr1, H(k, m))._perform_derivative()
vector_derivative = PartialDerivative(base_expr1, A(k))._perform_derivative()
scalar_derivative = PartialDerivative(base_expr1, tau)._perform_derivative()
assert (tensor_derivative - A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k)*L.delta(j, -m)) == 0
assert (vector_derivative - (tau**alpha*L.delta(j, -k) +
L.delta(L_0, -k)*A(-L_0)*A(j) +
A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k)*A(j) +
A(L_0)*A(-L_0)*L.delta(j, -k) +
L.delta(L_0, -k)*H(-L_0, j))).expand() == 0
assert (vector_derivative.contract_metric(L.metric).contract_delta(L.delta) -
(tau**alpha*L.delta(j, -k) + A(L_0)*A(-L_0)*L.delta(j, -k) + H(-k, j) + 2*A(j)*A(-k))).expand() == 0
assert scalar_derivative - alpha*1/tau*tau**alpha*A(j) == 0
def test_eval_partial_derivative_mixed_scalar_tensor_expr2():
tau, alpha = symbols("tau alpha")
base_expr2 = A(i)*A(-i) + tau**2
vector_expression = PartialDerivative(base_expr2, A(k))._perform_derivative()
assert (vector_expression -
(L.delta(L_0, -k)*A(-L_0) + A(L_0)*L.metric(-L_0, -L_1)*L.delta(L_1, -k))).expand() == 0
scalar_expression = PartialDerivative(base_expr2, tau)._perform_derivative()
assert scalar_expression == 2*tau
|
d9ad3e880f1dc5f82ab869ec0f6149574d65d371ca2b1f0b37e6fad106e15109 | from functools import wraps
from sympy import Matrix, eye, Integer, expand, Indexed, Sum
from sympy.combinatorics import Permutation
from sympy.core import S, Rational, Symbol, Basic, Add
from sympy.core.containers import Tuple
from sympy.core.symbol import symbols
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.tensor.array import Array
from sympy.tensor.tensor import TensorIndexType, tensor_indices, TensorSymmetry, \
get_symmetric_group_sgs, TensorIndex, tensor_mul, TensAdd, \
riemann_cyclic_replace, riemann_cyclic, TensMul, tensor_heads, \
TensorManager, TensExpr, TensorHead, canon_bp, \
tensorhead, tensorsymmetry, TensorType, substitute_indices
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy, ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.matrices import diag
def filter_warnings_decorator(f):
@wraps(f)
def wrapper():
with ignore_warnings(SymPyDeprecationWarning):
f()
return wrapper
def _is_equal(arg1, arg2):
if isinstance(arg1, TensExpr):
return arg1.equals(arg2)
elif isinstance(arg2, TensExpr):
return arg2.equals(arg1)
return arg1 == arg2
#################### Tests from tensor_can.py #######################
def test_canonicalize_no_slot_sym():
# A_d0 * B^d0; T_c = A^d0*B_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1 = tensor_indices('a,b,d0,d1', Lorentz)
A, B = tensor_heads('A,B', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*B(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*B(-L_0)'
# A^a * B^b; T_c = T
t = A(a)*B(b)
tc = t.canon_bp()
assert tc == t
# B^b * A^a
t1 = B(b)*A(a)
tc = t1.canon_bp()
assert str(tc) == 'A(a)*B(b)'
# A symmetric
# A^{b}_{d0}*A^{d0, a}; T_c = A^{a d0}*A{b}_{d0}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, -d0)*A(d0, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, -L_0)'
# A^{d1}_{d0}*B^d0*C_d1
# T_c = A^{d0 d1}*B_d0*C_d1
B, C = tensor_heads('B,C', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0)*C(-L_1)'
# A without symmetry
# A^{d1}_{d0}*B^d0*C_d1 ord=[d0,-d0,d1,-d1]; g = [2,1,0,3,4,5]
# T_c = A^{d0 d1}*B_d1*C_d0; can = [0,2,3,1,4,5]
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(d0)*C(-d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1)*C(-L_0)'
# A, B without symmetry
# A^{d1}_{d0}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d0 d1}
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_0, -L_1)'
# A_{d0}^{d1}*B_{d1}^{d0}
# T_c = A^{d0 d1}*B_{d1 d0}
t = A(-d0, d1)*B(-d1, d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-L_1, -L_0)'
# A, B, C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c=A^{d0 d1}*B_{a d1}*C_{d0 b}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_1)*C(-L_0, -b)'
# A symmetric, B and C without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b}
# T_c = A^{d0 d1}*B_{a d0}*C_{d1 b}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-L_1, -b)'
# A and C symmetric, B without symmetry
# A^{d1 d0}*B_{a d0}*C_{d1 b} ord=[a,b,d0,-d0,d1,-d1]
# T_c = A^{d0 d1}*B_{a d0}*C_{b d1}
C = TensorHead('C', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d1, d0)*B(-a, -d0)*C(-d1, -b)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1)*B(-a, -L_0)*C(-b, -L_1)'
def test_canonicalize_no_dummies():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
# A commuting
# A^c A^b A^a
# T_c = A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == 'A(a)*A(b)*A(c)'
# A anticommuting
# A^c A^b A^a
# T_c = -A^a A^b A^c
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(c)*A(b)*A(a)
tc = t.canon_bp()
assert str(tc) == '-A(a)*A(b)*A(c)'
# A commuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
# A anticommuting and symmetric
# A^{b,d}*A^{c,a}
# T_c = -A^{a c}*A^{b d}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2), 1)
t = A(b, d)*A(c, a)
tc = t.canon_bp()
assert str(tc) == '-A(a, c)*A(b, d)'
# A^{c,a}*A^{b,d}
# T_c = A^{a c}*A^{b d}
t = A(c, a)*A(b, d)
tc = t.canon_bp()
assert str(tc) == 'A(a, c)*A(b, d)'
def test_tensorhead_construction_without_symmetry():
L = TensorIndexType('Lorentz')
A1 = TensorHead('A', [L, L])
A2 = TensorHead('A', [L, L], TensorSymmetry.no_symmetry(2))
assert A1 == A2
A3 = TensorHead('A', [L, L], TensorSymmetry.fully_symmetric(2)) # Symmetric
assert A1 != A3
def test_no_metric_symmetry():
# no metric symmetry; A no symmetry
# A^d1_d0 * A^d0_d1
# T_c = A^d0_d1 * A^d1_d0
Lorentz = TensorIndexType('Lorentz', dummy_name='L', metric_symmetry=0)
d0, d1, d2, d3 = tensor_indices('d:4', Lorentz)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.no_symmetry(2))
t = A(d1, -d0)*A(d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)'
# A^d1_d2 * A^d0_d3 * A^d2_d1 * A^d3_d0
# T_c = A^d0_d1 * A^d1_d0 * A^d2_d3 * A^d3_d2
t = A(d1, -d2)*A(d0, -d3)*A(d2, -d1)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_0)*A(L_2, -L_3)*A(L_3, -L_2)'
# A^d0_d2 * A^d1_d3 * A^d3_d0 * A^d2_d1
# T_c = A^d0_d1 * A^d1_d2 * A^d2_d3 * A^d3_d0
t = A(d0, -d1)*A(d1, -d2)*A(d2, -d3)*A(d3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, -L_1)*A(L_1, -L_2)*A(L_2, -L_3)*A(L_3, -L_0)'
def test_canonicalize1():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Lorentz)
# A_d0*A^d0; ord = [d0,-d0]
# T_c = A^d0*A_d0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1))
t = A(-d0)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)'
# A commuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c = A^d0*A_d0*A^d1*A_d1*A^d2*A_d2
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert str(tc) == 'A(L_0)*A(-L_0)*A(L_1)*A(-L_1)*A(L_2)*A(-L_2)'
# A anticommuting
# A_d0*A_d1*A_d2*A^d2*A^d1*A^d0
# T_c 0
A = TensorHead('A', [Lorentz], TensorSymmetry.no_symmetry(1), 1)
t = A(-d0)*A(-d1)*A(-d2)*A(d2)*A(d1)*A(d0)
tc = t.canon_bp()
assert tc == 0
# A commuting symmetric
# A^{d0 b}*A^a_d1*A^d1_d0
# T_c = A^{a d0}*A^{b d1}*A_{d0 d1}
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(a, -d1)*A(d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0)*A(b, L_1)*A(-L_0, -L_1)'
# A, B commuting symmetric
# A^{d0 b}*A^d1_d0*B^a_d1
# T_c = A^{b d0}*A_d0^d1*B^a_d1
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(d0, b)*A(d1, -d0)*B(a, -d1)
tc = t.canon_bp()
assert str(tc) == 'A(b, L_0)*A(-L_0, L_1)*B(a, -L_1)'
# A commuting symmetric
# A^{d1 d0 b}*A^{a}_{d1 d0}; ord=[a,b, d0,-d0,d1,-d1]
# T_c = A^{a d0 d1}*A^{b}_{d0 d1}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
t = A(d1, d0, b)*A(a, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a, L_0, L_1)*A(b, -L_0, -L_1)'
# A^{d3 d0 d2}*A^a0_{d1 d2}*A^d1_d3^a1*A^{a2 a3}_d0
# T_c = A^{a0 d0 d1}*A^a1_d0^d2*A^{a2 a3 d3}*A_{d1 d2 d3}
t = A(d3, d0, d2)*A(a0, -d1, -d2)*A(d1, -d3, a1)*A(a2, a3, -d0)
tc = t.canon_bp()
assert str(tc) == 'A(a0, L_0, L_1)*A(a1, -L_0, L_2)*A(a2, a3, L_3)*A(-L_1, -L_2, -L_3)'
# A commuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# in this esxample and in the next three,
# renaming dummy indices and using symmetry of A,
# T = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
# can = 0
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3))
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert tc == 0
# A anticommuting symmetric, B antisymmetric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(L_0, L_1, L_2)*A(-L_0, -L_1, L_3)*B(-L_2, -L_3)'
# A anticommuting symmetric, B antisymmetric commuting, antisymmetric metric
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = -A^{d0 d1 d2} * A_{d0 d1}^d3 * B_{d2 d3}
Spinor = TensorIndexType('Spinor', dummy_name='S', metric_symmetry=-1)
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Spinor)
A = TensorHead('A', [Spinor]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == '-A(S_0, S_1, S_2)*A(-S_0, -S_1, S_3)*B(-S_2, -S_3)'
# A anticommuting symmetric, B antisymmetric anticommuting,
# no metric symmetry
# A^{d0 d1 d2} * A_{d2 d3 d1} * B_d0^d3
# T_c = A^{d0 d1 d2} * A_{d0 d1 d3} * B_d2^d3
Mat = TensorIndexType('Mat', metric_symmetry=0, dummy_name='M')
a, a0, a1, a2, a3, b, d0, d1, d2, d3 = \
tensor_indices('a,a0,a1,a2,a3,b,d0,d1,d2,d3', Mat)
A = TensorHead('A', [Mat]*3, TensorSymmetry.fully_symmetric(3), 1)
B = TensorHead('B', [Mat]*2, TensorSymmetry.fully_symmetric(-2))
t = A(d0, d1, d2)*A(-d2, -d3, -d1)*B(-d0, d3)
tc = t.canon_bp()
assert str(tc) == 'A(M_0, M_1, M_2)*A(-M_0, -M_1, -M_3)*B(-M_2, M_3)'
# Gamma anticommuting
# Gamma_{mu nu} * gamma^rho * Gamma^{nu mu alpha}
# T_c = -Gamma^{mu nu} * gamma^rho * Gamma_{alpha mu nu}
alpha, beta, gamma, mu, nu, rho = \
tensor_indices('alpha,beta,gamma,mu,nu,rho', Lorentz)
Gamma = TensorHead('Gamma', [Lorentz],
TensorSymmetry.fully_symmetric(1), 2)
Gamma2 = TensorHead('Gamma', [Lorentz]*2,
TensorSymmetry.fully_symmetric(-2), 2)
Gamma3 = TensorHead('Gamma', [Lorentz]*3,
TensorSymmetry.fully_symmetric(-3), 2)
t = Gamma2(-mu, -nu)*Gamma(rho)*Gamma3(nu, mu, alpha)
tc = t.canon_bp()
assert str(tc) == '-Gamma(L_0, L_1)*Gamma(rho)*Gamma(alpha, -L_0, -L_1)'
# Gamma_{mu nu} * Gamma^{gamma beta} * gamma_rho * Gamma^{nu mu alpha}
# T_c = Gamma^{mu nu} * Gamma^{beta gamma} * gamma_rho * Gamma^alpha_{mu nu}
t = Gamma2(mu, nu)*Gamma2(beta, gamma)*Gamma(-rho)*Gamma3(alpha, -mu, -nu)
tc = t.canon_bp()
assert str(tc) == 'Gamma(L_0, L_1)*Gamma(beta, gamma)*Gamma(-rho)*Gamma(alpha, -L_0, -L_1)'
# f^a_{b,c} antisymmetric in b,c; A_mu^a no symmetry
# f^c_{d a} * f_{c e b} * A_mu^d * A_nu^a * A^{nu e} * A^{mu b}
# g = [8,11,5, 9,13,7, 1,10, 3,4, 2,12, 0,6, 14,15]
# T_c = -f^{a b c} * f_a^{d e} * A^mu_b * A_{mu d} * A^nu_c * A_{nu e}
Flavor = TensorIndexType('Flavor', dummy_name='F')
a, b, c, d, e, ff = tensor_indices('a,b,c,d,e,f', Flavor)
mu, nu = tensor_indices('mu,nu', Lorentz)
f = TensorHead('f', [Flavor]*3, TensorSymmetry.direct_product(1, -2))
A = TensorHead('A', [Lorentz, Flavor], TensorSymmetry.no_symmetry(2))
t = f(c, -d, -a)*f(-c, -e, -b)*A(-mu, d)*A(-nu, a)*A(nu, e)*A(mu, b)
tc = t.canon_bp()
assert str(tc) == '-f(F_0, F_1, F_2)*f(-F_0, F_3, F_4)*A(L_0, -F_1)*A(-L_0, -F_3)*A(L_1, -F_2)*A(-L_1, -F_4)'
def test_bug_correction_tensor_indices():
# to make sure that tensor_indices does not return a list if creating
# only one index:
A = TensorIndexType("A")
i = tensor_indices('i', A)
assert not isinstance(i, (tuple, list))
assert isinstance(i, TensorIndex)
def test_riemann_invariants():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6, d7, d8, d9, d10, d11 = \
tensor_indices('d0:12', Lorentz)
# R^{d0 d1}_{d1 d0}; ord = [d0,-d0,d1,-d1]
# T_c = -R^{d0 d1}_{d0 d1}
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(d0, d1, -d1, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, -L_0, -L_1)'
# R_d11^d1_d0^d5 * R^{d6 d4 d0}_d5 * R_{d7 d2 d8 d9} *
# R_{d10 d3 d6 d4} * R^{d2 d7 d11}_d1 * R^{d8 d9 d3 d10}
# can = [0,2,4,6, 1,3,8,10, 5,7,12,14, 9,11,16,18, 13,15,20,22,
# 17,19,21<F10,23, 24,25]
# T_c = R^{d0 d1 d2 d3} * R_{d0 d1}^{d4 d5} * R_{d2 d3}^{d6 d7} *
# R_{d4 d5}^{d8 d9} * R_{d6 d7}^{d10 d11} * R_{d8 d9 d10 d11}
t = R(-d11,d1,-d0,d5)*R(d6,d4,d0,-d5)*R(-d7,-d2,-d8,-d9)* \
R(-d10,-d3,-d6,-d4)*R(d2,d7,d11,-d1)*R(d8,d9,d3,d10)
tc = t.canon_bp()
assert str(tc) == 'R(L_0, L_1, L_2, L_3)*R(-L_0, -L_1, L_4, L_5)*R(-L_2, -L_3, L_6, L_7)*R(-L_4, -L_5, L_8, L_9)*R(-L_6, -L_7, L_10, L_11)*R(-L_8, -L_9, -L_10, -L_11)'
def test_riemann_products():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
d0, d1, d2, d3, d4, d5, d6 = tensor_indices('d0:7', Lorentz)
a0, a1, a2, a3, a4, a5 = tensor_indices('a0:6', Lorentz)
a, b = tensor_indices('a,b', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
# R^{a b d0}_d0 = 0
t = R(a, b, d0, -d0)
tc = t.canon_bp()
assert tc == 0
# R^{d0 b a}_d0
# T_c = -R^{a d0 b}_d0
t = R(d0, b, a, -d0)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, b, -L_0)'
# R^d1_d2^b_d0 * R^{d0 a}_d1^d2; ord=[a,b,d0,-d0,d1,-d1,d2,-d2]
# T_c = -R^{a d0 d1 d2}* R^b_{d0 d1 d2}
t = R(d1, -d2, b, -d0)*R(d0, a, -d1, d2)
tc = t.canon_bp()
assert str(tc) == '-R(a, L_0, L_1, L_2)*R(b, -L_0, -L_1, -L_2)'
# A symmetric commuting
# R^{d6 d5}_d2^d1 * R^{d4 d0 d2 d3} * A_{d6 d0} A_{d3 d1} * A_{d4 d5}
# g = [12,10,5,2, 8,0,4,6, 13,1, 7,3, 9,11,14,15]
# T_c = -R^{d0 d1 d2 d3} * R_d0^{d4 d5 d6} * A_{d1 d4}*A_{d2 d5}*A_{d3 d6}
V = TensorHead('V', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = R(d6, d5, -d2, d1)*R(d4, d0, d2, d3)*V(-d6, -d0)*V(-d3, -d1)*V(-d4, -d5)
tc = t.canon_bp()
assert str(tc) == '-R(L_0, L_1, L_2, L_3)*R(-L_0, L_4, L_5, L_6)*V(-L_1, -L_4)*V(-L_2, -L_5)*V(-L_3, -L_6)'
# R^{d2 a0 a2 d0} * R^d1_d2^{a1 a3} * R^{a4 a5}_{d0 d1}
# T_c = R^{a0 d0 a2 d1}*R^{a1 a3}_d0^d2*R^{a4 a5}_{d1 d2}
t = R(d2, a0, a2, d0)*R(d1, -d2, a1, a3)*R(a4, a5, -d0, -d1)
tc = t.canon_bp()
assert str(tc) == 'R(a0, L_0, a2, L_1)*R(a1, a3, -L_0, L_2)*R(a4, a5, -L_1, -L_2)'
######################################################################
def test_canonicalize2():
D = Symbol('D')
Eucl = TensorIndexType('Eucl', metric_symmetry=1, dim=D, dummy_name='E')
i0,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11,i12,i13,i14 = \
tensor_indices('i0:15', Eucl)
A = TensorHead('A', [Eucl]*3, TensorSymmetry.fully_symmetric(-3))
# two examples from Cvitanovic, Group Theory page 59
# of identities for antisymmetric tensors of rank 3
# contracted according to the Kuratowski graph eq.(6.59)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i3,i7,i5)*A(-i2,-i5,i6)*A(-i4,-i6,i8)
t1 = t.canon_bp()
assert t1 == 0
# eq.(6.60)
#t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*
# A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i3,-i12,i14)
t = A(i0,i1,i2)*A(-i1,i3,i4)*A(-i2,i5,i6)*A(-i3,i7,i8)*A(-i6,-i7,i9)*\
A(-i8,i10,i13)*A(-i5,-i10,i11)*A(-i4,-i11,i12)*A(-i9,-i12,i14)
t1 = t.canon_bp()
assert t1 == 0
def test_canonicalize3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0,a1,a2,a3,a4 = tensor_indices('a0:5', Spinor)
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
t = chi(a1)*psi(a0)
t1 = t.canon_bp()
assert t1 == t
t = psi(a1)*chi(a0)
t1 = t.canon_bp()
assert t1 == -chi(a0)*psi(a1)
def test_TensorIndexType():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', metric_name='g', metric_symmetry=1,
dim=D, dummy_name='L')
m0, m1, m2, m3, m4 = tensor_indices('m0:5', Lorentz)
sym2 = TensorSymmetry.fully_symmetric(2)
sym2n = TensorSymmetry(*get_symmetric_group_sgs(2))
assert sym2 == sym2n
g = Lorentz.metric
assert str(g) == 'g(Lorentz,Lorentz)'
assert Lorentz.eps_dim == Lorentz.dim
TSpace = TensorIndexType('TSpace', dummy_name = 'TSpace')
i0, i1 = tensor_indices('i0 i1', TSpace)
g = TSpace.metric
A = TensorHead('A', [TSpace]*2, sym2)
assert str(A(i0,-i0).canon_bp()) == 'A(TSpace_0, -TSpace_0)'
def test_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
assert a.tensor_index_type == Lorentz
assert a != -a
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a,b)*B(-b,c)
indices = t.get_indices()
L_0 = TensorIndex('L_0', Lorentz)
assert indices == [a, L_0, -L_0, c]
raises(ValueError, lambda: tensor_indices(3, Lorentz))
raises(ValueError, lambda: A(a,b,c))
def test_TensorSymmetry():
assert TensorSymmetry.fully_symmetric(2) == \
TensorSymmetry(get_symmetric_group_sgs(2))
assert TensorSymmetry.fully_symmetric(-3) == \
TensorSymmetry(get_symmetric_group_sgs(3, True))
assert TensorSymmetry.direct_product(-4) == \
TensorSymmetry.fully_symmetric(-4)
assert TensorSymmetry.fully_symmetric(-1) == \
TensorSymmetry.fully_symmetric(1)
assert TensorSymmetry.direct_product(1, -1, 1) == \
TensorSymmetry.no_symmetry(3)
assert TensorSymmetry(get_symmetric_group_sgs(2)) == \
TensorSymmetry(*get_symmetric_group_sgs(2))
# TODO: add check for *get_symmetric_group_sgs(0)
sym = TensorSymmetry.fully_symmetric(-3)
assert sym.rank == 3
assert sym.base == Tuple(0, 1)
assert sym.generators == Tuple(Permutation(0, 1)(3, 4), Permutation(1, 2)(3, 4))
def test_TensExpr():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
g = Lorentz.metric
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
raises(ValueError, lambda: g(c, d)/g(a, b))
raises(ValueError, lambda: S.One/g(a, b))
raises(ValueError, lambda: (A(c, d) + g(c, d))/g(a, b))
raises(ValueError, lambda: S.One/(A(c, d) + g(c, d)))
raises(ValueError, lambda: A(a, b) + A(a, c))
A(a, b) + B(a, b) # assigned to t for below
#raises(NotImplementedError, lambda: TensExpr.__mul__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__add__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__radd__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__sub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rsub__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__div__(t, 'a'))
#raises(NotImplementedError, lambda: TensExpr.__rdiv__(t, 'a'))
with ignore_warnings(SymPyDeprecationWarning):
# DO NOT REMOVE THIS AFTER DEPRECATION REMOVED:
raises(ValueError, lambda: A(a, b)**2)
raises(NotImplementedError, lambda: 2**A(a, b))
raises(NotImplementedError, lambda: abs(A(a, b)))
def test_TensorHead():
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
A = TensorHead('A', [Lorentz]*2)
assert A.name == 'A'
assert A.index_types == [Lorentz, Lorentz]
assert A.rank == 2
assert A.symmetry == TensorSymmetry.no_symmetry(2)
assert A.comm == 0
def test_add1():
assert TensAdd().args == ()
assert TensAdd().doit() == 0
# simple example of algebraic expression
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a,b,d0,d1,i,j,k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t1 = A(b, -d0)*B(d0, a)
assert TensAdd(t1).equals(t1)
t2a = B(d0, a) + A(d0, a)
t2 = A(b, -d0)*t2a
assert str(t2) == 'A(b, -L_0)*(A(L_0, a) + B(L_0, a))'
t2 = t2.expand()
assert str(t2) == 'A(b, -L_0)*A(L_0, a) + A(b, -L_0)*B(L_0, a)'
t2 = t2.canon_bp()
assert str(t2) == 'A(a, L_0)*A(b, -L_0) + A(b, L_0)*B(a, -L_0)'
t2b = t2 + t1
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + A(b, -L_0)*B(L_0, a) + A(b, L_0)*B(a, -L_0)'
t2b = t2b.canon_bp()
assert str(t2b) == 'A(a, L_0)*A(b, -L_0) + 2*A(b, L_0)*B(a, -L_0)'
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = q(d0)*2
assert str(t) == '2*q(d0)'
t = 2*q(d0)
assert str(t) == '2*q(d0)'
t1 = p(d0) + 2*q(d0)
assert str(t1) == '2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
assert str(t2) == '2*q(-d0) + p(-d0)'
t1 = p(d0)
t3 = t1*t2
assert str(t3) == 'p(L_0)*(2*q(-L_0) + p(-L_0))'
t3 = t3.expand()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t3 = t2*t1
t3 = t3.expand()
assert str(t3) == 'p(-L_0)*p(L_0) + 2*q(-L_0)*p(L_0)'
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 2*p(L_0)*q(-L_0)'
t1 = p(d0) + 2*q(d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert str(t3) == 'p(L_0)*p(-L_0) + 4*p(L_0)*q(-L_0) + 4*q(L_0)*q(-L_0)'
t1 = p(d0) - 2*q(d0)
assert str(t1) == '-2*q(d0) + p(d0)'
t2 = p(-d0) + 2*q(-d0)
t3 = t1*t2
t3 = t3.canon_bp()
assert t3 == p(d0)*p(-d0) - 4*q(d0)*q(-d0)
t = p(i)*p(j)*(p(k) + q(k)) + p(i)*(p(j) + q(j))*(p(k) - 3*q(k))
t = t.canon_bp()
assert t == 2*p(i)*p(j)*p(k) - 2*p(i)*p(j)*q(k) + p(i)*p(k)*q(j) - 3*p(i)*q(j)*q(k)
t1 = (p(i) + q(i) + 2*r(i))*(p(j) - q(j))
t2 = (p(j) + q(j) + 2*r(j))*(p(i) - q(i))
t = t1 + t2
t = t.canon_bp()
assert t == 2*p(i)*p(j) + 2*p(i)*r(j) + 2*p(j)*r(i) - 2*q(i)*q(j) - 2*q(i)*r(j) - 2*q(j)*r(i)
t = p(i)*q(j)/2
assert 2*t == p(i)*q(j)
t = (p(i) + q(i))/2
assert 2*t == p(i) + q(i)
t = S.One - p(i)*p(-i)
t = t.canon_bp()
tz1 = t + p(-j)*p(j)
assert tz1 != 1
tz1 = tz1.canon_bp()
assert tz1.equals(1)
t = S.One + p(i)*p(-i)
assert (t - p(-j)*p(j)).canon_bp().equals(1)
t = A(a, b) + B(a, b)
assert t.rank == 2
t1 = t - A(a, b) - B(a, b)
assert t1 == 0
t = 1 - (A(a, -a) + B(a, -a))
t1 = 1 + (A(a, -a) + B(a, -a))
assert (t + t1).expand().equals(2)
t2 = 1 + A(a, -a)
assert t1 != t2
assert t2 != TensMul.from_data(0, [], [], [])
def test_special_eq_ne():
# test special equality cases:
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, d0, d1, i, j, k = tensor_indices('a,b,d0,d1,i,j,k', Lorentz)
# A, B symmetric
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p, q, r = tensor_heads('p,q,r', [Lorentz])
t = 0*A(a, b)
assert _is_equal(t, 0)
assert _is_equal(t, S.Zero)
assert p(i) != A(a, b)
assert A(a, -a) != A(a, b)
assert 0*(A(a, b) + B(a, b)) == 0
assert 0*(A(a, b) + B(a, b)) is S.Zero
assert 3*(A(a, b) - A(a, b)) is S.Zero
assert p(i) + q(i) != A(a, b)
assert p(i) + q(i) != A(a, b) + B(a, b)
assert p(i) - p(i) == 0
assert p(i) - p(i) is S.Zero
assert _is_equal(A(a, b), A(b, a))
def test_add2():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m, n, p, q = tensor_indices('m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
A = TensorHead('A', [Lorentz]*3, TensorSymmetry.fully_symmetric(-3))
t1 = 2*R(m, n, p, q) - R(m, q, n, p) + R(m, p, n, q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t1 = Rational(2, 3)*R(m,n,p,q) - Rational(1, 3)*R(m,q,n,p) + Rational(1, 3)*R(m,p,n,q)
t2 = t1*A(-n, -p, -q)
t2 = t2.canon_bp()
assert t2 == 0
t = A(m, -m, n) + A(n, p, -p)
t = t.canon_bp()
assert t == 0
def test_add3():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i0, i1 = tensor_indices('i0:2', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
B = TensorHead('B', [Lorentz])
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.args == (E**2, -px**2, -py**2, -pz**2, -A(i0)*A(-i0))
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.args == (-E**2, px**2, py**2, pz**2, A(i0)*A(-i0))
expr4 = B(i1)*B(-i1) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.args == (2*E**2, -2*px**2, -2*py**2, -2*pz**2, B(i1)*B(-i1), -A(i0)*A(-i0))
def test_mul():
from sympy.abc import x
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b, c, d = tensor_indices('a,b,c,d', Lorentz)
t = TensMul.from_data(S.One, [], [], [])
assert str(t) == '1'
A, B = tensor_heads('A B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = (1 + x)*A(a, b)
assert str(t) == '(x + 1)*A(a, b)'
assert t.index_types == [Lorentz, Lorentz]
assert t.rank == 2
assert t.dum == []
assert t.coeff == 1 + x
assert sorted(t.free) == [(a, 0), (b, 1)]
assert t.components == [A]
ts = A(a, b)
assert str(ts) == 'A(a, b)'
assert ts.index_types == [Lorentz, Lorentz]
assert ts.rank == 2
assert ts.dum == []
assert ts.coeff == 1
assert sorted(ts.free) == [(a, 0), (b, 1)]
assert ts.components == [A]
t = A(-b, a)*B(-a, c)*A(-c, d)
t1 = tensor_mul(*t.split())
assert t == t1
assert tensor_mul(*[]) == TensMul.from_data(S.One, [], [], [])
t = TensMul.from_data(1, [], [], [])
C = TensorHead('C', [])
assert str(C()) == 'C'
assert str(t) == '1'
assert t == 1
raises(ValueError, lambda: A(a, b)*A(a, c))
def test_substitute_indices():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
p = TensorHead('p', [Lorentz])
t = p(i)
t1 = t.substitute_indices((j, k))
assert t1 == t
t1 = t.substitute_indices((i, j))
assert t1 == p(j)
t1 = t.substitute_indices((i, -j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, j))
assert t1 == p(-j)
t1 = t.substitute_indices((-i, -j))
assert t1 == p(j)
t = A(m, n)
t1 = t.substitute_indices((m, i), (n, -i))
assert t1 == A(n, -n)
t1 = substitute_indices(t, (m, i), (n, -i))
assert t1 == A(n, -n)
t = A(i, k)*B(-k, -j)
t1 = t.substitute_indices((i, j), (j, k))
t1a = A(j, l)*B(-l, -k)
assert t1 == t1a
t1 = substitute_indices(t, (i, j), (j, k))
assert t1 == t1a
t = A(i, j) + B(i, j)
t1 = t.substitute_indices((j, -i))
t1a = A(i, -i) + B(i, -i)
assert t1 == t1a
t1 = substitute_indices(t, (j, -i))
assert t1 == t1a
def test_riemann_cyclic_replace():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0, m2, m1, m3)
t1 = riemann_cyclic_replace(t)
t1a = Rational(-1, 3)*R(m0, m3, m2, m1) + Rational(1, 3)*R(m0, m1, m2, m3) + Rational(2, 3)*R(m0, m2, m1, m3)
assert t1 == t1a
def test_riemann_cyclic():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
i, j, k, l, m, n, p, q = tensor_indices('i,j,k,l,m,n,p,q', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(i,j,k,l) + R(i,l,j,k) + R(i,k,l,j) - \
R(i,j,l,k) - R(i,l,k,j) - R(i,k,j,l)
t2 = t*R(-i,-j,-k,-l)
t3 = riemann_cyclic(t2)
assert t3 == 0
t = R(i,j,k,l)*(R(-i,-j,-k,-l) - 2*R(-i,-k,-j,-l))
t1 = riemann_cyclic(t)
assert t1 == 0
t = R(i,j,k,l)
t1 = riemann_cyclic(t)
assert t1 == Rational(-1, 3)*R(i, l, j, k) + Rational(1, 3)*R(i, k, j, l) + Rational(2, 3)*R(i, j, k, l)
t = R(i,j,k,l)*R(-k,-l,m,n)*(R(-m,-n,-i,-j) + 2*R(-m,-j,-n,-i))
t1 = riemann_cyclic(t)
assert t1 == 0
@XFAIL
def test_div():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
m0, m1, m2, m3 = tensor_indices('m0:4', Lorentz)
R = TensorHead('R', [Lorentz]*4, TensorSymmetry.riemann())
t = R(m0,m1,-m1,m3)
t1 = t/S(4)
assert str(t1) == '(1/4)*R(m0, L_0, -L_0, m3)'
t = t.canon_bp()
assert not t1._is_canon_bp
t1 = t*4
assert t1._is_canon_bp
t1 = t1/4
assert t1._is_canon_bp
def test_contract_metric1():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p = TensorHead('p', [Lorentz])
t = g(a, b)*p(-b)
t1 = t.contract_metric(g)
assert t1 == p(a)
A, B = tensor_heads('A,B', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
# case with g with all free indices
t1 = A(a,b)*B(-b,c)*g(d, e)
t2 = t1.contract_metric(g)
assert t1 == t2
# case of g(d, -d)
t1 = A(a,b)*B(-b,c)*g(-d, d)
t2 = t1.contract_metric(g)
assert t2 == D*A(a, d)*B(-d, c)
# g with one free index
t1 = A(a,b)*B(-b,-c)*g(c, d)
t2 = t1.contract_metric(g)
assert t2 == A(a, c)*B(-c, d)
# g with both indices contracted with another tensor
t1 = A(a,b)*B(-b,-c)*g(c, -a)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, b)*B(-b, -a))
t1 = A(a,b)*B(-b,-c)*g(c, d)*g(-a, -d)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a,b)*B(-b,-a))
t1 = A(a,b)*g(-a,-b)
t2 = t1.contract_metric(g)
assert _is_equal(t2, A(a, -a))
assert not t2.free
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
a, b = tensor_indices('a,b', Lorentz)
g = Lorentz.metric
assert _is_equal(g(a, -a).contract_metric(g), Lorentz.dim) # no dim
def test_contract_metric2():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e, L_0 = tensor_indices('a,b,c,d,e,L_0', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p,q', [Lorentz])
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == 3*D*p(a)*p(-a)*q(b)*q(-b)
t1 = g(a,b)*p(c)*p(-c)
t2 = 3*q(-a)*q(-b)
t = t1*t2
t = t.contract_metric(g)
t = t.canon_bp()
assert t == 3*p(a)*p(-a)*q(b)*q(-b)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = - 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t = 6*g(a,b)*g(-a,-b)*p(c)*p(-c)*q(d)*q(-d)
t = t.contract_metric(g)
t1 = 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) + 3*g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
assert t == (2 + 6*D)*p(a)*p(-a)*q(b)*q(-b)
t1 = p(a)*p(b) + p(a)*q(b) + 2*g(a,b)*p(c)*p(-c)
t2 = q(-a)*q(-b) - g(-a,-b)*q(c)*q(-c)
t = t1*t2
t = t.contract_metric(g)
t1 = (1 - 2*D)*p(a)*p(-a)*q(b)*q(-b) + p(a)*q(-a)*p(b)*q(-b)
assert canon_bp(t - t1) == 0
t = g(a,b)*g(c,d)*g(-b,-c)
t1 = t.contract_metric(g)
assert t1 == g(a, d)
t1 = g(a,b)*g(c,d) + g(a,c)*g(b,d) + g(a,d)*g(b,c)
t2 = t1.substitute_indices((a,-a),(b,-b),(c,-c),(d,-d))
t = t1*t2
t = t.contract_metric(g)
assert t.equals(3*D**2 + 6*D)
t = 2*p(a)*g(b,-b)
t1 = t.contract_metric(g)
assert t1.equals(2*D*p(a))
t = 2*p(a)*g(b,-a)
t1 = t.contract_metric(g)
assert t1 == 2*p(b)
M = Symbol('M')
t = (p(a)*p(b) + g(a, b)*M**2)*g(-a, -b) - D*M**2
t1 = t.contract_metric(g)
assert t1 == p(a)*p(-a)
A = TensorHead('A', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
t = A(a, b)*p(L_0)*g(-a, -b)
t1 = t.contract_metric(g)
assert str(t1) == 'A(L_1, -L_1)*p(L_0)' or str(t1) == 'A(-L_1, L_1)*p(L_0)'
def test_metric_contract3():
D = Symbol('D')
Spinor = TensorIndexType('Spinor', dim=D, metric_symmetry=-1, dummy_name='S')
a0, a1, a2, a3, a4 = tensor_indices('a0:5', Spinor)
C = Spinor.metric
chi, psi = tensor_heads('chi,psi', [Spinor], TensorSymmetry.no_symmetry(1), 1)
B = TensorHead('B', [Spinor]*2, TensorSymmetry.no_symmetry(2))
t = C(a0,-a0)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a0)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a1,a0)*C(-a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(-a0,a1)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(-D)
t = C(a1,-a0)*C(a0,-a1)
t1 = t.contract_metric(C)
assert t1.equals(D)
t = C(a0,a1)*B(-a1,-a0)
t1 = t.contract_metric(C)
t1 = t1.canon_bp()
assert _is_equal(t1, B(a0,-a0))
t = C(a1,a0)*B(-a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(a0,-a1)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,a1)*B(-a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(a0,-a0))
t = C(-a0,-a1)*B(a1,a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(-a1, a0)*B(a1,-a0)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(a0,-a0))
t = C(a0,a1)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, psi(a0))
t = C(a1,a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -psi(a0))
t = C(a0,a1)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(a1)*psi(-a1))
t = C(a1,a0)*chi(-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(a1)*psi(-a1))
t = C(-a1,a0)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(a0,-a1)*chi(-a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a0,-a1)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, chi(-a1)*psi(a1))
t = C(-a1,-a0)*chi(a0)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -chi(-a1)*psi(a1))
t = C(-a1,-a0)*B(a0,a2)*psi(a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, -B(-a1,a2)*psi(a1))
t = C(a1,a0)*B(-a2,-a0)*psi(-a1)
t1 = t.contract_metric(C)
assert _is_equal(t1, B(-a2,a1)*psi(-a1))
def test_epsilon():
Lorentz = TensorIndexType('Lorentz', dim=4, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
epsilon = Lorentz.epsilon
p, q, r, s = tensor_heads('p,q,r,s', [Lorentz])
t = epsilon(b,a,c,d)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(c,b,d,a)
t1 = t.canon_bp()
assert t1 == epsilon(a,b,c,d)
t = epsilon(c,a,d,b)
t1 = t.canon_bp()
assert t1 == -epsilon(a,b,c,d)
t = epsilon(a,b,c,d)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,b,d,a)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*q(-b)
t1 = t.canon_bp()
assert t1 == -epsilon(c,d,a,b)*p(-a)*q(-b)
t = epsilon(c,a,d,b)*p(-a)*p(-b)
t1 = t.canon_bp()
assert t1 == 0
t = epsilon(c,a,d,b)*p(-a)*q(-b) + epsilon(a,b,c,d)*p(-b)*q(-a)
t1 = t.canon_bp()
assert t1 == -2*epsilon(c,d,a,b)*p(-a)*q(-b)
# Test that epsilon can be create with a SymPy integer:
Lorentz = TensorIndexType('Lorentz', dim=Integer(4), dummy_name='L')
epsilon = Lorentz.epsilon
assert isinstance(epsilon, TensorHead)
def test_contract_delta1():
# see Group Theory by Cvitanovic page 9
n = Symbol('n')
Color = TensorIndexType('Color', dim=n, dummy_name='C')
a, b, c, d, e, f = tensor_indices('a,b,c,d,e,f', Color)
delta = Color.delta
def idn(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,c)*delta(d,b)
def T(a, b, d, c):
assert a.is_up and d.is_up
assert not (b.is_up or c.is_up)
return delta(a,b)*delta(d,c)
def P1(a, b, c, d):
return idn(a,b,c,d) - 1/n*T(a,b,c,d)
def P2(a, b, c, d):
return 1/n*T(a,b,c,d)
t = P1(a, -b, e, -f)*P1(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert canon_bp(t1 - P1(a, -b, d, -c)) == 0
t = P2(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == P2(a, -b, d, -c)
t = P1(a, -b, e, -f)*P2(f, -e, d, -c)
t1 = t.contract_delta(delta)
assert t1 == 0
t = P1(a, -b, b, -a)
t1 = t.contract_delta(delta)
assert t1.equals(n**2 - 1)
@filter_warnings_decorator
def test_fun():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
t = q(c)*p(a)*q(b) + g(a,b)*g(c,d)*q(-d)
assert t(a,b,c) == t
assert canon_bp(t - t(b,a,c) - q(c)*p(a)*q(b) + q(c)*p(b)*q(a)) == 0
assert t(b,c,d) == q(d)*p(b)*q(c) + g(b,c)*g(d,e)*q(-e)
t1 = t.substitute_indices((a,b),(b,a))
assert canon_bp(t1 - q(c)*p(b)*q(a) - g(a,b)*g(c,d)*q(-d)) == 0
# check that g_{a b; c} = 0
# example taken from L. Brewin
# "A brief introduction to Cadabra" arxiv:0903.2085
# dg_{a b c} = \partial_{a} g_{b c} is symmetric in b, c
dg = TensorHead('dg', [Lorentz]*3, TensorSymmetry.direct_product(1, 2))
# gamma^a_{b c} is the Christoffel symbol
gamma = S.Half*g(a,d)*(dg(-b,-d,-c) + dg(-c,-b,-d) - dg(-d,-b,-c))
# t = g_{a b; c}
t = dg(-c,-a,-b) - g(-a,-d)*gamma(d,-b,-c) - g(-b,-d)*gamma(d,-a,-c)
t = t.contract_metric(g)
assert t == 0
t = q(c)*p(a)*q(b)
assert t(b,c,d) == q(d)*p(b)*q(c)
def test_TensorManager():
Lorentz = TensorIndexType('Lorentz', dummy_name='L')
LorentzH = TensorIndexType('LorentzH', dummy_name='LH')
i, j = tensor_indices('i,j', Lorentz)
ih, jh = tensor_indices('ih,jh', LorentzH)
p, q = tensor_heads('p q', [Lorentz])
ph, qh = tensor_heads('ph qh', [LorentzH])
Gsymbol = Symbol('Gsymbol')
GHsymbol = Symbol('GHsymbol')
TensorManager.set_comm(Gsymbol, GHsymbol, 0)
G = TensorHead('G', [Lorentz], TensorSymmetry.no_symmetry(1), Gsymbol)
assert TensorManager._comm_i2symbol[G.comm] == Gsymbol
GH = TensorHead('GH', [LorentzH], TensorSymmetry.no_symmetry(1), GHsymbol)
ps = G(i)*p(-i)
psh = GH(ih)*ph(-ih)
t = ps + psh
t1 = t*t
assert canon_bp(t1 - ps*ps - 2*ps*psh - psh*psh) == 0
qs = G(i)*q(-i)
qsh = GH(ih)*qh(-ih)
assert _is_equal(ps*qsh, qsh*ps)
assert not _is_equal(ps*qs, qs*ps)
n = TensorManager.comm_symbols2i(Gsymbol)
assert TensorManager.comm_i2symbol(n) == Gsymbol
assert GHsymbol in TensorManager._comm_symbols2i
raises(ValueError, lambda: TensorManager.set_comm(GHsymbol, 1, 2))
TensorManager.set_comms((Gsymbol,GHsymbol,0),(Gsymbol,1,1))
assert TensorManager.get_comm(n, 1) == TensorManager.get_comm(1, n) == 1
TensorManager.clear()
assert TensorManager.comm == [{0:0, 1:0, 2:0}, {0:0, 1:1, 2:None}, {0:0, 1:None}]
assert GHsymbol not in TensorManager._comm_symbols2i
nh = TensorManager.comm_symbols2i(GHsymbol)
assert TensorManager.comm_i2symbol(nh) == GHsymbol
assert GHsymbol in TensorManager._comm_symbols2i
def test_hash():
D = Symbol('D')
Lorentz = TensorIndexType('Lorentz', dim=D, dummy_name='L')
a, b, c, d, e = tensor_indices('a,b,c,d,e', Lorentz)
g = Lorentz.metric
p, q = tensor_heads('p q', [Lorentz])
p_type = p.args[1]
t1 = p(a)*q(b)
t2 = p(a)*p(b)
assert hash(t1) != hash(t2)
t3 = p(a)*p(b) + g(a,b)
t4 = p(a)*p(b) - g(a,b)
assert hash(t3) != hash(t4)
assert a.func(*a.args) == a
assert Lorentz.func(*Lorentz.args) == Lorentz
assert g.func(*g.args) == g
assert p.func(*p.args) == p
assert p_type.func(*p_type.args) == p_type
assert p(a).func(*(p(a)).args) == p(a)
assert t1.func(*t1.args) == t1
assert t2.func(*t2.args) == t2
assert t3.func(*t3.args) == t3
assert t4.func(*t4.args) == t4
assert hash(a.func(*a.args)) == hash(a)
assert hash(Lorentz.func(*Lorentz.args)) == hash(Lorentz)
assert hash(g.func(*g.args)) == hash(g)
assert hash(p.func(*p.args)) == hash(p)
assert hash(p_type.func(*p_type.args)) == hash(p_type)
assert hash(p(a).func(*(p(a)).args)) == hash(p(a))
assert hash(t1.func(*t1.args)) == hash(t1)
assert hash(t2.func(*t2.args)) == hash(t2)
assert hash(t3.func(*t3.args)) == hash(t3)
assert hash(t4.func(*t4.args)) == hash(t4)
def check_all(obj):
return all([isinstance(_, Basic) for _ in obj.args])
assert check_all(a)
assert check_all(Lorentz)
assert check_all(g)
assert check_all(p)
assert check_all(p_type)
assert check_all(p(a))
assert check_all(t1)
assert check_all(t2)
assert check_all(t3)
assert check_all(t4)
tsymmetry = TensorSymmetry.direct_product(-2, 1, 3)
assert tsymmetry.func(*tsymmetry.args) == tsymmetry
assert hash(tsymmetry.func(*tsymmetry.args)) == hash(tsymmetry)
assert check_all(tsymmetry)
### TEST VALUED TENSORS ###
def _get_valued_base_test_variables():
minkowski = Matrix((
(1, 0, 0, 0),
(0, -1, 0, 0),
(0, 0, -1, 0),
(0, 0, 0, -1),
))
Lorentz = TensorIndexType('Lorentz', dim=4)
Lorentz.data = minkowski
i0, i1, i2, i3, i4 = tensor_indices('i0:5', Lorentz)
E, px, py, pz = symbols('E px py pz')
A = TensorHead('A', [Lorentz])
A.data = [E, px, py, pz]
B = TensorHead('B', [Lorentz], TensorSymmetry.no_symmetry(1), 'Gcomm')
B.data = range(4)
AB = TensorHead("AB", [Lorentz]*2)
AB.data = minkowski
ba_matrix = Matrix((
(1, 2, 3, 4),
(5, 6, 7, 8),
(9, 0, -1, -2),
(-3, -4, -5, -6),
))
BA = TensorHead("BA", [Lorentz]*2)
BA.data = ba_matrix
# Let's test the diagonal metric, with inverted Minkowski metric:
LorentzD = TensorIndexType('LorentzD')
LorentzD.data = [-1, 1, 1, 1]
mu0, mu1, mu2 = tensor_indices('mu0:3', LorentzD)
C = TensorHead('C', [LorentzD])
C.data = [E, px, py, pz]
### non-diagonal metric ###
ndm_matrix = (
(1, 1, 0,),
(1, 0, 1),
(0, 1, 0,),
)
ndm = TensorIndexType("ndm")
ndm.data = ndm_matrix
n0, n1, n2 = tensor_indices('n0:3', ndm)
NA = TensorHead('NA', [ndm])
NA.data = range(10, 13)
NB = TensorHead('NB', [ndm]*2)
NB.data = [[i+j for j in range(10, 13)] for i in range(10, 13)]
NC = TensorHead('NC', [ndm]*3)
NC.data = [[[i+j+k for k in range(4, 7)] for j in range(1, 4)] for i in range(2, 5)]
return (A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4)
@filter_warnings_decorator
def test_valued_tensor_iter():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
list_BA = [Array([1, 2, 3, 4]), Array([5, 6, 7, 8]), Array([9, 0, -1, -2]), Array([-3, -4, -5, -6])]
# iteration on VTensorHead
assert list(A) == [E, px, py, pz]
assert list(ba_matrix) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, -1, -2, -3, -4, -5, -6]
assert list(BA) == list_BA
# iteration on VTensMul
assert list(A(i1)) == [E, px, py, pz]
assert list(BA(i1, i2)) == list_BA
assert list(3 * BA(i1, i2)) == [3 * i for i in list_BA]
assert list(-5 * BA(i1, i2)) == [-5 * i for i in list_BA]
# iteration on VTensAdd
# A(i1) + A(i1)
assert list(A(i1) + A(i1)) == [2*E, 2*px, 2*py, 2*pz]
assert BA(i1, i2) - BA(i1, i2) == 0
assert list(BA(i1, i2) - 2 * BA(i1, i2)) == [-i for i in list_BA]
@filter_warnings_decorator
def test_valued_tensor_covariant_contravariant_elements():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert A(-i0)[0] == A(i0)[0]
assert A(-i0)[1] == -A(i0)[1]
assert AB(i0, i1)[1, 1] == -1
assert AB(i0, -i1)[1, 1] == 1
assert AB(-i0, -i1)[1, 1] == -1
assert AB(-i0, i1)[1, 1] == 1
@filter_warnings_decorator
def test_valued_tensor_get_matrix():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
matab = AB(i0, i1).get_matrix()
assert matab == Matrix([
[1, 0, 0, 0],
[0, -1, 0, 0],
[0, 0, -1, 0],
[0, 0, 0, -1],
])
# when alternating contravariant/covariant with [1, -1, -1, -1] metric
# it becomes the identity matrix:
assert AB(i0, -i1).get_matrix() == eye(4)
# covariant and contravariant forms:
assert A(i0).get_matrix() == Matrix([E, px, py, pz])
assert A(-i0).get_matrix() == Matrix([E, -px, -py, -pz])
@filter_warnings_decorator
def test_valued_tensor_contraction():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert (A(i0) * A(-i0)).data == E ** 2 - px ** 2 - py ** 2 - pz ** 2
assert (A(i0) * A(-i0)).data == A ** 2
assert (A(i0) * A(-i0)).data == A(i0) ** 2
assert (A(i0) * B(-i0)).data == -px - 2 * py - 3 * pz
for i in range(4):
for j in range(4):
assert (A(i0) * B(-i1))[i, j] == [E, px, py, pz][i] * [0, -1, -2, -3][j]
# test contraction on the alternative Minkowski metric: [-1, 1, 1, 1]
assert (C(mu0) * C(-mu0)).data == -E ** 2 + px ** 2 + py ** 2 + pz ** 2
contrexp = A(i0) * AB(i1, -i0)
assert A(i0).rank == 1
assert AB(i1, -i0).rank == 2
assert contrexp.rank == 1
for i in range(4):
assert contrexp[i] == [E, px, py, pz][i]
@filter_warnings_decorator
def test_valued_tensor_self_contraction():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert AB(i0, -i0).data == 4
assert BA(i0, -i0).data == 2
@filter_warnings_decorator
def test_valued_tensor_pow():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
assert C**2 == -E**2 + px**2 + py**2 + pz**2
assert C**1 == sqrt(-E**2 + px**2 + py**2 + pz**2)
assert C(mu0)**2 == C**2
assert C(mu0)**1 == C**1
@filter_warnings_decorator
def test_valued_tensor_expressions():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
x1, x2, x3 = symbols('x1:4')
# test coefficient in contraction:
rank2coeff = x1 * A(i3) * B(i2)
assert rank2coeff[1, 1] == x1 * px
assert rank2coeff[3, 3] == 3 * pz * x1
coeff_expr = ((x1 * A(i4)) * (B(-i4) / x2)).data
assert coeff_expr.expand() == -px*x1/x2 - 2*py*x1/x2 - 3*pz*x1/x2
add_expr = A(i0) + B(i0)
assert add_expr[0] == E
assert add_expr[1] == px + 1
assert add_expr[2] == py + 2
assert add_expr[3] == pz + 3
sub_expr = A(i0) - B(i0)
assert sub_expr[0] == E
assert sub_expr[1] == px - 1
assert sub_expr[2] == py - 2
assert sub_expr[3] == pz - 3
assert (add_expr * B(-i0)).data == -px - 2*py - 3*pz - 14
expr1 = x1*A(i0) + x2*B(i0)
expr2 = expr1 * B(i1) * (-4)
expr3 = expr2 + 3*x3*AB(i0, i1)
expr4 = expr3 / 2
assert expr4 * 2 == expr3
expr5 = (expr4 * BA(-i1, -i0))
assert expr5.data.expand() == 28*E*x1 + 12*px*x1 + 20*py*x1 + 28*pz*x1 + 136*x2 + 3*x3
@filter_warnings_decorator
def test_valued_tensor_add_scalar():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# one scalar summand after the contracted tensor
expr1 = A(i0)*A(-i0) - (E**2 - px**2 - py**2 - pz**2)
assert expr1.data == 0
# multiple scalar summands in front of the contracted tensor
expr2 = E**2 - px**2 - py**2 - pz**2 - A(i0)*A(-i0)
assert expr2.data == 0
# multiple scalar summands after the contracted tensor
expr3 = A(i0)*A(-i0) - E**2 + px**2 + py**2 + pz**2
assert expr3.data == 0
# multiple scalar summands and multiple tensors
expr4 = C(mu0)*C(-mu0) + 2*E**2 - 2*px**2 - 2*py**2 - 2*pz**2 - A(i0)*A(-i0)
assert expr4.data == 0
@filter_warnings_decorator
def test_noncommuting_components():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
euclid = TensorIndexType('Euclidean')
euclid.data = [1, 1]
i1, i2, i3 = tensor_indices('i1:4', euclid)
a, b, c, d = symbols('a b c d', commutative=False)
V1 = TensorHead('V1', [euclid]*2)
V1.data = [[a, b], (c, d)]
V2 = TensorHead('V2', [euclid]*2)
V2.data = [[a, c], [b, d]]
vtp = V1(i1, i2) * V2(-i2, -i1)
assert vtp.data == a**2 + b**2 + c**2 + d**2
assert vtp.data != a**2 + 2*b*c + d**2
vtp2 = V1(i1, i2)*V1(-i2, -i1)
assert vtp2.data == a**2 + b*c + c*b + d**2
assert vtp2.data != a**2 + 2*b*c + d**2
Vc = (b * V1(i1, -i1)).data
assert Vc.expand() == b * a + b * d
@filter_warnings_decorator
def test_valued_non_diagonal_metric():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
mmatrix = Matrix(ndm_matrix)
assert (NA(n0)*NA(-n0)).data == (NA(n0).get_matrix().T * mmatrix * NA(n0).get_matrix())[0, 0]
@filter_warnings_decorator
def test_valued_assign_numpy_ndarray():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# this is needed to make sure that a numpy.ndarray can be assigned to a
# tensor.
arr = [E+1, px-1, py, pz]
A.data = Array(arr)
for i in range(4):
assert A(i0).data[i] == arr[i]
qx, qy, qz = symbols('qx qy qz')
A(-i0).data = Array([E, qx, qy, qz])
for i in range(4):
assert A(i0).data[i] == [E, -qx, -qy, -qz][i]
assert A.data[i] == [E, -qx, -qy, -qz][i]
# test on multi-indexed tensors.
random_4x4_data = [[(i**3-3*i**2)%(j+7) for i in range(4)] for j in range(4)]
AB(-i0, -i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]
AB(-i0, i1).data = random_4x4_data
for i in range(4):
for j in range(4):
assert AB(i0, i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)
assert AB(-i0, i1).data[i, j] == random_4x4_data[i][j]
assert AB(i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if i else 1)*(-1 if j else 1)
assert AB(-i0, -i1).data[i, j] == random_4x4_data[i][j]*(-1 if j else 1)
@filter_warnings_decorator
def test_valued_metric_inverse():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
# let's assign some fancy matrix, just to verify it:
# (this has no physical sense, it's just testing sympy);
# it is symmetrical:
md = [[2, 2, 2, 1], [2, 3, 1, 0], [2, 1, 2, 3], [1, 0, 3, 2]]
Lorentz.data = md
m = Matrix(md)
metric = Lorentz.metric
minv = m.inv()
meye = eye(4)
# the Kronecker Delta:
KD = Lorentz.get_kronecker_delta()
for i in range(4):
for j in range(4):
assert metric(i0, i1).data[i, j] == m[i, j]
assert metric(-i0, -i1).data[i, j] == minv[i, j]
assert metric(i0, -i1).data[i, j] == meye[i, j]
assert metric(-i0, i1).data[i, j] == meye[i, j]
assert metric(i0, i1)[i, j] == m[i, j]
assert metric(-i0, -i1)[i, j] == minv[i, j]
assert metric(i0, -i1)[i, j] == meye[i, j]
assert metric(-i0, i1)[i, j] == meye[i, j]
assert KD(i0, -i1)[i, j] == meye[i, j]
@filter_warnings_decorator
def test_valued_canon_bp_swapaxes():
(A, B, AB, BA, C, Lorentz, E, px, py, pz, LorentzD, mu0, mu1, mu2, ndm, n0, n1,
n2, NA, NB, NC, minkowski, ba_matrix, ndm_matrix, i0, i1, i2, i3, i4) = _get_valued_base_test_variables()
e1 = A(i1)*A(i0)
e2 = e1.canon_bp()
assert e2 == A(i0)*A(i1)
for i in range(4):
for j in range(4):
assert e1[i, j] == e2[j, i]
o1 = B(i2)*A(i1)*B(i0)
o2 = o1.canon_bp()
for i in range(4):
for j in range(4):
for k in range(4):
assert o1[i, j, k] == o2[j, i, k]
@filter_warnings_decorator
def test_valued_components_with_wrong_symmetry():
IT = TensorIndexType('IT', dim=3)
i0, i1, i2, i3 = tensor_indices('i0:4', IT)
IT.data = [1, 1, 1]
A_nosym = TensorHead('A', [IT]*2)
A_sym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(2))
A_antisym = TensorHead('A', [IT]*2, TensorSymmetry.fully_symmetric(-2))
mat_nosym = Matrix([[1,2,3],[4,5,6],[7,8,9]])
mat_sym = mat_nosym + mat_nosym.T
mat_antisym = mat_nosym - mat_nosym.T
A_nosym.data = mat_nosym
A_nosym.data = mat_sym
A_nosym.data = mat_antisym
def assign(A, dat):
A.data = dat
A_sym.data = mat_sym
raises(ValueError, lambda: assign(A_sym, mat_nosym))
raises(ValueError, lambda: assign(A_sym, mat_antisym))
A_antisym.data = mat_antisym
raises(ValueError, lambda: assign(A_antisym, mat_sym))
raises(ValueError, lambda: assign(A_antisym, mat_nosym))
A_sym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
A_antisym.data = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
@filter_warnings_decorator
def test_issue_10972_TensMul_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
F.data = [[0, 1],
[-1, 0]]
mul_1 = F(mu, alpha) * u(-alpha) * F(nu, beta) * u(-beta)
assert (mul_1.data == Array([[0, 0], [0, 1]]))
mul_2 = F(mu, alpha) * F(nu, beta) * u(-alpha) * u(-beta)
assert (mul_2.data == mul_1.data)
assert ((mul_1 + mul_1).data == 2 * mul_1.data)
@filter_warnings_decorator
def test_TensMul_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='L', dim=4)
Lorentz.data = [-1, 1, 1, 1]
mu, nu, alpha, beta = tensor_indices('\\mu, \\nu, \\alpha, \\beta',
Lorentz)
u = TensorHead('u', [Lorentz])
u.data = [1, 0, 0, 0]
F = TensorHead('F', [Lorentz]*2, TensorSymmetry.fully_symmetric(-2))
Ex, Ey, Ez, Bx, By, Bz = symbols('E_x E_y E_z B_x B_y B_z')
F.data = [
[0, Ex, Ey, Ez],
[-Ex, 0, Bz, -By],
[-Ey, -Bz, 0, Bx],
[-Ez, By, -Bx, 0]]
E = F(mu, nu) * u(-nu)
assert ((E(mu) * E(nu)).data ==
Array([[0, 0, 0, 0],
[0, Ex ** 2, Ex * Ey, Ex * Ez],
[0, Ex * Ey, Ey ** 2, Ey * Ez],
[0, Ex * Ez, Ey * Ez, Ez ** 2]])
)
assert ((E(mu) * E(nu)).canon_bp().data == (E(mu) * E(nu)).data)
assert ((F(mu, alpha) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
- (E(mu) * E(nu)).data
)
assert ((F(alpha, mu) * F(beta, nu) * u(-alpha) * u(-beta)).data ==
(E(mu) * E(nu)).data
)
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
# tensor 'perp' is orthogonal to vector 'u'
perp = u(mu) * u(nu) + g(mu, nu)
mul_1 = u(-mu) * perp(mu, nu)
assert (mul_1.data == Array([0, 0, 0, 0]))
mul_2 = u(-mu) * perp(mu, alpha) * perp(nu, beta)
assert (mul_2.data == Array.zeros(4, 4, 4))
Fperp = perp(mu, alpha) * perp(nu, beta) * F(-alpha, -beta)
assert (Fperp.data[0, :] == Array([0, 0, 0, 0]))
assert (Fperp.data[:, 0] == Array([0, 0, 0, 0]))
mul_3 = u(-mu) * Fperp(mu, nu)
assert (mul_3.data == Array([0, 0, 0, 0]))
@filter_warnings_decorator
def test_issue_11020_TensAdd_data():
Lorentz = TensorIndexType('Lorentz', metric_symmetry=1, dummy_name='i', dim=2)
Lorentz.data = [-1, 1]
a, b, c, d = tensor_indices('a, b, c, d', Lorentz)
i0, i1 = tensor_indices('i_0:2', Lorentz)
# metric tensor
g = TensorHead('g', [Lorentz]*2, TensorSymmetry.fully_symmetric(2))
g.data = Lorentz.data
u = TensorHead('u', [Lorentz])
u.data = [1, 0]
add_1 = g(b, c) * g(d, i0) * u(-i0) - g(b, c) * u(d)
assert (add_1.data == Array.zeros(2, 2, 2))
# Now let us replace index `d` with `a`:
add_2 = g(b, c) * g(a, i0) * u(-i0) - g(b, c) * u(a)
assert (add_2.data == Array.zeros(2, 2, 2))
# some more tests
# perp is tensor orthogonal to u^\mu
perp = u(a) * u(b) + g(a, b)
mul_1 = u(-a) * perp(a, b)
assert (mul_1.data == Array([0, 0]))
mul_2 = u(-c) * perp(c, a) * perp(d, b)
assert (mul_2.data == Array.zeros(2, 2, 2))
def test_index_iteration():
L = TensorIndexType("Lorentz", dummy_name="L")
i0, i1, i2, i3, i4 = tensor_indices('i0:5', L)
L0 = tensor_indices('L_0', L)
L1 = tensor_indices('L_1', L)
A = TensorHead("A", [L, L])
B = TensorHead("B", [L, L], TensorSymmetry.fully_symmetric(2))
e1 = A(i0,i2)
e2 = A(i0,-i0)
e3 = A(i0,i1)*B(i2,i3)
e4 = A(i0,i1)*B(i2,-i1)
e5 = A(i0,i1)*B(-i0,-i1)
e6 = e1 + e4
assert list(e1._iterate_free_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e1._iterate_dummy_indices) == []
assert list(e1._iterate_indices) == [(i0, (1, 0)), (i2, (1, 1))]
assert list(e2._iterate_free_indices) == []
assert list(e2._iterate_dummy_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e2._iterate_indices) == [(L0, (1, 0)), (-L0, (1, 1))]
assert list(e3._iterate_free_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e3._iterate_dummy_indices) == []
assert list(e3._iterate_indices) == [(i0, (0, 1, 0)), (i1, (0, 1, 1)), (i2, (1, 1, 0)), (i3, (1, 1, 1))]
assert list(e4._iterate_free_indices) == [(i0, (0, 1, 0)), (i2, (1, 1, 0))]
assert list(e4._iterate_dummy_indices) == [(L0, (0, 1, 1)), (-L0, (1, 1, 1))]
assert list(e4._iterate_indices) == [(i0, (0, 1, 0)), (L0, (0, 1, 1)), (i2, (1, 1, 0)), (-L0, (1, 1, 1))]
assert list(e5._iterate_free_indices) == []
assert list(e5._iterate_dummy_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e5._iterate_indices) == [(L0, (0, 1, 0)), (L1, (0, 1, 1)), (-L0, (1, 1, 0)), (-L1, (1, 1, 1))]
assert list(e6._iterate_free_indices) == [(i0, (0, 0, 1, 0)), (i2, (0, 1, 1, 0)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert list(e6._iterate_dummy_indices) == [(L0, (0, 0, 1, 1)), (-L0, (0, 1, 1, 1))]
assert list(e6._iterate_indices) == [(i0, (0, 0, 1, 0)), (L0, (0, 0, 1, 1)), (i2, (0, 1, 1, 0)), (-L0, (0, 1, 1, 1)), (i0, (1, 1, 0)), (i2, (1, 1, 1))]
assert e1.get_indices() == [i0, i2]
assert e1.get_free_indices() == [i0, i2]
assert e2.get_indices() == [L0, -L0]
assert e2.get_free_indices() == []
assert e3.get_indices() == [i0, i1, i2, i3]
assert e3.get_free_indices() == [i0, i1, i2, i3]
assert e4.get_indices() == [i0, L0, i2, -L0]
assert e4.get_free_indices() == [i0, i2]
assert e5.get_indices() == [L0, L1, -L0, -L1]
assert e5.get_free_indices() == []
def test_tensor_expand():
L = TensorIndexType("L")
i, j, k = tensor_indices("i j k", L)
L_0 = TensorIndex("L_0", L)
A, B, C, D = tensor_heads("A B C D", [L])
assert isinstance(Add(A(i), B(i)), TensAdd)
assert isinstance(expand(A(i)+B(i)), TensAdd)
expr = A(i)*(A(-i)+B(-i))
assert expr.args == (A(L_0), A(-L_0) + B(-L_0))
assert expr != A(i)*A(-i) + A(i)*B(-i)
assert expr.expand() == A(i)*A(-i) + A(i)*B(-i)
assert str(expr) == "A(L_0)*(A(-L_0) + B(-L_0))"
expr = A(i)*A(j) + A(i)*B(j)
assert str(expr) == "A(i)*A(j) + A(i)*B(j)"
expr = A(-i)*(A(i)*A(j) + A(i)*B(j)*C(k)*C(-k))
assert expr != A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert expr.expand() == A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)*C(k)*C(-k)
assert str(expr) == "A(-L_0)*(A(L_0)*A(j) + A(L_0)*B(j)*C(L_1)*C(-L_1))"
assert str(expr.canon_bp()) == 'A(j)*A(L_0)*A(-L_0) + A(L_0)*A(-L_0)*B(j)*C(L_1)*C(-L_1)'
expr = A(-i)*(2*A(i)*A(j) + A(i)*B(j))
assert expr.expand() == 2*A(-i)*A(i)*A(j) + A(-i)*A(i)*B(j)
expr = 2*A(i)*A(-i)
assert expr.coeff == 2
expr = A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))
assert str(expr) == "A(i)*(B(j)*C(k) + C(j)*(A(k) + D(k)))"
assert str(expr.expand()) == "A(i)*B(j)*C(k) + A(i)*C(j)*A(k) + A(i)*C(j)*D(k)"
assert isinstance(TensMul(3), TensMul)
tm = TensMul(3).doit()
assert tm == 3
assert isinstance(tm, Integer)
p1 = B(j)*B(-j) + B(j)*C(-j)
p2 = C(-i)*p1
p3 = A(i)*p2
assert p3.expand() == A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = A(i)*(B(-i) + C(-i)*(B(j)*B(-j) + B(j)*C(-j)))
assert expr.expand() == A(i)*B(-i) + A(i)*C(-i)*B(j)*B(-j) + A(i)*C(-i)*B(j)*C(-j)
expr = C(-i)*(B(j)*B(-j) + B(j)*C(-j))
assert expr.expand() == C(-i)*B(j)*B(-j) + C(-i)*B(j)*C(-j)
def test_tensor_alternative_construction():
L = TensorIndexType("L")
i0, i1, i2, i3 = tensor_indices('i0:4', L)
A = TensorHead("A", [L])
x, y = symbols("x y")
assert A(i0) == A(Symbol("i0"))
assert A(-i0) == A(-Symbol("i0"))
raises(TypeError, lambda: A(x+y))
raises(ValueError, lambda: A(2*x))
def test_tensor_replacement():
L = TensorIndexType("L")
L2 = TensorIndexType("L2", dim=2)
i, j, k, l = tensor_indices("i j k l", L)
A, B, C, D = tensor_heads("A B C D", [L])
H = TensorHead("H", [L, L])
K = TensorHead("K", [L]*4)
expr = H(i, j)
repl = {H(i,-j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, -2], [3, -4]]))
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [-2, 4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [2, -4]])
# Test stability of optional parameter 'indices'
assert expr.replace_with_arrays(repl) == Array([[1, -2], [3, -4]])
expr = H(i,j)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
assert expr.replace_with_arrays(repl) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, j]) == Array([[1, 2], [3, 4]])
assert expr.replace_with_arrays(repl, [i, -j]) == Array([[1, -2], [3, -4]])
assert expr.replace_with_arrays(repl, [-i, j]) == Array([[1, 2], [-3, -4]])
assert expr.replace_with_arrays(repl, [-i, -j]) == Array([[1, -2], [-3, 4]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[1, 3], [2, 4]])
assert expr.replace_with_arrays(repl, [j, -i]) == Array([[1, -3], [2, -4]])
assert expr.replace_with_arrays(repl, [-j, i]) == Array([[1, 3], [-2, -4]])
assert expr.replace_with_arrays(repl, [-j, -i]) == Array([[1, -3], [-2, 4]])
# Not the same indices:
expr = H(i,k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
assert expr._extract_data(repl) == ([i, k], Array([[1, 2], [3, 4]]))
expr = A(i)*A(-i)
repl = {A(i): [1,2], L: diag(1, -1)}
assert expr._extract_data(repl) == ([], -3)
assert expr.replace_with_arrays(repl, []) == -3
expr = K(i, j, -j, k)*A(-i)*A(-k)
repl = {A(i): [1, 2], K(i,j,k,l): Array([1]*2**4).reshape(2,2,2,2), L: diag(1, -1)}
assert expr._extract_data(repl)
expr = H(j, k)
repl = {H(i,j): [[1,2],[3,4]], L: diag(1, -1)}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {B(i): [1, 2]}
raises(ValueError, lambda: expr._extract_data(repl))
expr = A(i)
repl = {A(i): [[1, 2], [3, 4]]}
raises(ValueError, lambda: expr._extract_data(repl))
# TensAdd:
expr = A(k)*H(i, j) + B(k)*H(i, j)
repl = {A(k): [1], B(k): [1], H(i, j): [[1, 2],[3,4]], L:diag(1,1)}
assert expr._extract_data(repl) == ([k, i, j], Array([[[2, 4], [6, 8]]]))
assert expr.replace_with_arrays(repl, [k, i, j]) == Array([[[2, 4], [6, 8]]])
assert expr.replace_with_arrays(repl, [k, j, i]) == Array([[[2, 6], [4, 8]]])
expr = A(k)*A(-k) + 100
repl = {A(k): [2, 3], L: diag(1, 1)}
assert expr.replace_with_arrays(repl, []) == 113
## Symmetrization:
expr = H(i, j) + H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[2, 5], [5, 8]]))
assert expr.replace_with_arrays(repl, [i, j]) == Array([[2, 5], [5, 8]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[2, 5], [5, 8]])
## Anti-symmetrization:
expr = H(i, j) - H(j, i)
repl = {H(i, j): [[1, 2], [3, 4]]}
assert expr.replace_with_arrays(repl, [i, j]) == Array([[0, -1], [1, 0]])
assert expr.replace_with_arrays(repl, [j, i]) == Array([[0, 1], [-1, 0]])
# Tensors with contractions in replacements:
expr = K(i, j, k, -k)
repl = {K(i, j, k, -k): [[1, 2], [3, 4]]}
assert expr._extract_data(repl) == ([i, j], Array([[1, 2], [3, 4]]))
expr = H(i, -i)
repl = {H(i, -i): 42}
assert expr._extract_data(repl) == ([], 42)
# Replace with array, raise exception if indices are not compatible:
expr = A(i)*A(j)
repl = {A(i): [1, 2]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [j]))
# Raise exception if array dimension is not compatible:
expr = A(i)
repl = {A(i): [[1, 2]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [i]))
# TensorIndexType with dimension, wrong dimension in replacement array:
u1, u2, u3 = tensor_indices("u1:4", L2)
U = TensorHead("U", [L2])
expr = U(u1)*U(-u2)
repl = {U(u1): [[1]]}
raises(ValueError, lambda: expr.replace_with_arrays(repl, [u1, -u2]))
def test_rewrite_tensor_to_Indexed():
L = TensorIndexType("L", dim=4)
A = TensorHead("A", [L]*4)
B = TensorHead("B", [L])
i0, i1, i2, i3 = symbols("i0:4")
L_0, L_1 = symbols("L_0:2")
a1 = A(i0, i1, i2, i3)
assert a1.rewrite(Indexed) == Indexed(Symbol("A"), i0, i1, i2, i3)
a2 = A(i0, -i0, i2, i3)
assert a2.rewrite(Indexed) == Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3))
a3 = a2 + A(i2, i3, i0, -i0)
assert a3.rewrite(Indexed) == \
Sum(Indexed(Symbol("A"), L_0, L_0, i2, i3), (L_0, 0, 3)) +\
Sum(Indexed(Symbol("A"), i2, i3, L_0, L_0), (L_0, 0, 3))
b1 = B(-i0)*a1
assert b1.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_0)*Indexed(Symbol("A"), L_0, i1, i2, i3), (L_0, 0, 3))
b2 = B(-i3)*a2
assert b2.rewrite(Indexed) == Sum(Indexed(Symbol("B"), L_1)*Indexed(Symbol("A"), L_0, L_0, i2, L_1), (L_0, 0, 3), (L_1, 0, 3))
def test_tensorsymmetry():
with warns_deprecated_sympy():
tensorsymmetry([1]*2)
def test_tensorhead():
with warns_deprecated_sympy():
tensorhead('A', [])
def test_TensorType():
with warns_deprecated_sympy():
sym2 = TensorSymmetry.fully_symmetric(2)
Lorentz = TensorIndexType('Lorentz')
S2 = TensorType([Lorentz]*2, sym2)
assert isinstance(S2, TensorType)
|
2d9629bb55a1b693e4a2ef74028cd5d658ca71dd2279559c86b66b3642b6f549 | from sympy.core import symbols, S, Pow, Function
from sympy.functions import exp
from sympy.testing.pytest import raises
from sympy.tensor.indexed import Idx, IndexedBase
from sympy.tensor.index_methods import IndexConformanceException
from sympy import get_contraction_structure, get_indices
def test_trivial_indices():
x, y = symbols('x y')
assert get_indices(x) == (set([]), {})
assert get_indices(x*y) == (set([]), {})
assert get_indices(x + y) == (set([]), {})
assert get_indices(x**y) == (set([]), {})
def test_get_indices_Indexed():
x = IndexedBase('x')
i, j = Idx('i'), Idx('j')
assert get_indices(x[i, j]) == (set([i, j]), {})
assert get_indices(x[j, i]) == (set([j, i]), {})
def test_get_indices_Idx():
f = Function('f')
i, j = Idx('i'), Idx('j')
assert get_indices(f(i)*j) == (set([i, j]), {})
assert get_indices(f(j, i)) == (set([j, i]), {})
assert get_indices(f(i)*i) == (set(), {})
def test_get_indices_mul():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
assert get_indices(x[j]*y[i]) == (set([i, j]), {})
assert get_indices(x[i]*y[j]) == (set([i, j]), {})
def test_get_indices_exceptions():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
raises(IndexConformanceException, lambda: get_indices(x[i] + y[j]))
def test_scalar_broadcast():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
assert get_indices(x[i] + y[i, i]) == (set([i]), {})
assert get_indices(x[i] + y[j, j]) == (set([i]), {})
def test_get_indices_add():
x = IndexedBase('x')
y = IndexedBase('y')
A = IndexedBase('A')
i, j, k = Idx('i'), Idx('j'), Idx('k')
assert get_indices(x[i] + 2*y[i]) == (set([i, ]), {})
assert get_indices(y[i] + 2*A[i, j]*x[j]) == (set([i, ]), {})
assert get_indices(y[i] + 2*(x[i] + A[i, j]*x[j])) == (set([i, ]), {})
assert get_indices(y[i] + x[i]*(A[j, j] + 1)) == (set([i, ]), {})
assert get_indices(
y[i] + x[i]*x[j]*(y[j] + A[j, k]*x[k])) == (set([i, ]), {})
def test_get_indices_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
A = IndexedBase('A')
i, j, k = Idx('i'), Idx('j'), Idx('k')
assert get_indices(Pow(x[i], y[j])) == (set([i, j]), {})
assert get_indices(Pow(x[i, k], y[j, k])) == (set([i, j, k]), {})
assert get_indices(Pow(A[i, k], y[k] + A[k, j]*x[j])) == (set([i, k]), {})
assert get_indices(Pow(2, x[i])) == get_indices(exp(x[i]))
# test of a design decision, this may change:
assert get_indices(Pow(x[i], 2)) == (set([i, ]), {})
def test_get_contraction_structure_basic():
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
assert get_contraction_structure(x[i]*y[j]) == {None: set([x[i]*y[j]])}
assert get_contraction_structure(x[i] + y[j]) == {None: set([x[i], y[j]])}
assert get_contraction_structure(x[i]*y[i]) == {(i,): set([x[i]*y[i]])}
assert get_contraction_structure(
1 + x[i]*y[i]) == {None: set([S.One]), (i,): set([x[i]*y[i]])}
assert get_contraction_structure(x[i]**y[i]) == {None: set([x[i]**y[i]])}
def test_get_contraction_structure_complex():
x = IndexedBase('x')
y = IndexedBase('y')
A = IndexedBase('A')
i, j, k = Idx('i'), Idx('j'), Idx('k')
expr1 = y[i] + A[i, j]*x[j]
d1 = {None: set([y[i]]), (j,): set([A[i, j]*x[j]])}
assert get_contraction_structure(expr1) == d1
expr2 = expr1*A[k, i] + x[k]
d2 = {None: set([x[k]]), (i,): set([expr1*A[k, i]]), expr1*A[k, i]: [d1]}
assert get_contraction_structure(expr2) == d2
def test_contraction_structure_simple_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
i, j, k = Idx('i'), Idx('j'), Idx('k')
ii_jj = x[i, i]**y[j, j]
assert get_contraction_structure(ii_jj) == {
None: set([ii_jj]),
ii_jj: [
{(i,): set([x[i, i]])},
{(j,): set([y[j, j]])}
]
}
ii_jk = x[i, i]**y[j, k]
assert get_contraction_structure(ii_jk) == {
None: set([x[i, i]**y[j, k]]),
x[i, i]**y[j, k]: [
{(i,): set([x[i, i]])}
]
}
def test_contraction_structure_Mul_and_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
i, j, k = Idx('i'), Idx('j'), Idx('k')
i_ji = x[i]**(y[j]*x[i])
assert get_contraction_structure(i_ji) == {None: set([i_ji])}
ij_i = (x[i]*y[j])**(y[i])
assert get_contraction_structure(ij_i) == {None: set([ij_i])}
j_ij_i = x[j]*(x[i]*y[j])**(y[i])
assert get_contraction_structure(j_ij_i) == {(j,): set([j_ij_i])}
j_i_ji = x[j]*x[i]**(y[j]*x[i])
assert get_contraction_structure(j_i_ji) == {(j,): set([j_i_ji])}
ij_exp_kki = x[i]*y[j]*exp(y[i]*y[k, k])
result = get_contraction_structure(ij_exp_kki)
expected = {
(i,): set([ij_exp_kki]),
ij_exp_kki: [{
None: set([exp(y[i]*y[k, k])]),
exp(y[i]*y[k, k]): [{
None: set([y[i]*y[k, k]]),
y[i]*y[k, k]: [{(k,): set([y[k, k]])}]
}]}
]
}
assert result == expected
def test_contraction_structure_Add_in_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
i, j, k = Idx('i'), Idx('j'), Idx('k')
s_ii_jj_s = (1 + x[i, i])**(1 + y[j, j])
expected = {
None: set([s_ii_jj_s]),
s_ii_jj_s: [
{None: set([S.One]), (i,): set([x[i, i]])},
{None: set([S.One]), (j,): set([y[j, j]])}
]
}
result = get_contraction_structure(s_ii_jj_s)
assert result == expected
s_ii_jk_s = (1 + x[i, i]) ** (1 + y[j, k])
expected_2 = {
None: set([(x[i, i] + 1)**(y[j, k] + 1)]),
s_ii_jk_s: [
{None: set([S.One]), (i,): set([x[i, i]])}
]
}
result_2 = get_contraction_structure(s_ii_jk_s)
assert result_2 == expected_2
def test_contraction_structure_Pow_in_Pow():
x = IndexedBase('x')
y = IndexedBase('y')
z = IndexedBase('z')
i, j, k = Idx('i'), Idx('j'), Idx('k')
ii_jj_kk = x[i, i]**y[j, j]**z[k, k]
expected = {
None: set([ii_jj_kk]),
ii_jj_kk: [
{(i,): set([x[i, i]])},
{
None: set([y[j, j]**z[k, k]]),
y[j, j]**z[k, k]: [
{(j,): set([y[j, j]])},
{(k,): set([z[k, k]])}
]
}
]
}
assert get_contraction_structure(ii_jj_kk) == expected
def test_ufunc_support():
f = Function('f')
g = Function('g')
x = IndexedBase('x')
y = IndexedBase('y')
i, j = Idx('i'), Idx('j')
a = symbols('a')
assert get_indices(f(x[i])) == (set([i]), {})
assert get_indices(f(x[i], y[j])) == (set([i, j]), {})
assert get_indices(f(y[i])*g(x[i])) == (set(), {})
assert get_indices(f(a, x[i])) == (set([i]), {})
assert get_indices(f(a, y[i], x[j])*g(x[i])) == (set([j]), {})
assert get_indices(g(f(x[i]))) == (set([i]), {})
assert get_contraction_structure(f(x[i])) == {None: set([f(x[i])])}
assert get_contraction_structure(
f(y[i])*g(x[i])) == {(i,): set([f(y[i])*g(x[i])])}
assert get_contraction_structure(
f(y[i])*g(f(x[i]))) == {(i,): set([f(y[i])*g(f(x[i]))])}
assert get_contraction_structure(
f(x[j], y[i])*g(x[i])) == {(i,): set([f(x[j], y[i])*g(x[i])])}
|
d7f4a73c01918745c6939332cfcb85512102c8a2a1d15964bccba95d89dc3838 | from sympy.core import symbols, Symbol, Tuple, oo, Dummy
from sympy.core.compatibility import iterable
from sympy.tensor.indexed import IndexException
from sympy.testing.pytest import raises, XFAIL
# import test:
from sympy import (IndexedBase, Idx, Indexed, S, sin, cos, exp, log, Sum,
Order, LessThan, StrictGreaterThan, GreaterThan, StrictLessThan,
Range, Subs, Function, KroneckerDelta, Derivative)
def test_Idx_construction():
i, a, b = symbols('i a b', integer=True)
assert Idx(i) != Idx(i, 1)
assert Idx(i, a) == Idx(i, (0, a - 1))
assert Idx(i, oo) == Idx(i, (0, oo))
x = symbols('x', integer=False)
raises(TypeError, lambda: Idx(x))
raises(TypeError, lambda: Idx(0.5))
raises(TypeError, lambda: Idx(i, x))
raises(TypeError, lambda: Idx(i, 0.5))
raises(TypeError, lambda: Idx(i, (x, 5)))
raises(TypeError, lambda: Idx(i, (2, x)))
raises(TypeError, lambda: Idx(i, (2, 3.5)))
def test_Idx_properties():
i, a, b = symbols('i a b', integer=True)
assert Idx(i).is_integer
assert Idx(i).name == 'i'
assert Idx(i + 2).name == 'i + 2'
assert Idx('foo').name == 'foo'
def test_Idx_bounds():
i, a, b = symbols('i a b', integer=True)
assert Idx(i).lower is None
assert Idx(i).upper is None
assert Idx(i, a).lower == 0
assert Idx(i, a).upper == a - 1
assert Idx(i, 5).lower == 0
assert Idx(i, 5).upper == 4
assert Idx(i, oo).lower == 0
assert Idx(i, oo).upper is oo
assert Idx(i, (a, b)).lower == a
assert Idx(i, (a, b)).upper == b
assert Idx(i, (1, 5)).lower == 1
assert Idx(i, (1, 5)).upper == 5
assert Idx(i, (-oo, oo)).lower is -oo
assert Idx(i, (-oo, oo)).upper is oo
def test_Idx_fixed_bounds():
i, a, b, x = symbols('i a b x', integer=True)
assert Idx(x).lower is None
assert Idx(x).upper is None
assert Idx(x, a).lower == 0
assert Idx(x, a).upper == a - 1
assert Idx(x, 5).lower == 0
assert Idx(x, 5).upper == 4
assert Idx(x, oo).lower == 0
assert Idx(x, oo).upper is oo
assert Idx(x, (a, b)).lower == a
assert Idx(x, (a, b)).upper == b
assert Idx(x, (1, 5)).lower == 1
assert Idx(x, (1, 5)).upper == 5
assert Idx(x, (-oo, oo)).lower is -oo
assert Idx(x, (-oo, oo)).upper is oo
def test_Idx_inequalities():
i14 = Idx("i14", (1, 4))
i79 = Idx("i79", (7, 9))
i46 = Idx("i46", (4, 6))
i35 = Idx("i35", (3, 5))
assert i14 <= 5
assert i14 < 5
assert not (i14 >= 5)
assert not (i14 > 5)
assert 5 >= i14
assert 5 > i14
assert not (5 <= i14)
assert not (5 < i14)
assert LessThan(i14, 5)
assert StrictLessThan(i14, 5)
assert not GreaterThan(i14, 5)
assert not StrictGreaterThan(i14, 5)
assert i14 <= 4
assert isinstance(i14 < 4, StrictLessThan)
assert isinstance(i14 >= 4, GreaterThan)
assert not (i14 > 4)
assert isinstance(i14 <= 1, LessThan)
assert not (i14 < 1)
assert i14 >= 1
assert isinstance(i14 > 1, StrictGreaterThan)
assert not (i14 <= 0)
assert not (i14 < 0)
assert i14 >= 0
assert i14 > 0
from sympy.abc import x
assert isinstance(i14 < x, StrictLessThan)
assert isinstance(i14 > x, StrictGreaterThan)
assert isinstance(i14 <= x, LessThan)
assert isinstance(i14 >= x, GreaterThan)
assert i14 < i79
assert i14 <= i79
assert not (i14 > i79)
assert not (i14 >= i79)
assert i14 <= i46
assert isinstance(i14 < i46, StrictLessThan)
assert isinstance(i14 >= i46, GreaterThan)
assert not (i14 > i46)
assert isinstance(i14 < i35, StrictLessThan)
assert isinstance(i14 > i35, StrictGreaterThan)
assert isinstance(i14 <= i35, LessThan)
assert isinstance(i14 >= i35, GreaterThan)
iNone1 = Idx("iNone1")
iNone2 = Idx("iNone2")
assert isinstance(iNone1 < iNone2, StrictLessThan)
assert isinstance(iNone1 > iNone2, StrictGreaterThan)
assert isinstance(iNone1 <= iNone2, LessThan)
assert isinstance(iNone1 >= iNone2, GreaterThan)
@XFAIL
def test_Idx_inequalities_current_fails():
i14 = Idx("i14", (1, 4))
assert S(5) >= i14
assert S(5) > i14
assert not (S(5) <= i14)
assert not (S(5) < i14)
def test_Idx_func_args():
i, a, b = symbols('i a b', integer=True)
ii = Idx(i)
assert ii.func(*ii.args) == ii
ii = Idx(i, a)
assert ii.func(*ii.args) == ii
ii = Idx(i, (a, b))
assert ii.func(*ii.args) == ii
def test_Idx_subs():
i, a, b = symbols('i a b', integer=True)
assert Idx(i, a).subs(a, b) == Idx(i, b)
assert Idx(i, a).subs(i, b) == Idx(b, a)
assert Idx(i).subs(i, 2) == Idx(2)
assert Idx(i, a).subs(a, 2) == Idx(i, 2)
assert Idx(i, (a, b)).subs(i, 2) == Idx(2, (a, b))
def test_IndexedBase_sugar():
i, j = symbols('i j', integer=True)
a = symbols('a')
A1 = Indexed(a, i, j)
A2 = IndexedBase(a)
assert A1 == A2[i, j]
assert A1 == A2[(i, j)]
assert A1 == A2[[i, j]]
assert A1 == A2[Tuple(i, j)]
assert all(a.is_Integer for a in A2[1, 0].args[1:])
def test_IndexedBase_subs():
i = symbols('i', integer=True)
a, b = symbols('a b')
A = IndexedBase(a)
B = IndexedBase(b)
assert A[i] == B[i].subs(b, a)
C = {1: 2}
assert C[1] == A[1].subs(A, C)
def test_IndexedBase_shape():
i, j, m, n = symbols('i j m n', integer=True)
a = IndexedBase('a', shape=(m, m))
b = IndexedBase('a', shape=(m, n))
assert b.shape == Tuple(m, n)
assert a[i, j] != b[i, j]
assert a[i, j] == b[i, j].subs(n, m)
assert b.func(*b.args) == b
assert b[i, j].func(*b[i, j].args) == b[i, j]
raises(IndexException, lambda: b[i])
raises(IndexException, lambda: b[i, i, j])
F = IndexedBase("F", shape=m)
assert F.shape == Tuple(m)
assert F[i].subs(i, j) == F[j]
raises(IndexException, lambda: F[i, j])
def test_IndexedBase_assumptions():
i = Symbol('i', integer=True)
a = Symbol('a')
A = IndexedBase(a, positive=True)
for c in (A, A[i]):
assert c.is_real
assert c.is_complex
assert not c.is_imaginary
assert c.is_nonnegative
assert c.is_nonzero
assert c.is_commutative
assert log(exp(c)) == c
assert A != IndexedBase(a)
assert A == IndexedBase(a, positive=True, real=True)
assert A[i] != Indexed(a, i)
def test_IndexedBase_assumptions_inheritance():
I = Symbol('I', integer=True)
I_inherit = IndexedBase(I)
I_explicit = IndexedBase('I', integer=True)
assert I_inherit.is_integer
assert I_explicit.is_integer
assert I_inherit.label.is_integer
assert I_explicit.label.is_integer
assert I_inherit == I_explicit
def test_issue_17652():
"""Regression test issue #17652.
IndexedBase.label should not upcast subclasses of Symbol
"""
class SubClass(Symbol):
pass
x = SubClass('X')
assert type(x) == SubClass
base = IndexedBase(x)
assert type(x) == SubClass
assert type(base.label) == SubClass
def test_Indexed_constructor():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, j)
assert A == Indexed(Symbol('A'), i, j)
assert A == Indexed(IndexedBase('A'), i, j)
raises(TypeError, lambda: Indexed(A, i, j))
raises(IndexException, lambda: Indexed("A"))
assert A.free_symbols == {A, A.base.label, i, j}
def test_Indexed_func_args():
i, j = symbols('i j', integer=True)
a = symbols('a')
A = Indexed(a, i, j)
assert A == A.func(*A.args)
def test_Indexed_subs():
i, j, k = symbols('i j k', integer=True)
a, b = symbols('a b')
A = IndexedBase(a)
B = IndexedBase(b)
assert A[i, j] == B[i, j].subs(b, a)
assert A[i, j] == A[i, k].subs(k, j)
def test_Indexed_properties():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, j)
assert A.name == 'A[i, j]'
assert A.rank == 2
assert A.indices == (i, j)
assert A.base == IndexedBase('A')
assert A.ranges == [None, None]
raises(IndexException, lambda: A.shape)
n, m = symbols('n m', integer=True)
assert Indexed('A', Idx(
i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
assert Indexed('A', Idx(i, m), Idx(j, n)).shape == Tuple(m, n)
raises(IndexException, lambda: Indexed("A", Idx(i, m), Idx(j)).shape)
def test_Indexed_shape_precedence():
i, j = symbols('i j', integer=True)
o, p = symbols('o p', integer=True)
n, m = symbols('n m', integer=True)
a = IndexedBase('a', shape=(o, p))
assert a.shape == Tuple(o, p)
assert Indexed(
a, Idx(i, m), Idx(j, n)).ranges == [Tuple(0, m - 1), Tuple(0, n - 1)]
assert Indexed(a, Idx(i, m), Idx(j, n)).shape == Tuple(o, p)
assert Indexed(
a, Idx(i, m), Idx(j)).ranges == [Tuple(0, m - 1), Tuple(None, None)]
assert Indexed(a, Idx(i, m), Idx(j)).shape == Tuple(o, p)
def test_complex_indices():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
assert A.rank == 2
assert A.indices == (i, i + j)
def test_not_interable():
i, j = symbols('i j', integer=True)
A = Indexed('A', i, i + j)
assert not iterable(A)
def test_Indexed_coeff():
N = Symbol('N', integer=True)
len_y = N
i = Idx('i', len_y-1)
y = IndexedBase('y', shape=(len_y,))
a = (1/y[i+1]*y[i]).coeff(y[i])
b = (y[i]/y[i+1]).coeff(y[i])
assert a == b
def test_differentiation():
from sympy.functions.special.tensor_functions import KroneckerDelta
i, j, k, l = symbols('i j k l', cls=Idx)
a = symbols('a')
m, n = symbols("m, n", integer=True, finite=True)
assert m.is_real
h, L = symbols('h L', cls=IndexedBase)
hi, hj = h[i], h[j]
expr = hi
assert expr.diff(hj) == KroneckerDelta(i, j)
assert expr.diff(hi) == KroneckerDelta(i, i)
expr = S(2) * hi
assert expr.diff(hj) == S(2) * KroneckerDelta(i, j)
assert expr.diff(hi) == S(2) * KroneckerDelta(i, i)
assert expr.diff(a) is S.Zero
assert Sum(expr, (i, -oo, oo)).diff(hj) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
assert Sum(expr.diff(hj), (i, -oo, oo)) == Sum(2*KroneckerDelta(i, j), (i, -oo, oo))
assert Sum(expr, (i, -oo, oo)).diff(hj).doit() == 2
assert Sum(expr.diff(hi), (i, -oo, oo)).doit() == Sum(2, (i, -oo, oo)).doit()
assert Sum(expr, (i, -oo, oo)).diff(hi).doit() is oo
expr = a * hj * hj / S(2)
assert expr.diff(hi) == a * h[j] * KroneckerDelta(i, j)
assert expr.diff(a) == hj * hj / S(2)
assert expr.diff(a, 2) is S.Zero
assert Sum(expr, (i, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
assert Sum(expr.diff(hi), (i, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (i, -oo, oo))
assert Sum(expr, (i, -oo, oo)).diff(hi).doit() == a*h[j]
assert Sum(expr, (j, -oo, oo)).diff(hi) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
assert Sum(expr.diff(hi), (j, -oo, oo)) == Sum(a*KroneckerDelta(i, j)*h[j], (j, -oo, oo))
assert Sum(expr, (j, -oo, oo)).diff(hi).doit() == a*h[i]
expr = a * sin(hj * hj)
assert expr.diff(hi) == 2*a*cos(hj * hj) * hj * KroneckerDelta(i, j)
assert expr.diff(hj) == 2*a*cos(hj * hj) * hj
expr = a * L[i, j] * h[j]
assert expr.diff(hi) == a*L[i, j]*KroneckerDelta(i, j)
assert expr.diff(hj) == a*L[i, j]
assert expr.diff(L[i, j]) == a*h[j]
assert expr.diff(L[k, l]) == a*KroneckerDelta(i, k)*KroneckerDelta(j, l)*h[j]
assert expr.diff(L[i, l]) == a*KroneckerDelta(j, l)*h[j]
assert Sum(expr, (j, -oo, oo)).diff(L[k, l]) == Sum(a * KroneckerDelta(i, k) * KroneckerDelta(j, l) * h[j], (j, -oo, oo))
assert Sum(expr, (j, -oo, oo)).diff(L[k, l]).doit() == a * KroneckerDelta(i, k) * h[l]
assert h[m].diff(h[m]) == 1
assert h[m].diff(h[n]) == KroneckerDelta(m, n)
assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (m, -oo, oo))
assert Sum(a*h[m], (m, -oo, oo)).diff(h[n]).doit() == a
assert Sum(a*h[m], (n, -oo, oo)).diff(h[n]) == Sum(a*KroneckerDelta(m, n), (n, -oo, oo))
assert Sum(a*h[m], (m, -oo, oo)).diff(h[m]).doit() == oo*a
def test_indexed_series():
A = IndexedBase("A")
i = symbols("i", integer=True)
assert sin(A[i]).series(A[i]) == A[i] - A[i]**3/6 + A[i]**5/120 + Order(A[i]**6, A[i])
def test_indexed_is_constant():
A = IndexedBase("A")
i, j, k = symbols("i,j,k")
assert not A[i].is_constant()
assert A[i].is_constant(j)
assert not A[1+2*i, k].is_constant()
assert not A[1+2*i, k].is_constant(i)
assert A[1+2*i, k].is_constant(j)
assert not A[1+2*i, k].is_constant(k)
def test_issue_12533():
d = IndexedBase('d')
assert IndexedBase(range(5)) == Range(0, 5, 1)
assert d[0].subs(Symbol("d"), range(5)) == 0
assert d[0].subs(d, range(5)) == 0
assert d[1].subs(d, range(5)) == 1
assert Indexed(Range(5), 2) == 2
def test_issue_12780():
n = symbols("n")
i = Idx("i", (0, n))
raises(TypeError, lambda: i.subs(n, 1.5))
def test_issue_18604():
m = symbols("m")
assert Idx("i", m).name == 'i'
assert Idx("i", m).lower == 0
assert Idx("i", m).upper == m - 1
m = symbols("m", real=False)
raises(TypeError, lambda: Idx("i", m))
def test_Subs_with_Indexed():
A = IndexedBase("A")
i, j, k = symbols("i,j,k")
x, y, z = symbols("x,y,z")
f = Function("f")
assert Subs(A[i], A[i], A[j]).diff(A[j]) == 1
assert Subs(A[i], A[i], x).diff(A[i]) == 0
assert Subs(A[i], A[i], x).diff(A[j]) == 0
assert Subs(A[i], A[i], x).diff(x) == 1
assert Subs(A[i], A[i], x).diff(y) == 0
assert Subs(A[i], A[i], A[j]).diff(A[k]) == KroneckerDelta(j, k)
assert Subs(x, x, A[i]).diff(A[j]) == KroneckerDelta(i, j)
assert Subs(f(A[i]), A[i], x).diff(A[j]) == 0
assert Subs(f(A[i]), A[i], A[k]).diff(A[j]) == Derivative(f(A[k]), A[k])*KroneckerDelta(j, k)
assert Subs(x, x, A[i]**2).diff(A[j]) == 2*KroneckerDelta(i, j)*A[i]
assert Subs(A[i], A[i], A[j]**2).diff(A[k]) == 2*KroneckerDelta(j, k)*A[j]
assert Subs(A[i]*x, x, A[i]).diff(A[i]) == 2*A[i]
assert Subs(A[i]*x, x, A[i]).diff(A[j]) == 2*A[i]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[j]).diff(A[i]) == A[j] + A[i]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[j]).diff(A[j]) == A[i] + A[j]*KroneckerDelta(i, j)
assert Subs(A[i]*x, x, A[i]).diff(A[k]) == 2*A[i]*KroneckerDelta(i, k)
assert Subs(A[i]*x, x, A[j]).diff(A[k]) == KroneckerDelta(i, k)*A[j] + KroneckerDelta(j, k)*A[i]
assert Subs(A[i]*x, A[i], x).diff(A[i]) == 0
assert Subs(A[i]*x, A[i], x).diff(A[j]) == 0
assert Subs(A[i]*x, A[j], x).diff(A[i]) == x
assert Subs(A[i]*x, A[j], x).diff(A[j]) == x*KroneckerDelta(i, j)
assert Subs(A[i]*x, A[i], x).diff(A[k]) == 0
assert Subs(A[i]*x, A[j], x).diff(A[k]) == x*KroneckerDelta(i, k)
def test_complicated_derivative_with_Indexed():
x, y = symbols("x,y", cls=IndexedBase)
sigma = symbols("sigma")
i, j, k = symbols("i,j,k")
m0,m1,m2,m3,m4,m5 = symbols("m0:6")
f = Function("f")
expr = f((x[i] - y[i])**2/sigma)
_xi_1 = symbols("xi_1", cls=Dummy)
assert expr.diff(x[m0]).dummy_eq(
(x[i] - y[i])*KroneckerDelta(i, m0)*\
2*Subs(
Derivative(f(_xi_1), _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma
)
assert expr.diff(x[m0]).diff(x[m1]).dummy_eq(
2*KroneckerDelta(i, m0)*\
KroneckerDelta(i, m1)*Subs(
Derivative(f(_xi_1), _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma + \
4*(x[i] - y[i])**2*KroneckerDelta(i, m0)*KroneckerDelta(i, m1)*\
Subs(
Derivative(f(_xi_1), _xi_1, _xi_1),
(_xi_1,),
((x[i] - y[i])**2/sigma,)
)/sigma**2
)
|
772f94e47c702c7b81ace6c59cfa0441014794cd0169ebe2a15dc366d3ade809 | import random
from sympy.combinatorics import Permutation
from sympy.combinatorics.permutations import _af_invert
from sympy.testing.pytest import raises
from sympy import symbols, sin, exp, log, cos, transpose, adjoint, conjugate, diff
from sympy.tensor.array import Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray, MutableSparseNDimArray
from sympy.tensor.array.arrayop import tensorproduct, tensorcontraction, derive_by_array, permutedims, Flatten
def test_import_NDimArray():
from sympy.tensor.array import NDimArray
del NDimArray
def test_tensorproduct():
x,y,z,t = symbols('x y z t')
from sympy.abc import a,b,c,d
assert tensorproduct() == 1
assert tensorproduct([x]) == Array([x])
assert tensorproduct([x], [y]) == Array([[x*y]])
assert tensorproduct([x], [y], [z]) == Array([[[x*y*z]]])
assert tensorproduct([x], [y], [z], [t]) == Array([[[[x*y*z*t]]]])
assert tensorproduct(x) == x
assert tensorproduct(x, y) == x*y
assert tensorproduct(x, y, z) == x*y*z
assert tensorproduct(x, y, z, t) == x*y*z*t
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
A = ArrayType([x, y])
B = ArrayType([1, 2, 3])
C = ArrayType([a, b, c, d])
assert tensorproduct(A, B, C) == ArrayType([[[a*x, b*x, c*x, d*x], [2*a*x, 2*b*x, 2*c*x, 2*d*x], [3*a*x, 3*b*x, 3*c*x, 3*d*x]],
[[a*y, b*y, c*y, d*y], [2*a*y, 2*b*y, 2*c*y, 2*d*y], [3*a*y, 3*b*y, 3*c*y, 3*d*y]]])
assert tensorproduct([x, y], [1, 2, 3]) == tensorproduct(A, B)
assert tensorproduct(A, 2) == ArrayType([2*x, 2*y])
assert tensorproduct(A, [2]) == ArrayType([[2*x], [2*y]])
assert tensorproduct([2], A) == ArrayType([[2*x, 2*y]])
assert tensorproduct(a, A) == ArrayType([a*x, a*y])
assert tensorproduct(a, A, B) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(A, B, a) == ArrayType([[a*x, 2*a*x, 3*a*x], [a*y, 2*a*y, 3*a*y]])
assert tensorproduct(B, a, A) == ArrayType([[a*x, a*y], [2*a*x, 2*a*y], [3*a*x, 3*a*y]])
# tests for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
a = SparseArrayType({1:2, 3:4},(1000, 2000))
b = SparseArrayType({1:2, 3:4},(1000, 2000))
assert tensorproduct(a, b) == ImmutableSparseNDimArray({2000001: 4, 2000003: 8, 6000001: 8, 6000003: 16}, (1000, 2000, 1000, 2000))
def test_tensorcontraction():
from sympy.abc import a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x
B = Array(range(18), (2, 3, 3))
assert tensorcontraction(B, (1, 2)) == Array([12, 39])
C1 = Array([a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x], (2, 3, 2, 2))
assert tensorcontraction(C1, (0, 2)) == Array([[a + o, b + p], [e + s, f + t], [i + w, j + x]])
assert tensorcontraction(C1, (0, 2, 3)) == Array([a + p, e + t, i + x])
assert tensorcontraction(C1, (2, 3)) == Array([[a + d, e + h, i + l], [m + p, q + t, u + x]])
def test_derivative_by_array():
from sympy.abc import i, j, t, x, y, z
bexpr = x*y**2*exp(z)*log(t)
sexpr = sin(bexpr)
cexpr = cos(bexpr)
a = Array([sexpr])
assert derive_by_array(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert derive_by_array(sexpr, [x, y, z]) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert derive_by_array(a, [x, y, z]) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert derive_by_array(sexpr, [[x, y], [z, t]]) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert derive_by_array(a, [[x, y], [z, t]]) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert derive_by_array([[x, y], [z, t]], [x, y]) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert derive_by_array([[x, y], [z, t]], [[x, y], [z, t]]) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(sexpr, t) == x*y**2*exp(z)*cos(x*y**2*exp(z)*log(t))/t
assert diff(sexpr, Array([x, y, z])) == Array([bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr, bexpr*cexpr])
assert diff(a, Array([x, y, z])) == Array([[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr], [bexpr*cexpr]])
assert diff(sexpr, Array([[x, y], [z, t]])) == Array([[bexpr/x*cexpr, 2*y*bexpr/y**2*cexpr], [bexpr*cexpr, bexpr/log(t)/t*cexpr]])
assert diff(a, Array([[x, y], [z, t]])) == Array([[[bexpr/x*cexpr], [2*y*bexpr/y**2*cexpr]], [[bexpr*cexpr], [bexpr/log(t)/t*cexpr]]])
assert diff(Array([[x, y], [z, t]]), Array([x, y])) == Array([[[1, 0], [0, 0]], [[0, 1], [0, 0]]])
assert diff(Array([[x, y], [z, t]]), Array([[x, y], [z, t]])) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]],
[[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
b = MutableSparseNDimArray({0:i, 1:j}, (10000, 20000))
assert derive_by_array(b, i) == ImmutableSparseNDimArray({0: 1}, (10000, 20000))
assert derive_by_array(b, (i, j)) == ImmutableSparseNDimArray({0: 1, 200000001: 1}, (2, 10000, 20000))
def test_issue_emerged_while_discussing_10972():
ua = Array([-1,0])
Fa = Array([[0, 1], [-1, 0]])
po = tensorproduct(Fa, ua, Fa, ua)
assert tensorcontraction(po, (1, 2), (4, 5)) == Array([[0, 0], [0, 1]])
sa = symbols('a0:144')
po = Array(sa, [2, 2, 3, 3, 2, 2])
assert tensorcontraction(po, (0, 1), (2, 3), (4, 5)) == sa[0] + sa[108] + sa[111] + sa[124] + sa[127] + sa[140] + sa[143] + sa[16] + sa[19] + sa[3] + sa[32] + sa[35]
assert tensorcontraction(po, (0, 1, 4, 5), (2, 3)) == sa[0] + sa[111] + sa[127] + sa[143] + sa[16] + sa[32]
assert tensorcontraction(po, (0, 1), (4, 5)) == Array([[sa[0] + sa[108] + sa[111] + sa[3], sa[112] + sa[115] + sa[4] + sa[7],
sa[11] + sa[116] + sa[119] + sa[8]], [sa[12] + sa[120] + sa[123] + sa[15],
sa[124] + sa[127] + sa[16] + sa[19], sa[128] + sa[131] + sa[20] + sa[23]],
[sa[132] + sa[135] + sa[24] + sa[27], sa[136] + sa[139] + sa[28] + sa[31],
sa[140] + sa[143] + sa[32] + sa[35]]])
assert tensorcontraction(po, (0, 1), (2, 3)) == Array([[sa[0] + sa[108] + sa[124] + sa[140] + sa[16] + sa[32], sa[1] + sa[109] + sa[125] + sa[141] + sa[17] + sa[33]],
[sa[110] + sa[126] + sa[142] + sa[18] + sa[2] + sa[34], sa[111] + sa[127] + sa[143] + sa[19] + sa[3] + sa[35]]])
def test_array_permutedims():
sa = symbols('a0:144')
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
m1 = ArrayType(sa[:6], (2, 3))
assert permutedims(m1, (1, 0)) == transpose(m1)
assert m1.tomatrix().T == permutedims(m1, (1, 0)).tomatrix()
assert m1.tomatrix().T == transpose(m1).tomatrix()
assert m1.tomatrix().C == conjugate(m1).tomatrix()
assert m1.tomatrix().H == adjoint(m1).tomatrix()
assert m1.tomatrix().T == m1.transpose().tomatrix()
assert m1.tomatrix().C == m1.conjugate().tomatrix()
assert m1.tomatrix().H == m1.adjoint().tomatrix()
raises(ValueError, lambda: permutedims(m1, (0,)))
raises(ValueError, lambda: permutedims(m1, (0, 0)))
raises(ValueError, lambda: permutedims(m1, (1, 2, 0)))
# Some tests with random arrays:
dims = 6
shape = [random.randint(1,5) for i in range(dims)]
elems = [random.random() for i in range(tensorproduct(*shape))]
ra = ArrayType(elems, shape)
perm = list(range(dims))
# Randomize the permutation:
random.shuffle(perm)
# Test inverse permutation:
assert permutedims(permutedims(ra, perm), _af_invert(perm)) == ra
# Test that permuted shape corresponds to action by `Permutation`:
assert permutedims(ra, perm).shape == tuple(Permutation(perm)(shape))
z = ArrayType.zeros(4,5,6,7)
assert permutedims(z, (2, 3, 1, 0)).shape == (6, 7, 5, 4)
assert permutedims(z, [2, 3, 1, 0]).shape == (6, 7, 5, 4)
assert permutedims(z, Permutation([2, 3, 1, 0])).shape == (6, 7, 5, 4)
po = ArrayType(sa, [2, 2, 3, 3, 2, 2])
raises(ValueError, lambda: permutedims(po, (1, 1)))
raises(ValueError, lambda: po.transpose())
raises(ValueError, lambda: po.adjoint())
assert permutedims(po, reversed(range(po.rank()))) == ArrayType(
[[[[[[sa[0], sa[72]], [sa[36], sa[108]]], [[sa[12], sa[84]], [sa[48], sa[120]]], [[sa[24],
sa[96]], [sa[60], sa[132]]]],
[[[sa[4], sa[76]], [sa[40], sa[112]]], [[sa[16],
sa[88]], [sa[52], sa[124]]],
[[sa[28], sa[100]], [sa[64], sa[136]]]],
[[[sa[8],
sa[80]], [sa[44], sa[116]]], [[sa[20], sa[92]], [sa[56], sa[128]]], [[sa[32],
sa[104]], [sa[68], sa[140]]]]],
[[[[sa[2], sa[74]], [sa[38], sa[110]]], [[sa[14],
sa[86]], [sa[50], sa[122]]], [[sa[26], sa[98]], [sa[62], sa[134]]]],
[[[sa[6],
sa[78]], [sa[42], sa[114]]], [[sa[18], sa[90]], [sa[54], sa[126]]], [[sa[30],
sa[102]], [sa[66], sa[138]]]],
[[[sa[10], sa[82]], [sa[46], sa[118]]], [[sa[22],
sa[94]], [sa[58], sa[130]]],
[[sa[34], sa[106]], [sa[70], sa[142]]]]]],
[[[[[sa[1],
sa[73]], [sa[37], sa[109]]], [[sa[13], sa[85]], [sa[49], sa[121]]], [[sa[25],
sa[97]], [sa[61], sa[133]]]],
[[[sa[5], sa[77]], [sa[41], sa[113]]], [[sa[17],
sa[89]], [sa[53], sa[125]]],
[[sa[29], sa[101]], [sa[65], sa[137]]]],
[[[sa[9],
sa[81]], [sa[45], sa[117]]], [[sa[21], sa[93]], [sa[57], sa[129]]], [[sa[33],
sa[105]], [sa[69], sa[141]]]]],
[[[[sa[3], sa[75]], [sa[39], sa[111]]], [[sa[15],
sa[87]], [sa[51], sa[123]]], [[sa[27], sa[99]], [sa[63], sa[135]]]],
[[[sa[7],
sa[79]], [sa[43], sa[115]]], [[sa[19], sa[91]], [sa[55], sa[127]]], [[sa[31],
sa[103]], [sa[67], sa[139]]]],
[[[sa[11], sa[83]], [sa[47], sa[119]]], [[sa[23],
sa[95]], [sa[59], sa[131]]],
[[sa[35], sa[107]], [sa[71], sa[143]]]]]]])
assert permutedims(po, (1, 0, 2, 3, 4, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10],
sa[11]]]],
[[[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18],
sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]]],
[[[sa[24], sa[25]], [sa[26],
sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34],
sa[35]]]]],
[[[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78],
sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]]],
[[[sa[84], sa[85]], [sa[86],
sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94],
sa[95]]]],
[[[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102],
sa[103]]],
[[sa[104], sa[105]], [sa[106], sa[107]]]]]], [[[[[sa[36], sa[37]], [sa[38],
sa[39]]],
[[sa[40], sa[41]], [sa[42], sa[43]]],
[[sa[44], sa[45]], [sa[46],
sa[47]]]],
[[[sa[48], sa[49]], [sa[50], sa[51]]],
[[sa[52], sa[53]], [sa[54],
sa[55]]],
[[sa[56], sa[57]], [sa[58], sa[59]]]],
[[[sa[60], sa[61]], [sa[62],
sa[63]]],
[[sa[64], sa[65]], [sa[66], sa[67]]],
[[sa[68], sa[69]], [sa[70],
sa[71]]]]], [
[[[sa[108], sa[109]], [sa[110], sa[111]]],
[[sa[112], sa[113]], [sa[114],
sa[115]]],
[[sa[116], sa[117]], [sa[118], sa[119]]]],
[[[sa[120], sa[121]], [sa[122],
sa[123]]],
[[sa[124], sa[125]], [sa[126], sa[127]]],
[[sa[128], sa[129]], [sa[130],
sa[131]]]],
[[[sa[132], sa[133]], [sa[134], sa[135]]],
[[sa[136], sa[137]], [sa[138],
sa[139]]],
[[sa[140], sa[141]], [sa[142], sa[143]]]]]]])
assert permutedims(po, (0, 2, 1, 4, 3, 5)) == ArrayType(
[[[[[[sa[0], sa[1]], [sa[4], sa[5]], [sa[8], sa[9]]], [[sa[2], sa[3]], [sa[6], sa[7]], [sa[10],
sa[11]]]],
[[[sa[36], sa[37]], [sa[40], sa[41]], [sa[44], sa[45]]], [[sa[38],
sa[39]], [sa[42], sa[43]], [sa[46], sa[47]]]]],
[[[[sa[12], sa[13]], [sa[16],
sa[17]], [sa[20], sa[21]]], [[sa[14], sa[15]], [sa[18], sa[19]], [sa[22],
sa[23]]]],
[[[sa[48], sa[49]], [sa[52], sa[53]], [sa[56], sa[57]]], [[sa[50],
sa[51]], [sa[54], sa[55]], [sa[58], sa[59]]]]],
[[[[sa[24], sa[25]], [sa[28],
sa[29]], [sa[32], sa[33]]], [[sa[26], sa[27]], [sa[30], sa[31]], [sa[34],
sa[35]]]],
[[[sa[60], sa[61]], [sa[64], sa[65]], [sa[68], sa[69]]], [[sa[62],
sa[63]], [sa[66], sa[67]], [sa[70], sa[71]]]]]],
[[[[[sa[72], sa[73]], [sa[76],
sa[77]], [sa[80], sa[81]]], [[sa[74], sa[75]], [sa[78], sa[79]], [sa[82],
sa[83]]]],
[[[sa[108], sa[109]], [sa[112], sa[113]], [sa[116], sa[117]]], [[sa[110],
sa[111]], [sa[114], sa[115]],
[sa[118], sa[119]]]]],
[[[[sa[84], sa[85]], [sa[88],
sa[89]], [sa[92], sa[93]]], [[sa[86], sa[87]], [sa[90], sa[91]], [sa[94],
sa[95]]]],
[[[sa[120], sa[121]], [sa[124], sa[125]], [sa[128], sa[129]]], [[sa[122],
sa[123]], [sa[126], sa[127]],
[sa[130], sa[131]]]]],
[[[[sa[96], sa[97]], [sa[100],
sa[101]], [sa[104], sa[105]]], [[sa[98], sa[99]], [sa[102], sa[103]], [sa[106],
sa[107]]]],
[[[sa[132], sa[133]], [sa[136], sa[137]], [sa[140], sa[141]]], [[sa[134],
sa[135]], [sa[138], sa[139]],
[sa[142], sa[143]]]]]]])
po2 = po.reshape(4, 9, 2, 2)
assert po2 == ArrayType([[[[sa[0], sa[1]], [sa[2], sa[3]]], [[sa[4], sa[5]], [sa[6], sa[7]]], [[sa[8], sa[9]], [sa[10], sa[11]]], [[sa[12], sa[13]], [sa[14], sa[15]]], [[sa[16], sa[17]], [sa[18], sa[19]]], [[sa[20], sa[21]], [sa[22], sa[23]]], [[sa[24], sa[25]], [sa[26], sa[27]]], [[sa[28], sa[29]], [sa[30], sa[31]]], [[sa[32], sa[33]], [sa[34], sa[35]]]], [[[sa[36], sa[37]], [sa[38], sa[39]]], [[sa[40], sa[41]], [sa[42], sa[43]]], [[sa[44], sa[45]], [sa[46], sa[47]]], [[sa[48], sa[49]], [sa[50], sa[51]]], [[sa[52], sa[53]], [sa[54], sa[55]]], [[sa[56], sa[57]], [sa[58], sa[59]]], [[sa[60], sa[61]], [sa[62], sa[63]]], [[sa[64], sa[65]], [sa[66], sa[67]]], [[sa[68], sa[69]], [sa[70], sa[71]]]], [[[sa[72], sa[73]], [sa[74], sa[75]]], [[sa[76], sa[77]], [sa[78], sa[79]]], [[sa[80], sa[81]], [sa[82], sa[83]]], [[sa[84], sa[85]], [sa[86], sa[87]]], [[sa[88], sa[89]], [sa[90], sa[91]]], [[sa[92], sa[93]], [sa[94], sa[95]]], [[sa[96], sa[97]], [sa[98], sa[99]]], [[sa[100], sa[101]], [sa[102], sa[103]]], [[sa[104], sa[105]], [sa[106], sa[107]]]], [[[sa[108], sa[109]], [sa[110], sa[111]]], [[sa[112], sa[113]], [sa[114], sa[115]]], [[sa[116], sa[117]], [sa[118], sa[119]]], [[sa[120], sa[121]], [sa[122], sa[123]]], [[sa[124], sa[125]], [sa[126], sa[127]]], [[sa[128], sa[129]], [sa[130], sa[131]]], [[sa[132], sa[133]], [sa[134], sa[135]]], [[sa[136], sa[137]], [sa[138], sa[139]]], [[sa[140], sa[141]], [sa[142], sa[143]]]]])
assert permutedims(po2, (3, 2, 0, 1)) == ArrayType([[[[sa[0], sa[4], sa[8], sa[12], sa[16], sa[20], sa[24], sa[28], sa[32]], [sa[36], sa[40], sa[44], sa[48], sa[52], sa[56], sa[60], sa[64], sa[68]], [sa[72], sa[76], sa[80], sa[84], sa[88], sa[92], sa[96], sa[100], sa[104]], [sa[108], sa[112], sa[116], sa[120], sa[124], sa[128], sa[132], sa[136], sa[140]]], [[sa[2], sa[6], sa[10], sa[14], sa[18], sa[22], sa[26], sa[30], sa[34]], [sa[38], sa[42], sa[46], sa[50], sa[54], sa[58], sa[62], sa[66], sa[70]], [sa[74], sa[78], sa[82], sa[86], sa[90], sa[94], sa[98], sa[102], sa[106]], [sa[110], sa[114], sa[118], sa[122], sa[126], sa[130], sa[134], sa[138], sa[142]]]], [[[sa[1], sa[5], sa[9], sa[13], sa[17], sa[21], sa[25], sa[29], sa[33]], [sa[37], sa[41], sa[45], sa[49], sa[53], sa[57], sa[61], sa[65], sa[69]], [sa[73], sa[77], sa[81], sa[85], sa[89], sa[93], sa[97], sa[101], sa[105]], [sa[109], sa[113], sa[117], sa[121], sa[125], sa[129], sa[133], sa[137], sa[141]]], [[sa[3], sa[7], sa[11], sa[15], sa[19], sa[23], sa[27], sa[31], sa[35]], [sa[39], sa[43], sa[47], sa[51], sa[55], sa[59], sa[63], sa[67], sa[71]], [sa[75], sa[79], sa[83], sa[87], sa[91], sa[95], sa[99], sa[103], sa[107]], [sa[111], sa[115], sa[119], sa[123], sa[127], sa[131], sa[135], sa[139], sa[143]]]]])
# test for large scale sparse array
for SparseArrayType in [ImmutableSparseNDimArray, MutableSparseNDimArray]:
A = SparseArrayType({1:1, 10000:2}, (10000, 20000, 10000))
assert permutedims(A, (0, 1, 2)) == A
assert permutedims(A, (1, 0, 2)) == SparseArrayType({1: 1, 100000000: 2}, (20000, 10000, 10000))
B = SparseArrayType({1:1, 20000:2}, (10000, 20000))
assert B.transpose() == SparseArrayType({10000: 1, 1: 2}, (20000, 10000))
def test_flatten():
from sympy import Matrix
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray, Matrix]:
A = ArrayType(range(24)).reshape(4, 6)
assert [i for i in Flatten(A)] == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]
for i, v in enumerate(Flatten(A)):
i == v
|
8eab0d4a3f30252cbea4af56f832bb894dabde292c33c9cf617b4d62ce802961 | from sympy.testing.pytest import raises
from sympy import (
Array, ImmutableDenseNDimArray, ImmutableSparseNDimArray,
MutableDenseNDimArray, MutableSparseNDimArray, sin, cos,
simplify
)
from sympy.abc import x, y
array_types = [
ImmutableDenseNDimArray,
ImmutableSparseNDimArray,
MutableDenseNDimArray,
MutableSparseNDimArray
]
def test_array_negative_indices():
for ArrayType in array_types:
test_array = ArrayType([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
assert test_array[:, -1] == Array([5, 10])
assert test_array[:, -2] == Array([4, 9])
assert test_array[:, -3] == Array([3, 8])
assert test_array[:, -4] == Array([2, 7])
assert test_array[:, -5] == Array([1, 6])
assert test_array[:, 0] == Array([1, 6])
assert test_array[:, 1] == Array([2, 7])
assert test_array[:, 2] == Array([3, 8])
assert test_array[:, 3] == Array([4, 9])
assert test_array[:, 4] == Array([5, 10])
raises(ValueError, lambda: test_array[:, -6])
raises(ValueError, lambda: test_array[-3, :])
assert test_array[-1, -1] == 10
def test_issue_18361():
A = Array([sin(2 * x) - 2 * sin(x) * cos(x)])
B = Array([sin(x)**2 + cos(x)**2, 0])
C = Array([(x + x**2)/(x*sin(y)**2 + x*cos(y)**2), 2*sin(x)*cos(x)])
assert simplify(A) == Array([0])
assert simplify(B) == Array([1, 0])
assert simplify(C) == Array([x + 1, sin(2*x)])
|
f6a7498995fd1e642a0c0121b0b0f30f5a4f3149b3ce1536bb7e601b7605c26f | from copy import copy
from sympy.tensor.array.dense_ndim_array import ImmutableDenseNDimArray
from sympy import Symbol, Rational, SparseMatrix, Dict, diff, symbols, Indexed, IndexedBase, S
from sympy.matrices import Matrix
from sympy.tensor.array.sparse_ndim_array import ImmutableSparseNDimArray
from sympy.testing.pytest import raises
def test_ndim_array_initiation():
arr_with_no_elements = ImmutableDenseNDimArray([], shape=(0,))
assert len(arr_with_no_elements) == 0
assert arr_with_no_elements.rank() == 1
raises(ValueError, lambda: ImmutableDenseNDimArray([0], shape=(0,)))
raises(ValueError, lambda: ImmutableDenseNDimArray([1, 2, 3], shape=(0,)))
raises(ValueError, lambda: ImmutableDenseNDimArray([], shape=()))
raises(ValueError, lambda: ImmutableSparseNDimArray([0], shape=(0,)))
raises(ValueError, lambda: ImmutableSparseNDimArray([1, 2, 3], shape=(0,)))
raises(ValueError, lambda: ImmutableSparseNDimArray([], shape=()))
arr_with_one_element = ImmutableDenseNDimArray([23])
assert len(arr_with_one_element) == 1
assert arr_with_one_element[0] == 23
assert arr_with_one_element[:] == ImmutableDenseNDimArray([23])
assert arr_with_one_element.rank() == 1
arr_with_symbol_element = ImmutableDenseNDimArray([Symbol('x')])
assert len(arr_with_symbol_element) == 1
assert arr_with_symbol_element[0] == Symbol('x')
assert arr_with_symbol_element[:] == ImmutableDenseNDimArray([Symbol('x')])
assert arr_with_symbol_element.rank() == 1
number5 = 5
vector = ImmutableDenseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector.rank() == 1
vector = ImmutableSparseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector._sparse_array == Dict()
assert vector.rank() == 1
n_dim_array = ImmutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
assert len(n_dim_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == (3, 3, 3, 3)
assert n_dim_array.rank() == 4
array_shape = (3, 3, 3, 3)
sparse_array = ImmutableSparseNDimArray.zeros(*array_shape)
assert len(sparse_array._sparse_array) == 0
assert len(sparse_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == array_shape
assert n_dim_array.rank() == 4
one_dim_array = ImmutableDenseNDimArray([2, 3, 1])
assert len(one_dim_array) == 3
assert one_dim_array.shape == (3,)
assert one_dim_array.rank() == 1
assert one_dim_array.tolist() == [2, 3, 1]
shape = (3, 3)
array_with_many_args = ImmutableSparseNDimArray.zeros(*shape)
assert len(array_with_many_args) == 3 * 3
assert array_with_many_args.shape == shape
assert array_with_many_args[0, 0] == 0
assert array_with_many_args.rank() == 2
shape = (int(3), int(3))
array_with_long_shape = ImmutableSparseNDimArray.zeros(*shape)
assert len(array_with_long_shape) == 3 * 3
assert array_with_long_shape.shape == shape
assert array_with_long_shape[int(0), int(0)] == 0
assert array_with_long_shape.rank() == 2
vector_with_long_shape = ImmutableDenseNDimArray(range(5), int(5))
assert len(vector_with_long_shape) == 5
assert vector_with_long_shape.shape == (int(5),)
assert vector_with_long_shape.rank() == 1
raises(ValueError, lambda: vector_with_long_shape[int(5)])
from sympy.abc import x
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
rank_zero_array = ArrayType(x)
assert len(rank_zero_array) == 1
assert rank_zero_array.shape == ()
assert rank_zero_array.rank() == 0
assert rank_zero_array[()] == x
raises(ValueError, lambda: rank_zero_array[0])
def test_reshape():
array = ImmutableDenseNDimArray(range(50), 50)
assert array.shape == (50,)
assert array.rank() == 1
array = array.reshape(5, 5, 2)
assert array.shape == (5, 5, 2)
assert array.rank() == 3
assert len(array) == 50
def test_getitem():
for ArrayType in [ImmutableDenseNDimArray, ImmutableSparseNDimArray]:
array = ArrayType(range(24)).reshape(2, 3, 4)
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
assert array[0, 0] == ArrayType([0, 1, 2, 3])
value = 0
for i in range(2):
for j in range(3):
for k in range(4):
assert array[i, j, k] == value
value += 1
raises(ValueError, lambda: array[3, 4, 5])
raises(ValueError, lambda: array[3, 4, 5, 6])
raises(ValueError, lambda: array[3, 4, 5, 3:4])
def test_iterator():
array = ImmutableDenseNDimArray(range(4), (2, 2))
array[0] == ImmutableDenseNDimArray([0, 1])
array[1] == ImmutableDenseNDimArray([2, 3])
array = array.reshape(4)
j = 0
for i in array:
assert i == j
j += 1
def test_sparse():
sparse_array = ImmutableSparseNDimArray([0, 0, 0, 1], (2, 2))
assert len(sparse_array) == 2 * 2
# dictionary where all data is, only non-zero entries are actually stored:
assert len(sparse_array._sparse_array) == 1
assert sparse_array.tolist() == [[0, 0], [0, 1]]
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
assert i == ImmutableSparseNDimArray(j)
def sparse_assignment():
sparse_array[0, 0] = 123
assert len(sparse_array._sparse_array) == 1
raises(TypeError, sparse_assignment)
assert len(sparse_array._sparse_array) == 1
assert sparse_array[0, 0] == 0
assert sparse_array/0 == ImmutableSparseNDimArray([[S.NaN, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
# test for large scale sparse array
# equality test
assert ImmutableSparseNDimArray.zeros(100000, 200000) == ImmutableSparseNDimArray.zeros(100000, 200000)
# __mul__ and __rmul__
a = ImmutableSparseNDimArray({200001: 1}, (100000, 200000))
assert a * 3 == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
assert 3 * a == ImmutableSparseNDimArray({200001: 3}, (100000, 200000))
assert a * 0 == ImmutableSparseNDimArray({}, (100000, 200000))
assert 0 * a == ImmutableSparseNDimArray({}, (100000, 200000))
# __div__
assert a/3 == ImmutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
# __neg__
assert -a == ImmutableSparseNDimArray({200001: -1}, (100000, 200000))
def test_calculation():
a = ImmutableDenseNDimArray([1]*9, (3, 3))
b = ImmutableDenseNDimArray([9]*9, (3, 3))
c = a + b
for i in c:
assert i == ImmutableDenseNDimArray([10, 10, 10])
assert c == ImmutableDenseNDimArray([10]*9, (3, 3))
assert c == ImmutableSparseNDimArray([10]*9, (3, 3))
c = b - a
for i in c:
assert i == ImmutableDenseNDimArray([8, 8, 8])
assert c == ImmutableDenseNDimArray([8]*9, (3, 3))
assert c == ImmutableSparseNDimArray([8]*9, (3, 3))
def test_ndim_array_converting():
dense_array = ImmutableDenseNDimArray([1, 2, 3, 4], (2, 2))
alist = dense_array.tolist()
alist == [[1, 2], [3, 4]]
matrix = dense_array.tomatrix()
assert (isinstance(matrix, Matrix))
for i in range(len(dense_array)):
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == dense_array.shape
assert ImmutableDenseNDimArray(matrix) == dense_array
assert ImmutableDenseNDimArray(matrix.as_immutable()) == dense_array
assert ImmutableDenseNDimArray(matrix.as_mutable()) == dense_array
sparse_array = ImmutableSparseNDimArray([1, 2, 3, 4], (2, 2))
alist = sparse_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = sparse_array.tomatrix()
assert(isinstance(matrix, SparseMatrix))
for i in range(len(sparse_array)):
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == sparse_array.shape
assert ImmutableSparseNDimArray(matrix) == sparse_array
assert ImmutableSparseNDimArray(matrix.as_immutable()) == sparse_array
assert ImmutableSparseNDimArray(matrix.as_mutable()) == sparse_array
def test_converting_functions():
arr_list = [1, 2, 3, 4]
arr_matrix = Matrix(((1, 2), (3, 4)))
# list
arr_ndim_array = ImmutableDenseNDimArray(arr_list, (2, 2))
assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
# Matrix
arr_ndim_array = ImmutableDenseNDimArray(arr_matrix)
assert (isinstance(arr_ndim_array, ImmutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
assert arr_matrix.shape == arr_ndim_array.shape
def test_equality():
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
third_list = [4, 3, 2, 1]
assert first_list == second_list
assert first_list != third_list
first_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
second_ndim_array = ImmutableDenseNDimArray(second_list, (2, 2))
fourth_ndim_array = ImmutableDenseNDimArray(first_list, (2, 2))
assert first_ndim_array == second_ndim_array
def assignment_attempt(a):
a[0, 0] = 0
raises(TypeError, lambda: assignment_attempt(second_ndim_array))
assert first_ndim_array == second_ndim_array
assert first_ndim_array == fourth_ndim_array
def test_arithmetic():
a = ImmutableDenseNDimArray([3 for i in range(9)], (3, 3))
b = ImmutableDenseNDimArray([7 for i in range(9)], (3, 3))
c1 = a + b
c2 = b + a
assert c1 == c2
d1 = a - b
d2 = b - a
assert d1 == d2 * (-1)
e1 = a * 5
e2 = 5 * a
e3 = copy(a)
e3 *= 5
assert e1 == e2 == e3
f1 = a / 5
f2 = copy(a)
f2 /= 5
assert f1 == f2
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
== type(e1) == type(e2) == type(e3) == type(f1)
z0 = -a
assert z0 == ImmutableDenseNDimArray([-3 for i in range(9)], (3, 3))
def test_higher_dimenions():
m3 = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert m3.tolist() == [[[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]],
[[22, 23, 24, 25],
[26, 27, 28, 29],
[30, 31, 32, 33]]]
assert m3._get_tuple_index(0) == (0, 0, 0)
assert m3._get_tuple_index(1) == (0, 0, 1)
assert m3._get_tuple_index(4) == (0, 1, 0)
assert m3._get_tuple_index(12) == (1, 0, 0)
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
m3_rebuilt = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
assert m3 == m3_rebuilt
m3_other = ImmutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
assert m3 == m3_other
def test_rebuild_immutable_arrays():
sparr = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
densarr = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert sparr == sparr.func(*sparr.args)
assert densarr == densarr.func(*densarr.args)
def test_slices():
md = ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:] == ImmutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert md[:, :, :] == md
sd = ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd == ImmutableSparseNDimArray(md)
assert sd[:] == ImmutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert sd[:, :, :] == sd
def test_diff_and_applyfunc():
from sympy.abc import x, y, z
md = ImmutableDenseNDimArray([[x, y], [x*z, x*y*z]])
assert md.diff(x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
assert diff(md, x) == ImmutableDenseNDimArray([[1, 0], [z, y*z]])
sd = ImmutableSparseNDimArray(md)
assert sd == ImmutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
assert sd.diff(x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
assert diff(sd, x) == ImmutableSparseNDimArray([[1, 0], [z, y*z]])
mdn = md.applyfunc(lambda x: x*3)
assert mdn == ImmutableDenseNDimArray([[3*x, 3*y], [3*x*z, 3*x*y*z]])
assert md != mdn
sdn = sd.applyfunc(lambda x: x/2)
assert sdn == ImmutableSparseNDimArray([[x/2, y/2], [x*z/2, x*y*z/2]])
assert sd != sdn
sdp = sd.applyfunc(lambda x: x+1)
assert sdp == ImmutableSparseNDimArray([[x + 1, y + 1], [x*z + 1, x*y*z + 1]])
assert sd != sdp
def test_op_priority():
from sympy.abc import x
md = ImmutableDenseNDimArray([1, 2, 3])
e1 = (1+x)*md
e2 = md*(1+x)
assert e1 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
assert e1 == e2
sd = ImmutableSparseNDimArray([1, 2, 3])
e3 = (1+x)*sd
e4 = sd*(1+x)
assert e3 == ImmutableDenseNDimArray([1+x, 2+2*x, 3+3*x])
assert e3 == e4
def test_symbolic_indexing():
x, y, z, w = symbols("x y z w")
M = ImmutableDenseNDimArray([[x, y], [z, w]])
i, j = symbols("i, j")
Mij = M[i, j]
assert isinstance(Mij, Indexed)
Ms = ImmutableSparseNDimArray([[2, 3*x], [4, 5]])
msij = Ms[i, j]
assert isinstance(msij, Indexed)
for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
A = IndexedBase("A", (0, 2))
assert A[0, 0].subs(A, M) == x
assert A[i, j].subs(A, M) == M[i, j]
assert M[i, j].subs(M, A) == A[i, j]
assert isinstance(M[3 * i - 2, j], Indexed)
assert M[3 * i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
assert isinstance(M[i, 0], Indexed)
assert M[i, 0].subs(i, 0) == M[0, 0]
assert M[0, i].subs(i, 1) == M[0, 1]
assert M[i, j].diff(x) == ImmutableDenseNDimArray([[1, 0], [0, 0]])[i, j]
assert Ms[i, j].diff(x) == ImmutableSparseNDimArray([[0, 3], [0, 0]])[i, j]
Mo = ImmutableDenseNDimArray([1, 2, 3])
assert Mo[i].subs(i, 1) == 2
Mos = ImmutableSparseNDimArray([1, 2, 3])
assert Mos[i].subs(i, 1) == 2
raises(ValueError, lambda: M[i, 2])
raises(ValueError, lambda: M[i, -1])
raises(ValueError, lambda: M[2, i])
raises(ValueError, lambda: M[-1, i])
raises(ValueError, lambda: Ms[i, 2])
raises(ValueError, lambda: Ms[i, -1])
raises(ValueError, lambda: Ms[2, i])
raises(ValueError, lambda: Ms[-1, i])
def test_issue_12665():
# Testing Python 3 hash of immutable arrays:
arr = ImmutableDenseNDimArray([1, 2, 3])
# This should NOT raise an exception:
hash(arr)
def test_zeros_without_shape():
arr = ImmutableDenseNDimArray.zeros()
assert arr == ImmutableDenseNDimArray(0)
|
afc7ecb4c4ca34d512a7b4cc3d20f1ef556beb8a2d8cbb6fb0d0fffd3f0c8dc0 | from copy import copy
from sympy.tensor.array.dense_ndim_array import MutableDenseNDimArray
from sympy import Symbol, Rational, SparseMatrix, diff, sympify, S
from sympy.matrices import Matrix
from sympy.tensor.array.sparse_ndim_array import MutableSparseNDimArray
from sympy.testing.pytest import raises
def test_ndim_array_initiation():
arr_with_one_element = MutableDenseNDimArray([23])
assert len(arr_with_one_element) == 1
assert arr_with_one_element[0] == 23
assert arr_with_one_element.rank() == 1
raises(ValueError, lambda: arr_with_one_element[1])
arr_with_symbol_element = MutableDenseNDimArray([Symbol('x')])
assert len(arr_with_symbol_element) == 1
assert arr_with_symbol_element[0] == Symbol('x')
assert arr_with_symbol_element.rank() == 1
number5 = 5
vector = MutableDenseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector.rank() == 1
raises(ValueError, lambda: arr_with_one_element[5])
vector = MutableSparseNDimArray.zeros(number5)
assert len(vector) == number5
assert vector.shape == (number5,)
assert vector._sparse_array == {}
assert vector.rank() == 1
n_dim_array = MutableDenseNDimArray(range(3**4), (3, 3, 3, 3,))
assert len(n_dim_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == (3, 3, 3, 3)
assert n_dim_array.rank() == 4
raises(ValueError, lambda: n_dim_array[0, 0, 0, 3])
raises(ValueError, lambda: n_dim_array[3, 0, 0, 0])
raises(ValueError, lambda: n_dim_array[3**4])
array_shape = (3, 3, 3, 3)
sparse_array = MutableSparseNDimArray.zeros(*array_shape)
assert len(sparse_array._sparse_array) == 0
assert len(sparse_array) == 3 * 3 * 3 * 3
assert n_dim_array.shape == array_shape
assert n_dim_array.rank() == 4
one_dim_array = MutableDenseNDimArray([2, 3, 1])
assert len(one_dim_array) == 3
assert one_dim_array.shape == (3,)
assert one_dim_array.rank() == 1
assert one_dim_array.tolist() == [2, 3, 1]
shape = (3, 3)
array_with_many_args = MutableSparseNDimArray.zeros(*shape)
assert len(array_with_many_args) == 3 * 3
assert array_with_many_args.shape == shape
assert array_with_many_args[0, 0] == 0
assert array_with_many_args.rank() == 2
shape = (int(3), int(3))
array_with_long_shape = MutableSparseNDimArray.zeros(*shape)
assert len(array_with_long_shape) == 3 * 3
assert array_with_long_shape.shape == shape
assert array_with_long_shape[int(0), int(0)] == 0
assert array_with_long_shape.rank() == 2
vector_with_long_shape = MutableDenseNDimArray(range(5), int(5))
assert len(vector_with_long_shape) == 5
assert vector_with_long_shape.shape == (int(5),)
assert vector_with_long_shape.rank() == 1
raises(ValueError, lambda: vector_with_long_shape[int(5)])
from sympy.abc import x
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
rank_zero_array = ArrayType(x)
assert len(rank_zero_array) == 1
assert rank_zero_array.shape == ()
assert rank_zero_array.rank() == 0
assert rank_zero_array[()] == x
raises(ValueError, lambda: rank_zero_array[0])
def test_sympify():
from sympy.abc import x, y, z, t
arr = MutableDenseNDimArray([[x, y], [1, z*t]])
arr_other = sympify(arr)
assert arr_other.shape == (2, 2)
assert arr_other == arr
def test_reshape():
array = MutableDenseNDimArray(range(50), 50)
assert array.shape == (50,)
assert array.rank() == 1
array = array.reshape(5, 5, 2)
assert array.shape == (5, 5, 2)
assert array.rank() == 3
assert len(array) == 50
def test_iterator():
array = MutableDenseNDimArray(range(4), (2, 2))
array[0] == MutableDenseNDimArray([0, 1])
array[1] == MutableDenseNDimArray([2, 3])
array = array.reshape(4)
j = 0
for i in array:
assert i == j
j += 1
def test_getitem():
for ArrayType in [MutableDenseNDimArray, MutableSparseNDimArray]:
array = ArrayType(range(24)).reshape(2, 3, 4)
assert array.tolist() == [[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]]]
assert array[0] == ArrayType([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])
assert array[0, 0] == ArrayType([0, 1, 2, 3])
value = 0
for i in range(2):
for j in range(3):
for k in range(4):
assert array[i, j, k] == value
value += 1
raises(ValueError, lambda: array[3, 4, 5])
raises(ValueError, lambda: array[3, 4, 5, 6])
raises(ValueError, lambda: array[3, 4, 5, 3:4])
def test_sparse():
sparse_array = MutableSparseNDimArray([0, 0, 0, 1], (2, 2))
assert len(sparse_array) == 2 * 2
# dictionary where all data is, only non-zero entries are actually stored:
assert len(sparse_array._sparse_array) == 1
assert sparse_array.tolist() == [[0, 0], [0, 1]]
for i, j in zip(sparse_array, [[0, 0], [0, 1]]):
assert i == MutableSparseNDimArray(j)
sparse_array[0, 0] = 123
assert len(sparse_array._sparse_array) == 2
assert sparse_array[0, 0] == 123
assert sparse_array/0 == MutableSparseNDimArray([[S.ComplexInfinity, S.NaN], [S.NaN, S.ComplexInfinity]], (2, 2))
# when element in sparse array become zero it will disappear from
# dictionary
sparse_array[0, 0] = 0
assert len(sparse_array._sparse_array) == 1
sparse_array[1, 1] = 0
assert len(sparse_array._sparse_array) == 0
assert sparse_array[0, 0] == 0
# test for large scale sparse array
# equality test
a = MutableSparseNDimArray.zeros(100000, 200000)
b = MutableSparseNDimArray.zeros(100000, 200000)
assert a == b
a[1, 1] = 1
b[1, 1] = 2
assert a != b
# __mul__ and __rmul__
assert a * 3 == MutableSparseNDimArray({200001: 3}, (100000, 200000))
assert 3 * a == MutableSparseNDimArray({200001: 3}, (100000, 200000))
assert a * 0 == MutableSparseNDimArray({}, (100000, 200000))
assert 0 * a == MutableSparseNDimArray({}, (100000, 200000))
# __div__
assert a/3 == MutableSparseNDimArray({200001: Rational(1, 3)}, (100000, 200000))
# __neg__
assert -a == MutableSparseNDimArray({200001: -1}, (100000, 200000))
def test_calculation():
a = MutableDenseNDimArray([1]*9, (3, 3))
b = MutableDenseNDimArray([9]*9, (3, 3))
c = a + b
for i in c:
assert i == MutableDenseNDimArray([10, 10, 10])
assert c == MutableDenseNDimArray([10]*9, (3, 3))
assert c == MutableSparseNDimArray([10]*9, (3, 3))
c = b - a
for i in c:
assert i == MutableSparseNDimArray([8, 8, 8])
assert c == MutableDenseNDimArray([8]*9, (3, 3))
assert c == MutableSparseNDimArray([8]*9, (3, 3))
def test_ndim_array_converting():
dense_array = MutableDenseNDimArray([1, 2, 3, 4], (2, 2))
alist = dense_array.tolist()
alist == [[1, 2], [3, 4]]
matrix = dense_array.tomatrix()
assert (isinstance(matrix, Matrix))
for i in range(len(dense_array)):
assert dense_array[dense_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == dense_array.shape
assert MutableDenseNDimArray(matrix) == dense_array
assert MutableDenseNDimArray(matrix.as_immutable()) == dense_array
assert MutableDenseNDimArray(matrix.as_mutable()) == dense_array
sparse_array = MutableSparseNDimArray([1, 2, 3, 4], (2, 2))
alist = sparse_array.tolist()
assert alist == [[1, 2], [3, 4]]
matrix = sparse_array.tomatrix()
assert(isinstance(matrix, SparseMatrix))
for i in range(len(sparse_array)):
assert sparse_array[sparse_array._get_tuple_index(i)] == matrix[i]
assert matrix.shape == sparse_array.shape
assert MutableSparseNDimArray(matrix) == sparse_array
assert MutableSparseNDimArray(matrix.as_immutable()) == sparse_array
assert MutableSparseNDimArray(matrix.as_mutable()) == sparse_array
def test_converting_functions():
arr_list = [1, 2, 3, 4]
arr_matrix = Matrix(((1, 2), (3, 4)))
# list
arr_ndim_array = MutableDenseNDimArray(arr_list, (2, 2))
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
# Matrix
arr_ndim_array = MutableDenseNDimArray(arr_matrix)
assert (isinstance(arr_ndim_array, MutableDenseNDimArray))
assert arr_matrix.tolist() == arr_ndim_array.tolist()
assert arr_matrix.shape == arr_ndim_array.shape
def test_equality():
first_list = [1, 2, 3, 4]
second_list = [1, 2, 3, 4]
third_list = [4, 3, 2, 1]
assert first_list == second_list
assert first_list != third_list
first_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
second_ndim_array = MutableDenseNDimArray(second_list, (2, 2))
third_ndim_array = MutableDenseNDimArray(third_list, (2, 2))
fourth_ndim_array = MutableDenseNDimArray(first_list, (2, 2))
assert first_ndim_array == second_ndim_array
second_ndim_array[0, 0] = 0
assert first_ndim_array != second_ndim_array
assert first_ndim_array != third_ndim_array
assert first_ndim_array == fourth_ndim_array
def test_arithmetic():
a = MutableDenseNDimArray([3 for i in range(9)], (3, 3))
b = MutableDenseNDimArray([7 for i in range(9)], (3, 3))
c1 = a + b
c2 = b + a
assert c1 == c2
d1 = a - b
d2 = b - a
assert d1 == d2 * (-1)
e1 = a * 5
e2 = 5 * a
e3 = copy(a)
e3 *= 5
assert e1 == e2 == e3
f1 = a / 5
f2 = copy(a)
f2 /= 5
assert f1 == f2
assert f1[0, 0] == f1[0, 1] == f1[0, 2] == f1[1, 0] == f1[1, 1] == \
f1[1, 2] == f1[2, 0] == f1[2, 1] == f1[2, 2] == Rational(3, 5)
assert type(a) == type(b) == type(c1) == type(c2) == type(d1) == type(d2) \
== type(e1) == type(e2) == type(e3) == type(f1)
z0 = -a
assert z0 == MutableDenseNDimArray([-3 for i in range(9)], (3, 3))
def test_higher_dimenions():
m3 = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert m3.tolist() == [[[10, 11, 12, 13],
[14, 15, 16, 17],
[18, 19, 20, 21]],
[[22, 23, 24, 25],
[26, 27, 28, 29],
[30, 31, 32, 33]]]
assert m3._get_tuple_index(0) == (0, 0, 0)
assert m3._get_tuple_index(1) == (0, 0, 1)
assert m3._get_tuple_index(4) == (0, 1, 0)
assert m3._get_tuple_index(12) == (1, 0, 0)
assert str(m3) == '[[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]]'
m3_rebuilt = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]])
assert m3 == m3_rebuilt
m3_other = MutableDenseNDimArray([[[10, 11, 12, 13], [14, 15, 16, 17], [18, 19, 20, 21]], [[22, 23, 24, 25], [26, 27, 28, 29], [30, 31, 32, 33]]], (2, 3, 4))
assert m3 == m3_other
def test_slices():
md = MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:] == MutableDenseNDimArray(range(10, 34), (2, 3, 4))
assert md[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert md[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert md[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert md[:, :, :] == md
sd = MutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd == MutableSparseNDimArray(md)
assert sd[:] == MutableSparseNDimArray(range(10, 34), (2, 3, 4))
assert sd[:, :, 0].tomatrix() == Matrix([[10, 14, 18], [22, 26, 30]])
assert sd[0, 1:2, :].tomatrix() == Matrix([[14, 15, 16, 17]])
assert sd[0, 1:3, :].tomatrix() == Matrix([[14, 15, 16, 17], [18, 19, 20, 21]])
assert sd[:, :, :] == sd
def test_slices_assign():
a = MutableDenseNDimArray(range(12), shape=(4, 3))
b = MutableSparseNDimArray(range(12), shape=(4, 3))
for i in [a, b]:
assert i.tolist() == [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[0, :] = [2, 2, 2]
assert i.tolist() == [[2, 2, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[0, 1:] = [8, 8]
assert i.tolist() == [[2, 8, 8], [3, 4, 5], [6, 7, 8], [9, 10, 11]]
i[1:3, 1] = [20, 44]
assert i.tolist() == [[2, 8, 8], [3, 20, 5], [6, 44, 8], [9, 10, 11]]
def test_diff():
from sympy.abc import x, y, z
md = MutableDenseNDimArray([[x, y], [x*z, x*y*z]])
assert md.diff(x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
assert diff(md, x) == MutableDenseNDimArray([[1, 0], [z, y*z]])
sd = MutableSparseNDimArray(md)
assert sd == MutableSparseNDimArray([x, y, x*z, x*y*z], (2, 2))
assert sd.diff(x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
assert diff(sd, x) == MutableSparseNDimArray([[1, 0], [z, y*z]])
|
0f36490af2ee8b7a09dd5f0f85cc43f0203d910724cc7ee7406d3df17337de6a | from sympy.tensor.array.array_comprehension import ArrayComprehension, ArrayComprehensionMap
from sympy.tensor.array import ImmutableDenseNDimArray
from sympy.abc import i, j, k, l
from sympy.testing.pytest import raises
from sympy.matrices import Matrix
def test_array_comprehension():
a = ArrayComprehension(i*j, (i, 1, 3), (j, 2, 4))
b = ArrayComprehension(i, (i, 1, j+1))
c = ArrayComprehension(i+j+k+l, (i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5))
d = ArrayComprehension(k, (i, 1, 5))
e = ArrayComprehension(i, (j, k+1, k+5))
assert a.doit().tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]]
assert a.shape == (3, 3)
assert a.is_shape_numeric == True
assert a.tolist() == [[2, 3, 4], [4, 6, 8], [6, 9, 12]]
assert a.tomatrix() == Matrix([
[2, 3, 4],
[4, 6, 8],
[6, 9, 12]])
assert len(a) == 9
assert isinstance(b.doit(), ArrayComprehension)
assert isinstance(a.doit(), ImmutableDenseNDimArray)
assert b.subs(j, 3) == ArrayComprehension(i, (i, 1, 4))
assert b.free_symbols == {j}
assert b.shape == (j + 1,)
assert b.rank() == 1
assert b.is_shape_numeric == False
assert c.free_symbols == set()
assert c.function == i + j + k + l
assert c.limits == ((i, 1, 2), (j, 1, 3), (k, 1, 4), (l, 1, 5))
assert c.doit().tolist() == [[[[4, 5, 6, 7, 8], [5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11]],
[[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]],
[[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]]],
[[[5, 6, 7, 8, 9], [6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12]],
[[6, 7, 8, 9, 10], [7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13]],
[[7, 8, 9, 10, 11], [8, 9, 10, 11, 12], [9, 10, 11, 12, 13], [10, 11, 12, 13, 14]]]]
assert c.free_symbols == set()
assert c.variables == [i, j, k, l]
assert c.bound_symbols == [i, j, k, l]
assert d.doit().tolist() == [k, k, k, k, k]
assert len(e) == 5
raises(TypeError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, [1, 3, 2])))
raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, 1)))
raises(ValueError, lambda: ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+1)))
raises(ValueError, lambda: len(ArrayComprehension(i*j, (i, 1, 3), (j, 2, j+4))))
raises(TypeError, lambda: ArrayComprehension(i*j, (i, 0, i + 1.5), (j, 0, 2)))
raises(ValueError, lambda: b.tolist())
raises(ValueError, lambda: b.tomatrix())
raises(ValueError, lambda: c.tomatrix())
def test_arraycomprehensionmap():
a = ArrayComprehensionMap(lambda i: i+1, (i, 1, 5))
assert a.doit().tolist() == [2, 3, 4, 5, 6]
assert a.shape == (5,)
assert a.is_shape_numeric
assert a.tolist() == [2, 3, 4, 5, 6]
assert len(a) == 5
assert isinstance(a.doit(), ImmutableDenseNDimArray)
expr = ArrayComprehensionMap(lambda i: i+1, (i, 1, k))
assert expr.doit() == expr
assert expr.subs(k, 4) == ArrayComprehensionMap(lambda i: i+1, (i, 1, 4))
assert expr.subs(k, 4).doit() == ImmutableDenseNDimArray([2, 3, 4, 5])
b = ArrayComprehensionMap(lambda i: i+1, (i, 1, 2), (i, 1, 3), (i, 1, 4), (i, 1, 5))
assert b.doit().tolist() == [[[[2, 3, 4, 5, 6], [3, 5, 7, 9, 11], [4, 7, 10, 13, 16], [5, 9, 13, 17, 21]],
[[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]],
[[4, 7, 10, 13, 16], [7, 13, 19, 25, 31], [10, 19, 28, 37, 46], [13, 25, 37, 49, 61]]],
[[[3, 5, 7, 9, 11], [5, 9, 13, 17, 21], [7, 13, 19, 25, 31], [9, 17, 25, 33, 41]],
[[5, 9, 13, 17, 21], [9, 17, 25, 33, 41], [13, 25, 37, 49, 61], [17, 33, 49, 65, 81]],
[[7, 13, 19, 25, 31], [13, 25, 37, 49, 61], [19, 37, 55, 73, 91], [25, 49, 73, 97, 121]]]]
# tests about lambda expression
assert ArrayComprehensionMap(lambda: 3, (i, 1, 5)).doit().tolist() == [3, 3, 3, 3, 3]
assert ArrayComprehensionMap(lambda i: i+1, (i, 1, 5)).doit().tolist() == [2, 3, 4, 5, 6]
raises(ValueError, lambda: ArrayComprehensionMap(lambda i, j: i+j, (i, 1, 5)).doit())
raises(ValueError, lambda: ArrayComprehensionMap(i*j, (i, 1, 3), (j, 2, 4)))
|
e655255a5988334dc3e5d33991494b803b3fedaa1eee34e57aa3e7f9eda65dcd | from typing import Dict, Any
from sympy.multipledispatch import dispatch
from sympy.multipledispatch.conflict import AmbiguityWarning
from sympy.testing.pytest import raises, XFAIL, warns
from functools import partial
test_namespace = dict() # type: Dict[str, Any]
orig_dispatch = dispatch
dispatch = partial(dispatch, namespace=test_namespace)
@XFAIL
def test_singledispatch():
@dispatch(int)
def f(x): # noqa:F811
return x + 1
@dispatch(int)
def g(x): # noqa:F811
return x + 2
@dispatch(float) # noqa:F811
def f(x): # noqa:F811
return x - 1
assert f(1) == 2
assert g(1) == 3
assert f(1.0) == 0
assert raises(NotImplementedError, lambda: f('hello'))
def test_multipledispatch():
@dispatch(int, int)
def f(x, y): # noqa:F811
return x + y
@dispatch(float, float) # noqa:F811
def f(x, y): # noqa:F811
return x - y
assert f(1, 2) == 3
assert f(1.0, 2.0) == -1.0
class A(object): pass
class B(object): pass
class C(A): pass
class D(C): pass
class E(C): pass
def test_inheritance():
@dispatch(A)
def f(x): # noqa:F811
return 'a'
@dispatch(B) # noqa:F811
def f(x): # noqa:F811
return 'b'
assert f(A()) == 'a'
assert f(B()) == 'b'
assert f(C()) == 'a'
@XFAIL
def test_inheritance_and_multiple_dispatch():
@dispatch(A, A)
def f(x, y): # noqa:F811
return type(x), type(y)
@dispatch(A, B) # noqa:F811
def f(x, y): # noqa:F811
return 0
assert f(A(), A()) == (A, A)
assert f(A(), C()) == (A, C)
assert f(A(), B()) == 0
assert f(C(), B()) == 0
assert raises(NotImplementedError, lambda: f(B(), B()))
def test_competing_solutions():
@dispatch(A)
def h(x): # noqa:F811
return 1
@dispatch(C) # noqa:F811
def h(x): # noqa:F811
return 2
assert h(D()) == 2
def test_competing_multiple():
@dispatch(A, B)
def h(x, y): # noqa:F811
return 1
@dispatch(C, B) # noqa:F811
def h(x, y): # noqa:F811
return 2
assert h(D(), B()) == 2
def test_competing_ambiguous():
test_namespace = dict()
dispatch = partial(orig_dispatch, namespace=test_namespace)
@dispatch(A, C)
def f(x, y): # noqa:F811
return 2
with warns(AmbiguityWarning):
@dispatch(C, A) # noqa:F811
def f(x, y): # noqa:F811
return 2
assert f(A(), C()) == f(C(), A()) == 2
# assert raises(Warning, lambda : f(C(), C()))
def test_caching_correct_behavior():
@dispatch(A)
def f(x): # noqa:F811
return 1
assert f(C()) == 1
@dispatch(C)
def f(x): # noqa:F811
return 2
assert f(C()) == 2
def test_union_types():
@dispatch((A, C))
def f(x): # noqa:F811
return 1
assert f(A()) == 1
assert f(C()) == 1
def test_namespaces():
ns1 = dict()
ns2 = dict()
def foo(x):
return 1
foo1 = orig_dispatch(int, namespace=ns1)(foo)
def foo(x):
return 2
foo2 = orig_dispatch(int, namespace=ns2)(foo)
assert foo1(0) == 1
assert foo2(0) == 2
"""
Fails
def test_dispatch_on_dispatch():
@dispatch(A)
@dispatch(C)
def q(x): # noqa:F811
return 1
assert q(A()) == 1
assert q(C()) == 1
"""
def test_methods():
class Foo(object):
@dispatch(float)
def f(self, x): # noqa:F811
return x - 1
@dispatch(int) # noqa:F811
def f(self, x): # noqa:F811
return x + 1
@dispatch(int)
def g(self, x): # noqa:F811
return x + 3
foo = Foo()
assert foo.f(1) == 2
assert foo.f(1.0) == 0.0
assert foo.g(1) == 4
def test_methods_multiple_dispatch():
class Foo(object):
@dispatch(A, A)
def f(x, y): # noqa:F811
return 1
@dispatch(A, C) # noqa:F811
def f(x, y): # noqa:F811
return 2
foo = Foo()
assert foo.f(A(), A()) == 1
assert foo.f(A(), C()) == 2
assert foo.f(C(), C()) == 2
|
43c46af1a67a5983eee0e9ccbfe5ee9aea4e07ab9e8181fe79de37036cdd3b7f | from sympy.multipledispatch.dispatcher import (Dispatcher, MDNotImplementedError,
MethodDispatcher, halt_ordering,
restart_ordering)
from sympy.testing.pytest import raises, XFAIL, warns
def identity(x):
return x
def inc(x):
return x + 1
def dec(x):
return x - 1
def test_dispatcher():
f = Dispatcher('f')
f.add((int,), inc)
f.add((float,), dec)
with warns(DeprecationWarning):
assert f.resolve((int,)) == inc
assert f.dispatch(int) is inc
assert f(1) == 2
assert f(1.0) == 0.0
def test_union_types():
f = Dispatcher('f')
f.register((int, float))(inc)
assert f(1) == 2
assert f(1.0) == 2.0
def test_dispatcher_as_decorator():
f = Dispatcher('f')
@f.register(int)
def inc(x): # noqa:F811
return x + 1
@f.register(float) # noqa:F811
def inc(x): # noqa:F811
return x - 1
assert f(1) == 2
assert f(1.0) == 0.0
def test_register_instance_method():
class Test(object):
__init__ = MethodDispatcher('f')
@__init__.register(list)
def _init_list(self, data):
self.data = data
@__init__.register(object)
def _init_obj(self, datum):
self.data = [datum]
a = Test(3)
b = Test([3])
assert a.data == b.data
def test_on_ambiguity():
f = Dispatcher('f')
def identity(x): return x
ambiguities = [False]
def on_ambiguity(dispatcher, amb):
ambiguities[0] = True
f.add((object, object), identity, on_ambiguity=on_ambiguity)
assert not ambiguities[0]
f.add((object, float), identity, on_ambiguity=on_ambiguity)
assert not ambiguities[0]
f.add((float, object), identity, on_ambiguity=on_ambiguity)
assert ambiguities[0]
@XFAIL
def test_raise_error_on_non_class():
f = Dispatcher('f')
assert raises(TypeError, lambda: f.add((1,), inc))
def test_docstring():
def one(x, y):
""" Docstring number one """
return x + y
def two(x, y):
""" Docstring number two """
return x + y
def three(x, y):
return x + y
master_doc = 'Doc of the multimethod itself'
f = Dispatcher('f', doc=master_doc)
f.add((object, object), one)
f.add((int, int), two)
f.add((float, float), three)
assert one.__doc__.strip() in f.__doc__
assert two.__doc__.strip() in f.__doc__
assert f.__doc__.find(one.__doc__.strip()) < \
f.__doc__.find(two.__doc__.strip())
assert 'object, object' in f.__doc__
assert master_doc in f.__doc__
def test_help():
def one(x, y):
""" Docstring number one """
return x + y
def two(x, y):
""" Docstring number two """
return x + y
def three(x, y):
""" Docstring number three """
return x + y
master_doc = 'Doc of the multimethod itself'
f = Dispatcher('f', doc=master_doc)
f.add((object, object), one)
f.add((int, int), two)
f.add((float, float), three)
assert f._help(1, 1) == two.__doc__
assert f._help(1.0, 2.0) == three.__doc__
def test_source():
def one(x, y):
""" Docstring number one """
return x + y
def two(x, y):
""" Docstring number two """
return x - y
master_doc = 'Doc of the multimethod itself'
f = Dispatcher('f', doc=master_doc)
f.add((int, int), one)
f.add((float, float), two)
assert 'x + y' in f._source(1, 1)
assert 'x - y' in f._source(1.0, 1.0)
@XFAIL
def test_source_raises_on_missing_function():
f = Dispatcher('f')
assert raises(TypeError, lambda: f.source(1))
def test_halt_method_resolution():
g = [0]
def on_ambiguity(a, b):
g[0] += 1
f = Dispatcher('f')
halt_ordering()
def func(*args):
pass
f.add((int, object), func)
f.add((object, int), func)
assert g == [0]
restart_ordering(on_ambiguity=on_ambiguity)
assert g == [1]
assert set(f.ordering) == set([(int, object), (object, int)])
@XFAIL
def test_no_implementations():
f = Dispatcher('f')
assert raises(NotImplementedError, lambda: f('hello'))
@XFAIL
def test_register_stacking():
f = Dispatcher('f')
@f.register(list)
@f.register(tuple)
def rev(x):
return x[::-1]
assert f((1, 2, 3)) == (3, 2, 1)
assert f([1, 2, 3]) == [3, 2, 1]
assert raises(NotImplementedError, lambda: f('hello'))
assert rev('hello') == 'olleh'
def test_dispatch_method():
f = Dispatcher('f')
@f.register(list)
def rev(x):
return x[::-1]
@f.register(int, int)
def add(x, y):
return x + y
class MyList(list):
pass
assert f.dispatch(list) is rev
assert f.dispatch(MyList) is rev
assert f.dispatch(int, int) is add
@XFAIL
def test_not_implemented():
f = Dispatcher('f')
@f.register(object)
def _(x):
return 'default'
@f.register(int)
def _(x):
if x % 2 == 0:
return 'even'
else:
raise MDNotImplementedError()
assert f('hello') == 'default' # default behavior
assert f(2) == 'even' # specialized behavior
assert f(3) == 'default' # fall bac to default behavior
assert raises(NotImplementedError, lambda: f(1, 2))
@XFAIL
def test_not_implemented_error():
f = Dispatcher('f')
@f.register(float)
def _(a):
raise MDNotImplementedError()
assert raises(NotImplementedError, lambda: f(1.0))
|
43f059fe00a1be667fbba1cb46715ffe90cb2b7bf8f0d9341a7b7fd65e918475 | from sympy.testing.pytest import warns_deprecated_sympy
def test_C():
from sympy.deprecated.class_registry import C
with warns_deprecated_sympy():
C.Add
|
07fa8b757678aa0798902ebc4591229f99d634991cda71ec44a2890408c617a3 | """Implementation of DPLL algorithm
Features:
- Clause learning
- Watch literal scheme
- VSIDS heuristic
References:
- https://en.wikipedia.org/wiki/DPLL_algorithm
"""
from __future__ import print_function, division
from collections import defaultdict
from heapq import heappush, heappop
from sympy import ordered
from sympy.assumptions.cnf import EncodedCNF
def dpll_satisfiable(expr, all_models=False):
"""
Check satisfiability of a propositional sentence.
It returns a model rather than True when it succeeds.
Returns a generator of all models if all_models is True.
Examples
========
>>> from sympy.abc import A, B
>>> from sympy.logic.algorithms.dpll2 import dpll_satisfiable
>>> dpll_satisfiable(A & ~B)
{A: True, B: False}
>>> dpll_satisfiable(A & ~A)
False
"""
if not isinstance(expr, EncodedCNF):
exprs = EncodedCNF()
exprs.add_prop(expr)
expr = exprs
# Return UNSAT when False (encoded as 0) is present in the CNF
if {0} in expr.data:
if all_models:
return (f for f in [False])
return False
solver = SATSolver(expr.data, expr.variables, set(), expr.symbols)
models = solver._find_model()
if all_models:
return _all_models(models)
try:
return next(models)
except StopIteration:
return False
# Uncomment to confirm the solution is valid (hitting set for the clauses)
#else:
#for cls in clauses_int_repr:
#assert solver.var_settings.intersection(cls)
def _all_models(models):
satisfiable = False
try:
while True:
yield next(models)
satisfiable = True
except StopIteration:
if not satisfiable:
yield False
class SATSolver(object):
"""
Class for representing a SAT solver capable of
finding a model to a boolean theory in conjunctive
normal form.
"""
def __init__(self, clauses, variables, var_settings, symbols=None,
heuristic='vsids', clause_learning='none', INTERVAL=500):
self.var_settings = var_settings
self.heuristic = heuristic
self.is_unsatisfied = False
self._unit_prop_queue = []
self.update_functions = []
self.INTERVAL = INTERVAL
if symbols is None:
self.symbols = list(ordered(variables))
else:
self.symbols = symbols
self._initialize_variables(variables)
self._initialize_clauses(clauses)
if 'vsids' == heuristic:
self._vsids_init()
self.heur_calculate = self._vsids_calculate
self.heur_lit_assigned = self._vsids_lit_assigned
self.heur_lit_unset = self._vsids_lit_unset
self.heur_clause_added = self._vsids_clause_added
# Note: Uncomment this if/when clause learning is enabled
#self.update_functions.append(self._vsids_decay)
else:
raise NotImplementedError
if 'simple' == clause_learning:
self.add_learned_clause = self._simple_add_learned_clause
self.compute_conflict = self.simple_compute_conflict
self.update_functions.append(self.simple_clean_clauses)
elif 'none' == clause_learning:
self.add_learned_clause = lambda x: None
self.compute_conflict = lambda: None
else:
raise NotImplementedError
# Create the base level
self.levels = [Level(0)]
self._current_level.varsettings = var_settings
# Keep stats
self.num_decisions = 0
self.num_learned_clauses = 0
self.original_num_clauses = len(self.clauses)
def _initialize_variables(self, variables):
"""Set up the variable data structures needed."""
self.sentinels = defaultdict(set)
self.occurrence_count = defaultdict(int)
self.variable_set = [False] * (len(variables) + 1)
def _initialize_clauses(self, clauses):
"""Set up the clause data structures needed.
For each clause, the following changes are made:
- Unit clauses are queued for propagation right away.
- Non-unit clauses have their first and last literals set as sentinels.
- The number of clauses a literal appears in is computed.
"""
self.clauses = []
for cls in clauses:
self.clauses.append(list(cls))
for i in range(len(self.clauses)):
# Handle the unit clauses
if 1 == len(self.clauses[i]):
self._unit_prop_queue.append(self.clauses[i][0])
continue
self.sentinels[self.clauses[i][0]].add(i)
self.sentinels[self.clauses[i][-1]].add(i)
for lit in self.clauses[i]:
self.occurrence_count[lit] += 1
def _find_model(self):
"""
Main DPLL loop. Returns a generator of models.
Variables are chosen successively, and assigned to be either
True or False. If a solution is not found with this setting,
the opposite is chosen and the search continues. The solver
halts when every variable has a setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> list(l._find_model())
[{1: True, 2: False, 3: False}, {1: True, 2: True, 3: True}]
>>> from sympy.abc import A, B, C
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set(), [A, B, C])
>>> list(l._find_model())
[{A: True, B: False, C: False}, {A: True, B: True, C: True}]
"""
# We use this variable to keep track of if we should flip a
# variable setting in successive rounds
flip_var = False
# Check if unit prop says the theory is unsat right off the bat
self._simplify()
if self.is_unsatisfied:
return
# While the theory still has clauses remaining
while True:
# Perform cleanup / fixup at regular intervals
if self.num_decisions % self.INTERVAL == 0:
for func in self.update_functions:
func()
if flip_var:
# We have just backtracked and we are trying to opposite literal
flip_var = False
lit = self._current_level.decision
else:
# Pick a literal to set
lit = self.heur_calculate()
self.num_decisions += 1
# Stopping condition for a satisfying theory
if 0 == lit:
yield dict((self.symbols[abs(lit) - 1],
lit > 0) for lit in self.var_settings)
while self._current_level.flipped:
self._undo()
if len(self.levels) == 1:
return
flip_lit = -self._current_level.decision
self._undo()
self.levels.append(Level(flip_lit, flipped=True))
flip_var = True
continue
# Start the new decision level
self.levels.append(Level(lit))
# Assign the literal, updating the clauses it satisfies
self._assign_literal(lit)
# _simplify the theory
self._simplify()
# Check if we've made the theory unsat
if self.is_unsatisfied:
self.is_unsatisfied = False
# We unroll all of the decisions until we can flip a literal
while self._current_level.flipped:
self._undo()
# If we've unrolled all the way, the theory is unsat
if 1 == len(self.levels):
return
# Detect and add a learned clause
self.add_learned_clause(self.compute_conflict())
# Try the opposite setting of the most recent decision
flip_lit = -self._current_level.decision
self._undo()
self.levels.append(Level(flip_lit, flipped=True))
flip_var = True
########################
# Helper Methods #
########################
@property
def _current_level(self):
"""The current decision level data structure
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{1}, {2}], {1, 2}, set())
>>> next(l._find_model())
{1: True, 2: True}
>>> l._current_level.decision
0
>>> l._current_level.flipped
False
>>> l._current_level.var_settings
{1, 2}
"""
return self.levels[-1]
def _clause_sat(self, cls):
"""Check if a clause is satisfied by the current variable setting.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{1}, {-1}], {1}, set())
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l._clause_sat(0)
False
>>> l._clause_sat(1)
True
"""
for lit in self.clauses[cls]:
if lit in self.var_settings:
return True
return False
def _is_sentinel(self, lit, cls):
"""Check if a literal is a sentinel of a given clause.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l._is_sentinel(2, 3)
True
>>> l._is_sentinel(-3, 1)
False
"""
return cls in self.sentinels[lit]
def _assign_literal(self, lit):
"""Make a literal assignment.
The literal assignment must be recorded as part of the current
decision level. Additionally, if the literal is marked as a
sentinel of any clause, then a new sentinel must be chosen. If
this is not possible, then unit propagation is triggered and
another literal is added to the queue to be set in the future.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l.var_settings
{-3, -2, 1}
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l._assign_literal(-1)
>>> try:
... next(l._find_model())
... except StopIteration:
... pass
>>> l.var_settings
{-1}
"""
self.var_settings.add(lit)
self._current_level.var_settings.add(lit)
self.variable_set[abs(lit)] = True
self.heur_lit_assigned(lit)
sentinel_list = list(self.sentinels[-lit])
for cls in sentinel_list:
if not self._clause_sat(cls):
other_sentinel = None
for newlit in self.clauses[cls]:
if newlit != -lit:
if self._is_sentinel(newlit, cls):
other_sentinel = newlit
elif not self.variable_set[abs(newlit)]:
self.sentinels[-lit].remove(cls)
self.sentinels[newlit].add(cls)
other_sentinel = None
break
# Check if no sentinel update exists
if other_sentinel:
self._unit_prop_queue.append(other_sentinel)
def _undo(self):
"""
_undo the changes of the most recent decision level.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> level = l._current_level
>>> level.decision, level.var_settings, level.flipped
(-3, {-3, -2}, False)
>>> l._undo()
>>> level = l._current_level
>>> level.decision, level.var_settings, level.flipped
(0, {1}, False)
"""
# Undo the variable settings
for lit in self._current_level.var_settings:
self.var_settings.remove(lit)
self.heur_lit_unset(lit)
self.variable_set[abs(lit)] = False
# Pop the level off the stack
self.levels.pop()
#########################
# Propagation #
#########################
"""
Propagation methods should attempt to soundly simplify the boolean
theory, and return True if any simplification occurred and False
otherwise.
"""
def _simplify(self):
"""Iterate over the various forms of propagation to simplify the theory.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.variable_set
[False, False, False, False]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
>>> l._simplify()
>>> l.variable_set
[False, True, False, False]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, -1: set(), 2: {0, 3},
...3: {2, 4}}
"""
changed = True
while changed:
changed = False
changed |= self._unit_prop()
changed |= self._pure_literal()
def _unit_prop(self):
"""Perform unit propagation on the current theory."""
result = len(self._unit_prop_queue) > 0
while self._unit_prop_queue:
next_lit = self._unit_prop_queue.pop()
if -next_lit in self.var_settings:
self.is_unsatisfied = True
self._unit_prop_queue = []
return False
else:
self._assign_literal(next_lit)
return result
def _pure_literal(self):
"""Look for pure literals and assign them when found."""
return False
#########################
# Heuristics #
#########################
def _vsids_init(self):
"""Initialize the data structures needed for the VSIDS heuristic."""
self.lit_heap = []
self.lit_scores = {}
for var in range(1, len(self.variable_set)):
self.lit_scores[var] = float(-self.occurrence_count[var])
self.lit_scores[-var] = float(-self.occurrence_count[-var])
heappush(self.lit_heap, (self.lit_scores[var], var))
heappush(self.lit_heap, (self.lit_scores[-var], -var))
def _vsids_decay(self):
"""Decay the VSIDS scores for every literal.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_scores
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
>>> l._vsids_decay()
>>> l.lit_scores
{-3: -1.0, -2: -1.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -1.0}
"""
# We divide every literal score by 2 for a decay factor
# Note: This doesn't change the heap property
for lit in self.lit_scores.keys():
self.lit_scores[lit] /= 2.0
def _vsids_calculate(self):
"""
VSIDS Heuristic Calculation
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_heap
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
>>> l._vsids_calculate()
-3
>>> l.lit_heap
[(-2.0, -2), (-2.0, 2), (0.0, -1), (0.0, 1), (-2.0, 3)]
"""
if len(self.lit_heap) == 0:
return 0
# Clean out the front of the heap as long the variables are set
while self.variable_set[abs(self.lit_heap[0][1])]:
heappop(self.lit_heap)
if len(self.lit_heap) == 0:
return 0
return heappop(self.lit_heap)[1]
def _vsids_lit_assigned(self, lit):
"""Handle the assignment of a literal for the VSIDS heuristic."""
pass
def _vsids_lit_unset(self, lit):
"""Handle the unsetting of a literal for the VSIDS heuristic.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.lit_heap
[(-2.0, -3), (-2.0, 2), (-2.0, -2), (0.0, 1), (-2.0, 3), (0.0, -1)]
>>> l._vsids_lit_unset(2)
>>> l.lit_heap
[(-2.0, -3), (-2.0, -2), (-2.0, -2), (-2.0, 2), (-2.0, 3), (0.0, -1),
...(-2.0, 2), (0.0, 1)]
"""
var = abs(lit)
heappush(self.lit_heap, (self.lit_scores[var], var))
heappush(self.lit_heap, (self.lit_scores[-var], -var))
def _vsids_clause_added(self, cls):
"""Handle the addition of a new clause for the VSIDS heuristic.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.num_learned_clauses
0
>>> l.lit_scores
{-3: -2.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -2.0, 3: -2.0}
>>> l._vsids_clause_added({2, -3})
>>> l.num_learned_clauses
1
>>> l.lit_scores
{-3: -1.0, -2: -2.0, -1: 0.0, 1: 0.0, 2: -1.0, 3: -2.0}
"""
self.num_learned_clauses += 1
for lit in cls:
self.lit_scores[lit] += 1
########################
# Clause Learning #
########################
def _simple_add_learned_clause(self, cls):
"""Add a new clause to the theory.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> l.num_learned_clauses
0
>>> l.clauses
[[2, -3], [1], [3, -3], [2, -2], [3, -2]]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4}}
>>> l._simple_add_learned_clause([3])
>>> l.clauses
[[2, -3], [1], [3, -3], [2, -2], [3, -2], [3]]
>>> l.sentinels
{-3: {0, 2}, -2: {3, 4}, 2: {0, 3}, 3: {2, 4, 5}}
"""
cls_num = len(self.clauses)
self.clauses.append(cls)
for lit in cls:
self.occurrence_count[lit] += 1
self.sentinels[cls[0]].add(cls_num)
self.sentinels[cls[-1]].add(cls_num)
self.heur_clause_added(cls)
def _simple_compute_conflict(self):
""" Build a clause representing the fact that at least one decision made
so far is wrong.
Examples
========
>>> from sympy.logic.algorithms.dpll2 import SATSolver
>>> l = SATSolver([{2, -3}, {1}, {3, -3}, {2, -2},
... {3, -2}], {1, 2, 3}, set())
>>> next(l._find_model())
{1: True, 2: False, 3: False}
>>> l._simple_compute_conflict()
[3]
"""
return [-(level.decision) for level in self.levels[1:]]
def _simple_clean_clauses(self):
"""Clean up learned clauses."""
pass
class Level(object):
"""
Represents a single level in the DPLL algorithm, and contains
enough information for a sound backtracking procedure.
"""
def __init__(self, decision, flipped=False):
self.decision = decision
self.var_settings = set()
self.flipped = flipped
|
6f7411595d48727fdf86918eb5546ec19c82c5a6d7e280e73f0f8d8e78f8e3e8 | """Implementation of DPLL algorithm
Further improvements: eliminate calls to pl_true, implement branching rules,
efficient unit propagation.
References:
- https://en.wikipedia.org/wiki/DPLL_algorithm
- https://www.researchgate.net/publication/242384772_Implementations_of_the_DPLL_Algorithm
"""
from __future__ import print_function, division
from sympy import default_sort_key
from sympy.logic.boolalg import Or, Not, conjuncts, disjuncts, to_cnf, \
to_int_repr, _find_predicates
from sympy.assumptions.cnf import CNF
from sympy.logic.inference import pl_true, literal_symbol
def dpll_satisfiable(expr):
"""
Check satisfiability of a propositional sentence.
It returns a model rather than True when it succeeds
>>> from sympy.abc import A, B
>>> from sympy.logic.algorithms.dpll import dpll_satisfiable
>>> dpll_satisfiable(A & ~B)
{A: True, B: False}
>>> dpll_satisfiable(A & ~A)
False
"""
if not isinstance(expr, CNF):
clauses = conjuncts(to_cnf(expr))
else:
clauses = expr.clauses
if False in clauses:
return False
symbols = sorted(_find_predicates(expr), key=default_sort_key)
symbols_int_repr = set(range(1, len(symbols) + 1))
clauses_int_repr = to_int_repr(clauses, symbols)
result = dpll_int_repr(clauses_int_repr, symbols_int_repr, {})
if not result:
return result
output = {}
for key in result:
output.update({symbols[key - 1]: result[key]})
return output
def dpll(clauses, symbols, model):
"""
Compute satisfiability in a partial model.
Clauses is an array of conjuncts.
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import dpll
>>> dpll([A, B, D], [A, B], {D: False})
False
"""
# compute DP kernel
P, value = find_unit_clause(clauses, model)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = ~P
clauses = unit_propagate(clauses, P)
P, value = find_unit_clause(clauses, model)
P, value = find_pure_symbol(symbols, clauses)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = ~P
clauses = unit_propagate(clauses, P)
P, value = find_pure_symbol(symbols, clauses)
# end DP kernel
unknown_clauses = []
for c in clauses:
val = pl_true(c, model)
if val is False:
return False
if val is not True:
unknown_clauses.append(c)
if not unknown_clauses:
return model
if not clauses:
return model
P = symbols.pop()
model_copy = model.copy()
model.update({P: True})
model_copy.update({P: False})
symbols_copy = symbols[:]
return (dpll(unit_propagate(unknown_clauses, P), symbols, model) or
dpll(unit_propagate(unknown_clauses, Not(P)), symbols_copy, model_copy))
def dpll_int_repr(clauses, symbols, model):
"""
Compute satisfiability in a partial model.
Arguments are expected to be in integer representation
>>> from sympy.logic.algorithms.dpll import dpll_int_repr
>>> dpll_int_repr([{1}, {2}, {3}], {1, 2}, {3: False})
False
"""
# compute DP kernel
P, value = find_unit_clause_int_repr(clauses, model)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = -P
clauses = unit_propagate_int_repr(clauses, P)
P, value = find_unit_clause_int_repr(clauses, model)
P, value = find_pure_symbol_int_repr(symbols, clauses)
while P:
model.update({P: value})
symbols.remove(P)
if not value:
P = -P
clauses = unit_propagate_int_repr(clauses, P)
P, value = find_pure_symbol_int_repr(symbols, clauses)
# end DP kernel
unknown_clauses = []
for c in clauses:
val = pl_true_int_repr(c, model)
if val is False:
return False
if val is not True:
unknown_clauses.append(c)
if not unknown_clauses:
return model
P = symbols.pop()
model_copy = model.copy()
model.update({P: True})
model_copy.update({P: False})
symbols_copy = symbols.copy()
return (dpll_int_repr(unit_propagate_int_repr(unknown_clauses, P), symbols, model) or
dpll_int_repr(unit_propagate_int_repr(unknown_clauses, -P), symbols_copy, model_copy))
### helper methods for DPLL
def pl_true_int_repr(clause, model={}):
"""
Lightweight version of pl_true.
Argument clause represents the set of args of an Or clause. This is used
inside dpll_int_repr, it is not meant to be used directly.
>>> from sympy.logic.algorithms.dpll import pl_true_int_repr
>>> pl_true_int_repr({1, 2}, {1: False})
>>> pl_true_int_repr({1, 2}, {1: False, 2: False})
False
"""
result = False
for lit in clause:
if lit < 0:
p = model.get(-lit)
if p is not None:
p = not p
else:
p = model.get(lit)
if p is True:
return True
elif p is None:
result = None
return result
def unit_propagate(clauses, symbol):
"""
Returns an equivalent set of clauses
If a set of clauses contains the unit clause l, the other clauses are
simplified by the application of the two following rules:
1. every clause containing l is removed
2. in every clause that contains ~l this literal is deleted
Arguments are expected to be in CNF.
>>> from sympy import symbols
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import unit_propagate
>>> unit_propagate([A | B, D | ~B, B], B)
[D, B]
"""
output = []
for c in clauses:
if c.func != Or:
output.append(c)
continue
for arg in c.args:
if arg == ~symbol:
output.append(Or(*[x for x in c.args if x != ~symbol]))
break
if arg == symbol:
break
else:
output.append(c)
return output
def unit_propagate_int_repr(clauses, s):
"""
Same as unit_propagate, but arguments are expected to be in integer
representation
>>> from sympy.logic.algorithms.dpll import unit_propagate_int_repr
>>> unit_propagate_int_repr([{1, 2}, {3, -2}, {2}], 2)
[{3}]
"""
negated = {-s}
return [clause - negated for clause in clauses if s not in clause]
def find_pure_symbol(symbols, unknown_clauses):
"""
Find a symbol and its value if it appears only as a positive literal
(or only as a negative) in clauses.
>>> from sympy import symbols
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import find_pure_symbol
>>> find_pure_symbol([A, B, D], [A|~B,~B|~D,D|A])
(A, True)
"""
for sym in symbols:
found_pos, found_neg = False, False
for c in unknown_clauses:
if not found_pos and sym in disjuncts(c):
found_pos = True
if not found_neg and Not(sym) in disjuncts(c):
found_neg = True
if found_pos != found_neg:
return sym, found_pos
return None, None
def find_pure_symbol_int_repr(symbols, unknown_clauses):
"""
Same as find_pure_symbol, but arguments are expected
to be in integer representation
>>> from sympy.logic.algorithms.dpll import find_pure_symbol_int_repr
>>> find_pure_symbol_int_repr({1,2,3},
... [{1, -2}, {-2, -3}, {3, 1}])
(1, True)
"""
all_symbols = set().union(*unknown_clauses)
found_pos = all_symbols.intersection(symbols)
found_neg = all_symbols.intersection([-s for s in symbols])
for p in found_pos:
if -p not in found_neg:
return p, True
for p in found_neg:
if -p not in found_pos:
return -p, False
return None, None
def find_unit_clause(clauses, model):
"""
A unit clause has only 1 variable that is not bound in the model.
>>> from sympy import symbols
>>> from sympy.abc import A, B, D
>>> from sympy.logic.algorithms.dpll import find_unit_clause
>>> find_unit_clause([A | B | D, B | ~D, A | ~B], {A:True})
(B, False)
"""
for clause in clauses:
num_not_in_model = 0
for literal in disjuncts(clause):
sym = literal_symbol(literal)
if sym not in model:
num_not_in_model += 1
P, value = sym, not isinstance(literal, Not)
if num_not_in_model == 1:
return P, value
return None, None
def find_unit_clause_int_repr(clauses, model):
"""
Same as find_unit_clause, but arguments are expected to be in
integer representation.
>>> from sympy.logic.algorithms.dpll import find_unit_clause_int_repr
>>> find_unit_clause_int_repr([{1, 2, 3},
... {2, -3}, {1, -2}], {1: True})
(2, False)
"""
bound = set(model) | set(-sym for sym in model)
for clause in clauses:
unbound = clause - bound
if len(unbound) == 1:
p = unbound.pop()
if p < 0:
return -p, False
else:
return p, True
return None, None
|
62e0b38a9ae59d5f79784f4c35f742c3ec8060be2d4cb68129c0b580efc06052 | from sympy.assumptions.ask import Q
from sympy.core.numbers import oo
from sympy.core.relational import Equality, Eq, Ne
from sympy.core.singleton import S
from sympy.core.symbol import (Dummy, symbols)
from sympy.functions import Piecewise
from sympy.functions.elementary.miscellaneous import Max, Min
from sympy.functions.elementary.trigonometric import sin
from sympy.sets.sets import (EmptySet, Interval, Union)
from sympy.simplify.simplify import simplify
from sympy.logic.boolalg import (
And, Boolean, Equivalent, ITE, Implies, Nand, Nor, Not, Or,
POSform, SOPform, Xor, Xnor, conjuncts, disjuncts,
distribute_or_over_and, distribute_and_over_or,
eliminate_implications, is_nnf, is_cnf, is_dnf, simplify_logic,
to_nnf, to_cnf, to_dnf, to_int_repr, bool_map, true, false,
BooleanAtom, is_literal, term_to_integer, integer_to_term,
truth_table, as_Boolean, to_anf, is_anf, distribute_xor_over_and,
anf_coeffs, ANFform, bool_minterm, bool_maxterm, bool_monomial)
from sympy.assumptions.cnf import CNF
from sympy.testing.pytest import raises, XFAIL, slow
from sympy.utilities import cartes
from itertools import combinations
A, B, C, D = symbols('A:D')
a, b, c, d, e, w, x, y, z = symbols('a:e w:z')
def test_overloading():
"""Test that |, & are overloaded as expected"""
assert A & B == And(A, B)
assert A | B == Or(A, B)
assert (A & B) | C == Or(And(A, B), C)
assert A >> B == Implies(A, B)
assert A << B == Implies(B, A)
assert ~A == Not(A)
assert A ^ B == Xor(A, B)
def test_And():
assert And() is true
assert And(A) == A
assert And(True) is true
assert And(False) is false
assert And(True, True) is true
assert And(True, False) is false
assert And(False, False) is false
assert And(True, A) == A
assert And(False, A) is false
assert And(True, True, True) is true
assert And(True, True, A) == A
assert And(True, False, A) is false
assert And(1, A) == A
raises(TypeError, lambda: And(2, A))
raises(TypeError, lambda: And(A < 2, A))
assert And(A < 1, A >= 1) is false
e = A > 1
assert And(e, e.canonical) == e.canonical
g, l, ge, le = A > B, B < A, A >= B, B <= A
assert And(g, l, ge, le) == And(l, le)
def test_Or():
assert Or() is false
assert Or(A) == A
assert Or(True) is true
assert Or(False) is false
assert Or(True, True) is true
assert Or(True, False) is true
assert Or(False, False) is false
assert Or(True, A) is true
assert Or(False, A) == A
assert Or(True, False, False) is true
assert Or(True, False, A) is true
assert Or(False, False, A) == A
assert Or(1, A) is true
raises(TypeError, lambda: Or(2, A))
raises(TypeError, lambda: Or(A < 2, A))
assert Or(A < 1, A >= 1) is true
e = A > 1
assert Or(e, e.canonical) == e
g, l, ge, le = A > B, B < A, A >= B, B <= A
assert Or(g, l, ge, le) == Or(g, ge)
def test_Xor():
assert Xor() is false
assert Xor(A) == A
assert Xor(A, A) is false
assert Xor(True, A, A) is true
assert Xor(A, A, A, A, A) == A
assert Xor(True, False, False, A, B) == ~Xor(A, B)
assert Xor(True) is true
assert Xor(False) is false
assert Xor(True, True) is false
assert Xor(True, False) is true
assert Xor(False, False) is false
assert Xor(True, A) == ~A
assert Xor(False, A) == A
assert Xor(True, False, False) is true
assert Xor(True, False, A) == ~A
assert Xor(False, False, A) == A
assert isinstance(Xor(A, B), Xor)
assert Xor(A, B, Xor(C, D)) == Xor(A, B, C, D)
assert Xor(A, B, Xor(B, C)) == Xor(A, C)
assert Xor(A < 1, A >= 1, B) == Xor(0, 1, B) == Xor(1, 0, B)
e = A > 1
assert Xor(e, e.canonical) == Xor(0, 0) == Xor(1, 1)
def test_rewrite_as_And():
expr = x ^ y
assert expr.rewrite(And) == (x | y) & (~x | ~y)
def test_rewrite_as_Or():
expr = x ^ y
assert expr.rewrite(Or) == (x & ~y) | (y & ~x)
def test_rewrite_as_Nand():
expr = (y & z) | (z & ~w)
assert expr.rewrite(Nand) == ~(~(y & z) & ~(z & ~w))
def test_rewrite_as_Nor():
expr = z & (y | ~w)
assert expr.rewrite(Nor) == ~(~z | ~(y | ~w))
def test_Not():
raises(TypeError, lambda: Not(True, False))
assert Not(True) is false
assert Not(False) is true
assert Not(0) is true
assert Not(1) is false
assert Not(2) is false
def test_Nand():
assert Nand() is false
assert Nand(A) == ~A
assert Nand(True) is false
assert Nand(False) is true
assert Nand(True, True) is false
assert Nand(True, False) is true
assert Nand(False, False) is true
assert Nand(True, A) == ~A
assert Nand(False, A) is true
assert Nand(True, True, True) is false
assert Nand(True, True, A) == ~A
assert Nand(True, False, A) is true
def test_Nor():
assert Nor() is true
assert Nor(A) == ~A
assert Nor(True) is false
assert Nor(False) is true
assert Nor(True, True) is false
assert Nor(True, False) is false
assert Nor(False, False) is true
assert Nor(True, A) is false
assert Nor(False, A) == ~A
assert Nor(True, True, True) is false
assert Nor(True, True, A) is false
assert Nor(True, False, A) is false
def test_Xnor():
assert Xnor() is true
assert Xnor(A) == ~A
assert Xnor(A, A) is true
assert Xnor(True, A, A) is false
assert Xnor(A, A, A, A, A) == ~A
assert Xnor(True) is false
assert Xnor(False) is true
assert Xnor(True, True) is true
assert Xnor(True, False) is false
assert Xnor(False, False) is true
assert Xnor(True, A) == A
assert Xnor(False, A) == ~A
assert Xnor(True, False, False) is false
assert Xnor(True, False, A) == A
assert Xnor(False, False, A) == ~A
def test_Implies():
raises(ValueError, lambda: Implies(A, B, C))
assert Implies(True, True) is true
assert Implies(True, False) is false
assert Implies(False, True) is true
assert Implies(False, False) is true
assert Implies(0, A) is true
assert Implies(1, 1) is true
assert Implies(1, 0) is false
assert A >> B == B << A
assert (A < 1) >> (A >= 1) == (A >= 1)
assert (A < 1) >> (S.One > A) is true
assert A >> A is true
def test_Equivalent():
assert Equivalent(A, B) == Equivalent(B, A) == Equivalent(A, B, A)
assert Equivalent() is true
assert Equivalent(A, A) == Equivalent(A) is true
assert Equivalent(True, True) == Equivalent(False, False) is true
assert Equivalent(True, False) == Equivalent(False, True) is false
assert Equivalent(A, True) == A
assert Equivalent(A, False) == Not(A)
assert Equivalent(A, B, True) == A & B
assert Equivalent(A, B, False) == ~A & ~B
assert Equivalent(1, A) == A
assert Equivalent(0, A) == Not(A)
assert Equivalent(A, Equivalent(B, C)) != Equivalent(Equivalent(A, B), C)
assert Equivalent(A < 1, A >= 1) is false
assert Equivalent(A < 1, A >= 1, 0) is false
assert Equivalent(A < 1, A >= 1, 1) is false
assert Equivalent(A < 1, S.One > A) == Equivalent(1, 1) == Equivalent(0, 0)
assert Equivalent(Equality(A, B), Equality(B, A)) is true
def test_equals():
assert Not(Or(A, B)).equals(And(Not(A), Not(B))) is True
assert Equivalent(A, B).equals((A >> B) & (B >> A)) is True
assert ((A | ~B) & (~A | B)).equals((~A & ~B) | (A & B)) is True
assert (A >> B).equals(~A >> ~B) is False
assert (A >> (B >> A)).equals(A >> (C >> A)) is False
raises(NotImplementedError, lambda: (A & B).equals(A > B))
def test_simplification():
"""
Test working of simplification methods.
"""
set1 = [[0, 0, 1], [0, 1, 1], [1, 0, 0], [1, 1, 0]]
set2 = [[0, 0, 0], [0, 1, 0], [1, 0, 1], [1, 1, 1]]
assert SOPform([x, y, z], set1) == Or(And(Not(x), z), And(Not(z), x))
assert Not(SOPform([x, y, z], set2)) == \
Not(Or(And(Not(x), Not(z)), And(x, z)))
assert POSform([x, y, z], set1 + set2) is true
assert SOPform([x, y, z], set1 + set2) is true
assert SOPform([Dummy(), Dummy(), Dummy()], set1 + set2) is true
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
[1, 1, 1, 1]]
dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(Not(w), z), And(y, z)))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, 3, 7, 11, 15]
dontcares = [0, 2, 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(Not(w), z), And(y, z)))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, [0, 0, 1, 1], 7, [1, 0, 1, 1],
[1, 1, 1, 1]]
dontcares = [0, [0, 0, 1, 0], 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(Not(w), z), And(y, z)))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [1, {y: 1, z: 1}]
dontcares = [0, [0, 0, 1, 0], 5]
assert (
SOPform([w, x, y, z], minterms, dontcares) ==
Or(And(Not(w), z), And(y, z)))
assert POSform([w, x, y, z], minterms, dontcares) == And(Or(Not(w), y), z)
minterms = [{y: 1, z: 1}, 1]
dontcares = [[0, 0, 0, 0]]
minterms = [[0, 0, 0]]
raises(ValueError, lambda: SOPform([w, x, y, z], minterms))
raises(ValueError, lambda: POSform([w, x, y, z], minterms))
raises(TypeError, lambda: POSform([w, x, y, z], ["abcdefg"]))
# test simplification
ans = And(A, Or(B, C))
assert simplify_logic(A & (B | C)) == ans
assert simplify_logic((A & B) | (A & C)) == ans
assert simplify_logic(Implies(A, B)) == Or(Not(A), B)
assert simplify_logic(Equivalent(A, B)) == \
Or(And(A, B), And(Not(A), Not(B)))
assert simplify_logic(And(Equality(A, 2), C)) == And(Equality(A, 2), C)
assert simplify_logic(And(Equality(A, 2), A)) is S.false
assert simplify_logic(And(Equality(A, 2), A)) == And(Equality(A, 2), A)
assert simplify_logic(And(Equality(A, B), C)) == And(Equality(A, B), C)
assert simplify_logic(Or(And(Equality(A, 3), B), And(Equality(A, 3), C))) \
== And(Equality(A, 3), Or(B, C))
b = (~x & ~y & ~z) | (~x & ~y & z)
e = And(A, b)
assert simplify_logic(e) == A & ~x & ~y
raises(ValueError, lambda: simplify_logic(A & (B | C), form='blabla'))
# Check that expressions with nine variables or more are not simplified
# (without the force-flag)
a, b, c, d, e, f, g, h, j = symbols('a b c d e f g h j')
expr = a & b & c & d & e & f & g & h & j | \
a & b & c & d & e & f & g & h & ~j
# This expression can be simplified to get rid of the j variables
assert simplify_logic(expr) == expr
# check input
ans = SOPform([x, y], [[1, 0]])
assert SOPform([x, y], [[1, 0]]) == ans
assert POSform([x, y], [[1, 0]]) == ans
raises(ValueError, lambda: SOPform([x], [[1]], [[1]]))
assert SOPform([x], [[1]], [[0]]) is true
assert SOPform([x], [[0]], [[1]]) is true
assert SOPform([x], [], []) is false
raises(ValueError, lambda: POSform([x], [[1]], [[1]]))
assert POSform([x], [[1]], [[0]]) is true
assert POSform([x], [[0]], [[1]]) is true
assert POSform([x], [], []) is false
# check working of simplify
assert simplify((A & B) | (A & C)) == And(A, Or(B, C))
assert simplify(And(x, Not(x))) == False
assert simplify(Or(x, Not(x))) == True
assert simplify(And(Eq(x, 0), Eq(x, y))) == And(Eq(x, 0), Eq(y, 0))
assert And(Eq(x - 1, 0), Eq(x, y)).simplify() == And(Eq(x, 1), Eq(y, 1))
assert And(Ne(x - 1, 0), Ne(x, y)).simplify() == And(Ne(x, 1), Ne(x, y))
assert And(Eq(x - 1, 0), Ne(x, y)).simplify() == And(Eq(x, 1), Ne(y, 1))
assert And(Eq(x - 1, 0), Eq(x, z + y), Eq(y + x, 0)).simplify(
) == And(Eq(x, 1), Eq(y, -1), Eq(z, 2))
assert And(Eq(x - 1, 0), Eq(x + 2, 3)).simplify() == Eq(x, 1)
assert And(Ne(x - 1, 0), Ne(x + 2, 3)).simplify() == Ne(x, 1)
assert And(Eq(x - 1, 0), Eq(x + 2, 2)).simplify() == False
assert And(Ne(x - 1, 0), Ne(x + 2, 2)).simplify(
) == And(Ne(x, 1), Ne(x, 0))
def test_bool_map():
"""
Test working of bool_map function.
"""
minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], [1, 0, 1, 1],
[1, 1, 1, 1]]
assert bool_map(Not(Not(a)), a) == (a, {a: a})
assert bool_map(SOPform([w, x, y, z], minterms),
POSform([w, x, y, z], minterms)) == \
(And(Or(Not(w), y), Or(Not(x), y), z), {x: x, w: w, z: z, y: y})
assert bool_map(SOPform([x, z, y], [[1, 0, 1]]),
SOPform([a, b, c], [[1, 0, 1]])) != False
function1 = SOPform([x, z, y], [[1, 0, 1], [0, 0, 1]])
function2 = SOPform([a, b, c], [[1, 0, 1], [1, 0, 0]])
assert bool_map(function1, function2) == \
(function1, {y: a, z: b})
assert bool_map(Xor(x, y), ~Xor(x, y)) == False
assert bool_map(And(x, y), Or(x, y)) is None
assert bool_map(And(x, y), And(x, y, z)) is None
# issue 16179
assert bool_map(Xor(x, y, z), ~Xor(x, y, z)) == False
assert bool_map(Xor(a, x, y, z), ~Xor(a, x, y, z)) == False
def test_bool_symbol():
"""Test that mixing symbols with boolean values
works as expected"""
assert And(A, True) == A
assert And(A, True, True) == A
assert And(A, False) is false
assert And(A, True, False) is false
assert Or(A, True) is true
assert Or(A, False) == A
def test_is_boolean():
assert true.is_Boolean
assert (A & B).is_Boolean
assert (A | B).is_Boolean
assert (~A).is_Boolean
assert (A ^ B).is_Boolean
def test_subs():
assert (A & B).subs(A, True) == B
assert (A & B).subs(A, False) is false
assert (A & B).subs(B, True) == A
assert (A & B).subs(B, False) is false
assert (A & B).subs({A: True, B: True}) is true
assert (A | B).subs(A, True) is true
assert (A | B).subs(A, False) == B
assert (A | B).subs(B, True) is true
assert (A | B).subs(B, False) == A
assert (A | B).subs({A: True, B: True}) is true
"""
we test for axioms of boolean algebra
see https://en.wikipedia.org/wiki/Boolean_algebra_(structure)
"""
def test_commutative():
"""Test for commutativity of And and Or"""
A, B = map(Boolean, symbols('A,B'))
assert A & B == B & A
assert A | B == B | A
def test_and_associativity():
"""Test for associativity of And"""
assert (A & B) & C == A & (B & C)
def test_or_assicativity():
assert ((A | B) | C) == (A | (B | C))
def test_double_negation():
a = Boolean()
assert ~(~a) == a
# test methods
def test_eliminate_implications():
assert eliminate_implications(Implies(A, B, evaluate=False)) == (~A) | B
assert eliminate_implications(
A >> (C >> Not(B))) == Or(Or(Not(B), Not(C)), Not(A))
assert eliminate_implications(Equivalent(A, B, C, D)) == \
(~A | B) & (~B | C) & (~C | D) & (~D | A)
def test_conjuncts():
assert conjuncts(A & B & C) == {A, B, C}
assert conjuncts((A | B) & C) == {A | B, C}
assert conjuncts(A) == {A}
assert conjuncts(True) == {True}
assert conjuncts(False) == {False}
def test_disjuncts():
assert disjuncts(A | B | C) == {A, B, C}
assert disjuncts((A | B) & C) == {(A | B) & C}
assert disjuncts(A) == {A}
assert disjuncts(True) == {True}
assert disjuncts(False) == {False}
def test_distribute():
assert distribute_and_over_or(Or(And(A, B), C)) == And(Or(A, C), Or(B, C))
assert distribute_or_over_and(And(A, Or(B, C))) == Or(And(A, B), And(A, C))
assert distribute_xor_over_and(And(A, Xor(B, C))) == Xor(And(A, B), And(A, C))
def test_to_anf():
x, y, z = symbols('x,y,z')
assert to_anf(And(x, y)) == And(x, y)
assert to_anf(Or(x, y)) == Xor(x, y, And(x, y))
assert to_anf(Or(Implies(x, y), And(x, y), y)) == \
Xor(x, True, x & y, remove_true=False)
assert to_anf(Or(Nand(x, y), Nor(x, y), Xnor(x, y), Implies(x, y))) == True
assert to_anf(Or(x, Not(y), Nor(x,z), And(x, y), Nand(y, z))) == \
Xor(True, And(y, z), And(x, y, z), remove_true=False)
assert to_anf(Xor(x, y)) == Xor(x, y)
assert to_anf(Not(x)) == Xor(x, True, remove_true=False)
assert to_anf(Nand(x, y)) == Xor(True, And(x, y), remove_true=False)
assert to_anf(Nor(x, y)) == Xor(x, y, True, And(x, y), remove_true=False)
assert to_anf(Implies(x, y)) == Xor(x, True, And(x, y), remove_true=False)
assert to_anf(Equivalent(x, y)) == Xor(x, y, True, remove_true=False)
assert to_anf(Nand(x | y, x >> y), deep=False) == \
Xor(True, And(Or(x, y), Implies(x, y)), remove_true=False)
assert to_anf(Nor(x ^ y, x & y), deep=False) == \
Xor(True, Or(Xor(x, y), And(x, y)), remove_true=False)
def test_to_nnf():
assert to_nnf(true) is true
assert to_nnf(false) is false
assert to_nnf(A) == A
assert to_nnf(A | ~A | B) is true
assert to_nnf(A & ~A & B) is false
assert to_nnf(A >> B) == ~A | B
assert to_nnf(Equivalent(A, B, C)) == (~A | B) & (~B | C) & (~C | A)
assert to_nnf(A ^ B ^ C) == \
(A | B | C) & (~A | ~B | C) & (A | ~B | ~C) & (~A | B | ~C)
assert to_nnf(ITE(A, B, C)) == (~A | B) & (A | C)
assert to_nnf(Not(A | B | C)) == ~A & ~B & ~C
assert to_nnf(Not(A & B & C)) == ~A | ~B | ~C
assert to_nnf(Not(A >> B)) == A & ~B
assert to_nnf(Not(Equivalent(A, B, C))) == And(Or(A, B, C), Or(~A, ~B, ~C))
assert to_nnf(Not(A ^ B ^ C)) == \
(~A | B | C) & (A | ~B | C) & (A | B | ~C) & (~A | ~B | ~C)
assert to_nnf(Not(ITE(A, B, C))) == (~A | ~B) & (A | ~C)
assert to_nnf((A >> B) ^ (B >> A)) == (A & ~B) | (~A & B)
assert to_nnf((A >> B) ^ (B >> A), False) == \
(~A | ~B | A | B) & ((A & ~B) | (~A & B))
assert ITE(A, 1, 0).to_nnf() == A
assert ITE(A, 0, 1).to_nnf() == ~A
# although ITE can hold non-Boolean, it will complain if
# an attempt is made to convert the ITE to Boolean nnf
raises(TypeError, lambda: ITE(A < 1, [1], B).to_nnf())
def test_to_cnf():
assert to_cnf(~(B | C)) == And(Not(B), Not(C))
assert to_cnf((A & B) | C) == And(Or(A, C), Or(B, C))
assert to_cnf(A >> B) == (~A) | B
assert to_cnf(A >> (B & C)) == (~A | B) & (~A | C)
assert to_cnf(A & (B | C) | ~A & (B | C), True) == B | C
assert to_cnf(A & B) == And(A, B)
assert to_cnf(Equivalent(A, B)) == And(Or(A, Not(B)), Or(B, Not(A)))
assert to_cnf(Equivalent(A, B & C)) == \
(~A | B) & (~A | C) & (~B | ~C | A)
assert to_cnf(Equivalent(A, B | C), True) == \
And(Or(Not(B), A), Or(Not(C), A), Or(B, C, Not(A)))
assert to_cnf(A + 1) == A + 1
def test_to_CNF():
assert CNF.CNF_to_cnf(CNF.to_CNF(~(B | C))) == to_cnf(~(B | C))
assert CNF.CNF_to_cnf(CNF.to_CNF((A & B) | C)) == to_cnf((A & B) | C)
assert CNF.CNF_to_cnf(CNF.to_CNF(A >> B)) == to_cnf(A >> B)
assert CNF.CNF_to_cnf(CNF.to_CNF(A >> (B & C))) == to_cnf(A >> (B & C))
assert CNF.CNF_to_cnf(CNF.to_CNF(A & (B | C) | ~A & (B | C))) == to_cnf(A & (B | C) | ~A & (B | C))
assert CNF.CNF_to_cnf(CNF.to_CNF(A & B)) == to_cnf(A & B)
def test_to_dnf():
assert to_dnf(~(B | C)) == And(Not(B), Not(C))
assert to_dnf(A & (B | C)) == Or(And(A, B), And(A, C))
assert to_dnf(A >> B) == (~A) | B
assert to_dnf(A >> (B & C)) == (~A) | (B & C)
assert to_dnf(A | B) == A | B
assert to_dnf(Equivalent(A, B), True) == \
Or(And(A, B), And(Not(A), Not(B)))
assert to_dnf(Equivalent(A, B & C), True) == \
Or(And(A, B, C), And(Not(A), Not(B)), And(Not(A), Not(C)))
assert to_dnf(A + 1) == A + 1
def test_to_int_repr():
x, y, z = map(Boolean, symbols('x,y,z'))
def sorted_recursive(arg):
try:
return sorted(sorted_recursive(x) for x in arg)
except TypeError: # arg is not a sequence
return arg
assert sorted_recursive(to_int_repr([x | y, z | x], [x, y, z])) == \
sorted_recursive([[1, 2], [1, 3]])
assert sorted_recursive(to_int_repr([x | y, z | ~x], [x, y, z])) == \
sorted_recursive([[1, 2], [3, -1]])
def test_is_anf():
x, y = symbols('x,y')
assert is_anf(true) is True
assert is_anf(false) is True
assert is_anf(x) is True
assert is_anf(And(x, y)) is True
assert is_anf(Xor(x, y, And(x, y))) is True
assert is_anf(Xor(x, y, Or(x, y))) is False
assert is_anf(Xor(Not(x), y)) is False
def test_is_nnf():
assert is_nnf(true) is True
assert is_nnf(A) is True
assert is_nnf(~A) is True
assert is_nnf(A & B) is True
assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), False) is True
assert is_nnf((A | B) & (~A | ~B)) is True
assert is_nnf(Not(Or(A, B))) is False
assert is_nnf(A ^ B) is False
assert is_nnf((A & B) | (~A & A) | (~B & B) | (~A & ~B), True) is False
def test_is_cnf():
assert is_cnf(x) is True
assert is_cnf(x | y | z) is True
assert is_cnf(x & y & z) is True
assert is_cnf((x | y) & z) is True
assert is_cnf((x & y) | z) is False
assert is_cnf(~(x & y) | z) is False
def test_is_dnf():
assert is_dnf(x) is True
assert is_dnf(x | y | z) is True
assert is_dnf(x & y & z) is True
assert is_dnf((x & y) | z) is True
assert is_dnf((x | y) & z) is False
assert is_dnf(~(x | y) & z) is False
def test_ITE():
A, B, C = symbols('A:C')
assert ITE(True, False, True) is false
assert ITE(True, True, False) is true
assert ITE(False, True, False) is false
assert ITE(False, False, True) is true
assert isinstance(ITE(A, B, C), ITE)
A = True
assert ITE(A, B, C) == B
A = False
assert ITE(A, B, C) == C
B = True
assert ITE(And(A, B), B, C) == C
assert ITE(Or(A, False), And(B, True), False) is false
assert ITE(x, A, B) == Not(x)
assert ITE(x, B, A) == x
assert ITE(1, x, y) == x
assert ITE(0, x, y) == y
raises(TypeError, lambda: ITE(2, x, y))
raises(TypeError, lambda: ITE(1, [], y))
raises(TypeError, lambda: ITE(1, (), y))
raises(TypeError, lambda: ITE(1, y, []))
assert ITE(1, 1, 1) is S.true
assert isinstance(ITE(1, 1, 1, evaluate=False), ITE)
raises(TypeError, lambda: ITE(x > 1, y, x))
assert ITE(Eq(x, True), y, x) == ITE(x, y, x)
assert ITE(Eq(x, False), y, x) == ITE(~x, y, x)
assert ITE(Ne(x, True), y, x) == ITE(~x, y, x)
assert ITE(Ne(x, False), y, x) == ITE(x, y, x)
assert ITE(Eq(S. true, x), y, x) == ITE(x, y, x)
assert ITE(Eq(S.false, x), y, x) == ITE(~x, y, x)
assert ITE(Ne(S.true, x), y, x) == ITE(~x, y, x)
assert ITE(Ne(S.false, x), y, x) == ITE(x, y, x)
# 0 and 1 in the context are not treated as True/False
# so the equality must always be False since dissimilar
# objects cannot be equal
assert ITE(Eq(x, 0), y, x) == x
assert ITE(Eq(x, 1), y, x) == x
assert ITE(Ne(x, 0), y, x) == y
assert ITE(Ne(x, 1), y, x) == y
assert ITE(Eq(x, 0), y, z).subs(x, 0) == y
assert ITE(Eq(x, 0), y, z).subs(x, 1) == z
raises(ValueError, lambda: ITE(x > 1, y, x, z))
def test_is_literal():
assert is_literal(True) is True
assert is_literal(False) is True
assert is_literal(A) is True
assert is_literal(~A) is True
assert is_literal(Or(A, B)) is False
assert is_literal(Q.zero(A)) is True
assert is_literal(Not(Q.zero(A))) is True
assert is_literal(Or(A, B)) is False
assert is_literal(And(Q.zero(A), Q.zero(B))) is False
def test_operators():
# Mostly test __and__, __rand__, and so on
assert True & A == A & True == A
assert False & A == A & False == False
assert A & B == And(A, B)
assert True | A == A | True == True
assert False | A == A | False == A
assert A | B == Or(A, B)
assert ~A == Not(A)
assert True >> A == A << True == A
assert False >> A == A << False == True
assert A >> True == True << A == True
assert A >> False == False << A == ~A
assert A >> B == B << A == Implies(A, B)
assert True ^ A == A ^ True == ~A
assert False ^ A == A ^ False == A
assert A ^ B == Xor(A, B)
def test_true_false():
assert true is S.true
assert false is S.false
assert true is not True
assert false is not False
assert true
assert not false
assert true == True
assert false == False
assert not (true == False)
assert not (false == True)
assert not (true == false)
assert hash(true) == hash(True)
assert hash(false) == hash(False)
assert len({true, True}) == len({false, False}) == 1
assert isinstance(true, BooleanAtom)
assert isinstance(false, BooleanAtom)
# We don't want to subclass from bool, because bool subclasses from
# int. But operators like &, |, ^, <<, >>, and ~ act differently on 0 and
# 1 then we want them to on true and false. See the docstrings of the
# various And, Or, etc. functions for examples.
assert not isinstance(true, bool)
assert not isinstance(false, bool)
# Note: using 'is' comparison is important here. We want these to return
# true and false, not True and False
assert Not(true) is false
assert Not(True) is false
assert Not(false) is true
assert Not(False) is true
assert ~true is false
assert ~false is true
for T, F in cartes([True, true], [False, false]):
assert And(T, F) is false
assert And(F, T) is false
assert And(F, F) is false
assert And(T, T) is true
assert And(T, x) == x
assert And(F, x) is false
if not (T is True and F is False):
assert T & F is false
assert F & T is false
if F is not False:
assert F & F is false
if T is not True:
assert T & T is true
assert Or(T, F) is true
assert Or(F, T) is true
assert Or(F, F) is false
assert Or(T, T) is true
assert Or(T, x) is true
assert Or(F, x) == x
if not (T is True and F is False):
assert T | F is true
assert F | T is true
if F is not False:
assert F | F is false
if T is not True:
assert T | T is true
assert Xor(T, F) is true
assert Xor(F, T) is true
assert Xor(F, F) is false
assert Xor(T, T) is false
assert Xor(T, x) == ~x
assert Xor(F, x) == x
if not (T is True and F is False):
assert T ^ F is true
assert F ^ T is true
if F is not False:
assert F ^ F is false
if T is not True:
assert T ^ T is false
assert Nand(T, F) is true
assert Nand(F, T) is true
assert Nand(F, F) is true
assert Nand(T, T) is false
assert Nand(T, x) == ~x
assert Nand(F, x) is true
assert Nor(T, F) is false
assert Nor(F, T) is false
assert Nor(F, F) is true
assert Nor(T, T) is false
assert Nor(T, x) is false
assert Nor(F, x) == ~x
assert Implies(T, F) is false
assert Implies(F, T) is true
assert Implies(F, F) is true
assert Implies(T, T) is true
assert Implies(T, x) == x
assert Implies(F, x) is true
assert Implies(x, T) is true
assert Implies(x, F) == ~x
if not (T is True and F is False):
assert T >> F is false
assert F << T is false
assert F >> T is true
assert T << F is true
if F is not False:
assert F >> F is true
assert F << F is true
if T is not True:
assert T >> T is true
assert T << T is true
assert Equivalent(T, F) is false
assert Equivalent(F, T) is false
assert Equivalent(F, F) is true
assert Equivalent(T, T) is true
assert Equivalent(T, x) == x
assert Equivalent(F, x) == ~x
assert Equivalent(x, T) == x
assert Equivalent(x, F) == ~x
assert ITE(T, T, T) is true
assert ITE(T, T, F) is true
assert ITE(T, F, T) is false
assert ITE(T, F, F) is false
assert ITE(F, T, T) is true
assert ITE(F, T, F) is false
assert ITE(F, F, T) is true
assert ITE(F, F, F) is false
assert all(i.simplify(1, 2) is i for i in (S.true, S.false))
def test_bool_as_set():
assert ITE(y <= 0, False, y >= 1).as_set() == Interval(1, oo)
assert And(x <= 2, x >= -2).as_set() == Interval(-2, 2)
assert Or(x >= 2, x <= -2).as_set() == Interval(-oo, -2) + Interval(2, oo)
assert Not(x > 2).as_set() == Interval(-oo, 2)
# issue 10240
assert Not(And(x > 2, x < 3)).as_set() == \
Union(Interval(-oo, 2), Interval(3, oo))
assert true.as_set() == S.UniversalSet
assert false.as_set() == EmptySet()
assert x.as_set() == S.UniversalSet
assert And(Or(x < 1, x > 3), x < 2).as_set() == Interval.open(-oo, 1)
assert And(x < 1, sin(x) < 3).as_set() == (x < 1).as_set()
raises(NotImplementedError, lambda: (sin(x) < 1).as_set())
@XFAIL
def test_multivariate_bool_as_set():
x, y = symbols('x,y')
assert And(x >= 0, y >= 0).as_set() == Interval(0, oo)*Interval(0, oo)
assert Or(x >= 0, y >= 0).as_set() == S.Reals*S.Reals - \
Interval(-oo, 0, True, True)*Interval(-oo, 0, True, True)
def test_all_or_nothing():
x = symbols('x', extended_real=True)
args = x >= -oo, x <= oo
v = And(*args)
if v.func is And:
assert len(v.args) == len(args) - args.count(S.true)
else:
assert v == True
v = Or(*args)
if v.func is Or:
assert len(v.args) == 2
else:
assert v == True
def test_canonical_atoms():
assert true.canonical == true
assert false.canonical == false
def test_negated_atoms():
assert true.negated == false
assert false.negated == true
def test_issue_8777():
assert And(x > 2, x < oo).as_set() == Interval(2, oo, left_open=True)
assert And(x >= 1, x < oo).as_set() == Interval(1, oo)
assert (x < oo).as_set() == Interval(-oo, oo)
assert (x > -oo).as_set() == Interval(-oo, oo)
def test_issue_8975():
assert Or(And(-oo < x, x <= -2), And(2 <= x, x < oo)).as_set() == \
Interval(-oo, -2) + Interval(2, oo)
def test_term_to_integer():
assert term_to_integer([1, 0, 1, 0, 0, 1, 0]) == 82
assert term_to_integer('0010101000111001') == 10809
def test_integer_to_term():
assert integer_to_term(777) == [1, 1, 0, 0, 0, 0, 1, 0, 0, 1]
assert integer_to_term(123, 3) == [1, 1, 1, 1, 0, 1, 1]
assert integer_to_term(456, 16) == [0, 0, 0, 0, 0, 0, 0, 1,
1, 1, 0, 0, 1, 0, 0, 0]
def test_truth_table():
assert list(truth_table(And(x, y), [x, y], input=False)) == \
[False, False, False, True]
assert list(truth_table(x | y, [x, y], input=False)) == \
[False, True, True, True]
assert list(truth_table(x >> y, [x, y], input=False)) == \
[True, True, False, True]
assert list(truth_table(And(x, y), [x, y])) == \
[([0, 0], False), ([0, 1], False), ([1, 0], False), ([1, 1], True)]
def test_issue_8571():
for t in (S.true, S.false):
raises(TypeError, lambda: +t)
raises(TypeError, lambda: -t)
raises(TypeError, lambda: abs(t))
# use int(bool(t)) to get 0 or 1
raises(TypeError, lambda: int(t))
for o in [S.Zero, S.One, x]:
for _ in range(2):
raises(TypeError, lambda: o + t)
raises(TypeError, lambda: o - t)
raises(TypeError, lambda: o % t)
raises(TypeError, lambda: o*t)
raises(TypeError, lambda: o/t)
raises(TypeError, lambda: o**t)
o, t = t, o # do again in reversed order
def test_expand_relational():
n = symbols('n', negative=True)
p, q = symbols('p q', positive=True)
r = ((n + q*(-n/q + 1))/(q*(-n/q + 1)) < 0)
assert r is not S.false
assert r.expand() is S.false
assert (q > 0).expand() is S.true
def test_issue_12717():
assert S.true.is_Atom == True
assert S.false.is_Atom == True
def test_as_Boolean():
nz = symbols('nz', nonzero=True)
assert all(as_Boolean(i) is S.true for i in (True, S.true, 1, nz))
z = symbols('z', zero=True)
assert all(as_Boolean(i) is S.false for i in (False, S.false, 0, z))
assert all(as_Boolean(i) == i for i in (x, x < 0))
for i in (2, S(2), x + 1, []):
raises(TypeError, lambda: as_Boolean(i))
def test_binary_symbols():
assert ITE(x < 1, y, z).binary_symbols == set((y, z))
for f in (Eq, Ne):
assert f(x, 1).binary_symbols == set()
assert f(x, True).binary_symbols == set([x])
assert f(x, False).binary_symbols == set([x])
assert S.true.binary_symbols == set()
assert S.false.binary_symbols == set()
assert x.binary_symbols == set([x])
assert And(x, Eq(y, False), Eq(z, 1)).binary_symbols == set([x, y])
assert Q.prime(x).binary_symbols == set()
assert Q.is_true(x < 1).binary_symbols == set()
assert Q.is_true(x).binary_symbols == set([x])
assert Q.is_true(Eq(x, True)).binary_symbols == set([x])
assert Q.prime(x).binary_symbols == set()
def test_BooleanFunction_diff():
assert And(x, y).diff(x) == Piecewise((0, Eq(y, False)), (1, True))
def test_issue_14700():
A, B, C, D, E, F, G, H = symbols('A B C D E F G H')
q = ((B & D & H & ~F) | (B & H & ~C & ~D) | (B & H & ~C & ~F) |
(B & H & ~D & ~G) | (B & H & ~F & ~G) | (C & G & ~B & ~D) |
(C & G & ~D & ~H) | (C & G & ~F & ~H) | (D & F & H & ~B) |
(D & F & ~G & ~H) | (B & D & F & ~C & ~H) | (D & E & F & ~B & ~C) |
(D & F & ~A & ~B & ~C) | (D & F & ~A & ~C & ~H) |
(A & B & D & F & ~E & ~H))
soldnf = ((B & D & H & ~F) | (D & F & H & ~B) | (B & H & ~C & ~D) |
(B & H & ~D & ~G) | (C & G & ~B & ~D) | (C & G & ~D & ~H) |
(C & G & ~F & ~H) | (D & F & ~G & ~H) | (D & E & F & ~C & ~H) |
(D & F & ~A & ~C & ~H) | (A & B & D & F & ~E & ~H))
solcnf = ((B | C | D) & (B | D | G) & (C | D | H) & (C | F | H) &
(D | G | H) & (F | G | H) & (B | F | ~D | ~H) &
(~B | ~D | ~F | ~H) & (D | ~B | ~C | ~G | ~H) &
(A | H | ~C | ~D | ~F | ~G) & (H | ~C | ~D | ~E | ~F | ~G) &
(B | E | H | ~A | ~D | ~F | ~G))
assert simplify_logic(q, "dnf") == soldnf
assert simplify_logic(q, "cnf") == solcnf
minterms = [[0, 1, 0, 0], [0, 1, 0, 1], [0, 1, 1, 0], [0, 1, 1, 1],
[0, 0, 1, 1], [1, 0, 1, 1]]
dontcares = [[1, 0, 0, 0], [1, 0, 0, 1], [1, 1, 0, 0], [1, 1, 0, 1]]
assert SOPform([w, x, y, z], minterms) == (x & ~w) | (y & z & ~x)
# Should not be more complicated with don't cares
assert SOPform([w, x, y, z], minterms, dontcares) == \
(x & ~w) | (y & z & ~x)
def test_relational_simplification():
w, x, y, z = symbols('w x y z', real=True)
d, e = symbols('d e', real=False)
# Test all combinations or sign and order
assert Or(x >= y, x < y).simplify() == S.true
assert Or(x >= y, y > x).simplify() == S.true
assert Or(x >= y, -x > -y).simplify() == S.true
assert Or(x >= y, -y < -x).simplify() == S.true
assert Or(-x <= -y, x < y).simplify() == S.true
assert Or(-x <= -y, -x > -y).simplify() == S.true
assert Or(-x <= -y, y > x).simplify() == S.true
assert Or(-x <= -y, -y < -x).simplify() == S.true
assert Or(y <= x, x < y).simplify() == S.true
assert Or(y <= x, y > x).simplify() == S.true
assert Or(y <= x, -x > -y).simplify() == S.true
assert Or(y <= x, -y < -x).simplify() == S.true
assert Or(-y >= -x, x < y).simplify() == S.true
assert Or(-y >= -x, y > x).simplify() == S.true
assert Or(-y >= -x, -x > -y).simplify() == S.true
assert Or(-y >= -x, -y < -x).simplify() == S.true
assert Or(x < y, x >= y).simplify() == S.true
assert Or(y > x, x >= y).simplify() == S.true
assert Or(-x > -y, x >= y).simplify() == S.true
assert Or(-y < -x, x >= y).simplify() == S.true
assert Or(x < y, -x <= -y).simplify() == S.true
assert Or(-x > -y, -x <= -y).simplify() == S.true
assert Or(y > x, -x <= -y).simplify() == S.true
assert Or(-y < -x, -x <= -y).simplify() == S.true
assert Or(x < y, y <= x).simplify() == S.true
assert Or(y > x, y <= x).simplify() == S.true
assert Or(-x > -y, y <= x).simplify() == S.true
assert Or(-y < -x, y <= x).simplify() == S.true
assert Or(x < y, -y >= -x).simplify() == S.true
assert Or(y > x, -y >= -x).simplify() == S.true
assert Or(-x > -y, -y >= -x).simplify() == S.true
assert Or(-y < -x, -y >= -x).simplify() == S.true
# Some other tests
assert Or(x >= y, w < z, x <= y).simplify() == S.true
assert And(x >= y, x < y).simplify() == S.false
assert Or(x >= y, Eq(y, x)).simplify() == (x >= y)
assert And(x >= y, Eq(y, x)).simplify() == Eq(x, y)
assert Or(Eq(x, y), x >= y, w < y, z < y).simplify() == \
Or(x >= y, y > Min(w, z))
assert And(Eq(x, y), x >= y, w < y, y >= z, z < y).simplify() == \
And(Eq(x, y), y > Max(w, z))
assert Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
(Eq(x, y) | (x >= 1) | (y > Min(2, z)))
assert And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y).simplify() == \
(Eq(x, y) & (x >= 1) & (y >= 5) & (y > z))
assert (Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)).simplify() == \
(Eq(x, y) & Eq(d, e) & (d >= e))
assert And(Eq(x, y), Eq(x, -y)).simplify() == And(Eq(x, 0), Eq(y, 0))
assert Xor(x >= y, x <= y).simplify() == Ne(x, y)
@slow
def test_relational_simplification_numerically():
def test_simplification_numerically_function(original, simplified):
symb = original.free_symbols
n = len(symb)
valuelist = list(set(list(combinations(list(range(-(n-1), n))*n, n))))
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.subs(sublist)
simplifiedvalue = simplified.subs(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for {}"\
"".format(original, simplified, sublist)
w, x, y, z = symbols('w x y z', real=True)
d, e = symbols('d e', real=False)
expressions = (And(Eq(x, y), x >= y, w < y, y >= z, z < y),
And(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
Or(Eq(x, y), x >= 1, 2 < y, y >= 5, z < y),
And(x >= y, Eq(y, x)),
Or(And(Eq(x, y), x >= y, w < y, Or(y >= z, z < y)),
And(Eq(x, y), x >= 1, 2 < y, y >= -1, z < y)),
(Eq(x, y) & Eq(d, e) & (x >= y) & (d >= e)),
)
for expression in expressions:
test_simplification_numerically_function(expression,
expression.simplify())
def test_relational_simplification_patterns_numerically():
from sympy.core import Wild
from sympy.logic.boolalg import simplify_patterns_and, \
simplify_patterns_or, simplify_patterns_xor
a = Wild('a')
b = Wild('b')
c = Wild('c')
symb = [a, b, c]
patternlists = [simplify_patterns_and(), simplify_patterns_or(),
simplify_patterns_xor()]
for patternlist in patternlists:
for pattern in patternlist:
original = pattern[0]
simplified = pattern[1]
valuelist = list(set(list(combinations(list(range(-2, 2))*3, 3))))
for values in valuelist:
sublist = dict(zip(symb, values))
originalvalue = original.subs(sublist)
simplifiedvalue = simplified.subs(sublist)
assert originalvalue == simplifiedvalue, "Original: {}\nand"\
" simplified: {}\ndo not evaluate to the same value for"\
"{}".format(original, simplified, sublist)
def test_issue_16803():
n = symbols('n')
# No simplification done, but should not raise an exception
assert ((n > 3) | (n < 0) | ((n > 0) & (n < 3))).simplify() == \
((n > 3) | (n < 0) | ((n > 0) & (n < 3)))
def test_issue_17530():
r = {x: oo, y: oo}
assert Or(x + y > 0, x - y < 0).subs(r)
assert not And(x + y < 0, x - y < 0).subs(r)
raises(TypeError, lambda: Or(x + y < 0, x - y < 0).subs(r))
raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
raises(TypeError, lambda: And(x + y > 0, x - y < 0).subs(r))
def test_anf_coeffs():
assert anf_coeffs([1, 0]) == [1, 1]
assert anf_coeffs([0, 0, 0, 1]) == [0, 0, 0, 1]
assert anf_coeffs([0, 1, 1, 1]) == [0, 1, 1, 1]
assert anf_coeffs([1, 1, 1, 0]) == [1, 0, 0, 1]
assert anf_coeffs([1, 0, 0, 0]) == [1, 1, 1, 1]
assert anf_coeffs([1, 0, 0, 1]) == [1, 1, 1, 0]
assert anf_coeffs([1, 1, 0, 1]) == [1, 0, 1, 1]
def test_ANFform():
x, y = symbols('x,y')
assert ANFform([x], [1, 1]) == True
assert ANFform([x], [0, 0]) == False
assert ANFform([x], [1, 0]) == Xor(x, True, remove_true=False)
assert ANFform([x, y], [1, 1, 1, 0]) == \
Xor(True, And(x, y), remove_true=False)
def test_bool_minterm():
x, y = symbols('x,y')
assert bool_minterm(3, [x, y]) == And(x, y)
assert bool_minterm([1, 0], [x, y]) == And(Not(y), x)
def test_bool_maxterm():
x, y = symbols('x,y')
assert bool_maxterm(2, [x, y]) == Or(Not(x), y)
assert bool_maxterm([0, 1], [x, y]) == Or(Not(y), x)
def test_bool_monomial():
x, y = symbols('x,y')
assert bool_monomial(1, [x, y]) == y
assert bool_monomial([1, 1], [x, y]) == And(x, y)
|
de76f9db053f7234a2162f34205f15fd3b420baef2f7c9aea550b8f5aa0e2338 | """For more tests on satisfiability, see test_dimacs"""
from sympy import symbols, Q
from sympy.logic.boolalg import And, Implies, Equivalent, true, false
from sympy.logic.inference import literal_symbol, \
pl_true, satisfiable, valid, entails, PropKB
from sympy.logic.algorithms.dpll import dpll, dpll_satisfiable, \
find_pure_symbol, find_unit_clause, unit_propagate, \
find_pure_symbol_int_repr, find_unit_clause_int_repr, \
unit_propagate_int_repr
from sympy.logic.algorithms.dpll2 import dpll_satisfiable as dpll2_satisfiable
from sympy.testing.pytest import raises
def test_literal():
A, B = symbols('A,B')
assert literal_symbol(True) is True
assert literal_symbol(False) is False
assert literal_symbol(A) is A
assert literal_symbol(~A) is A
def test_find_pure_symbol():
A, B, C = symbols('A,B,C')
assert find_pure_symbol([A], [A]) == (A, True)
assert find_pure_symbol([A, B], [~A | B, ~B | A]) == (None, None)
assert find_pure_symbol([A, B, C], [ A | ~B, ~B | ~C, C | A]) == (A, True)
assert find_pure_symbol([A, B, C], [~A | B, B | ~C, C | A]) == (B, True)
assert find_pure_symbol([A, B, C], [~A | ~B, ~B | ~C, C | A]) == (B, False)
assert find_pure_symbol(
[A, B, C], [~A | B, ~B | ~C, C | A]) == (None, None)
def test_find_pure_symbol_int_repr():
assert find_pure_symbol_int_repr([1], [set([1])]) == (1, True)
assert find_pure_symbol_int_repr([1, 2],
[set([-1, 2]), set([-2, 1])]) == (None, None)
assert find_pure_symbol_int_repr([1, 2, 3],
[set([1, -2]), set([-2, -3]), set([3, 1])]) == (1, True)
assert find_pure_symbol_int_repr([1, 2, 3],
[set([-1, 2]), set([2, -3]), set([3, 1])]) == (2, True)
assert find_pure_symbol_int_repr([1, 2, 3],
[set([-1, -2]), set([-2, -3]), set([3, 1])]) == (2, False)
assert find_pure_symbol_int_repr([1, 2, 3],
[set([-1, 2]), set([-2, -3]), set([3, 1])]) == (None, None)
def test_unit_clause():
A, B, C = symbols('A,B,C')
assert find_unit_clause([A], {}) == (A, True)
assert find_unit_clause([A, ~A], {}) == (A, True) # Wrong ??
assert find_unit_clause([A | B], {A: True}) == (B, True)
assert find_unit_clause([A | B], {B: True}) == (A, True)
assert find_unit_clause(
[A | B | C, B | ~C, A | ~B], {A: True}) == (B, False)
assert find_unit_clause([A | B | C, B | ~C, A | B], {A: True}) == (B, True)
assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
def test_unit_clause_int_repr():
assert find_unit_clause_int_repr(map(set, [[1]]), {}) == (1, True)
assert find_unit_clause_int_repr(map(set, [[1], [-1]]), {}) == (1, True)
assert find_unit_clause_int_repr([set([1, 2])], {1: True}) == (2, True)
assert find_unit_clause_int_repr([set([1, 2])], {2: True}) == (1, True)
assert find_unit_clause_int_repr(map(set,
[[1, 2, 3], [2, -3], [1, -2]]), {1: True}) == (2, False)
assert find_unit_clause_int_repr(map(set,
[[1, 2, 3], [3, -3], [1, 2]]), {1: True}) == (2, True)
A, B, C = symbols('A,B,C')
assert find_unit_clause([A | B | C, B | ~C, A ], {}) == (A, True)
def test_unit_propagate():
A, B, C = symbols('A,B,C')
assert unit_propagate([A | B], A) == []
assert unit_propagate([A | B, ~A | C, ~C | B, A], A) == [C, ~C | B, A]
def test_unit_propagate_int_repr():
assert unit_propagate_int_repr([set([1, 2])], 1) == []
assert unit_propagate_int_repr(map(set,
[[1, 2], [-1, 3], [-3, 2], [1]]), 1) == [set([3]), set([-3, 2])]
def test_dpll():
"""This is also tested in test_dimacs"""
A, B, C = symbols('A,B,C')
assert dpll([A | B], [A, B], {A: True, B: True}) == {A: True, B: True}
def test_dpll_satisfiable():
A, B, C = symbols('A,B,C')
assert dpll_satisfiable( A & ~A ) is False
assert dpll_satisfiable( A & ~B ) == {A: True, B: False}
assert dpll_satisfiable(
A | B ) in ({A: True}, {B: True}, {A: True, B: True})
assert dpll_satisfiable(
(~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
assert dpll_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False},
{A: True, C: True}, {B: True, C: True})
assert dpll_satisfiable( A & B & C ) == {A: True, B: True, C: True}
assert dpll_satisfiable( (A | B) & (A >> B) ) == {B: True}
assert dpll_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
assert dpll_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
def test_dpll2_satisfiable():
A, B, C = symbols('A,B,C')
assert dpll2_satisfiable( A & ~A ) is False
assert dpll2_satisfiable( A & ~B ) == {A: True, B: False}
assert dpll2_satisfiable(
A | B ) in ({A: True}, {B: True}, {A: True, B: True})
assert dpll2_satisfiable(
(~A | B) & (~B | A) ) in ({A: True, B: True}, {A: False, B: False})
assert dpll2_satisfiable( (A | B) & (~B | C) ) in ({A: True, B: False, C: True},
{A: True, B: True, C: True})
assert dpll2_satisfiable( A & B & C ) == {A: True, B: True, C: True}
assert dpll2_satisfiable( (A | B) & (A >> B) ) in ({B: True, A: False},
{B: True, A: True})
assert dpll2_satisfiable( Equivalent(A, B) & A ) == {A: True, B: True}
assert dpll2_satisfiable( Equivalent(A, B) & ~A ) == {A: False, B: False}
def test_satisfiable():
A, B, C = symbols('A,B,C')
assert satisfiable(A & (A >> B) & ~B) is False
def test_valid():
A, B, C = symbols('A,B,C')
assert valid(A >> (B >> A)) is True
assert valid((A >> (B >> C)) >> ((A >> B) >> (A >> C))) is True
assert valid((~B >> ~A) >> (A >> B)) is True
assert valid(A | B | C) is False
assert valid(A >> B) is False
def test_pl_true():
A, B, C = symbols('A,B,C')
assert pl_true(True) is True
assert pl_true( A & B, {A: True, B: True}) is True
assert pl_true( A | B, {A: True}) is True
assert pl_true( A | B, {B: True}) is True
assert pl_true( A | B, {A: None, B: True}) is True
assert pl_true( A >> B, {A: False}) is True
assert pl_true( A | B | ~C, {A: False, B: True, C: True}) is True
assert pl_true(Equivalent(A, B), {A: False, B: False}) is True
# test for false
assert pl_true(False) is False
assert pl_true( A & B, {A: False, B: False}) is False
assert pl_true( A & B, {A: False}) is False
assert pl_true( A & B, {B: False}) is False
assert pl_true( A | B, {A: False, B: False}) is False
#test for None
assert pl_true(B, {B: None}) is None
assert pl_true( A & B, {A: True, B: None}) is None
assert pl_true( A >> B, {A: True, B: None}) is None
assert pl_true(Equivalent(A, B), {A: None}) is None
assert pl_true(Equivalent(A, B), {A: True, B: None}) is None
# Test for deep
assert pl_true(A | B, {A: False}, deep=True) is None
assert pl_true(~A & ~B, {A: False}, deep=True) is None
assert pl_true(A | B, {A: False, B: False}, deep=True) is False
assert pl_true(A & B & (~A | ~B), {A: True}, deep=True) is False
assert pl_true((C >> A) >> (B >> A), {C: True}, deep=True) is True
def test_pl_true_wrong_input():
from sympy import pi
raises(ValueError, lambda: pl_true('John Cleese'))
raises(ValueError, lambda: pl_true(42 + pi + pi ** 2))
raises(ValueError, lambda: pl_true(42))
def test_entails():
A, B, C = symbols('A, B, C')
assert entails(A, [A >> B, ~B]) is False
assert entails(B, [Equivalent(A, B), A]) is True
assert entails((A >> B) >> (~A >> ~B)) is False
assert entails((A >> B) >> (~B >> ~A)) is True
def test_PropKB():
A, B, C = symbols('A,B,C')
kb = PropKB()
assert kb.ask(A >> B) is False
assert kb.ask(A >> (B >> A)) is True
kb.tell(A >> B)
kb.tell(B >> C)
assert kb.ask(A) is False
assert kb.ask(B) is False
assert kb.ask(C) is False
assert kb.ask(~A) is False
assert kb.ask(~B) is False
assert kb.ask(~C) is False
assert kb.ask(A >> C) is True
kb.tell(A)
assert kb.ask(A) is True
assert kb.ask(B) is True
assert kb.ask(C) is True
assert kb.ask(~C) is False
kb.retract(A)
assert kb.ask(C) is False
def test_propKB_tolerant():
""""tolerant to bad input"""
kb = PropKB()
A, B, C = symbols('A,B,C')
assert kb.ask(B) is False
def test_satisfiable_non_symbols():
x, y = symbols('x y')
assumptions = Q.zero(x*y)
facts = Implies(Q.zero(x*y), Q.zero(x) | Q.zero(y))
query = ~Q.zero(x) & ~Q.zero(y)
refutations = [
{Q.zero(x): True, Q.zero(x*y): True},
{Q.zero(y): True, Q.zero(x*y): True},
{Q.zero(x): True, Q.zero(y): True, Q.zero(x*y): True},
{Q.zero(x): True, Q.zero(y): False, Q.zero(x*y): True},
{Q.zero(x): False, Q.zero(y): True, Q.zero(x*y): True}]
assert not satisfiable(And(assumptions, facts, query), algorithm='dpll')
assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll') in refutations
assert not satisfiable(And(assumptions, facts, query), algorithm='dpll2')
assert satisfiable(And(assumptions, facts, ~query), algorithm='dpll2') in refutations
def test_satisfiable_bool():
from sympy.core.singleton import S
assert satisfiable(true) == {true: true}
assert satisfiable(S.true) == {true: true}
assert satisfiable(false) is False
assert satisfiable(S.false) is False
def test_satisfiable_all_models():
from sympy.abc import A, B
assert next(satisfiable(False, all_models=True)) is False
assert list(satisfiable((A >> ~A) & A , all_models=True)) == [False]
assert list(satisfiable(True, all_models=True)) == [{true: true}]
models = [{A: True, B: False}, {A: False, B: True}]
result = satisfiable(A ^ B, all_models=True)
models.remove(next(result))
models.remove(next(result))
raises(StopIteration, lambda: next(result))
assert not models
assert list(satisfiable(Equivalent(A, B), all_models=True)) == \
[{A: False, B: False}, {A: True, B: True}]
models = [{A: False, B: False}, {A: False, B: True}, {A: True, B: True}]
for model in satisfiable(A >> B, all_models=True):
models.remove(model)
assert not models
# This is a santiy test to check that only the required number
# of solutions are generated. The expr below has 2**100 - 1 models
# which would time out the test if all are generated at once.
from sympy import numbered_symbols
from sympy.logic.boolalg import Or
sym = numbered_symbols()
X = [next(sym) for i in range(100)]
result = satisfiable(Or(*X), all_models=True)
for i in range(10):
assert next(result)
|
fe3d673bb20bc793e481eb926404e80bfe2b7067b88e0ed4bda898e3bf0895a3 | from sympy import (
Rational, Poly, Symbol, N, I, Abs, sqrt, exp, Float, sin,
cos, symbols)
from sympy.matrices import eye, Matrix
from sympy.matrices.matrices import MatrixEigen
from sympy.matrices.common import _MinimalMatrix, _CastableMatrix
from sympy.abc import x, y
from sympy.core.singleton import S
from sympy.testing.pytest import raises, XFAIL
from sympy.matrices.matrices import NonSquareMatrixError, MatrixError
from sympy.simplify.simplify import simplify
class EigenOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixEigen):
pass
def test_eigen():
R = Rational
assert eye(3).charpoly(x) == Poly((x - 1)**3, x)
assert eye(3).charpoly(y) == Poly((y - 1)**3, y)
M = Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
assert M.eigenvals(multiple=False) == {S.One: 3}
assert M.eigenvals(multiple=True) == [1, 1, 1]
assert M.eigenvects() == (
[(1, 3, [Matrix([1, 0, 0]),
Matrix([0, 1, 0]),
Matrix([0, 0, 1])])])
assert M.left_eigenvects() == (
[(1, 3, [Matrix([[1, 0, 0]]),
Matrix([[0, 1, 0]]),
Matrix([[0, 0, 1]])])])
M = Matrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
assert M.eigenvals() == {2*S.One: 1, -S.One: 1, S.Zero: 1}
assert M.eigenvects() == (
[
(-1, 1, [Matrix([-1, 1, 0])]),
( 0, 1, [Matrix([0, -1, 1])]),
( 2, 1, [Matrix([R(2, 3), R(1, 3), 1])])
])
assert M.left_eigenvects() == (
[
(-1, 1, [Matrix([[-2, 1, 1]])]),
(0, 1, [Matrix([[-1, -1, 1]])]),
(2, 1, [Matrix([[1, 1, 1]])])
])
a = Symbol('a')
M = Matrix([[a, 0],
[0, 1]])
assert M.eigenvals() == {a: 1, S.One: 1}
M = Matrix([[1, -1],
[1, 3]])
assert M.eigenvects() == ([(2, 2, [Matrix(2, 1, [-1, 1])])])
assert M.left_eigenvects() == ([(2, 2, [Matrix([[1, 1]])])])
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
a = R(15, 2)
b = 3*33**R(1, 2)
c = R(13, 2)
d = (R(33, 8) + 3*b/8)
e = (R(33, 8) - 3*b/8)
def NS(e, n):
return str(N(e, n))
r = [
(a - b/2, 1, [Matrix([(12 + 24/(c - b/2))/((c - b/2)*e) + 3/(c - b/2),
(6 + 12/(c - b/2))/e, 1])]),
( 0, 1, [Matrix([1, -2, 1])]),
(a + b/2, 1, [Matrix([(12 + 24/(c + b/2))/((c + b/2)*d) + 3/(c + b/2),
(6 + 12/(c + b/2))/d, 1])]),
]
r1 = [(NS(r[i][0], 2), NS(r[i][1], 2),
[NS(j, 2) for j in r[i][2][0]]) for i in range(len(r))]
r = M.eigenvects()
r2 = [(NS(r[i][0], 2), NS(r[i][1], 2),
[NS(j, 2) for j in r[i][2][0]]) for i in range(len(r))]
assert sorted(r1) == sorted(r2)
eps = Symbol('eps', real=True)
M = Matrix([[abs(eps), I*eps ],
[-I*eps, abs(eps) ]])
assert M.eigenvects() == (
[
( 0, 1, [Matrix([[-I*eps/abs(eps)], [1]])]),
( 2*abs(eps), 1, [ Matrix([[I*eps/abs(eps)], [1]]) ] ),
])
assert M.left_eigenvects() == (
[
(0, 1, [Matrix([[I*eps/Abs(eps), 1]])]),
(2*Abs(eps), 1, [Matrix([[-I*eps/Abs(eps), 1]])])
])
M = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
M._eigenvects = M.eigenvects(simplify=False)
assert max(i.q for i in M._eigenvects[0][2][0]) > 1
M._eigenvects = M.eigenvects(simplify=True)
assert max(i.q for i in M._eigenvects[0][2][0]) == 1
M = Matrix([[Rational(1, 4), 1], [1, 1]])
assert M.eigenvects(simplify=True) == [
(Rational(5, 8) - sqrt(73)/8, 1, [Matrix([[-sqrt(73)/8 - Rational(3, 8)], [1]])]),
(Rational(5, 8) + sqrt(73)/8, 1, [Matrix([[Rational(-3, 8) + sqrt(73)/8], [1]])])]
assert M.eigenvects(simplify=False) == [
(Rational(5, 8) - sqrt(73)/8, 1, [Matrix([[-1/(-Rational(3, 8) + sqrt(73)/8)], [1]])]),
(Rational(5, 8) + sqrt(73)/8, 1, [Matrix([[8/(3 + sqrt(73))], [1]])])]
m = Matrix([[1, .6, .6], [.6, .9, .9], [.9, .6, .6]])
evals = { Rational(5, 4) - sqrt(385)/20: 1, sqrt(385)/20 + Rational(5, 4): 1, S.Zero: 1}
assert m.eigenvals() == evals
nevals = list(sorted(m.eigenvals(rational=False).keys()))
sevals = list(sorted(evals.keys()))
assert all(abs(nevals[i] - sevals[i]) < 1e-9 for i in range(len(nevals)))
# issue 10719
assert Matrix([]).eigenvals() == {}
assert Matrix([]).eigenvects() == []
# issue 15119
raises(NonSquareMatrixError, lambda : Matrix([[1, 2], [0, 4], [0, 0]]).eigenvals())
raises(NonSquareMatrixError, lambda : Matrix([[1, 0], [3, 4], [5, 6]]).eigenvals())
raises(NonSquareMatrixError, lambda : Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals())
raises(NonSquareMatrixError, lambda : Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals())
raises(NonSquareMatrixError, lambda : Matrix([[1, 2, 3], [0, 5, 6]]).eigenvals(error_when_incomplete = False))
raises(NonSquareMatrixError, lambda : Matrix([[1, 0, 0], [4, 5, 0]]).eigenvals(error_when_incomplete = False))
# issue 15125
from sympy.core.function import count_ops
q = Symbol("q", positive = True)
m = Matrix([[-2, exp(-q), 1], [exp(q), -2, 1], [1, 1, -2]])
assert count_ops(m.eigenvals(simplify=False)) > count_ops(m.eigenvals(simplify=True))
assert count_ops(m.eigenvals(simplify=lambda x: x)) > count_ops(m.eigenvals(simplify=True))
assert isinstance(m.eigenvals(simplify=True, multiple=False), dict)
assert isinstance(m.eigenvals(simplify=True, multiple=True), list)
assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=False), dict)
assert isinstance(m.eigenvals(simplify=lambda x: x, multiple=True), list)
@XFAIL
def test_eigen_vects():
m = Matrix(2, 2, [1, 0, 0, I])
raises(NotImplementedError, lambda: m.is_diagonalizable(True))
# !!! bug because of eigenvects() or roots(x**2 + (-1 - I)*x + I, x)
# see issue 5292
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
(P, D) = m.diagonalize(True)
def test_issue_8240():
# Eigenvalues of large triangular matrices
n = 200
diagonal_variables = [Symbol('x%s' % i) for i in range(n)]
M = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
M[i][i] = diagonal_variables[i]
M = Matrix(M)
eigenvals = M.eigenvals()
assert len(eigenvals) == n
for i in range(n):
assert eigenvals[diagonal_variables[i]] == 1
eigenvals = M.eigenvals(multiple=True)
assert set(eigenvals) == set(diagonal_variables)
# with multiplicity
M = Matrix([[x, 0, 0], [1, y, 0], [2, 3, x]])
eigenvals = M.eigenvals()
assert eigenvals == {x: 2, y: 1}
eigenvals = M.eigenvals(multiple=True)
assert len(eigenvals) == 3
assert eigenvals.count(x) == 2
assert eigenvals.count(y) == 1
# EigenOnlyMatrix tests
def test_eigenvals():
M = EigenOnlyMatrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
assert M.eigenvals() == {2*S.One: 1, -S.One: 1, S.Zero: 1}
# if we cannot factor the char poly, we raise an error
m = Matrix([
[3, 0, 0, 0, -3],
[0, -3, -3, 0, 3],
[0, 3, 0, 3, 0],
[0, 0, 3, 0, 3],
[3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m.eigenvals())
def test_eigenvects():
M = EigenOnlyMatrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
vecs = M.eigenvects()
for val, mult, vec_list in vecs:
assert len(vec_list) == 1
assert M*vec_list[0] == val*vec_list[0]
def test_left_eigenvects():
M = EigenOnlyMatrix([[0, 1, 1],
[1, 0, 0],
[1, 1, 1]])
vecs = M.left_eigenvects()
for val, mult, vec_list in vecs:
assert len(vec_list) == 1
assert vec_list[0]*M == val*vec_list[0]
def test_diagonalize():
m = EigenOnlyMatrix(2, 2, [0, -1, 1, 0])
raises(MatrixError, lambda: m.diagonalize(reals_only=True))
P, D = m.diagonalize()
assert D.is_diagonal()
assert D == Matrix([
[-I, 0],
[ 0, I]])
# make sure we use floats out if floats are passed in
m = EigenOnlyMatrix(2, 2, [0, .5, .5, 0])
P, D = m.diagonalize()
assert all(isinstance(e, Float) for e in D.values())
assert all(isinstance(e, Float) for e in P.values())
_, D2 = m.diagonalize(reals_only=True)
assert D == D2
def test_is_diagonalizable():
a, b, c = symbols('a b c')
m = EigenOnlyMatrix(2, 2, [a, c, c, b])
assert m.is_symmetric()
assert m.is_diagonalizable()
assert not EigenOnlyMatrix(2, 2, [1, 1, 0, 1]).is_diagonalizable()
m = EigenOnlyMatrix(2, 2, [0, -1, 1, 0])
assert m.is_diagonalizable()
assert not m.is_diagonalizable(reals_only=True)
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: m.jordan_form())
# the next two tests test the cases where the old
# algorithm failed due to the fact that the block structure can
# *NOT* be determined from algebraic and geometric multiplicity alone
# This can be seen most easily when one lets compute the J.c.f. of a matrix that
# is in J.c.f already.
m = EigenOnlyMatrix(4, 4, [2, 1, 0, 0,
0, 2, 1, 0,
0, 0, 2, 0,
0, 0, 0, 2
])
P, J = m.jordan_form()
assert m == J
m = EigenOnlyMatrix(4, 4, [2, 1, 0, 0,
0, 2, 0, 0,
0, 0, 2, 1,
0, 0, 0, 2
])
P, J = m.jordan_form()
assert m == J
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
P, J = A.jordan_form()
assert simplify(P*J*P.inv()) == A
assert EigenOnlyMatrix(1, 1, [1]).jordan_form() == (
Matrix([1]), Matrix([1]))
assert EigenOnlyMatrix(1, 1, [1]).jordan_form(
calc_transform=False) == Matrix([1])
# make sure if we cannot factor the characteristic polynomial, we raise an error
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m.jordan_form())
# make sure that if the input has floats, the output does too
m = Matrix([
[ 0.6875, 0.125 + 0.1875*sqrt(3)],
[0.125 + 0.1875*sqrt(3), 0.3125]])
P, J = m.jordan_form()
assert all(isinstance(x, Float) or x == 0 for x in P)
assert all(isinstance(x, Float) or x == 0 for x in J)
def test_singular_values():
x = Symbol('x', real=True)
A = EigenOnlyMatrix([[0, 1*I], [2, 0]])
# if singular values can be sorted, they should be in decreasing order
assert A.singular_values() == [2, 1]
A = eye(3)
A[1, 1] = x
A[2, 2] = 5
vals = A.singular_values()
# since Abs(x) cannot be sorted, test set equality
assert set(vals) == set([5, 1, Abs(x)])
A = EigenOnlyMatrix([[sin(x), cos(x)], [-cos(x), sin(x)]])
vals = [sv.trigsimp() for sv in A.singular_values()]
assert vals == [S.One, S.One]
A = EigenOnlyMatrix([
[2, 4],
[1, 3],
[0, 0],
[0, 0]
])
assert A.singular_values() == \
[sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221))]
assert A.T.singular_values() == \
[sqrt(sqrt(221) + 15), sqrt(15 - sqrt(221)), 0, 0]
def test___eq__():
assert (EigenOnlyMatrix(
[[0, 1, 1],
[1, 0, 0],
[1, 1, 1]]) == {}) is False
|
966b6feead5a65828ca546fb45accb88e7cf879a2b86c607cf2577aa2d325bee | from sympy.assumptions import Q
from sympy.core.add import Add
from sympy.core.function import Function
from sympy.core.numbers import I, Integer, oo, pi, Rational
from sympy.core.singleton import S
from sympy.core.symbol import Symbol, symbols
from sympy.functions.elementary.complexes import Abs
from sympy.functions.elementary.exponential import exp
from sympy.functions.elementary.miscellaneous import sqrt
from sympy.functions.elementary.trigonometric import cos, sin
from sympy.matrices.common import (ShapeError, NonSquareMatrixError,
_MinimalMatrix, _CastableMatrix, MatrixShaping, MatrixProperties,
MatrixOperations, MatrixArithmetic, MatrixSpecial)
from sympy.matrices.matrices import (MatrixDeterminant,
MatrixReductions, MatrixSubspaces, MatrixCalculus)
from sympy.matrices import (Matrix, diag, eye,
matrix_multiply_elementwise, ones, zeros, SparseMatrix, banded)
from sympy.simplify.simplify import simplify
from sympy.utilities.iterables import flatten
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.abc import x, y, z
# classes to test the basic matrix classes
class ShapingOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixShaping):
pass
def eye_Shaping(n):
return ShapingOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Shaping(n):
return ShapingOnlyMatrix(n, n, lambda i, j: 0)
class PropertiesOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixProperties):
pass
def eye_Properties(n):
return PropertiesOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Properties(n):
return PropertiesOnlyMatrix(n, n, lambda i, j: 0)
class OperationsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixOperations):
pass
def eye_Operations(n):
return OperationsOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Operations(n):
return OperationsOnlyMatrix(n, n, lambda i, j: 0)
class ArithmeticOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixArithmetic):
pass
def eye_Arithmetic(n):
return ArithmeticOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Arithmetic(n):
return ArithmeticOnlyMatrix(n, n, lambda i, j: 0)
class DeterminantOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixDeterminant):
pass
def eye_Determinant(n):
return DeterminantOnlyMatrix(n, n, lambda i, j: int(i == j))
class ReductionsOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixReductions):
pass
def eye_Reductions(n):
return ReductionsOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Reductions(n):
return ReductionsOnlyMatrix(n, n, lambda i, j: 0)
class SpecialOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSpecial):
pass
class SubspaceOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixSubspaces):
pass
class CalculusOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixCalculus):
pass
def test__MinimalMatrix():
x = _MinimalMatrix(2, 3, [1, 2, 3, 4, 5, 6])
assert x.rows == 2
assert x.cols == 3
assert x[2] == 3
assert x[1, 1] == 5
assert list(x) == [1, 2, 3, 4, 5, 6]
assert list(x[1, :]) == [4, 5, 6]
assert list(x[:, 1]) == [2, 5]
assert list(x[:, :]) == list(x)
assert x[:, :] == x
assert _MinimalMatrix(x) == x
assert _MinimalMatrix([[1, 2, 3], [4, 5, 6]]) == x
assert _MinimalMatrix(([1, 2, 3], [4, 5, 6])) == x
assert _MinimalMatrix([(1, 2, 3), (4, 5, 6)]) == x
assert _MinimalMatrix(((1, 2, 3), (4, 5, 6))) == x
assert not (_MinimalMatrix([[1, 2], [3, 4], [5, 6]]) == x)
# ShapingOnlyMatrix tests
def test_vec():
m = ShapingOnlyMatrix(2, 2, [1, 3, 2, 4])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
flat_lst = [S.One, S.Half, x*y, S.Zero, x, y, z, x**2, y, -S.One, z*x, 3]
m = ShapingOnlyMatrix(3, 4, flat_lst)
assert m.tolist() == lst
def test_row_col_del():
e = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(ValueError, lambda: e.row_del(5))
raises(ValueError, lambda: e.row_del(-5))
raises(ValueError, lambda: e.col_del(5))
raises(ValueError, lambda: e.col_del(-5))
assert e.row_del(2) == e.row_del(-1) == Matrix([[1, 2, 3], [4, 5, 6]])
assert e.col_del(2) == e.col_del(-1) == Matrix([[1, 2], [4, 5], [7, 8]])
assert e.row_del(1) == e.row_del(-2) == Matrix([[1, 2, 3], [7, 8, 9]])
assert e.col_del(1) == e.col_del(-2) == Matrix([[1, 3], [4, 6], [7, 9]])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A, B, C, D = diag(a, b, b), diag(a, b, c), diag(a, c, b), diag(c, c, b)
A = ShapingOnlyMatrix(A.rows, A.cols, A)
B = ShapingOnlyMatrix(B.rows, B.cols, B)
C = ShapingOnlyMatrix(C.rows, C.cols, C)
D = ShapingOnlyMatrix(D.rows, D.cols, D)
assert A.get_diag_blocks() == [a, b, b]
assert B.get_diag_blocks() == [a, b, c]
assert C.get_diag_blocks() == [a, c, b]
assert D.get_diag_blocks() == [c, c, b]
def test_shape():
m = ShapingOnlyMatrix(1, 2, [0, 0])
m.shape == (1, 2)
def test_reshape():
m0 = eye_Shaping(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = ShapingOnlyMatrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_row_col():
m = ShapingOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert m.row(0) == Matrix(1, 3, [1, 2, 3])
assert m.col(0) == Matrix(3, 1, [1, 4, 7])
def test_row_join():
assert eye_Shaping(3).row_join(Matrix([7, 7, 7])) == \
Matrix([[1, 0, 0, 7],
[0, 1, 0, 7],
[0, 0, 1, 7]])
def test_col_join():
assert eye_Shaping(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye_Shaping(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros_Shaping(3).col_insert(i, c4).row(0).tolist()) == l
# issue 13643
assert eye_Shaping(6).col_insert(3, Matrix([[2, 2], [2, 2], [2, 2], [2, 2], [2, 2], [2, 2]])) == \
Matrix([[1, 0, 0, 2, 2, 0, 0, 0],
[0, 1, 0, 2, 2, 0, 0, 0],
[0, 0, 1, 2, 2, 0, 0, 0],
[0, 0, 0, 2, 2, 1, 0, 0],
[0, 0, 0, 2, 2, 0, 1, 0],
[0, 0, 0, 2, 2, 0, 0, 1]])
def test_extract():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_hstack():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
assert m == m.hstack(m)
assert m.hstack(m, m, m) == ShapingOnlyMatrix.hstack(m, m, m) == Matrix([
[0, 1, 2, 0, 1, 2, 0, 1, 2],
[3, 4, 5, 3, 4, 5, 3, 4, 5],
[6, 7, 8, 6, 7, 8, 6, 7, 8],
[9, 10, 11, 9, 10, 11, 9, 10, 11]])
raises(ShapeError, lambda: m.hstack(m, m2))
assert Matrix.hstack() == Matrix()
# test regression #12938
M1 = Matrix.zeros(0, 0)
M2 = Matrix.zeros(0, 1)
M3 = Matrix.zeros(0, 2)
M4 = Matrix.zeros(0, 3)
m = ShapingOnlyMatrix.hstack(M1, M2, M3, M4)
assert m.rows == 0 and m.cols == 6
def test_vstack():
m = ShapingOnlyMatrix(4, 3, lambda i, j: i*3 + j)
m2 = ShapingOnlyMatrix(3, 4, lambda i, j: i*3 + j)
assert m == m.vstack(m)
assert m.vstack(m, m, m) == ShapingOnlyMatrix.vstack(m, m, m) == Matrix([
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11],
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[9, 10, 11]])
raises(ShapeError, lambda: m.vstack(m, m2))
assert Matrix.vstack() == Matrix()
# PropertiesOnlyMatrix tests
def test_atoms():
m = PropertiesOnlyMatrix(2, 2, [1, 2, x, 1 - 1/x])
assert m.atoms() == {S.One, S(2), S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_free_symbols():
assert PropertiesOnlyMatrix([[x], [0]]).free_symbols == {x}
def test_has():
A = PropertiesOnlyMatrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = PropertiesOnlyMatrix(((2, y), (2, 3)))
assert not A.has(x)
def test_is_anti_symmetric():
x = symbols('x')
assert PropertiesOnlyMatrix(2, 1, [1, 2]).is_anti_symmetric() is False
m = PropertiesOnlyMatrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in m])
assert m.is_anti_symmetric(simplify=False) is True
m = PropertiesOnlyMatrix(3, 3, [x.expand() for x in [S.One] + list(m)[1:]])
assert m.is_anti_symmetric() is False
def test_diagonal_symmetrical():
m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = PropertiesOnlyMatrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = PropertiesOnlyMatrix(3, 3, diag(1, 2, 3))
assert m.is_diagonal()
assert m.is_symmetric()
m = PropertiesOnlyMatrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = PropertiesOnlyMatrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = PropertiesOnlyMatrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = PropertiesOnlyMatrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_is_hermitian():
a = PropertiesOnlyMatrix([[1, I], [-I, 1]])
assert a.is_hermitian
a = PropertiesOnlyMatrix([[2*I, I], [-I, 1]])
assert a.is_hermitian is False
a = PropertiesOnlyMatrix([[x, I], [-I, 1]])
assert a.is_hermitian is None
a = PropertiesOnlyMatrix([[x, 1], [-I, 1]])
assert a.is_hermitian is False
def test_is_Identity():
assert eye_Properties(3).is_Identity
assert not PropertiesOnlyMatrix(zeros(3)).is_Identity
assert not PropertiesOnlyMatrix(ones(3)).is_Identity
# issue 6242
assert not PropertiesOnlyMatrix([[1, 0, 0]]).is_Identity
def test_is_symbolic():
a = PropertiesOnlyMatrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = PropertiesOnlyMatrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, x, 3]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = PropertiesOnlyMatrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_upper is True
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_upper is False
def test_is_lower():
a = PropertiesOnlyMatrix([[1, 2, 3]])
assert a.is_lower is False
a = PropertiesOnlyMatrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_square():
m = PropertiesOnlyMatrix([[1], [1]])
m2 = PropertiesOnlyMatrix([[2, 2], [2, 2]])
assert not m.is_square
assert m2.is_square
def test_is_symmetric():
m = PropertiesOnlyMatrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
m = PropertiesOnlyMatrix(2, 2, [0, 1, 0, 1])
assert not m.is_symmetric()
def test_is_hessenberg():
A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = PropertiesOnlyMatrix(3, 3, [3, 2, 0, 4, 4, 1, 1, 5, 2])
assert A.is_lower_hessenberg
A = PropertiesOnlyMatrix(3, 3, [3, 2, -1, 4, 4, 1, 1, 5, 2])
assert A.is_lower_hessenberg is False
assert A.is_upper_hessenberg is False
A = PropertiesOnlyMatrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
def test_is_zero():
assert PropertiesOnlyMatrix(0, 0, []).is_zero_matrix
assert PropertiesOnlyMatrix([[0, 0], [0, 0]]).is_zero_matrix
assert PropertiesOnlyMatrix(zeros(3, 4)).is_zero_matrix
assert not PropertiesOnlyMatrix(eye(3)).is_zero_matrix
assert PropertiesOnlyMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert PropertiesOnlyMatrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert PropertiesOnlyMatrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_values():
assert set(PropertiesOnlyMatrix(2, 2, [0, 1, 2, 3]
).values()) == set([1, 2, 3])
x = Symbol('x', real=True)
assert set(PropertiesOnlyMatrix(2, 2, [x, 0, 0, 1]
).values()) == set([x, 1])
# OperationsOnlyMatrix tests
def test_applyfunc():
m0 = OperationsOnlyMatrix(eye(3))
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
assert m0.applyfunc(lambda x: 1) == ones(3)
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = OperationsOnlyMatrix([[0, 1], [-I, 0]])
assert ans.adjoint() == Matrix(dat)
def test_as_real_imag():
m1 = OperationsOnlyMatrix(2, 2, [1, 2, 3, 4])
m3 = OperationsOnlyMatrix(2, 2,
[1 + S.ImaginaryUnit, 2 + 2*S.ImaginaryUnit,
3 + 3*S.ImaginaryUnit, 4 + 4*S.ImaginaryUnit])
a, b = m3.as_real_imag()
assert a == m1
assert b == m1
def test_conjugate():
M = OperationsOnlyMatrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_doit():
a = OperationsOnlyMatrix([[Add(x, x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_evalf():
a = OperationsOnlyMatrix(2, 1, [sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_expand():
m0 = OperationsOnlyMatrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert OperationsOnlyMatrix(1, 1, [exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
def test_refine():
m0 = OperationsOnlyMatrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_replace():
F, G = symbols('F, G', cls=Function)
K = OperationsOnlyMatrix(2, 2, lambda i, j: G(i+j))
M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
F, G = symbols('F, G', cls=Function)
K = OperationsOnlyMatrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1) \
: G(1)}), (G(2), {F(2): G(2)})])
M = OperationsOnlyMatrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G, True)
assert N == K
def test_simplify():
n = Symbol('n')
f = Function('f')
M = OperationsOnlyMatrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
assert M.simplify() == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = OperationsOnlyMatrix([[eq]])
assert M.simplify() == Matrix([[eq]])
assert M.simplify(ratio=oo) == Matrix([[eq.simplify(ratio=oo)]])
def test_subs():
assert OperationsOnlyMatrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert OperationsOnlyMatrix([[x*y]]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([[(x - 1)*(y - 1)]])
def test_trace():
M = OperationsOnlyMatrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_xreplace():
assert OperationsOnlyMatrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert OperationsOnlyMatrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
def test_permute():
a = OperationsOnlyMatrix(3, 4, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
raises(IndexError, lambda: a.permute([[0, 5]]))
raises(ValueError, lambda: a.permute(Symbol('x')))
b = a.permute_rows([[0, 2], [0, 1]])
assert a.permute([[0, 2], [0, 1]]) == b == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
b = a.permute_cols([[0, 2], [0, 1]])
assert a.permute([[0, 2], [0, 1]], orientation='cols') == b ==\
Matrix([
[ 2, 3, 1, 4],
[ 6, 7, 5, 8],
[10, 11, 9, 12]])
b = a.permute_cols([[0, 2], [0, 1]], direction='backward')
assert a.permute([[0, 2], [0, 1]], orientation='cols', direction='backward') == b ==\
Matrix([
[ 3, 1, 2, 4],
[ 7, 5, 6, 8],
[11, 9, 10, 12]])
assert a.permute([1, 2, 0, 3]) == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
from sympy.combinatorics import Permutation
assert a.permute(Permutation([1, 2, 0, 3])) == Matrix([
[5, 6, 7, 8],
[9, 10, 11, 12],
[1, 2, 3, 4]])
# ArithmeticOnlyMatrix tests
def test_abs():
m = ArithmeticOnlyMatrix([[1, -2], [x, y]])
assert abs(m) == ArithmeticOnlyMatrix([[1, 2], [Abs(x), Abs(y)]])
def test_add():
m = ArithmeticOnlyMatrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == ArithmeticOnlyMatrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_multiplication():
a = ArithmeticOnlyMatrix((
(1, 2),
(3, 1),
(0, 6),
))
b = ArithmeticOnlyMatrix((
(1, 2),
(3, 0),
))
raises(ShapeError, lambda: b*a)
raises(TypeError, lambda: a*{})
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
h = a.multiply_elementwise(c)
assert h == matrix_multiply_elementwise(a, c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: a.multiply_elementwise(b))
c = b * Symbol("x")
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, ArithmeticOnlyMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
def test_matmul():
a = Matrix([[1, 2], [3, 4]])
assert a.__matmul__(2) == NotImplemented
assert a.__rmatmul__(2) == NotImplemented
#This is done this way because @ is only supported in Python 3.5+
#To check 2@a case
try:
eval('2 @ a')
except SyntaxError:
pass
except TypeError: #TypeError is raised in case of NotImplemented is returned
pass
#Check a@2 case
try:
eval('a @ 2')
except SyntaxError:
pass
except TypeError: #TypeError is raised in case of NotImplemented is returned
pass
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
A = ArithmeticOnlyMatrix([[2, 3], [4, 5]])
assert (A**5)[:] == (6140, 8097, 10796, 14237)
A = ArithmeticOnlyMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == (290, 262, 251, 448, 440, 368, 702, 954, 433)
assert A**0 == eye(3)
assert A**1 == A
assert (ArithmeticOnlyMatrix([[2]]) ** 100)[0, 0] == 2**100
assert ArithmeticOnlyMatrix([[1, 2], [3, 4]])**Integer(2) == ArithmeticOnlyMatrix([[7, 10], [15, 22]])
A = Matrix([[1,2],[4,5]])
assert A.pow(20, method='cayley') == A.pow(20, method='multiply')
def test_neg():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert -n == ArithmeticOnlyMatrix(1, 2, [-1, -2])
def test_sub():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert n - n == ArithmeticOnlyMatrix(1, 2, [0, 0])
def test_div():
n = ArithmeticOnlyMatrix(1, 2, [1, 2])
assert n/2 == ArithmeticOnlyMatrix(1, 2, [S.Half, S(2)/2])
# ReductionsOnlyMatrix tests
def test_row_op():
e = eye_Reductions(3)
raises(ValueError, lambda: e.elementary_row_op("abc"))
raises(ValueError, lambda: e.elementary_row_op())
raises(ValueError, lambda: e.elementary_row_op('n->kn', row=5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->kn', row=-5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=1, row2=5))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=5, row2=1))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=-5, row2=1))
raises(ValueError, lambda: e.elementary_row_op('n<->m', row1=1, row2=-5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=1, row2=5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=5, row2=1, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=-5, row2=1, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=1, row2=-5, k=5))
raises(ValueError, lambda: e.elementary_row_op('n->n+km', row1=1, row2=1, k=5))
# test various ways to set arguments
assert e.elementary_row_op("n->kn", 0, 5) == Matrix([[5, 0, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_row_op("n->kn", 1, 5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_row_op("n->kn", row=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_row_op("n->kn", row1=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_row_op("n<->m", 0, 1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_row_op("n<->m", row1=0, row2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_row_op("n<->m", row=0, row2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_row_op("n->n+km", 0, 5, 1) == Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_row_op("n->n+km", row=0, k=5, row2=1) == Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_row_op("n->n+km", row1=0, k=5, row2=1) == Matrix([[1, 5, 0], [0, 1, 0], [0, 0, 1]])
# make sure the matrix doesn't change size
a = ReductionsOnlyMatrix(2, 3, [0]*6)
assert a.elementary_row_op("n->kn", 1, 5) == Matrix(2, 3, [0]*6)
assert a.elementary_row_op("n<->m", 0, 1) == Matrix(2, 3, [0]*6)
assert a.elementary_row_op("n->n+km", 0, 5, 1) == Matrix(2, 3, [0]*6)
def test_col_op():
e = eye_Reductions(3)
raises(ValueError, lambda: e.elementary_col_op("abc"))
raises(ValueError, lambda: e.elementary_col_op())
raises(ValueError, lambda: e.elementary_col_op('n->kn', col=5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->kn', col=-5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=1, col2=5))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=5, col2=1))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=-5, col2=1))
raises(ValueError, lambda: e.elementary_col_op('n<->m', col1=1, col2=-5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=1, col2=5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=5, col2=1, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=-5, col2=1, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=1, col2=-5, k=5))
raises(ValueError, lambda: e.elementary_col_op('n->n+km', col1=1, col2=1, k=5))
# test various ways to set arguments
assert e.elementary_col_op("n->kn", 0, 5) == Matrix([[5, 0, 0], [0, 1, 0], [0, 0, 1]])
assert e.elementary_col_op("n->kn", 1, 5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_col_op("n->kn", col=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_col_op("n->kn", col1=1, k=5) == Matrix([[1, 0, 0], [0, 5, 0], [0, 0, 1]])
assert e.elementary_col_op("n<->m", 0, 1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_col_op("n<->m", col1=0, col2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_col_op("n<->m", col=0, col2=1) == Matrix([[0, 1, 0], [1, 0, 0], [0, 0, 1]])
assert e.elementary_col_op("n->n+km", 0, 5, 1) == Matrix([[1, 0, 0], [5, 1, 0], [0, 0, 1]])
assert e.elementary_col_op("n->n+km", col=0, k=5, col2=1) == Matrix([[1, 0, 0], [5, 1, 0], [0, 0, 1]])
assert e.elementary_col_op("n->n+km", col1=0, k=5, col2=1) == Matrix([[1, 0, 0], [5, 1, 0], [0, 0, 1]])
# make sure the matrix doesn't change size
a = ReductionsOnlyMatrix(2, 3, [0]*6)
assert a.elementary_col_op("n->kn", 1, 5) == Matrix(2, 3, [0]*6)
assert a.elementary_col_op("n<->m", 0, 1) == Matrix(2, 3, [0]*6)
assert a.elementary_col_op("n->n+km", 0, 5, 1) == Matrix(2, 3, [0]*6)
def test_is_echelon():
zro = zeros_Reductions(3)
ident = eye_Reductions(3)
assert zro.is_echelon
assert ident.is_echelon
a = ReductionsOnlyMatrix(0, 0, [])
assert a.is_echelon
a = ReductionsOnlyMatrix(2, 3, [3, 2, 1, 0, 0, 6])
assert a.is_echelon
a = ReductionsOnlyMatrix(2, 3, [0, 0, 6, 3, 2, 1])
assert not a.is_echelon
x = Symbol('x')
a = ReductionsOnlyMatrix(3, 1, [x, 0, 0])
assert a.is_echelon
a = ReductionsOnlyMatrix(3, 1, [x, x, 0])
assert not a.is_echelon
a = ReductionsOnlyMatrix(3, 3, [0, 0, 0, 1, 2, 3, 0, 0, 0])
assert not a.is_echelon
def test_echelon_form():
# echelon form is not unique, but the result
# must be row-equivalent to the original matrix
# and it must be in echelon form.
a = zeros_Reductions(3)
e = eye_Reductions(3)
# we can assume the zero matrix and the identity matrix shouldn't change
assert a.echelon_form() == a
assert e.echelon_form() == e
a = ReductionsOnlyMatrix(0, 0, [])
assert a.echelon_form() == a
a = ReductionsOnlyMatrix(1, 1, [5])
assert a.echelon_form() == a
# now we get to the real tests
def verify_row_null_space(mat, rows, nulls):
for v in nulls:
assert all(t.is_zero for t in a_echelon*v)
for v in rows:
if not all(t.is_zero for t in v):
assert not all(t.is_zero for t in a_echelon*v.transpose())
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
nulls = [Matrix([
[ 1],
[-2],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
nulls = []
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(3, 3, [2, 1, 3, 0, 0, 0, 2, 1, 3])
nulls = [Matrix([
[Rational(-1, 2)],
[ 1],
[ 0]]),
Matrix([
[Rational(-3, 2)],
[ 0],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
# this one requires a row swap
a = ReductionsOnlyMatrix(3, 3, [2, 1, 3, 0, 0, 0, 1, 1, 3])
nulls = [Matrix([
[ 0],
[ -3],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(3, 3, [0, 3, 3, 0, 2, 2, 0, 1, 1])
nulls = [Matrix([
[1],
[0],
[0]]),
Matrix([
[ 0],
[-1],
[ 1]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
a = ReductionsOnlyMatrix(2, 3, [2, 2, 3, 3, 3, 0])
nulls = [Matrix([
[-1],
[1],
[0]])]
rows = [a[i, :] for i in range(a.rows)]
a_echelon = a.echelon_form()
assert a_echelon.is_echelon
verify_row_null_space(a, rows, nulls)
def test_rref():
e = ReductionsOnlyMatrix(0, 0, [])
assert e.rref(pivots=False) == e
e = ReductionsOnlyMatrix(1, 1, [1])
a = ReductionsOnlyMatrix(1, 1, [5])
assert e.rref(pivots=False) == a.rref(pivots=False) == e
a = ReductionsOnlyMatrix(3, 1, [1, 2, 3])
assert a.rref(pivots=False) == Matrix([[1], [0], [0]])
a = ReductionsOnlyMatrix(1, 3, [1, 2, 3])
assert a.rref(pivots=False) == Matrix([[1, 2, 3]])
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert a.rref(pivots=False) == Matrix([
[1, 0, -1],
[0, 1, 2],
[0, 0, 0]])
a = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 1, 2, 3, 1, 2, 3])
b = ReductionsOnlyMatrix(3, 3, [1, 2, 3, 0, 0, 0, 0, 0, 0])
c = ReductionsOnlyMatrix(3, 3, [0, 0, 0, 1, 2, 3, 0, 0, 0])
d = ReductionsOnlyMatrix(3, 3, [0, 0, 0, 0, 0, 0, 1, 2, 3])
assert a.rref(pivots=False) == \
b.rref(pivots=False) == \
c.rref(pivots=False) == \
d.rref(pivots=False) == b
e = eye_Reductions(3)
z = zeros_Reductions(3)
assert e.rref(pivots=False) == e
assert z.rref(pivots=False) == z
a = ReductionsOnlyMatrix([
[ 0, 0, 1, 2, 2, -5, 3],
[-1, 5, 2, 2, 1, -7, 5],
[ 0, 0, -2, -3, -3, 8, -5],
[-1, 5, 0, -1, -2, 1, 0]])
mat, pivot_offsets = a.rref()
assert mat == Matrix([
[1, -5, 0, 0, 1, 1, -1],
[0, 0, 1, 0, 0, -1, 1],
[0, 0, 0, 1, 1, -2, 1],
[0, 0, 0, 0, 0, 0, 0]])
assert pivot_offsets == (0, 2, 3)
a = ReductionsOnlyMatrix([[Rational(1, 19), Rational(1, 5), 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11],
[ 12, 13, 14, 15]])
assert a.rref(pivots=False) == Matrix([
[1, 0, 0, Rational(-76, 157)],
[0, 1, 0, Rational(-5, 157)],
[0, 0, 1, Rational(238, 157)],
[0, 0, 0, 0]])
x = Symbol('x')
a = ReductionsOnlyMatrix(2, 3, [x, 1, 1, sqrt(x), x, 1])
for i, j in zip(a.rref(pivots=False),
[1, 0, sqrt(x)*(-x + 1)/(-x**Rational(5, 2) + x),
0, 1, 1/(sqrt(x) + x + 1)]):
assert simplify(i - j).is_zero
# SpecialOnlyMatrix tests
def test_eye():
assert list(SpecialOnlyMatrix.eye(2, 2)) == [1, 0, 0, 1]
assert list(SpecialOnlyMatrix.eye(2)) == [1, 0, 0, 1]
assert type(SpecialOnlyMatrix.eye(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.eye(2, cls=Matrix)) == Matrix
def test_ones():
assert list(SpecialOnlyMatrix.ones(2, 2)) == [1, 1, 1, 1]
assert list(SpecialOnlyMatrix.ones(2)) == [1, 1, 1, 1]
assert SpecialOnlyMatrix.ones(2, 3) == Matrix([[1, 1, 1], [1, 1, 1]])
assert type(SpecialOnlyMatrix.ones(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.ones(2, cls=Matrix)) == Matrix
def test_zeros():
assert list(SpecialOnlyMatrix.zeros(2, 2)) == [0, 0, 0, 0]
assert list(SpecialOnlyMatrix.zeros(2)) == [0, 0, 0, 0]
assert SpecialOnlyMatrix.zeros(2, 3) == Matrix([[0, 0, 0], [0, 0, 0]])
assert type(SpecialOnlyMatrix.zeros(2)) == SpecialOnlyMatrix
assert type(SpecialOnlyMatrix.zeros(2, cls=Matrix)) == Matrix
def test_diag_make():
diag = SpecialOnlyMatrix.diag
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b) == Matrix([
[1, 2, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0],
[0, 0, 3, x, 0, 0],
[0, 0, y, 3, 0, 0],
[0, 0, 0, 0, 3, x],
[0, 0, 0, 0, y, 3],
])
assert diag(a, b, c) == Matrix([
[1, 2, 0, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0, 0],
[0, 0, 3, x, 0, 0, 0],
[0, 0, y, 3, 0, 0, 0],
[0, 0, 0, 0, 3, x, 3],
[0, 0, 0, 0, y, 3, z],
[0, 0, 0, 0, x, y, z],
])
assert diag(a, c, b) == Matrix([
[1, 2, 0, 0, 0, 0, 0],
[2, 3, 0, 0, 0, 0, 0],
[0, 0, 3, x, 3, 0, 0],
[0, 0, y, 3, z, 0, 0],
[0, 0, x, y, z, 0, 0],
[0, 0, 0, 0, 0, 3, x],
[0, 0, 0, 0, 0, y, 3],
])
a = Matrix([x, y, z])
b = Matrix([[1, 2], [3, 4]])
c = Matrix([[5, 6]])
# this "wandering diagonal" is what makes this
# a block diagonal where each block is independent
# of the others
assert diag(a, 7, b, c) == Matrix([
[x, 0, 0, 0, 0, 0],
[y, 0, 0, 0, 0, 0],
[z, 0, 0, 0, 0, 0],
[0, 7, 0, 0, 0, 0],
[0, 0, 1, 2, 0, 0],
[0, 0, 3, 4, 0, 0],
[0, 0, 0, 0, 5, 6]])
raises(ValueError, lambda: diag(a, 7, b, c, rows=5))
assert diag(1) == Matrix([[1]])
assert diag(1, rows=2) == Matrix([[1, 0], [0, 0]])
assert diag(1, cols=2) == Matrix([[1, 0], [0, 0]])
assert diag(1, rows=3, cols=2) == Matrix([[1, 0], [0, 0], [0, 0]])
assert diag(*[2, 3]) == Matrix([
[2, 0],
[0, 3]])
assert diag(Matrix([2, 3])) == Matrix([
[2],
[3]])
assert diag([1, [2, 3], 4], unpack=False) == \
diag([[1], [2, 3], [4]], unpack=False) == Matrix([
[1, 0],
[2, 3],
[4, 0]])
assert type(diag(1)) == SpecialOnlyMatrix
assert type(diag(1, cls=Matrix)) == Matrix
assert Matrix.diag([1, 2, 3]) == Matrix.diag(1, 2, 3)
assert Matrix.diag([1, 2, 3], unpack=False).shape == (3, 1)
assert Matrix.diag([[1, 2, 3]]).shape == (3, 1)
assert Matrix.diag([[1, 2, 3]], unpack=False).shape == (1, 3)
assert Matrix.diag([[[1, 2, 3]]]).shape == (1, 3)
# kerning can be used to move the starting point
assert Matrix.diag(ones(0, 2), 1, 2) == Matrix([
[0, 0, 1, 0],
[0, 0, 0, 2]])
assert Matrix.diag(ones(2, 0), 1, 2) == Matrix([
[0, 0],
[0, 0],
[1, 0],
[0, 2]])
def test_diagonal():
m = Matrix(3, 3, range(9))
d = m.diagonal()
assert d == m.diagonal(0)
assert tuple(d) == (0, 4, 8)
assert tuple(m.diagonal(1)) == (1, 5)
assert tuple(m.diagonal(-1)) == (3, 7)
assert tuple(m.diagonal(2)) == (2,)
assert type(m.diagonal()) == type(m)
s = SparseMatrix(3, 3, {(1, 1): 1})
assert type(s.diagonal()) == type(s)
assert type(m) != type(s)
raises(ValueError, lambda: m.diagonal(3))
raises(ValueError, lambda: m.diagonal(-3))
raises(ValueError, lambda: m.diagonal(pi))
M = ones(2, 3)
assert banded({i: list(M.diagonal(i))
for i in range(1-M.rows, M.cols)}) == M
def test_jordan_block():
assert SpecialOnlyMatrix.jordan_block(3, 2) == SpecialOnlyMatrix.jordan_block(3, eigenvalue=2) \
== SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) \
== SpecialOnlyMatrix.jordan_block(3, 2, band='upper') \
== SpecialOnlyMatrix.jordan_block(
size=3, eigenval=2, eigenvalue=2) \
== Matrix([
[2, 1, 0],
[0, 2, 1],
[0, 0, 2]])
assert SpecialOnlyMatrix.jordan_block(3, 2, band='lower') == Matrix([
[2, 0, 0],
[1, 2, 0],
[0, 1, 2]])
# missing eigenvalue
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(2))
# non-integral size
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(3.5, 2))
# size not specified
raises(ValueError, lambda: SpecialOnlyMatrix.jordan_block(eigenvalue=2))
# inconsistent eigenvalue
raises(ValueError,
lambda: SpecialOnlyMatrix.jordan_block(
eigenvalue=2, eigenval=4))
# Deprecated feature
with warns_deprecated_sympy():
assert (SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) ==
SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2)))
with warns_deprecated_sympy():
assert (SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2) ==
SpecialOnlyMatrix(3, 3, (2, 1, 0, 0, 2, 1, 0, 0, 2)))
with warns_deprecated_sympy():
assert SpecialOnlyMatrix.jordan_block(3, 2) == \
SpecialOnlyMatrix.jordan_block(cols=3, eigenvalue=2) == \
SpecialOnlyMatrix.jordan_block(rows=3, eigenvalue=2)
with warns_deprecated_sympy():
assert SpecialOnlyMatrix.jordan_block(
rows=4, cols=3, eigenvalue=2) == \
Matrix([
[2, 1, 0],
[0, 2, 1],
[0, 0, 2],
[0, 0, 0]])
# Using alias keyword
assert SpecialOnlyMatrix.jordan_block(size=3, eigenvalue=2) == \
SpecialOnlyMatrix.jordan_block(size=3, eigenval=2)
# SubspaceOnlyMatrix tests
def test_columnspace():
m = SubspaceOnlyMatrix([[ 1, 2, 0, 2, 5],
[-2, -5, 1, -1, -8],
[ 0, -3, 3, 4, 1],
[ 3, 6, 0, -7, 2]])
basis = m.columnspace()
assert basis[0] == Matrix([1, -2, 0, 3])
assert basis[1] == Matrix([2, -5, -3, 6])
assert basis[2] == Matrix([2, -1, 4, -7])
assert len(basis) == 3
assert Matrix.hstack(m, *basis).columnspace() == basis
def test_rowspace():
m = SubspaceOnlyMatrix([[ 1, 2, 0, 2, 5],
[-2, -5, 1, -1, -8],
[ 0, -3, 3, 4, 1],
[ 3, 6, 0, -7, 2]])
basis = m.rowspace()
assert basis[0] == Matrix([[1, 2, 0, 2, 5]])
assert basis[1] == Matrix([[0, -1, 1, 3, 2]])
assert basis[2] == Matrix([[0, 0, 0, 5, 5]])
assert len(basis) == 3
def test_nullspace():
m = SubspaceOnlyMatrix([[ 1, 2, 0, 2, 5],
[-2, -5, 1, -1, -8],
[ 0, -3, 3, 4, 1],
[ 3, 6, 0, -7, 2]])
basis = m.nullspace()
assert basis[0] == Matrix([-2, 1, 1, 0, 0])
assert basis[1] == Matrix([-1, -1, 0, -1, 1])
# make sure the null space is really gets zeroed
assert all(e.is_zero for e in m*basis[0])
assert all(e.is_zero for e in m*basis[1])
def test_orthogonalize():
m = Matrix([[1, 2], [3, 4]])
assert m.orthogonalize(Matrix([[2], [1]])) == [Matrix([[2], [1]])]
assert m.orthogonalize(Matrix([[2], [1]]), normalize=True) == \
[Matrix([[2*sqrt(5)/5], [sqrt(5)/5]])]
assert m.orthogonalize(Matrix([[1], [2]]), Matrix([[-1], [4]])) == \
[Matrix([[1], [2]]), Matrix([[Rational(-12, 5)], [Rational(6, 5)]])]
assert m.orthogonalize(Matrix([[0], [0]]), Matrix([[-1], [4]])) == \
[Matrix([[-1], [4]])]
assert m.orthogonalize(Matrix([[0], [0]])) == []
n = Matrix([[9, 1, 9], [3, 6, 10], [8, 5, 2]])
vecs = [Matrix([[-5], [1]]), Matrix([[-5], [2]]), Matrix([[-5], [-2]])]
assert n.orthogonalize(*vecs) == \
[Matrix([[-5], [1]]), Matrix([[Rational(5, 26)], [Rational(25, 26)]])]
vecs = [Matrix([0, 0, 0]), Matrix([1, 2, 3]), Matrix([1, 4, 5])]
raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
vecs = [Matrix([1, 2, 3]), Matrix([4, 5, 6]), Matrix([7, 8, 9])]
raises(ValueError, lambda: Matrix.orthogonalize(*vecs, rankcheck=True))
# CalculusOnlyMatrix tests
@XFAIL
def test_diff():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [x, y])
# TODO: currently not working as ``_MinimalMatrix`` cannot be sympified:
assert m.diff(x) == Matrix(2, 1, [1, 0])
def test_integrate():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [x, y])
assert m.integrate(x) == Matrix(2, 1, [x**2/2, y*x])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = CalculusOnlyMatrix(3, 1, [rho*cos(phi), rho*sin(phi), rho**2])
Y = CalculusOnlyMatrix(2, 1, [rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
m = CalculusOnlyMatrix(2, 2, [1, 2, 3, 4])
m2 = CalculusOnlyMatrix(4, 1, [1, 2, 3, 4])
raises(TypeError, lambda: m.jacobian(Matrix([1, 2])))
raises(TypeError, lambda: m2.jacobian(m))
def test_limit():
x, y = symbols('x y')
m = CalculusOnlyMatrix(2, 1, [1/x, y])
assert m.limit(x, 5) == Matrix(2, 1, [Rational(1, 5), y])
def test_issue_13774():
M = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
v = [1, 1, 1]
raises(TypeError, lambda: M*v)
raises(TypeError, lambda: v*M)
|
06ac10e1e712f7caf375552a2f823988f8d31d6c5913ede6daa8da9460f9eae0 | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densesolve import LU_solve, rref_solve, cholesky_solve
from sympy import Dummy
from sympy import QQ
def test_LU_solve():
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
assert LU_solve([[QQ(2), QQ(-1), QQ(-2)], [QQ(-4), QQ(6), QQ(3)], [QQ(-4), QQ(-2), QQ(8)]], [[x], [y], [z]], [[QQ(-1)], [QQ(13)], [QQ(-6)]], QQ) == [[QQ(2,1)], [QQ(3, 1)], [QQ(1, 1)]]
def test_cholesky_solve():
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
assert cholesky_solve([[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)], [QQ(-5), QQ(0), QQ(11)]], [[x], [y], [z]], [[QQ(2)], [QQ(3)], [QQ(1)]], QQ) == [[QQ(-1, 225)], [QQ(23, 135)], [QQ(4, 45)]]
def test_rref_solve():
x, y, z = Dummy('x'), Dummy('y'), Dummy('z')
assert rref_solve([[QQ(25), QQ(15), QQ(-5)], [QQ(15), QQ(18), QQ(0)], [QQ(-5), QQ(0), QQ(11)]], [[x], [y], [z]], [[QQ(2)], [QQ(3)], [QQ(1)]], QQ) == [[QQ(-1, 225)], [QQ(23, 135)], [QQ(4, 45)]]
|
8009a121ce5de286a8e6a97040dd0141fc617ca0a5434b432a41b2bac83ac27f | from sympy import Abs, S, Symbol, symbols, I, Rational, PurePoly, Float
from sympy.matrices import \
Matrix, MutableSparseMatrix, ImmutableSparseMatrix, SparseMatrix, eye, \
ones, zeros, ShapeError
from sympy.testing.pytest import raises
def test_sparse_matrix():
def sparse_eye(n):
return SparseMatrix.eye(n)
def sparse_zeros(n):
return SparseMatrix.zeros(n)
# creation args
raises(TypeError, lambda: SparseMatrix(1, 2))
a = SparseMatrix((
(1, 0),
(0, 1)
))
assert SparseMatrix(a) == a
from sympy.matrices import MutableSparseMatrix, MutableDenseMatrix
a = MutableSparseMatrix([])
b = MutableDenseMatrix([1, 2])
assert a.row_join(b) == b
assert a.col_join(b) == b
assert type(a.row_join(b)) == type(a)
assert type(a.col_join(b)) == type(a)
# make sure 0 x n matrices get stacked correctly
sparse_matrices = [SparseMatrix.zeros(0, n) for n in range(4)]
assert SparseMatrix.hstack(*sparse_matrices) == Matrix(0, 6, [])
sparse_matrices = [SparseMatrix.zeros(n, 0) for n in range(4)]
assert SparseMatrix.vstack(*sparse_matrices) == Matrix(6, 0, [])
# test element assignment
a = SparseMatrix((
(1, 0),
(0, 1)
))
a[3] = 4
assert a[1, 1] == 4
a[3] = 1
a[0, 0] = 2
assert a == SparseMatrix((
(2, 0),
(0, 1)
))
a[1, 0] = 5
assert a == SparseMatrix((
(2, 0),
(5, 1)
))
a[1, 1] = 0
assert a == SparseMatrix((
(2, 0),
(5, 0)
))
assert a._smat == {(0, 0): 2, (1, 0): 5}
# test_multiplication
a = SparseMatrix((
(1, 2),
(3, 1),
(0, 6),
))
b = SparseMatrix((
(1, 2),
(3, 0),
))
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
x = Symbol("x")
c = b * Symbol("x")
assert isinstance(c, SparseMatrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c = 5 * b
assert isinstance(c, SparseMatrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
#test_power
A = SparseMatrix([[2, 3], [4, 5]])
assert (A**5)[:] == [6140, 8097, 10796, 14237]
A = SparseMatrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
# test_creation
x = Symbol("x")
a = SparseMatrix([[x, 0], [0, 0]])
m = a
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
b = SparseMatrix(2, 2, [x, 0, 0, 0])
m = b
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
assert a == b
S = sparse_eye(3)
S.row_del(1)
assert S == SparseMatrix([
[1, 0, 0],
[0, 0, 1]])
S = sparse_eye(3)
S.col_del(1)
assert S == SparseMatrix([
[1, 0],
[0, 0],
[0, 1]])
S = SparseMatrix.eye(3)
S[2, 1] = 2
S.col_swap(1, 0)
assert S == SparseMatrix([
[0, 1, 0],
[1, 0, 0],
[2, 0, 1]])
a = SparseMatrix(1, 2, [1, 2])
b = a.copy()
c = a.copy()
assert a[0] == 1
a.row_del(0)
assert a == SparseMatrix(0, 2, [])
b.col_del(1)
assert b == SparseMatrix(1, 1, [1])
assert SparseMatrix([[1, 2, 3], [1, 2], [1]]) == Matrix([
[1, 2, 3],
[1, 2, 0],
[1, 0, 0]])
assert SparseMatrix(4, 4, {(1, 1): sparse_eye(2)}) == Matrix([
[0, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0],
[0, 0, 0, 0]])
raises(ValueError, lambda: SparseMatrix(1, 1, {(1, 1): 1}))
assert SparseMatrix(1, 2, [1, 2]).tolist() == [[1, 2]]
assert SparseMatrix(2, 2, [1, [2, 3]]).tolist() == [[1, 0], [2, 3]]
raises(ValueError, lambda: SparseMatrix(2, 2, [1]))
raises(ValueError, lambda: SparseMatrix(1, 1, [[1, 2]]))
assert SparseMatrix([.1]).has(Float)
# autosizing
assert SparseMatrix(None, {(0, 1): 0}).shape == (0, 0)
assert SparseMatrix(None, {(0, 1): 1}).shape == (1, 2)
assert SparseMatrix(None, None, {(0, 1): 1}).shape == (1, 2)
raises(ValueError, lambda: SparseMatrix(None, 1, [[1, 2]]))
raises(ValueError, lambda: SparseMatrix(1, None, [[1, 2]]))
raises(ValueError, lambda: SparseMatrix(3, 3, {(0, 0): ones(2), (1, 1): 2}))
# test_determinant
x, y = Symbol('x'), Symbol('y')
assert SparseMatrix(1, 1, [0]).det() == 0
assert SparseMatrix([[1]]).det() == 1
assert SparseMatrix(((-3, 2), (8, -5))).det() == -1
assert SparseMatrix(((x, 1), (y, 2*y))).det() == 2*x*y - y
assert SparseMatrix(( (1, 1, 1),
(1, 2, 3),
(1, 3, 6) )).det() == 1
assert SparseMatrix(( ( 3, -2, 0, 5),
(-2, 1, -2, 2),
( 0, -2, 5, 0),
( 5, 0, 3, 4) )).det() == -289
assert SparseMatrix(( ( 1, 2, 3, 4),
( 5, 6, 7, 8),
( 9, 10, 11, 12),
(13, 14, 15, 16) )).det() == 0
assert SparseMatrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(2, 0, 0, 0, 3) )).det() == 275
assert SparseMatrix(( (1, 0, 1, 2, 12),
(2, 0, 1, 1, 4),
(2, 1, 1, -1, 3),
(3, 2, -1, 1, 8),
(1, 1, 1, 0, 6) )).det() == -55
assert SparseMatrix(( (-5, 2, 3, 4, 5),
( 1, -4, 3, 4, 5),
( 1, 2, -3, 4, 5),
( 1, 2, 3, -2, 5),
( 1, 2, 3, 4, -1) )).det() == 11664
assert SparseMatrix(( ( 3, 0, 0, 0),
(-2, 1, 0, 0),
( 0, -2, 5, 0),
( 5, 0, 3, 4) )).det() == 60
assert SparseMatrix(( ( 1, 0, 0, 0),
( 5, 0, 0, 0),
( 9, 10, 11, 0),
(13, 14, 15, 16) )).det() == 0
assert SparseMatrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(0, 0, 0, 0, 3) )).det() == 243
assert SparseMatrix(( ( 2, 7, -1, 3, 2),
( 0, 0, 1, 0, 1),
(-2, 0, 7, 0, 2),
(-3, -2, 4, 5, 3),
( 1, 0, 0, 0, 1) )).det() == 123
# test_slicing
m0 = sparse_eye(4)
assert m0[:3, :3] == sparse_eye(3)
assert m0[2:4, 0:2] == sparse_zeros(2)
m1 = SparseMatrix(3, 3, lambda i, j: i + j)
assert m1[0, :] == SparseMatrix(1, 3, (0, 1, 2))
assert m1[1:3, 1] == SparseMatrix(2, 1, (2, 3))
m2 = SparseMatrix(
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
assert m2[:, -1] == SparseMatrix(4, 1, [3, 7, 11, 15])
assert m2[-2:, :] == SparseMatrix([[8, 9, 10, 11], [12, 13, 14, 15]])
assert SparseMatrix([[1, 2], [3, 4]])[[1], [1]] == Matrix([[4]])
# test_submatrix_assignment
m = sparse_zeros(4)
m[2:4, 2:4] = sparse_eye(2)
assert m == SparseMatrix([(0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)])
assert len(m._smat) == 2
m[:2, :2] = sparse_eye(2)
assert m == sparse_eye(4)
m[:, 0] = SparseMatrix(4, 1, (1, 2, 3, 4))
assert m == SparseMatrix([(1, 0, 0, 0),
(2, 1, 0, 0),
(3, 0, 1, 0),
(4, 0, 0, 1)])
m[:, :] = sparse_zeros(4)
assert m == sparse_zeros(4)
m[:, :] = ((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16))
assert m == SparseMatrix((( 1, 2, 3, 4),
( 5, 6, 7, 8),
( 9, 10, 11, 12),
(13, 14, 15, 16)))
m[:2, 0] = [0, 0]
assert m == SparseMatrix((( 0, 2, 3, 4),
( 0, 6, 7, 8),
( 9, 10, 11, 12),
(13, 14, 15, 16)))
# test_reshape
m0 = sparse_eye(3)
assert m0.reshape(1, 9) == SparseMatrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = SparseMatrix(3, 4, lambda i, j: i + j)
assert m1.reshape(4, 3) == \
SparseMatrix([(0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)])
assert m1.reshape(2, 6) == \
SparseMatrix([(0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)])
# test_applyfunc
m0 = sparse_eye(3)
assert m0.applyfunc(lambda x: 2*x) == sparse_eye(3)*2
assert m0.applyfunc(lambda x: 0 ) == sparse_zeros(3)
# test__eval_Abs
assert abs(SparseMatrix(((x, 1), (y, 2*y)))) == SparseMatrix(((Abs(x), 1), (Abs(y), 2*Abs(y))))
# test_LUdecomp
testmat = SparseMatrix([[ 0, 2, 5, 3],
[ 3, 3, 7, 4],
[ 8, 4, 0, 2],
[-2, 6, 3, 4]])
L, U, p = testmat.LUdecomposition()
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)
testmat = SparseMatrix([[ 6, -2, 7, 4],
[ 0, 3, 6, 7],
[ 1, -2, 7, 4],
[-9, 2, 6, 3]])
L, U, p = testmat.LUdecomposition()
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == sparse_zeros(4)
x, y, z = Symbol('x'), Symbol('y'), Symbol('z')
M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
L, U, p = M.LUdecomposition()
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - M == sparse_zeros(3)
# test_LUsolve
A = SparseMatrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = SparseMatrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = SparseMatrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = SparseMatrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
# test_inverse
A = sparse_eye(4)
assert A.inv() == sparse_eye(4)
assert A.inv(method="CH") == sparse_eye(4)
assert A.inv(method="LDL") == sparse_eye(4)
A = SparseMatrix([[2, 3, 5],
[3, 6, 2],
[7, 2, 6]])
Ainv = SparseMatrix(Matrix(A).inv())
assert A*Ainv == sparse_eye(3)
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
A = SparseMatrix([[2, 3, 5],
[3, 6, 2],
[5, 2, 6]])
Ainv = SparseMatrix(Matrix(A).inv())
assert A*Ainv == sparse_eye(3)
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
# test_cross
v1 = Matrix(1, 3, [1, 2, 3])
v2 = Matrix(1, 3, [3, 4, 5])
assert v1.cross(v2) == Matrix(1, 3, [-2, 4, -2])
assert v1.norm(2)**2 == 14
# conjugate
a = SparseMatrix(((1, 2 + I), (3, 4)))
assert a.C == SparseMatrix([
[1, 2 - I],
[3, 4]
])
# mul
assert a*Matrix(2, 2, [1, 0, 0, 1]) == a
assert a + Matrix(2, 2, [1, 1, 1, 1]) == SparseMatrix([
[2, 3 + I],
[4, 5]
])
# col join
assert a.col_join(sparse_eye(2)) == SparseMatrix([
[1, 2 + I],
[3, 4],
[1, 0],
[0, 1]
])
# symmetric
assert not a.is_symmetric(simplify=False)
# test_cofactor
assert sparse_eye(3) == sparse_eye(3).cofactor_matrix()
test = SparseMatrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
assert test.cofactor_matrix() == \
SparseMatrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
test = SparseMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert test.cofactor_matrix() == \
SparseMatrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])
# test_jacobian
x = Symbol('x')
y = Symbol('y')
L = SparseMatrix(1, 2, [x**2*y, 2*y**2 + x*y])
syms = [x, y]
assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
L = SparseMatrix(1, 2, [x, x**2*y**3])
assert L.jacobian(syms) == SparseMatrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
# test_QR
A = Matrix([[1, 2], [2, 3]])
Q, S = A.QRdecomposition()
R = Rational
assert Q == Matrix([
[ 5**R(-1, 2), (R(2)/5)*(R(1)/5)**R(-1, 2)],
[2*5**R(-1, 2), (-R(1)/5)*(R(1)/5)**R(-1, 2)]])
assert S == Matrix([
[5**R(1, 2), 8*5**R(-1, 2)],
[ 0, (R(1)/5)**R(1, 2)]])
assert Q*S == A
assert Q.T * Q == sparse_eye(2)
R = Rational
# test nullspace
# first test reduced row-ech form
M = SparseMatrix([[5, 7, 2, 1],
[1, 6, 2, -1]])
out, tmp = M.rref()
assert out == Matrix([[1, 0, -R(2)/23, R(13)/23],
[0, 1, R(8)/23, R(-6)/23]])
M = SparseMatrix([[ 1, 3, 0, 2, 6, 3, 1],
[-2, -6, 0, -2, -8, 3, 1],
[ 3, 9, 0, 0, 6, 6, 2],
[-1, -3, 0, 1, 0, 9, 3]])
out, tmp = M.rref()
assert out == Matrix([[1, 3, 0, 0, 2, 0, 0],
[0, 0, 0, 1, 2, 0, 0],
[0, 0, 0, 0, 0, 1, R(1)/3],
[0, 0, 0, 0, 0, 0, 0]])
# now check the vectors
basis = M.nullspace()
assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0])
assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0])
assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0])
assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1)/3, 1])
# test eigen
x = Symbol('x')
y = Symbol('y')
sparse_eye3 = sparse_eye(3)
assert sparse_eye3.charpoly(x) == PurePoly(((x - 1)**3))
assert sparse_eye3.charpoly(y) == PurePoly(((y - 1)**3))
# test values
M = Matrix([( 0, 1, -1),
( 1, 1, 0),
(-1, 0, 1)])
vals = M.eigenvals()
assert sorted(vals.keys()) == [-1, 1, 2]
R = Rational
M = Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
assert M.eigenvects() == [(1, 3, [
Matrix([1, 0, 0]),
Matrix([0, 1, 0]),
Matrix([0, 0, 1])])]
M = Matrix([[5, 0, 2],
[3, 2, 0],
[0, 0, 1]])
assert M.eigenvects() == [(1, 1, [Matrix([R(-1)/2, R(3)/2, 1])]),
(2, 1, [Matrix([0, 1, 0])]),
(5, 1, [Matrix([1, 1, 0])])]
assert M.zeros(3, 5) == SparseMatrix(3, 5, {})
A = SparseMatrix(10, 10, {(0, 0): 18, (0, 9): 12, (1, 4): 18, (2, 7): 16, (3, 9): 12, (4, 2): 19, (5, 7): 16, (6, 2): 12, (9, 7): 18})
assert A.row_list() == [(0, 0, 18), (0, 9, 12), (1, 4, 18), (2, 7, 16), (3, 9, 12), (4, 2, 19), (5, 7, 16), (6, 2, 12), (9, 7, 18)]
assert A.col_list() == [(0, 0, 18), (4, 2, 19), (6, 2, 12), (1, 4, 18), (2, 7, 16), (5, 7, 16), (9, 7, 18), (0, 9, 12), (3, 9, 12)]
assert SparseMatrix.eye(2).nnz() == 2
def test_transpose():
assert SparseMatrix(((1, 2), (3, 4))).transpose() == \
SparseMatrix(((1, 3), (2, 4)))
def test_trace():
assert SparseMatrix(((1, 2), (3, 4))).trace() == 5
assert SparseMatrix(((0, 0), (0, 4))).trace() == 4
def test_CL_RL():
assert SparseMatrix(((1, 2), (3, 4))).row_list() == \
[(0, 0, 1), (0, 1, 2), (1, 0, 3), (1, 1, 4)]
assert SparseMatrix(((1, 2), (3, 4))).col_list() == \
[(0, 0, 1), (1, 0, 3), (0, 1, 2), (1, 1, 4)]
def test_add():
assert SparseMatrix(((1, 0), (0, 1))) + SparseMatrix(((0, 1), (1, 0))) == \
SparseMatrix(((1, 1), (1, 1)))
a = SparseMatrix(100, 100, lambda i, j: int(j != 0 and i % j == 0))
b = SparseMatrix(100, 100, lambda i, j: int(i != 0 and j % i == 0))
assert (len(a._smat) + len(b._smat) - len((a + b)._smat) > 0)
def test_errors():
raises(ValueError, lambda: SparseMatrix(1.4, 2, lambda i, j: 0))
raises(TypeError, lambda: SparseMatrix([1, 2, 3], [1, 2]))
raises(ValueError, lambda: SparseMatrix([[1, 2], [3, 4]])[(1, 2, 3)])
raises(IndexError, lambda: SparseMatrix([[1, 2], [3, 4]])[5])
raises(ValueError, lambda: SparseMatrix([[1, 2], [3, 4]])[1, 2, 3])
raises(TypeError,
lambda: SparseMatrix([[1, 2], [3, 4]]).copyin_list([0, 1], set([])))
raises(
IndexError, lambda: SparseMatrix([[1, 2], [3, 4]])[1, 2])
raises(TypeError, lambda: SparseMatrix([1, 2, 3]).cross(1))
raises(IndexError, lambda: SparseMatrix(1, 2, [1, 2])[3])
raises(ShapeError,
lambda: SparseMatrix(1, 2, [1, 2]) + SparseMatrix(2, 1, [2, 1]))
def test_len():
assert not SparseMatrix()
assert SparseMatrix() == SparseMatrix([])
assert SparseMatrix() == SparseMatrix([[]])
def test_sparse_zeros_sparse_eye():
assert SparseMatrix.eye(3) == eye(3, cls=SparseMatrix)
assert len(SparseMatrix.eye(3)._smat) == 3
assert SparseMatrix.zeros(3) == zeros(3, cls=SparseMatrix)
assert len(SparseMatrix.zeros(3)._smat) == 0
def test_copyin():
s = SparseMatrix(3, 3, {})
s[1, 0] = 1
assert s[:, 0] == SparseMatrix(Matrix([0, 1, 0]))
assert s[3] == 1
assert s[3: 4] == [1]
s[1, 1] = 42
assert s[1, 1] == 42
assert s[1, 1:] == SparseMatrix([[42, 0]])
s[1, 1:] = Matrix([[5, 6]])
assert s[1, :] == SparseMatrix([[1, 5, 6]])
s[1, 1:] = [[42, 43]]
assert s[1, :] == SparseMatrix([[1, 42, 43]])
s[0, 0] = 17
assert s[:, :1] == SparseMatrix([17, 1, 0])
s[0, 0] = [1, 1, 1]
assert s[:, 0] == SparseMatrix([1, 1, 1])
s[0, 0] = Matrix([1, 1, 1])
assert s[:, 0] == SparseMatrix([1, 1, 1])
s[0, 0] = SparseMatrix([1, 1, 1])
assert s[:, 0] == SparseMatrix([1, 1, 1])
def test_sparse_solve():
from sympy.matrices import SparseMatrix
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
assert A.cholesky() == Matrix([
[ 5, 0, 0],
[ 3, 3, 0],
[-1, 1, 3]])
assert A.cholesky() * A.cholesky().T == Matrix([
[25, 15, -5],
[15, 18, 0],
[-5, 0, 11]])
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L, D = A.LDLdecomposition()
assert 15*L == Matrix([
[15, 0, 0],
[ 9, 15, 0],
[-3, 5, 15]])
assert D == Matrix([
[25, 0, 0],
[ 0, 9, 0],
[ 0, 0, 9]])
assert L * D * L.T == A
A = SparseMatrix(((3, 0, 2), (0, 0, 1), (1, 2, 0)))
assert A.inv() * A == SparseMatrix(eye(3))
A = SparseMatrix([
[ 2, -1, 0],
[-1, 2, -1],
[ 0, 0, 2]])
ans = SparseMatrix([
[Rational(2, 3), Rational(1, 3), Rational(1, 6)],
[Rational(1, 3), Rational(2, 3), Rational(1, 3)],
[ 0, 0, S.Half]])
assert A.inv(method='CH') == ans
assert A.inv(method='LDL') == ans
assert A * ans == SparseMatrix(eye(3))
s = A.solve(A[:, 0], 'LDL')
assert A*s == A[:, 0]
s = A.solve(A[:, 0], 'CH')
assert A*s == A[:, 0]
A = A.col_join(A)
s = A.solve_least_squares(A[:, 0], 'CH')
assert A*s == A[:, 0]
s = A.solve_least_squares(A[:, 0], 'LDL')
assert A*s == A[:, 0]
def test_lower_triangular_solve():
a, b, c, d = symbols('a:d')
u, v, w, x = symbols('u:x')
A = SparseMatrix([[a, 0], [c, d]])
B = MutableSparseMatrix([[u, v], [w, x]])
C = ImmutableSparseMatrix([[u, v], [w, x]])
sol = Matrix([[u/a, v/a], [(w - c*u/a)/d, (x - c*v/a)/d]])
assert A.lower_triangular_solve(B) == sol
assert A.lower_triangular_solve(C) == sol
def test_upper_triangular_solve():
a, b, c, d = symbols('a:d')
u, v, w, x = symbols('u:x')
A = SparseMatrix([[a, b], [0, d]])
B = MutableSparseMatrix([[u, v], [w, x]])
C = ImmutableSparseMatrix([[u, v], [w, x]])
sol = Matrix([[(u - b*w/d)/a, (v - b*x/d)/a], [w/d, x/d]])
assert A.upper_triangular_solve(B) == sol
assert A.upper_triangular_solve(C) == sol
def test_diagonal_solve():
a, d = symbols('a d')
u, v, w, x = symbols('u:x')
A = SparseMatrix([[a, 0], [0, d]])
B = MutableSparseMatrix([[u, v], [w, x]])
C = ImmutableSparseMatrix([[u, v], [w, x]])
sol = Matrix([[u/a, v/a], [w/d, x/d]])
assert A.diagonal_solve(B) == sol
assert A.diagonal_solve(C) == sol
def test_hermitian():
x = Symbol('x')
a = SparseMatrix([[0, I], [-I, 0]])
assert a.is_hermitian
a = SparseMatrix([[1, I], [-I, 1]])
assert a.is_hermitian
a[0, 0] = 2*I
assert a.is_hermitian is False
a[0, 0] = x
assert a.is_hermitian is None
a[0, 1] = a[1, 0]*I
assert a.is_hermitian is False
|
4be263d277c32e6532c5def2061eebb6cd92b77b400fdc9d0638af8fa8279e03 | import random
from sympy.core.numbers import I
from sympy import symbols, Symbol, Rational, sqrt, Poly
from sympy.matrices import Matrix, eye, ones
from sympy.abc import x, y, z
from sympy.testing.pytest import raises
from sympy.matrices.matrices import MatrixDeterminant
from sympy.matrices.common import NonSquareMatrixError, _MinimalMatrix, _CastableMatrix
class DeterminantOnlyMatrix(_MinimalMatrix, _CastableMatrix, MatrixDeterminant):
pass
def test_determinant():
for M in [Matrix(), Matrix([[1]])]:
assert (
M.det() ==
M._eval_det_bareiss() ==
M._eval_det_berkowitz() ==
M._eval_det_lu() ==
1)
M = Matrix(( (-3, 2),
( 8, -5) ))
assert M.det(method="bareiss") == -1
assert M.det(method="berkowitz") == -1
assert M.det(method="lu") == -1
M = Matrix(( (x, 1),
(y, 2*y) ))
assert M.det(method="bareiss") == 2*x*y - y
assert M.det(method="berkowitz") == 2*x*y - y
assert M.det(method="lu") == 2*x*y - y
M = Matrix(( (1, 1, 1),
(1, 2, 3),
(1, 3, 6) ))
assert M.det(method="bareiss") == 1
assert M.det(method="berkowitz") == 1
assert M.det(method="lu") == 1
M = Matrix(( ( 3, -2, 0, 5),
(-2, 1, -2, 2),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="bareiss") == -289
assert M.det(method="berkowitz") == -289
assert M.det(method="lu") == -289
M = Matrix(( ( 1, 2, 3, 4),
( 5, 6, 7, 8),
( 9, 10, 11, 12),
(13, 14, 15, 16) ))
assert M.det(method="bareiss") == 0
assert M.det(method="berkowitz") == 0
assert M.det(method="lu") == 0
M = Matrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(2, 0, 0, 0, 3) ))
assert M.det(method="bareiss") == 275
assert M.det(method="berkowitz") == 275
assert M.det(method="lu") == 275
M = Matrix(( ( 3, 0, 0, 0),
(-2, 1, 0, 0),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="bareiss") == 60
assert M.det(method="berkowitz") == 60
assert M.det(method="lu") == 60
M = Matrix(( ( 1, 0, 0, 0),
( 5, 0, 0, 0),
( 9, 10, 11, 0),
(13, 14, 15, 16) ))
assert M.det(method="bareiss") == 0
assert M.det(method="berkowitz") == 0
assert M.det(method="lu") == 0
M = Matrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(0, 0, 0, 0, 3) ))
assert M.det(method="bareiss") == 243
assert M.det(method="berkowitz") == 243
assert M.det(method="lu") == 243
M = Matrix(( (1, 0, 1, 2, 12),
(2, 0, 1, 1, 4),
(2, 1, 1, -1, 3),
(3, 2, -1, 1, 8),
(1, 1, 1, 0, 6) ))
assert M.det(method="bareiss") == -55
assert M.det(method="berkowitz") == -55
assert M.det(method="lu") == -55
M = Matrix(( (-5, 2, 3, 4, 5),
( 1, -4, 3, 4, 5),
( 1, 2, -3, 4, 5),
( 1, 2, 3, -2, 5),
( 1, 2, 3, 4, -1) ))
assert M.det(method="bareiss") == 11664
assert M.det(method="berkowitz") == 11664
assert M.det(method="lu") == 11664
M = Matrix(( ( 2, 7, -1, 3, 2),
( 0, 0, 1, 0, 1),
(-2, 0, 7, 0, 2),
(-3, -2, 4, 5, 3),
( 1, 0, 0, 0, 1) ))
assert M.det(method="bareiss") == 123
assert M.det(method="berkowitz") == 123
assert M.det(method="lu") == 123
M = Matrix(( (x, y, z),
(1, 0, 0),
(y, z, x) ))
assert M.det(method="bareiss") == z**2 - x*y
assert M.det(method="berkowitz") == z**2 - x*y
assert M.det(method="lu") == z**2 - x*y
# issue 13835
a = symbols('a')
M = lambda n: Matrix([[i + a*j for i in range(n)]
for j in range(n)])
assert M(5).det() == 0
assert M(6).det() == 0
assert M(7).det() == 0
def test_issue_14517():
M = Matrix([
[ 0, 10*I, 10*I, 0],
[10*I, 0, 0, 10*I],
[10*I, 0, 5 + 2*I, 10*I],
[ 0, 10*I, 10*I, 5 + 2*I]])
ev = M.eigenvals()
# test one random eigenvalue, the computation is a little slow
test_ev = random.choice(list(ev.keys()))
assert (M - test_ev*eye(4)).det() == 0
def test_legacy_det():
# Minimal support for legacy keys for 'method' in det()
# Partially copied from test_determinant()
M = Matrix(( ( 3, -2, 0, 5),
(-2, 1, -2, 2),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="bareis") == -289
assert M.det(method="det_lu") == -289
assert M.det(method="det_LU") == -289
M = Matrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(2, 0, 0, 0, 3) ))
assert M.det(method="bareis") == 275
assert M.det(method="det_lu") == 275
assert M.det(method="Bareis") == 275
M = Matrix(( (1, 0, 1, 2, 12),
(2, 0, 1, 1, 4),
(2, 1, 1, -1, 3),
(3, 2, -1, 1, 8),
(1, 1, 1, 0, 6) ))
assert M.det(method="bareis") == -55
assert M.det(method="det_lu") == -55
assert M.det(method="BAREISS") == -55
M = Matrix(( ( 3, 0, 0, 0),
(-2, 1, 0, 0),
( 0, -2, 5, 0),
( 5, 0, 3, 4) ))
assert M.det(method="bareiss") == 60
assert M.det(method="berkowitz") == 60
assert M.det(method="lu") == 60
M = Matrix(( ( 1, 0, 0, 0),
( 5, 0, 0, 0),
( 9, 10, 11, 0),
(13, 14, 15, 16) ))
assert M.det(method="bareiss") == 0
assert M.det(method="berkowitz") == 0
assert M.det(method="lu") == 0
M = Matrix(( (3, 2, 0, 0, 0),
(0, 3, 2, 0, 0),
(0, 0, 3, 2, 0),
(0, 0, 0, 3, 2),
(0, 0, 0, 0, 3) ))
assert M.det(method="bareiss") == 243
assert M.det(method="berkowitz") == 243
assert M.det(method="lu") == 243
M = Matrix(( (-5, 2, 3, 4, 5),
( 1, -4, 3, 4, 5),
( 1, 2, -3, 4, 5),
( 1, 2, 3, -2, 5),
( 1, 2, 3, 4, -1) ))
assert M.det(method="bareis") == 11664
assert M.det(method="det_lu") == 11664
assert M.det(method="BERKOWITZ") == 11664
M = Matrix(( ( 2, 7, -1, 3, 2),
( 0, 0, 1, 0, 1),
(-2, 0, 7, 0, 2),
(-3, -2, 4, 5, 3),
( 1, 0, 0, 0, 1) ))
assert M.det(method="bareis") == 123
assert M.det(method="det_lu") == 123
assert M.det(method="LU") == 123
def eye_Determinant(n):
return DeterminantOnlyMatrix(n, n, lambda i, j: int(i == j))
def zeros_Determinant(n):
return DeterminantOnlyMatrix(n, n, lambda i, j: 0)
def test_det():
a = DeterminantOnlyMatrix(2, 3, [1, 2, 3, 4, 5, 6])
raises(NonSquareMatrixError, lambda: a.det())
z = zeros_Determinant(2)
ey = eye_Determinant(2)
assert z.det() == 0
assert ey.det() == 1
x = Symbol('x')
a = DeterminantOnlyMatrix(0, 0, [])
b = DeterminantOnlyMatrix(1, 1, [5])
c = DeterminantOnlyMatrix(2, 2, [1, 2, 3, 4])
d = DeterminantOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 8])
e = DeterminantOnlyMatrix(4, 4,
[x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
from sympy.abc import i, j, k, l, m, n
f = DeterminantOnlyMatrix(3, 3, [i, l, m, 0, j, n, 0, 0, k])
g = DeterminantOnlyMatrix(3, 3, [i, 0, 0, l, j, 0, m, n, k])
h = DeterminantOnlyMatrix(3, 3, [x**3, 0, 0, i, x**-1, 0, j, k, x**-2])
# the method keyword for `det` doesn't kick in until 4x4 matrices,
# so there is no need to test all methods on smaller ones
assert a.det() == 1
assert b.det() == 5
assert c.det() == -2
assert d.det() == 3
assert e.det() == 4*x - 24
assert e.det(method='bareiss') == 4*x - 24
assert e.det(method='berkowitz') == 4*x - 24
assert f.det() == i*j*k
assert g.det() == i*j*k
assert h.det() == 1
raises(ValueError, lambda: e.det(iszerofunc="test"))
def test_adjugate():
x = Symbol('x')
e = DeterminantOnlyMatrix(4, 4,
[x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
adj = Matrix([
[ 4, -8, 4, 0],
[ 76, -14*x - 68, 14*x - 8, -4*x + 24],
[-122, 17*x + 142, -21*x + 4, 8*x - 48],
[ 48, -4*x - 72, 8*x, -4*x + 24]])
assert e.adjugate() == adj
assert e.adjugate(method='bareiss') == adj
assert e.adjugate(method='berkowitz') == adj
a = DeterminantOnlyMatrix(2, 3, [1, 2, 3, 4, 5, 6])
raises(NonSquareMatrixError, lambda: a.adjugate())
def test_util():
R = Rational
v1 = Matrix(1, 3, [1, 2, 3])
v2 = Matrix(1, 3, [3, 4, 5])
assert v1.norm() == sqrt(14)
assert v1.project(v2) == Matrix(1, 3, [R(39)/25, R(52)/25, R(13)/5])
assert Matrix.zeros(1, 2) == Matrix(1, 2, [0, 0])
assert ones(1, 2) == Matrix(1, 2, [1, 1])
assert v1.copy() == v1
# cofactor
assert eye(3) == eye(3).cofactor_matrix()
test = Matrix([[1, 3, 2], [2, 6, 3], [2, 3, 6]])
assert test.cofactor_matrix() == \
Matrix([[27, -6, -6], [-12, 2, 3], [-3, 1, 0]])
test = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert test.cofactor_matrix() == \
Matrix([[-3, 6, -3], [6, -12, 6], [-3, 6, -3]])
def test_cofactor_and_minors():
x = Symbol('x')
e = DeterminantOnlyMatrix(4, 4,
[x, 1, 2, 3, 4, 5, 6, 7, 2, 9, 10, 11, 12, 13, 14, 14])
m = Matrix([
[ x, 1, 3],
[ 2, 9, 11],
[12, 13, 14]])
cm = Matrix([
[ 4, 76, -122, 48],
[-8, -14*x - 68, 17*x + 142, -4*x - 72],
[ 4, 14*x - 8, -21*x + 4, 8*x],
[ 0, -4*x + 24, 8*x - 48, -4*x + 24]])
sub = Matrix([
[x, 1, 2],
[4, 5, 6],
[2, 9, 10]])
assert e.minor_submatrix(1, 2) == m
assert e.minor_submatrix(-1, -1) == sub
assert e.minor(1, 2) == -17*x - 142
assert e.cofactor(1, 2) == 17*x + 142
assert e.cofactor_matrix() == cm
assert e.cofactor_matrix(method="bareiss") == cm
assert e.cofactor_matrix(method="berkowitz") == cm
raises(ValueError, lambda: e.cofactor(4, 5))
raises(ValueError, lambda: e.minor(4, 5))
raises(ValueError, lambda: e.minor_submatrix(4, 5))
a = DeterminantOnlyMatrix(2, 3, [1, 2, 3, 4, 5, 6])
assert a.minor_submatrix(0, 0) == Matrix([[5, 6]])
raises(ValueError, lambda:
DeterminantOnlyMatrix(0, 0, []).minor_submatrix(0, 0))
raises(NonSquareMatrixError, lambda: a.cofactor(0, 0))
raises(NonSquareMatrixError, lambda: a.minor(0, 0))
raises(NonSquareMatrixError, lambda: a.cofactor_matrix())
def test_charpoly():
x, y = Symbol('x'), Symbol('y')
z, t = Symbol('z'), Symbol('t')
from sympy.abc import a,b,c
m = DeterminantOnlyMatrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
assert eye_Determinant(3).charpoly(x) == Poly((x - 1)**3, x)
assert eye_Determinant(3).charpoly(y) == Poly((y - 1)**3, y)
assert m.charpoly() == Poly(x**3 - 15*x**2 - 18*x, x)
raises(NonSquareMatrixError, lambda: Matrix([[1], [2]]).charpoly())
n = DeterminantOnlyMatrix(4, 4, [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
assert n.charpoly() == Poly(x**4, x)
n = DeterminantOnlyMatrix(4, 4, [45, 0, 0, 0, 0, 23, 0, 0, 0, 0, 87, 0, 0, 0, 0, 12])
assert n.charpoly() == Poly(x**4 - 167*x**3 + 8811*x**2 - 173457*x + 1080540, x)
n = DeterminantOnlyMatrix(3, 3, [x, 0, 0, a, y, 0, b, c, z])
assert n.charpoly() == Poly(t**3 - (x+y+z)*t**2 + t*(x*y+y*z+x*z) - x*y*z , t)
|
efa2596823c9feded2ba57ca73953d0ae2ebe2852971d12de97f63dfb2206dde | from sympy import Rational, I, expand_mul, S, simplify
from sympy.matrices.matrices import NonSquareMatrixError
from sympy.matrices import Matrix, zeros, eye, SparseMatrix
from sympy.abc import x, y, z
from sympy.testing.pytest import raises
def test_LUdecomp():
testmat = Matrix([[0, 2, 5, 3],
[3, 3, 7, 4],
[8, 4, 0, 2],
[-2, 6, 3, 4]])
L, U, p = testmat.LUdecomposition()
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4)
testmat = Matrix([[6, -2, 7, 4],
[0, 3, 6, 7],
[1, -2, 7, 4],
[-9, 2, 6, 3]])
L, U, p = testmat.LUdecomposition()
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4)
# non-square
testmat = Matrix([[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]])
L, U, p = testmat.LUdecomposition(rankcheck=False)
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == zeros(4, 3)
# square and singular
testmat = Matrix([[1, 2, 3],
[2, 4, 6],
[4, 5, 6]])
L, U, p = testmat.LUdecomposition(rankcheck=False)
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - testmat == zeros(3)
M = Matrix(((1, x, 1), (2, y, 0), (y, 0, z)))
L, U, p = M.LUdecomposition()
assert L.is_lower
assert U.is_upper
assert (L*U).permute_rows(p, 'backward') - M == zeros(3)
mL = Matrix((
(1, 0, 0),
(2, 3, 0),
))
assert mL.is_lower is True
assert mL.is_upper is False
mU = Matrix((
(1, 2, 3),
(0, 4, 5),
))
assert mU.is_lower is False
assert mU.is_upper is True
# test FF LUdecomp
M = Matrix([[1, 3, 3],
[3, 2, 6],
[3, 2, 2]])
P, L, Dee, U = M.LUdecompositionFF()
assert P*M == L*Dee.inv()*U
M = Matrix([[1, 2, 3, 4],
[3, -1, 2, 3],
[3, 1, 3, -2],
[6, -1, 0, 2]])
P, L, Dee, U = M.LUdecompositionFF()
assert P*M == L*Dee.inv()*U
M = Matrix([[0, 0, 1],
[2, 3, 0],
[3, 1, 4]])
P, L, Dee, U = M.LUdecompositionFF()
assert P*M == L*Dee.inv()*U
# issue 15794
M = Matrix(
[[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
)
raises(ValueError, lambda : M.LUdecomposition_Simple(rankcheck=True))
def test_QR():
A = Matrix([[1, 2], [2, 3]])
Q, S = A.QRdecomposition()
R = Rational
assert Q == Matrix([
[ 5**R(-1, 2), (R(2)/5)*(R(1)/5)**R(-1, 2)],
[2*5**R(-1, 2), (-R(1)/5)*(R(1)/5)**R(-1, 2)]])
assert S == Matrix([[5**R(1, 2), 8*5**R(-1, 2)], [0, (R(1)/5)**R(1, 2)]])
assert Q*S == A
assert Q.T * Q == eye(2)
A = Matrix([[1, 1, 1], [1, 1, 3], [2, 3, 4]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
def test_QR_non_square():
# Narrow (cols < rows) matrices
A = Matrix([[9, 0, 26], [12, 0, -7], [0, 4, 4], [0, -3, -3]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, -1, 4], [1, 4, -2], [1, 4, 2], [1, -1, 0]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix(2, 1, [1, 2])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
# Wide (cols > rows) matrices
A = Matrix([[1, 2, 3], [4, 5, 6]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, 2, 3, 4], [1, 4, 9, 16], [1, 8, 27, 64]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix(1, 2, [1, 2])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
def test_QR_trivial():
# Rank deficient matrices
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
# Zero rank matrices
A = Matrix([[0, 0, 0]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0], [0, 0, 0]])
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0], [0, 0, 0]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
# Rank deficient matrices with zero norm from beginning columns
A = Matrix([[0, 0, 0], [1, 2, 3]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0, 0], [1, 2, 3, 4], [0, 0, 0, 0], [2, 4, 6, 8]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0], [1, 2, 3]]).T
Q, R = A.QRdecomposition()
assert Q.T * Q == eye(Q.cols)
assert R.is_upper
assert A == Q*R
def test_LUdecomposition_Simple_iszerofunc():
# Test if callable passed to matrices.LUdecomposition_Simple() as iszerofunc keyword argument is used inside
# matrices.LUdecomposition_Simple()
magic_string = "I got passed in!"
def goofyiszero(value):
raise ValueError(magic_string)
try:
lu, p = Matrix([[1, 0], [0, 1]]).LUdecomposition_Simple(iszerofunc=goofyiszero)
except ValueError as err:
assert magic_string == err.args[0]
return
assert False
def test_LUdecomposition_iszerofunc():
# Test if callable passed to matrices.LUdecomposition() as iszerofunc keyword argument is used inside
# matrices.LUdecomposition_Simple()
magic_string = "I got passed in!"
def goofyiszero(value):
raise ValueError(magic_string)
try:
l, u, p = Matrix([[1, 0], [0, 1]]).LUdecomposition(iszerofunc=goofyiszero)
except ValueError as err:
assert magic_string == err.args[0]
return
assert False
def test_LDLdecomposition():
raises(NonSquareMatrixError, lambda: Matrix((1, 2)).LDLdecomposition())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).LDLdecomposition())
raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).LDLdecomposition())
raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).LDLdecomposition())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).LDLdecomposition(hermitian=False))
A = Matrix(((1, 5), (5, 1)))
L, D = A.LDLdecomposition(hermitian=False)
assert L * D * L.T == A
A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L, D = A.LDLdecomposition()
assert L * D * L.T == A
assert L.is_lower
assert L == Matrix([[1, 0, 0], [ Rational(3, 5), 1, 0], [Rational(-1, 5), Rational(1, 3), 1]])
assert D.is_diagonal()
assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]])
A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
L, D = A.LDLdecomposition()
assert expand_mul(L * D * L.H) == A
assert L == Matrix(((1, 0, 0), (I/2, 1, 0), (S.Half - I/2, 0, 1)))
assert D == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9)))
raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).LDLdecomposition())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).LDLdecomposition())
raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).LDLdecomposition())
raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).LDLdecomposition())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).LDLdecomposition(hermitian=False))
A = SparseMatrix(((1, 5), (5, 1)))
L, D = A.LDLdecomposition(hermitian=False)
assert L * D * L.T == A
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L, D = A.LDLdecomposition()
assert L * D * L.T == A
assert L.is_lower
assert L == Matrix([[1, 0, 0], [ Rational(3, 5), 1, 0], [Rational(-1, 5), Rational(1, 3), 1]])
assert D.is_diagonal()
assert D == Matrix([[25, 0, 0], [0, 9, 0], [0, 0, 9]])
A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
L, D = A.LDLdecomposition()
assert expand_mul(L * D * L.H) == A
assert L == Matrix(((1, 0, 0), (I/2, 1, 0), (S.Half - I/2, 0, 1)))
assert D == Matrix(((4, 0, 0), (0, 1, 0), (0, 0, 9)))
def test_pinv_succeeds_with_rank_decomposition_method():
# Test rank decomposition method of pseudoinverse succeeding
As = [Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0,0,0,0,0,0]])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
def test_rank_decomposition():
a = Matrix(0, 0, [])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
a = Matrix(1, 1, [5])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
a = Matrix(3, 3, [1, 2, 3, 1, 2, 3, 1, 2, 3])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
a = Matrix([
[0, 0, 1, 2, 2, -5, 3],
[-1, 5, 2, 2, 1, -7, 5],
[0, 0, -2, -3, -3, 8, -5],
[-1, 5, 0, -1, -2, 1, 0]])
c, f = a.rank_decomposition()
assert f.is_echelon
assert c.cols == f.rows == a.rank()
assert c * f == a
|
71dce23ca4d716df4e33cc9f3bdc4525a002cbcb05aceeb63b4c6e3858bbead8 | from sympy import Symbol, Poly
from sympy.polys.solvers import RawMatrix as Matrix
from sympy.matrices.normalforms import invariant_factors, smith_normal_form
from sympy.polys.domains import ZZ, QQ
def test_smith_normal():
m = Matrix([[12, 6, 4,8],[3,9,6,12],[2,16,14,28],[20,10,10,20]])
setattr(m, 'ring', ZZ)
smf = Matrix([[1, 0, 0, 0], [0, 10, 0, 0], [0, 0, -30, 0], [0, 0, 0, 0]])
assert smith_normal_form(m) == smf
x = Symbol('x')
m = Matrix([[Poly(x-1), Poly(1, x),Poly(-1,x)],
[0, Poly(x), Poly(-1,x)],
[Poly(0,x),Poly(-1,x),Poly(x)]])
setattr(m, 'ring', QQ[x])
invs = (Poly(1, x, domain='QQ'), Poly(x - 1, domain='QQ'), Poly(x**2 - 1, domain='QQ'))
assert invariant_factors(m) == invs
m = Matrix([[2, 4]])
setattr(m, 'ring', ZZ)
smf = Matrix([[2, 0]])
assert smith_normal_form(m) == smf
|
bca430e3ffee730ac78b2cc5df77514dda5f07a43a9a19c257451b4bb9071678 | from itertools import product
from sympy import (ImmutableMatrix, Matrix, eye, zeros, S, Equality,
Unequality, ImmutableSparseMatrix, SparseMatrix, sympify,
integrate)
from sympy.abc import x, y
from sympy.testing.pytest import raises
IM = ImmutableMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
ieye = ImmutableMatrix(eye(3))
def test_immutable_creation():
assert IM.shape == (3, 3)
assert IM[1, 2] == 6
assert IM[2, 2] == 9
def test_immutability():
with raises(TypeError):
IM[2, 2] = 5
def test_slicing():
assert IM[1, :] == ImmutableMatrix([[4, 5, 6]])
assert IM[:2, :2] == ImmutableMatrix([[1, 2], [4, 5]])
def test_subs():
A = ImmutableMatrix([[1, 2], [3, 4]])
B = ImmutableMatrix([[1, 2], [x, 4]])
C = ImmutableMatrix([[-x, x*y], [-(x + y), y**2]])
assert B.subs(x, 3) == A
assert (x*B).subs(x, 3) == 3*A
assert (x*eye(2) + B).subs(x, 3) == 3*eye(2) + A
assert C.subs([[x, -1], [y, -2]]) == A
assert C.subs([(x, -1), (y, -2)]) == A
assert C.subs({x: -1, y: -2}) == A
assert C.subs({x: y - 1, y: x - 1}, simultaneous=True) == \
ImmutableMatrix([[1 - y, (x - 1)*(y - 1)], [2 - x - y, (x - 1)**2]])
def test_as_immutable():
X = Matrix([[1, 2], [3, 4]])
assert sympify(X) == X.as_immutable() == ImmutableMatrix([[1, 2], [3, 4]])
X = SparseMatrix(5, 5, {})
assert sympify(X) == X.as_immutable() == ImmutableSparseMatrix(
[[0 for i in range(5)] for i in range(5)])
def test_function_return_types():
# Lets ensure that decompositions of immutable matrices remain immutable
# I.e. do MatrixBase methods return the correct class?
X = ImmutableMatrix([[1, 2], [3, 4]])
Y = ImmutableMatrix([[1], [0]])
q, r = X.QRdecomposition()
assert (type(q), type(r)) == (ImmutableMatrix, ImmutableMatrix)
assert type(X.LUsolve(Y)) == ImmutableMatrix
assert type(X.QRsolve(Y)) == ImmutableMatrix
X = ImmutableMatrix([[5, 2], [2, 7]])
assert X.T == X
assert X.is_symmetric
assert type(X.cholesky()) == ImmutableMatrix
L, D = X.LDLdecomposition()
assert (type(L), type(D)) == (ImmutableMatrix, ImmutableMatrix)
X = ImmutableMatrix([[1, 2], [2, 1]])
assert X.is_diagonalizable()
assert X.det() == -3
assert X.norm(2) == 3
assert type(X.eigenvects()[0][2][0]) == ImmutableMatrix
assert type(zeros(3, 3).as_immutable().nullspace()[0]) == ImmutableMatrix
X = ImmutableMatrix([[1, 0], [2, 1]])
assert type(X.lower_triangular_solve(Y)) == ImmutableMatrix
assert type(X.T.upper_triangular_solve(Y)) == ImmutableMatrix
assert type(X.minor_submatrix(0, 0)) == ImmutableMatrix
# issue 6279
# https://github.com/sympy/sympy/issues/6279
# Test that Immutable _op_ Immutable => Immutable and not MatExpr
def test_immutable_evaluation():
X = ImmutableMatrix(eye(3))
A = ImmutableMatrix(3, 3, range(9))
assert isinstance(X + A, ImmutableMatrix)
assert isinstance(X * A, ImmutableMatrix)
assert isinstance(X * 2, ImmutableMatrix)
assert isinstance(2 * X, ImmutableMatrix)
assert isinstance(A**2, ImmutableMatrix)
def test_deterimant():
assert ImmutableMatrix(4, 4, lambda i, j: i + j).det() == 0
def test_Equality():
assert Equality(IM, IM) is S.true
assert Unequality(IM, IM) is S.false
assert Equality(IM, IM.subs(1, 2)) is S.false
assert Unequality(IM, IM.subs(1, 2)) is S.true
assert Equality(IM, 2) is S.false
assert Unequality(IM, 2) is S.true
M = ImmutableMatrix([x, y])
assert Equality(M, IM) is S.false
assert Unequality(M, IM) is S.true
assert Equality(M, M.subs(x, 2)).subs(x, 2) is S.true
assert Unequality(M, M.subs(x, 2)).subs(x, 2) is S.false
assert Equality(M, M.subs(x, 2)).subs(x, 3) is S.false
assert Unequality(M, M.subs(x, 2)).subs(x, 3) is S.true
def test_integrate():
intIM = integrate(IM, x)
assert intIM.shape == IM.shape
assert all([intIM[i, j] == (1 + j + 3*i)*x for i, j in
product(range(3), range(3))])
|
495db3179a2e0a26e9b0b2cff60943792653977a7344051e6e7a6896fcb684b7 | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densetools import eye
from sympy.matrices.densearith import add, sub, mulmatmat, mulmatscaler
from sympy import ZZ
def test_add():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = [[ZZ(5), ZZ(4), ZZ(9)], [ZZ(3), ZZ(7), ZZ(1)], [ZZ(12), ZZ(13), ZZ(14)]]
c = [[ZZ(12)], [ZZ(17)], [ZZ(21)]]
d = [[ZZ(3)], [ZZ(4)], [ZZ(5)]]
e = [[ZZ(12), ZZ(78)], [ZZ(56), ZZ(79)]]
f = [[ZZ.zero, ZZ.zero], [ZZ.zero, ZZ.zero]]
assert add(a, b, ZZ) == [[ZZ(8), ZZ(11), ZZ(13)], [ZZ(5), ZZ(11), ZZ(6)], [ZZ(18), ZZ(15), ZZ(17)]]
assert add(c, d, ZZ) == [[ZZ(15)], [ZZ(21)], [ZZ(26)]]
assert add(e, f, ZZ) == e
def test_sub():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = [[ZZ(5), ZZ(4), ZZ(9)], [ZZ(3), ZZ(7), ZZ(1)], [ZZ(12), ZZ(13), ZZ(14)]]
c = [[ZZ(12)], [ZZ(17)], [ZZ(21)]]
d = [[ZZ(3)], [ZZ(4)], [ZZ(5)]]
e = [[ZZ(12), ZZ(78)], [ZZ(56), ZZ(79)]]
f = [[ZZ.zero, ZZ.zero], [ZZ.zero, ZZ.zero]]
assert sub(a, b, ZZ) == [[ZZ(-2), ZZ(3), ZZ(-5)], [ZZ(-1), ZZ(-3), ZZ(4)], [ZZ(-6), ZZ(-11), ZZ(-11)]]
assert sub(c, d, ZZ) == [[ZZ(9)], [ZZ(13)], [ZZ(16)]]
assert sub(e, f, ZZ) == e
def test_mulmatmat():
a = [[ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]]
b = [[ZZ(1), ZZ(2)], [ZZ(7), ZZ(8)]]
c = eye(2, ZZ)
d = [[ZZ(6)], [ZZ(7)]]
assert mulmatmat(a, b, ZZ) == [[ZZ(31), ZZ(38)], [ZZ(47), ZZ(58)]]
assert mulmatmat(a, c, ZZ) == [[ZZ(3), ZZ(4)], [ZZ(5), ZZ(6)]]
assert mulmatmat(b, d, ZZ) == [[ZZ(20)], [ZZ(98)]]
def test_mulmatscaler():
a = eye(3, ZZ)
b = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
assert mulmatscaler(a, ZZ(4), ZZ) == [[ZZ(4), ZZ(0), ZZ(0)], [ZZ(0), ZZ(4), ZZ(0)], [ZZ(0), ZZ(0), ZZ(4)]]
assert mulmatscaler(b, ZZ(1), ZZ) == [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
|
b4a8fe431a2b0486b25c3fcdc7b70af1fe04417767611f9e7451a681790fbe56 | from sympy.testing.pytest import ignore_warnings
from sympy.utilities.exceptions import SymPyDeprecationWarning
with ignore_warnings(SymPyDeprecationWarning):
from sympy.matrices.densetools import trace, transpose, eye
from sympy import ZZ
def test_trace():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = eye(2, ZZ)
assert trace(a, ZZ) == ZZ(10)
assert trace(b, ZZ) == ZZ(2)
def test_transpose():
a = [[ZZ(3), ZZ(7), ZZ(4)], [ZZ(2), ZZ(4), ZZ(5)], [ZZ(6), ZZ(2), ZZ(3)]]
b = eye(4, ZZ)
assert transpose(a, ZZ) == ([[ZZ(3), ZZ(2), ZZ(6)], [ZZ(7), ZZ(4), ZZ(2)], [ZZ(4), ZZ(5), ZZ(3)]])
assert transpose(b, ZZ) == b
|
78742d408606ae746fb59eceb61dd5cee0c7cf5a3f6b7380198f39132b8a22d5 | """
We have a few different kind of Matrices
Matrix, ImmutableMatrix, MatrixExpr
Here we test the extent to which they cooperate
"""
from sympy import symbols
from sympy.matrices import (Matrix, MatrixSymbol, eye, Identity,
ImmutableMatrix)
from sympy.matrices.expressions import MatrixExpr, MatAdd
from sympy.matrices.common import classof
from sympy.testing.pytest import raises
SM = MatrixSymbol('X', 3, 3)
SV = MatrixSymbol('v', 3, 1)
MM = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
IM = ImmutableMatrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
meye = eye(3)
imeye = ImmutableMatrix(eye(3))
ideye = Identity(3)
a, b, c = symbols('a,b,c')
def test_IM_MM():
assert isinstance(MM + IM, ImmutableMatrix)
assert isinstance(IM + MM, ImmutableMatrix)
assert isinstance(2*IM + MM, ImmutableMatrix)
assert MM.equals(IM)
def test_ME_MM():
assert isinstance(Identity(3) + MM, MatrixExpr)
assert isinstance(SM + MM, MatAdd)
assert isinstance(MM + SM, MatAdd)
assert (Identity(3) + MM)[1, 1] == 6
def test_equality():
a, b, c = Identity(3), eye(3), ImmutableMatrix(eye(3))
for x in [a, b, c]:
for y in [a, b, c]:
assert x.equals(y)
def test_matrix_symbol_MM():
X = MatrixSymbol('X', 3, 3)
Y = eye(3) + X
assert Y[1, 1] == 1 + X[1, 1]
def test_matrix_symbol_vector_matrix_multiplication():
A = MM * SV
B = IM * SV
assert A == B
C = (SV.T * MM.T).T
assert B == C
D = (SV.T * IM.T).T
assert C == D
def test_indexing_interactions():
assert (a * IM)[1, 1] == 5*a
assert (SM + IM)[1, 1] == SM[1, 1] + IM[1, 1]
assert (SM * IM)[1, 1] == SM[1, 0]*IM[0, 1] + SM[1, 1]*IM[1, 1] + \
SM[1, 2]*IM[2, 1]
def test_classof():
A = Matrix(3, 3, range(9))
B = ImmutableMatrix(3, 3, range(9))
C = MatrixSymbol('C', 3, 3)
assert classof(A, A) == Matrix
assert classof(B, B) == ImmutableMatrix
assert classof(A, B) == ImmutableMatrix
assert classof(B, A) == ImmutableMatrix
raises(TypeError, lambda: classof(A, C))
|
aaf5733689428760b7a0053af389b90b871f9f98727d26d02de5923683ec0450 | from sympy.matrices.sparsetools import _doktocsr, _csrtodok, banded
from sympy import eye, ones, zeros, Matrix, SparseMatrix
from sympy.testing.pytest import raises
def test_doktocsr():
a = SparseMatrix([[1, 2, 0, 0], [0, 3, 9, 0], [0, 1, 4, 0]])
b = SparseMatrix(4, 6, [10, 20, 0, 0, 0, 0, 0, 30, 0, 40, 0, 0, 0, 0, 50,
60, 70, 0, 0, 0, 0, 0, 0, 80])
c = SparseMatrix(4, 4, [0, 0, 0, 0, 0, 12, 0, 2, 15, 0, 12, 0, 0, 0, 0, 4])
d = SparseMatrix(10, 10, {(1, 1): 12, (3, 5): 7, (7, 8): 12})
e = SparseMatrix([[0, 0, 0], [1, 0, 2], [3, 0, 0]])
f = SparseMatrix(7, 8, {(2, 3): 5, (4, 5):12})
assert _doktocsr(a) == [[1, 2, 3, 9, 1, 4], [0, 1, 1, 2, 1, 2],
[0, 2, 4, 6], [3, 4]]
assert _doktocsr(b) == [[10, 20, 30, 40, 50, 60, 70, 80],
[0, 1, 1, 3, 2, 3, 4, 5], [0, 2, 4, 7, 8], [4, 6]]
assert _doktocsr(c) == [[12, 2, 15, 12, 4], [1, 3, 0, 2, 3],
[0, 0, 2, 4, 5], [4, 4]]
assert _doktocsr(d) == [[12, 7, 12], [1, 5, 8],
[0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3], [10, 10]]
assert _doktocsr(e) == [[1, 2, 3], [0, 2, 0], [0, 0, 2, 3], [3, 3]]
assert _doktocsr(f) == [[5, 12], [3, 5], [0, 0, 0, 1, 1, 2, 2, 2], [7, 8]]
def test_csrtodok():
h = [[5, 7, 5], [2, 1, 3], [0, 1, 1, 3], [3, 4]]
g = [[12, 5, 4], [2, 4, 2], [0, 1, 2, 3], [3, 7]]
i = [[1, 3, 12], [0, 2, 4], [0, 2, 3], [2, 5]]
j = [[11, 15, 12, 15], [2, 4, 1, 2], [0, 1, 1, 2, 3, 4], [5, 8]]
k = [[1, 3], [2, 1], [0, 1, 1, 2], [3, 3]]
assert _csrtodok(h) == SparseMatrix(3, 4,
{(0, 2): 5, (2, 1): 7, (2, 3): 5})
assert _csrtodok(g) == SparseMatrix(3, 7,
{(0, 2): 12, (1, 4): 5, (2, 2): 4})
assert _csrtodok(i) == SparseMatrix([[1, 0, 3, 0, 0], [0, 0, 0, 0, 12]])
assert _csrtodok(j) == SparseMatrix(5, 8,
{(0, 2): 11, (2, 4): 15, (3, 1): 12, (4, 2): 15})
assert _csrtodok(k) == SparseMatrix(3, 3, {(0, 2): 1, (2, 1): 3})
def test_banded():
raises(TypeError, lambda: banded())
raises(TypeError, lambda: banded(1))
raises(TypeError, lambda: banded(1, 2))
raises(TypeError, lambda: banded(1, 2, 3))
raises(TypeError, lambda: banded(1, 2, 3, 4))
raises(ValueError, lambda: banded({0: (1, 2)}, rows=1))
raises(ValueError, lambda: banded({0: (1, 2)}, cols=1))
raises(ValueError, lambda: banded(1, {0: (1, 2)}))
raises(ValueError, lambda: banded(2, 1, {0: (1, 2)}))
raises(ValueError, lambda: banded(1, 2, {0: (1, 2)}))
assert isinstance(banded(2, 4, {}), SparseMatrix)
assert banded(2, 4, {}) == zeros(2, 4)
assert banded({0: 0, 1: 0}) == zeros(0)
assert banded({0: Matrix([1, 2])}) == Matrix([1, 2])
assert banded({1: [1, 2, 3, 0], -1: [4, 5, 6]}) == \
banded({1: (1, 2, 3), -1: (4, 5, 6)}) == \
Matrix([
[0, 1, 0, 0],
[4, 0, 2, 0],
[0, 5, 0, 3],
[0, 0, 6, 0]])
assert banded(3, 4, {-1: 1, 0: 2, 1: 3}) == \
Matrix([
[2, 3, 0, 0],
[1, 2, 3, 0],
[0, 1, 2, 3]])
s = lambda d: (1 + d)**2
assert banded(5, {0: s, 2: s}) == \
Matrix([
[1, 0, 1, 0, 0],
[0, 4, 0, 4, 0],
[0, 0, 9, 0, 9],
[0, 0, 0, 16, 0],
[0, 0, 0, 0, 25]])
assert banded(2, {0: 1}) == \
Matrix([
[1, 0],
[0, 1]])
assert banded(2, 3, {0: 1}) == \
Matrix([
[1, 0, 0],
[0, 1, 0]])
vert = Matrix([1, 2, 3])
assert banded({0: vert}, cols=3) == \
Matrix([
[1, 0, 0],
[2, 1, 0],
[3, 2, 1],
[0, 3, 2],
[0, 0, 3]])
assert banded(4, {0: ones(2)}) == \
Matrix([
[1, 1, 0, 0],
[1, 1, 0, 0],
[0, 0, 1, 1],
[0, 0, 1, 1]])
raises(ValueError, lambda: banded({0: 2, 1: ones(2)}, rows=5))
assert banded({0: 2, 2: (ones(2),)*3}) == \
Matrix([
[2, 0, 1, 1, 0, 0, 0, 0],
[0, 2, 1, 1, 0, 0, 0, 0],
[0, 0, 2, 0, 1, 1, 0, 0],
[0, 0, 0, 2, 1, 1, 0, 0],
[0, 0, 0, 0, 2, 0, 1, 1],
[0, 0, 0, 0, 0, 2, 1, 1]])
raises(ValueError, lambda: banded({0: (2,)*5, 1: (ones(2),)*3}))
u2 = Matrix([[1, 1], [0, 1]])
assert banded({0: (2,)*5, 1: (u2,)*3}) == \
Matrix([
[2, 1, 1, 0, 0, 0, 0],
[0, 2, 1, 0, 0, 0, 0],
[0, 0, 2, 1, 1, 0, 0],
[0, 0, 0, 2, 1, 0, 0],
[0, 0, 0, 0, 2, 1, 1],
[0, 0, 0, 0, 0, 0, 1]])
assert banded({0:(0, ones(2)), 2: 2}) == \
Matrix([
[0, 0, 2],
[0, 1, 1],
[0, 1, 1]])
raises(ValueError, lambda: banded({0: (0, ones(2)), 1: 2}))
assert banded({0: 1}, cols=3) == banded({0: 1}, rows=3) == eye(3)
assert banded({1: 1}, rows=3) == Matrix([
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]])
|
9d9ed4d0ed4067d5e6aff30d46e2fc6b6d3920abbfdb4deb9353727b058ce4a7 | import random
from sympy import (
Abs, Add, E, Float, I, Integer, Max, Min, Poly, Pow, PurePoly, Rational,
S, Symbol, cos, exp, log, expand_mul, oo, pi, signsimp, simplify, sin,
sqrt, symbols, sympify, trigsimp, tan, sstr, diff, Function, expand)
from sympy.matrices.matrices import (ShapeError, MatrixError,
NonSquareMatrixError, DeferredVector, _find_reasonable_pivot_naive,
_simplify)
from sympy.matrices import (
GramSchmidt, ImmutableMatrix, ImmutableSparseMatrix, Matrix,
SparseMatrix, casoratian, diag, eye, hessian,
matrix_multiply_elementwise, ones, randMatrix, rot_axis1, rot_axis2,
rot_axis3, wronskian, zeros, MutableDenseMatrix, ImmutableDenseMatrix, MatrixSymbol)
from sympy.core.compatibility import iterable, Hashable
from sympy.core import Tuple, Wild
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.utilities.iterables import flatten, capture
from sympy.testing.pytest import raises, XFAIL, skip, warns_deprecated_sympy
from sympy.solvers import solve
from sympy.assumptions import Q
from sympy.tensor.array import Array
from sympy.matrices.expressions import MatPow
from sympy.abc import a, b, c, d, x, y, z, t
# don't re-order this list
classes = (Matrix, SparseMatrix, ImmutableMatrix, ImmutableSparseMatrix)
def test_args():
for n, cls in enumerate(classes):
m = cls.zeros(3, 2)
# all should give back the same type of arguments, e.g. ints for shape
assert m.shape == (3, 2) and all(type(i) is int for i in m.shape)
assert m.rows == 3 and type(m.rows) is int
assert m.cols == 2 and type(m.cols) is int
if not n % 2:
assert type(m._mat) in (list, tuple, Tuple)
else:
assert type(m._smat) is dict
def test_division():
v = Matrix(1, 2, [x, y])
assert v.__div__(z) == Matrix(1, 2, [x/z, y/z])
assert v.__truediv__(z) == Matrix(1, 2, [x/z, y/z])
assert v/z == Matrix(1, 2, [x/z, y/z])
def test_sum():
m = Matrix([[1, 2, 3], [x, y, x], [2*y, -50, z*x]])
assert m + m == Matrix([[2, 4, 6], [2*x, 2*y, 2*x], [4*y, -100, 2*z*x]])
n = Matrix(1, 2, [1, 2])
raises(ShapeError, lambda: m + n)
def test_abs():
m = Matrix(1, 2, [-3, x])
n = Matrix(1, 2, [3, Abs(x)])
assert abs(m) == n
def test_addition():
a = Matrix((
(1, 2),
(3, 1),
))
b = Matrix((
(1, 2),
(3, 0),
))
assert a + b == a.add(b) == Matrix([[2, 4], [6, 1]])
def test_fancy_index_matrix():
for M in (Matrix, SparseMatrix):
a = M(3, 3, range(9))
assert a == a[:, :]
assert a[1, :] == Matrix(1, 3, [3, 4, 5])
assert a[:, 1] == Matrix([1, 4, 7])
assert a[[0, 1], :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[[0, 1], 2] == a[[0, 1], [2]]
assert a[2, [0, 1]] == a[[2], [0, 1]]
assert a[:, [0, 1]] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[0, 0] == 0
assert a[0:2, :] == Matrix([[0, 1, 2], [3, 4, 5]])
assert a[:, 0:2] == Matrix([[0, 1], [3, 4], [6, 7]])
assert a[::2, 1] == a[[0, 2], 1]
assert a[1, ::2] == a[1, [0, 2]]
a = M(3, 3, range(9))
assert a[[0, 2, 1, 2, 1], :] == Matrix([
[0, 1, 2],
[6, 7, 8],
[3, 4, 5],
[6, 7, 8],
[3, 4, 5]])
assert a[:, [0,2,1,2,1]] == Matrix([
[0, 2, 1, 2, 1],
[3, 5, 4, 5, 4],
[6, 8, 7, 8, 7]])
a = SparseMatrix.zeros(3)
a[1, 2] = 2
a[0, 1] = 3
a[2, 0] = 4
assert a.extract([1, 1], [2]) == Matrix([
[2],
[2]])
assert a.extract([1, 0], [2, 2, 2]) == Matrix([
[2, 2, 2],
[0, 0, 0]])
assert a.extract([1, 0, 1, 2], [2, 0, 1, 0]) == Matrix([
[2, 0, 0, 0],
[0, 0, 3, 0],
[2, 0, 0, 0],
[0, 4, 0, 4]])
def test_multiplication():
a = Matrix((
(1, 2),
(3, 1),
(0, 6),
))
b = Matrix((
(1, 2),
(3, 0),
))
c = a*b
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
try:
eval('c = a @ b')
except SyntaxError:
pass
else:
assert c[0, 0] == 7
assert c[0, 1] == 2
assert c[1, 0] == 6
assert c[1, 1] == 6
assert c[2, 0] == 18
assert c[2, 1] == 0
h = matrix_multiply_elementwise(a, c)
assert h == a.multiply_elementwise(c)
assert h[0, 0] == 7
assert h[0, 1] == 4
assert h[1, 0] == 18
assert h[1, 1] == 6
assert h[2, 0] == 0
assert h[2, 1] == 0
raises(ShapeError, lambda: matrix_multiply_elementwise(a, b))
c = b * Symbol("x")
assert isinstance(c, Matrix)
assert c[0, 0] == x
assert c[0, 1] == 2*x
assert c[1, 0] == 3*x
assert c[1, 1] == 0
c2 = x * b
assert c == c2
c = 5 * b
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
try:
eval('c = 5 @ b')
except SyntaxError:
pass
else:
assert isinstance(c, Matrix)
assert c[0, 0] == 5
assert c[0, 1] == 2*5
assert c[1, 0] == 3*5
assert c[1, 1] == 0
def test_power():
raises(NonSquareMatrixError, lambda: Matrix((1, 2))**2)
R = Rational
A = Matrix([[2, 3], [4, 5]])
assert (A**-3)[:] == [R(-269)/8, R(153)/8, R(51)/2, R(-29)/2]
assert (A**5)[:] == [6140, 8097, 10796, 14237]
A = Matrix([[2, 1, 3], [4, 2, 4], [6, 12, 1]])
assert (A**3)[:] == [290, 262, 251, 448, 440, 368, 702, 954, 433]
assert A**0 == eye(3)
assert A**1 == A
assert (Matrix([[2]]) ** 100)[0, 0] == 2**100
assert eye(2)**10000000 == eye(2)
assert Matrix([[1, 2], [3, 4]])**Integer(2) == Matrix([[7, 10], [15, 22]])
A = Matrix([[33, 24], [48, 57]])
assert (A**S.Half)[:] == [5, 2, 4, 7]
A = Matrix([[0, 4], [-1, 5]])
assert (A**S.Half)**2 == A
assert Matrix([[1, 0], [1, 1]])**S.Half == Matrix([[1, 0], [S.Half, 1]])
assert Matrix([[1, 0], [1, 1]])**0.5 == Matrix([[1.0, 0], [0.5, 1.0]])
from sympy.abc import a, b, n
assert Matrix([[1, a], [0, 1]])**n == Matrix([[1, a*n], [0, 1]])
assert Matrix([[b, a], [0, b]])**n == Matrix([[b**n, a*b**(n-1)*n], [0, b**n]])
assert Matrix([
[a**n, a**(n - 1)*n, (a**n*n**2 - a**n*n)/(2*a**2)],
[ 0, a**n, a**(n - 1)*n],
[ 0, 0, a**n]])
assert Matrix([[a, 1, 0], [0, a, 0], [0, 0, b]])**n == Matrix([
[a**n, a**(n-1)*n, 0],
[0, a**n, 0],
[0, 0, b**n]])
A = Matrix([[1, 0], [1, 7]])
assert A._matrix_pow_by_jordan_blocks(S(3)) == A._eval_pow_by_recursion(3)
A = Matrix([[2]])
assert A**10 == Matrix([[2**10]]) == A._matrix_pow_by_jordan_blocks(S(10)) == \
A._eval_pow_by_recursion(10)
# testing a matrix that cannot be jordan blocked issue 11766
m = Matrix([[3, 0, 0, 0, -3], [0, -3, -3, 0, 3], [0, 3, 0, 3, 0], [0, 0, 3, 0, 3], [3, 0, 0, 3, 0]])
raises(MatrixError, lambda: m._matrix_pow_by_jordan_blocks(S(10)))
# test issue 11964
raises(MatrixError, lambda: Matrix([[1, 1], [3, 3]])._matrix_pow_by_jordan_blocks(S(-10)))
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 0]]) # Nilpotent jordan block size 3
assert A**10.0 == Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[8, 1], [3, 2]])
assert A**10.0 == Matrix([[1760744107, 272388050], [817164150, 126415807]])
A = Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 1
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]]) # Nilpotent jordan block size 2
assert A**10.0 == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
n = Symbol('n', integer=True)
assert isinstance(A**n, MatPow)
n = Symbol('n', integer=True, negative=True)
raises(ValueError, lambda: A**n)
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == Matrix([
[KroneckerDelta(0, n), KroneckerDelta(1, n), -KroneckerDelta(0, n) - KroneckerDelta(1, n) + 1],
[ 0, KroneckerDelta(0, n), 1 - KroneckerDelta(0, n)],
[ 0, 0, 1]])
assert A**(n + 2) == Matrix([[0, 0, 1], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**Rational(3, 2))
A = Matrix([[0, 0, 1], [3, 0, 1], [4, 3, 1]])
assert A**5.0 == Matrix([[168, 72, 89], [291, 144, 161], [572, 267, 329]])
assert A**5.0 == A**5
A = Matrix([[0, 1, 0],[-1, 0, 0],[0, 0, 0]])
n = Symbol("n")
An = A**n
assert An.subs(n, 2).doit() == A**2
raises(ValueError, lambda: An.subs(n, -2).doit())
assert An * An == A**(2*n)
# concretizing behavior for non-integer and complex powers
A = Matrix([[0,0,0],[0,0,0],[0,0,0]])
n = Symbol('n', integer=True, positive=True)
assert A**n == A
n = Symbol('n', integer=True, nonnegative=True)
assert A**n == diag(0**n, 0**n, 0**n)
assert (A**n).subs(n, 0) == eye(3)
assert (A**n).subs(n, 1) == zeros(3)
A = Matrix ([[2,0,0],[0,2,0],[0,0,2]])
assert A**2.1 == diag (2**2.1, 2**2.1, 2**2.1)
assert A**I == diag (2**I, 2**I, 2**I)
A = Matrix([[0, 1, 0], [0, 0, 1], [0, 0, 1]])
raises(ValueError, lambda: A**2.1)
raises(ValueError, lambda: A**I)
A = Matrix([[S.Half, S.Half], [S.Half, S.Half]])
assert A**S.Half == A
A = Matrix([[1, 1],[3, 3]])
assert A**S.Half == Matrix ([[S.Half, S.Half], [3*S.Half, 3*S.Half]])
def test_issue_17247_expression_blowup_1():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
assert M.exp().expand() == Matrix([
[ (exp(2*x) + exp(2))/2, (-exp(2*x) + exp(2))/2],
[(-exp(2*x) + exp(2))/2, (exp(2*x) + exp(2))/2]])
def test_issue_17247_expression_blowup_2():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
P, J = M.jordan_form ()
assert P*J*P.inv()
def test_issue_17247_expression_blowup_3():
M = Matrix([[1+x, 1-x], [1-x, 1+x]])
assert M**100 == Matrix([
[633825300114114700748351602688*x**100 + 633825300114114700748351602688, 633825300114114700748351602688 - 633825300114114700748351602688*x**100],
[633825300114114700748351602688 - 633825300114114700748351602688*x**100, 633825300114114700748351602688*x**100 + 633825300114114700748351602688]])
def test_issue_17247_expression_blowup_4():
# This matrix takes extremely long on current master even with intermediate simplification so an abbreviated version is used. It is left here for test in case of future optimizations.
# M = Matrix(S('''[
# [ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256, 15/128 - 3*I/32, 19/256 + 551*I/1024],
# [-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096, 129/256 - 549*I/512, 42533/16384 + 29103*I/8192],
# [ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128, 3/64 + 13*I/64, -23/32 - 59*I/256],
# [ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024, 119/128 + 143*I/128, -10879/2048 + 4343*I/4096],
# [ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
# [ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
# [ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
# [ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
# [ -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
# [ 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
# [ -4, 9 - 5*I, -4*I, 27/2 + 6*I, -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
# [ -2*I, 119/8 + 29*I/4, 1/4 + 5*I/2, -23/8 - 57*I/16, 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
# assert M**10 == Matrix([
# [ 7*(-221393644768594642173548179825793834595 - 1861633166167425978847110897013541127952*I)/9671406556917033397649408, 15*(31670992489131684885307005100073928751695 + 10329090958303458811115024718207404523808*I)/77371252455336267181195264, 7*(-3710978679372178839237291049477017392703 + 1377706064483132637295566581525806894169*I)/19342813113834066795298816, (9727707023582419994616144751727760051598 - 59261571067013123836477348473611225724433*I)/9671406556917033397649408, (31896723509506857062605551443641668183707 + 54643444538699269118869436271152084599580*I)/38685626227668133590597632, (-2024044860947539028275487595741003997397402 + 130959428791783397562960461903698670485863*I)/309485009821345068724781056, 3*(26190251453797590396533756519358368860907 - 27221191754180839338002754608545400941638*I)/77371252455336267181195264, (1154643595139959842768960128434994698330461 + 3385496216250226964322872072260446072295634*I)/618970019642690137449562112, 3*(-31849347263064464698310044805285774295286 - 11877437776464148281991240541742691164309*I)/77371252455336267181195264, (4661330392283532534549306589669150228040221 - 4171259766019818631067810706563064103956871*I)/1237940039285380274899124224, (9598353794289061833850770474812760144506 + 358027153990999990968244906482319780943983*I)/309485009821345068724781056, (-9755135335127734571547571921702373498554177 - 4837981372692695195747379349593041939686540*I)/2475880078570760549798248448],
# [(-379516731607474268954110071392894274962069 - 422272153179747548473724096872271700878296*I)/77371252455336267181195264, (41324748029613152354787280677832014263339501 - 12715121258662668420833935373453570749288074*I)/1237940039285380274899124224, (-339216903907423793947110742819264306542397 + 494174755147303922029979279454787373566517*I)/77371252455336267181195264, (-18121350839962855576667529908850640619878381 - 37413012454129786092962531597292531089199003*I)/1237940039285380274899124224, (2489661087330511608618880408199633556675926 + 1137821536550153872137379935240732287260863*I)/309485009821345068724781056, (-136644109701594123227587016790354220062972119 + 110130123468183660555391413889600443583585272*I)/4951760157141521099596496896, (1488043981274920070468141664150073426459593 - 9691968079933445130866371609614474474327650*I)/1237940039285380274899124224, 27*(4636797403026872518131756991410164760195942 + 3369103221138229204457272860484005850416533*I)/4951760157141521099596496896, (-8534279107365915284081669381642269800472363 + 2241118846262661434336333368511372725482742*I)/1237940039285380274899124224, (60923350128174260992536531692058086830950875 - 263673488093551053385865699805250505661590126*I)/9903520314283042199192993792, (18520943561240714459282253753348921824172569 + 24846649186468656345966986622110971925703604*I)/4951760157141521099596496896, (-232781130692604829085973604213529649638644431 + 35981505277760667933017117949103953338570617*I)/9903520314283042199192993792],
# [ (8742968295129404279528270438201520488950 + 3061473358639249112126847237482570858327*I)/4835703278458516698824704, (-245657313712011778432792959787098074935273 + 253113767861878869678042729088355086740856*I)/38685626227668133590597632, (1947031161734702327107371192008011621193 - 19462330079296259148177542369999791122762*I)/9671406556917033397649408, (552856485625209001527688949522750288619217 + 392928441196156725372494335248099016686580*I)/77371252455336267181195264, (-44542866621905323121630214897126343414629 + 3265340021421335059323962377647649632959*I)/19342813113834066795298816, (136272594005759723105646069956434264218730 - 330975364731707309489523680957584684763587*I)/38685626227668133590597632, (27392593965554149283318732469825168894401 + 75157071243800133880129376047131061115278*I)/38685626227668133590597632, 7*(-357821652913266734749960136017214096276154 - 45509144466378076475315751988405961498243*I)/309485009821345068724781056, (104485001373574280824835174390219397141149 - 99041000529599568255829489765415726168162*I)/77371252455336267181195264, (1198066993119982409323525798509037696321291 + 4249784165667887866939369628840569844519936*I)/618970019642690137449562112, (-114985392587849953209115599084503853611014 - 52510376847189529234864487459476242883449*I)/77371252455336267181195264, (6094620517051332877965959223269600650951573 - 4683469779240530439185019982269137976201163*I)/1237940039285380274899124224],
# [ (611292255597977285752123848828590587708323 - 216821743518546668382662964473055912169502*I)/77371252455336267181195264, (-1144023204575811464652692396337616594307487 + 12295317806312398617498029126807758490062855*I)/309485009821345068724781056, (-374093027769390002505693378578475235158281 - 573533923565898290299607461660384634333639*I)/77371252455336267181195264, (47405570632186659000138546955372796986832987 - 2837476058950808941605000274055970055096534*I)/1237940039285380274899124224, (-571573207393621076306216726219753090535121 + 533381457185823100878764749236639320783831*I)/77371252455336267181195264, (-7096548151856165056213543560958582513797519 - 24035731898756040059329175131592138642195366*I)/618970019642690137449562112, (2396762128833271142000266170154694033849225 + 1448501087375679588770230529017516492953051*I)/309485009821345068724781056, (-150609293845161968447166237242456473262037053 + 92581148080922977153207018003184520294188436*I)/4951760157141521099596496896, 5*(270278244730804315149356082977618054486347 - 1997830155222496880429743815321662710091562*I)/1237940039285380274899124224, (62978424789588828258068912690172109324360330 + 44803641177219298311493356929537007630129097*I)/2475880078570760549798248448, 19*(-451431106327656743945775812536216598712236 + 114924966793632084379437683991151177407937*I)/1237940039285380274899124224, (63417747628891221594106738815256002143915995 - 261508229397507037136324178612212080871150958*I)/9903520314283042199192993792],
# [ (-2144231934021288786200752920446633703357 + 2305614436009705803670842248131563850246*I)/1208925819614629174706176, (-90720949337459896266067589013987007078153 - 221951119475096403601562347412753844534569*I)/19342813113834066795298816, (11590973613116630788176337262688659880376 + 6514520676308992726483494976339330626159*I)/4835703278458516698824704, 3*(-131776217149000326618649542018343107657237 + 79095042939612668486212006406818285287004*I)/38685626227668133590597632, (10100577916793945997239221374025741184951 - 28631383488085522003281589065994018550748*I)/9671406556917033397649408, 67*(10090295594251078955008130473573667572549 + 10449901522697161049513326446427839676762*I)/77371252455336267181195264, (-54270981296988368730689531355811033930513 - 3413683117592637309471893510944045467443*I)/19342813113834066795298816, (440372322928679910536575560069973699181278 - 736603803202303189048085196176918214409081*I)/77371252455336267181195264, (33220374714789391132887731139763250155295 + 92055083048787219934030779066298919603554*I)/38685626227668133590597632, 5*(-594638554579967244348856981610805281527116 - 82309245323128933521987392165716076704057*I)/309485009821345068724781056, (128056368815300084550013708313312073721955 - 114619107488668120303579745393765245911404*I)/77371252455336267181195264, 21*(59839959255173222962789517794121843393573 + 241507883613676387255359616163487405826334*I)/618970019642690137449562112],
# [ (-13454485022325376674626653802541391955147 + 184471402121905621396582628515905949793486*I)/19342813113834066795298816, (-6158730123400322562149780662133074862437105 - 3416173052604643794120262081623703514107476*I)/154742504910672534362390528, (770558003844914708453618983120686116100419 - 127758381209767638635199674005029818518766*I)/77371252455336267181195264, (-4693005771813492267479835161596671660631703 + 12703585094750991389845384539501921531449948*I)/309485009821345068724781056, (-295028157441149027913545676461260860036601 - 841544569970643160358138082317324743450770*I)/77371252455336267181195264, (56716442796929448856312202561538574275502893 + 7216818824772560379753073185990186711454778*I)/1237940039285380274899124224, 15*(-87061038932753366532685677510172566368387 + 61306141156647596310941396434445461895538*I)/154742504910672534362390528, (-3455315109680781412178133042301025723909347 - 24969329563196972466388460746447646686670670*I)/618970019642690137449562112, (2453418854160886481106557323699250865361849 + 1497886802326243014471854112161398141242514*I)/309485009821345068724781056, (-151343224544252091980004429001205664193082173 + 90471883264187337053549090899816228846836628*I)/4951760157141521099596496896, (1652018205533026103358164026239417416432989 - 9959733619236515024261775397109724431400162*I)/1237940039285380274899124224, 3*(40676374242956907656984876692623172736522006 + 31023357083037817469535762230872667581366205*I)/4951760157141521099596496896],
# [ (-1226990509403328460274658603410696548387 - 4131739423109992672186585941938392788458*I)/1208925819614629174706176, (162392818524418973411975140074368079662703 + 23706194236915374831230612374344230400704*I)/9671406556917033397649408, (-3935678233089814180000602553655565621193 + 2283744757287145199688061892165659502483*I)/1208925819614629174706176, (-2400210250844254483454290806930306285131 - 315571356806370996069052930302295432758205*I)/19342813113834066795298816, (13365917938215281056563183751673390817910 + 15911483133819801118348625831132324863881*I)/4835703278458516698824704, 3*(-215950551370668982657516660700301003897855 + 51684341999223632631602864028309400489378*I)/38685626227668133590597632, (20886089946811765149439844691320027184765 - 30806277083146786592790625980769214361844*I)/9671406556917033397649408, (562180634592713285745940856221105667874855 + 1031543963988260765153550559766662245114916*I)/77371252455336267181195264, (-65820625814810177122941758625652476012867 - 12429918324787060890804395323920477537595*I)/19342813113834066795298816, (319147848192012911298771180196635859221089 - 402403304933906769233365689834404519960394*I)/38685626227668133590597632, (23035615120921026080284733394359587955057 + 115351677687031786114651452775242461310624*I)/38685626227668133590597632, (-3426830634881892756966440108592579264936130 - 1022954961164128745603407283836365128598559*I)/309485009821345068724781056],
# [ (-192574788060137531023716449082856117537757 - 69222967328876859586831013062387845780692*I)/19342813113834066795298816, (2736383768828013152914815341491629299773262 - 2773252698016291897599353862072533475408743*I)/77371252455336267181195264, (-23280005281223837717773057436155921656805 + 214784953368021840006305033048142888879224*I)/19342813113834066795298816, (-3035247484028969580570400133318947903462326 - 2195168903335435855621328554626336958674325*I)/77371252455336267181195264, (984552428291526892214541708637840971548653 - 64006622534521425620714598573494988589378*I)/77371252455336267181195264, (-3070650452470333005276715136041262898509903 + 7286424705750810474140953092161794621989080*I)/154742504910672534362390528, (-147848877109756404594659513386972921139270 - 416306113044186424749331418059456047650861*I)/38685626227668133590597632, (55272118474097814260289392337160619494260781 + 7494019668394781211907115583302403519488058*I)/1237940039285380274899124224, (-581537886583682322424771088996959213068864 + 542191617758465339135308203815256798407429*I)/77371252455336267181195264, (-6422548983676355789975736799494791970390991 - 23524183982209004826464749309156698827737702*I)/618970019642690137449562112, 7*(180747195387024536886923192475064903482083 + 84352527693562434817771649853047924991804*I)/154742504910672534362390528, (-135485179036717001055310712747643466592387031 + 102346575226653028836678855697782273460527608*I)/4951760157141521099596496896],
# [ (3384238362616083147067025892852431152105 + 156724444932584900214919898954874618256*I)/604462909807314587353088, (-59558300950677430189587207338385764871866 + 114427143574375271097298201388331237478857*I)/4835703278458516698824704, (-1356835789870635633517710130971800616227 - 7023484098542340388800213478357340875410*I)/1208925819614629174706176, (234884918567993750975181728413524549575881 + 79757294640629983786895695752733890213506*I)/9671406556917033397649408, (-7632732774935120473359202657160313866419 + 2905452608512927560554702228553291839465*I)/1208925819614629174706176, (52291747908702842344842889809762246649489 - 520996778817151392090736149644507525892649*I)/19342813113834066795298816, (17472406829219127839967951180375981717322 + 23464704213841582137898905375041819568669*I)/4835703278458516698824704, (-911026971811893092350229536132730760943307 + 150799318130900944080399439626714846752360*I)/38685626227668133590597632, (26234457233977042811089020440646443590687 - 45650293039576452023692126463683727692890*I)/9671406556917033397649408, 3*(288348388717468992528382586652654351121357 + 454526517721403048270274049572136109264668*I)/77371252455336267181195264, (-91583492367747094223295011999405657956347 - 12704691128268298435362255538069612411331*I)/19342813113834066795298816, (411208730251327843849027957710164064354221 - 569898526380691606955496789378230959965898*I)/38685626227668133590597632],
# [ (27127513117071487872628354831658811211795 - 37765296987901990355760582016892124833857*I)/4835703278458516698824704, (1741779916057680444272938534338833170625435 + 3083041729779495966997526404685535449810378*I)/77371252455336267181195264, 3*(-60642236251815783728374561836962709533401 - 24630301165439580049891518846174101510744*I)/19342813113834066795298816, 3*(445885207364591681637745678755008757483408 - 350948497734812895032502179455610024541643*I)/38685626227668133590597632, (-47373295621391195484367368282471381775684 + 219122969294089357477027867028071400054973*I)/19342813113834066795298816, (-2801565819673198722993348253876353741520438 - 2250142129822658548391697042460298703335701*I)/77371252455336267181195264, (801448252275607253266997552356128790317119 - 50890367688077858227059515894356594900558*I)/77371252455336267181195264, (-5082187758525931944557763799137987573501207 + 11610432359082071866576699236013484487676124*I)/309485009821345068724781056, (-328925127096560623794883760398247685166830 - 643447969697471610060622160899409680422019*I)/77371252455336267181195264, 15*(2954944669454003684028194956846659916299765 + 33434406416888505837444969347824812608566*I)/1237940039285380274899124224, (-415749104352001509942256567958449835766827 + 479330966144175743357171151440020955412219*I)/77371252455336267181195264, 3*(-4639987285852134369449873547637372282914255 - 11994411888966030153196659207284951579243273*I)/1237940039285380274899124224],
# [ (-478846096206269117345024348666145495601 + 1249092488629201351470551186322814883283*I)/302231454903657293676544, (-17749319421930878799354766626365926894989 - 18264580106418628161818752318217357231971*I)/1208925819614629174706176, (2801110795431528876849623279389579072819 + 363258850073786330770713557775566973248*I)/604462909807314587353088, (-59053496693129013745775512127095650616252 + 78143588734197260279248498898321500167517*I)/4835703278458516698824704, (-283186724922498212468162690097101115349 - 6443437753863179883794497936345437398276*I)/1208925819614629174706176, (188799118826748909206887165661384998787543 + 84274736720556630026311383931055307398820*I)/9671406556917033397649408, (-5482217151670072904078758141270295025989 + 1818284338672191024475557065444481298568*I)/1208925819614629174706176, (56564463395350195513805521309731217952281 - 360208541416798112109946262159695452898431*I)/19342813113834066795298816, 11*(1259539805728870739006416869463689438068 + 1409136581547898074455004171305324917387*I)/4835703278458516698824704, 5*(-123701190701414554945251071190688818343325 + 30997157322590424677294553832111902279712*I)/38685626227668133590597632, (16130917381301373033736295883982414239781 - 32752041297570919727145380131926943374516*I)/9671406556917033397649408, (650301385108223834347093740500375498354925 + 899526407681131828596801223402866051809258*I)/77371252455336267181195264],
# [ (9011388245256140876590294262420614839483 + 8167917972423946282513000869327525382672*I)/1208925819614629174706176, (-426393174084720190126376382194036323028924 + 180692224825757525982858693158209545430621*I)/9671406556917033397649408, (24588556702197802674765733448108154175535 - 45091766022876486566421953254051868331066*I)/4835703278458516698824704, (1872113939365285277373877183750416985089691 + 3030392393733212574744122057679633775773130*I)/77371252455336267181195264, (-222173405538046189185754954524429864167549 - 75193157893478637039381059488387511299116*I)/19342813113834066795298816, (2670821320766222522963689317316937579844558 - 2645837121493554383087981511645435472169191*I)/77371252455336267181195264, 5*(-2100110309556476773796963197283876204940 + 41957457246479840487980315496957337371937*I)/19342813113834066795298816, (-5733743755499084165382383818991531258980593 - 3328949988392698205198574824396695027195732*I)/154742504910672534362390528, (707827994365259025461378911159398206329247 - 265730616623227695108042528694302299777294*I)/77371252455336267181195264, (-1442501604682933002895864804409322823788319 + 11504137805563265043376405214378288793343879*I)/309485009821345068724781056, (-56130472299445561499538726459719629522285 - 61117552419727805035810982426639329818864*I)/9671406556917033397649408, (39053692321126079849054272431599539429908717 - 10209127700342570953247177602860848130710666*I)/1237940039285380274899124224]])
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
assert M**10 == Matrix(S('''[
[ 7369525394972778926719607798014571861/604462909807314587353088 - 229284202061790301477392339912557559*I/151115727451828646838272, -19704281515163975949388435612632058035/1208925819614629174706176 + 14319858347987648723768698170712102887*I/302231454903657293676544, -3623281909451783042932142262164941211/604462909807314587353088 - 6039240602494288615094338643452320495*I/604462909807314587353088, 109260497799140408739847239685705357695/2417851639229258349412352 - 7427566006564572463236368211555511431*I/2417851639229258349412352, -16095803767674394244695716092817006641/2417851639229258349412352 + 10336681897356760057393429626719177583*I/1208925819614629174706176, -42207883340488041844332828574359769743/2417851639229258349412352 - 182332262671671273188016400290188468499*I/4835703278458516698824704],
[50566491050825573392726324995779608259/1208925819614629174706176 - 90047007594468146222002432884052362145*I/2417851639229258349412352, 74273703462900000967697427843983822011/1208925819614629174706176 + 265947522682943571171988741842776095421*I/1208925819614629174706176, -116900341394390200556829767923360888429/2417851639229258349412352 - 53153263356679268823910621474478756845*I/2417851639229258349412352, 195407378023867871243426523048612490249/1208925819614629174706176 - 1242417915995360200584837585002906728929*I/9671406556917033397649408, -863597594389821970177319682495878193/302231454903657293676544 + 476936100741548328800725360758734300481*I/9671406556917033397649408, -3154451590535653853562472176601754835575/19342813113834066795298816 - 232909875490506237386836489998407329215*I/2417851639229258349412352],
[ -1715444997702484578716037230949868543/302231454903657293676544 + 5009695651321306866158517287924120777*I/302231454903657293676544, -30551582497996879620371947949342101301/604462909807314587353088 - 7632518367986526187139161303331519629*I/151115727451828646838272, 312680739924495153190604170938220575/18889465931478580854784 - 108664334509328818765959789219208459*I/75557863725914323419136, -14693696966703036206178521686918865509/604462909807314587353088 + 72345386220900843930147151999899692401*I/1208925819614629174706176, -8218872496728882299722894680635296519/1208925819614629174706176 - 16776782833358893712645864791807664983*I/1208925819614629174706176, 143237839169380078671242929143670635137/2417851639229258349412352 + 2883817094806115974748882735218469447*I/2417851639229258349412352],
[ 3087979417831061365023111800749855987/151115727451828646838272 + 34441942370802869368851419102423997089*I/604462909807314587353088, -148309181940158040917731426845476175667/604462909807314587353088 - 263987151804109387844966835369350904919*I/9671406556917033397649408, 50259518594816377378747711930008883165/1208925819614629174706176 - 95713974916869240305450001443767979653*I/2417851639229258349412352, 153466447023875527996457943521467271119/2417851639229258349412352 + 517285524891117105834922278517084871349*I/2417851639229258349412352, -29184653615412989036678939366291205575/604462909807314587353088 - 27551322282526322041080173287022121083*I/1208925819614629174706176, 196404220110085511863671393922447671649/1208925819614629174706176 - 1204712019400186021982272049902206202145*I/9671406556917033397649408],
[ -2632581805949645784625606590600098779/151115727451828646838272 - 589957435912868015140272627522612771*I/37778931862957161709568, 26727850893953715274702844733506310247/302231454903657293676544 - 10825791956782128799168209600694020481*I/302231454903657293676544, -1036348763702366164044671908440791295/151115727451828646838272 + 3188624571414467767868303105288107375*I/151115727451828646838272, -36814959939970644875593411585393242449/604462909807314587353088 - 18457555789119782404850043842902832647*I/302231454903657293676544, 12454491297984637815063964572803058647/604462909807314587353088 - 340489532842249733975074349495329171*I/302231454903657293676544, -19547211751145597258386735573258916681/604462909807314587353088 + 87299583775782199663414539883938008933*I/1208925819614629174706176],
[ -40281994229560039213253423262678393183/604462909807314587353088 - 2939986850065527327299273003299736641*I/604462909807314587353088, 331940684638052085845743020267462794181/2417851639229258349412352 - 284574901963624403933361315517248458969*I/1208925819614629174706176, 6453843623051745485064693628073010961/302231454903657293676544 + 36062454107479732681350914931391590957*I/604462909807314587353088, -147665869053634695632880753646441962067/604462909807314587353088 - 305987938660447291246597544085345123927*I/9671406556917033397649408, 107821369195275772166593879711259469423/2417851639229258349412352 - 11645185518211204108659001435013326687*I/302231454903657293676544, 64121228424717666402009446088588091619/1208925819614629174706176 + 265557133337095047883844369272389762133*I/1208925819614629174706176]]'''))
def test_issue_17247_expression_blowup_5():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
assert M.charpoly('x') == PurePoly(x**6 + (-6 - 6*I)*x**5 + 36*I*x**4, x, domain='EX')
def test_issue_17247_expression_blowup_6():
M = Matrix(8, 8, [x+i for i in range (64)])
assert M.det('bareiss') == 0
def test_issue_17247_expression_blowup_7():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
assert M.det('berkowitz') == 0
@XFAIL # dotprodsimp is not on by default in this function
def test_issue_17247_expression_blowup_8():
M = Matrix(8, 8, [x+i for i in range (64)])
assert M.det('lu') == 0
def test_issue_17247_expression_blowup_9():
M = Matrix(8, 8, [x+i for i in range (64)])
assert M.rref() == (Matrix([
[1, 0, -1, -2, -3, -4, -5, -6],
[0, 1, 2, 3, 4, 5, 6, 7],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0]]), (0, 1))
def test_issue_17247_expression_blowup_10():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
assert M.cofactor(0, 0) == 0
def test_issue_17247_expression_blowup_11():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
assert M.cofactor_matrix() == Matrix(6, 6, [0]*36)
def test_issue_17247_expression_blowup_12():
M = Matrix(6, 6, lambda i, j: 1 + (-1)**(i+j)*I)
assert M.eigenvals() == {6: 1, 6*I: 1, 0: 4}
def test_issue_17247_expression_blowup_13():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
ev = M.eigenvects()
assert ev[0][:2] == (0, 2)
assert ev[0][2][0] == Matrix([[0],[-1],[0],[1]])
assert ev[1][:2] == (x - sqrt(2)*(x - 1) + 1, 1)
assert (ev[1][2][0] - Matrix([
[-(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7)],
[ (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2))],
[ -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2))],
[ 1]])).expand() == Matrix([[0],[0],[0],[0]])
assert ev[2][:2] == (x + sqrt(2)*(x - 1) + 1, 1)
assert (ev[2][2][0] - Matrix([
[-(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
[ (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
[ -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
[ 1]])).expand() == Matrix([[0],[0],[0],[0]])
def test_issue_17247_expression_blowup_14():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
assert M.echelon_form() == Matrix([
[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x],
[ 0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0],
[ 0, 0, 0, 0, 0, 0, 0, 0]])
def test_issue_17247_expression_blowup_15():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
assert M.rowspace() == [Matrix([[x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x, x + 1, 1 - x]]), Matrix([[0, 4*x, 0, 4*x, 0, 4*x, 0, 4*x]])]
def test_issue_17247_expression_blowup_16():
M = Matrix(8, 8, ([1+x, 1-x]*4 + [1-x, 1+x]*4)*4)
assert M.columnspace() == [Matrix([[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x]]), Matrix([[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1],[1 - x],[x + 1]])]
def test_issue_17247_expression_blowup_17():
M = Matrix(8, 8, [x+i for i in range (64)])
assert M.nullspace() == [
Matrix([[1],[-2],[1],[0],[0],[0],[0],[0]]),
Matrix([[2],[-3],[0],[1],[0],[0],[0],[0]]),
Matrix([[3],[-4],[0],[0],[1],[0],[0],[0]]),
Matrix([[4],[-5],[0],[0],[0],[1],[0],[0]]),
Matrix([[5],[-6],[0],[0],[0],[0],[1],[0]]),
Matrix([[6],[-7],[0],[0],[0],[0],[0],[1]])]
def test_issue_17247_expression_blowup_18():
M = Matrix(6, 6, ([1+x, 1-x]*3 + [1-x, 1+x]*3)*3)
assert not M.is_nilpotent()
def test_issue_17247_expression_blowup_19():
M = Matrix(S('''[
[ -3/4, 0, 1/4 + I/2, 0],
[ 0, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 1/2 - I, 0, 0, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert not M.is_diagonalizable()
def test_issue_17247_expression_blowup_20():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
assert M.diagonalize() == (Matrix([
[1, 1, 0, (x + 1)/(x - 1)],
[1, -1, 0, 0],
[1, 1, 1, 0],
[0, 0, 0, 1]]),
Matrix([
[2, 0, 0, 0],
[0, 2*x, 0, 0],
[0, 0, x + 1, 0],
[0, 0, 0, x + 1]]))
def test_issue_17247_expression_blowup_21():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.inv(method='GE') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
@XFAIL # dotprodsimp is not on by default in this function
def test_issue_17247_expression_blowup_22():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.inv(method='LU') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_23():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.inv(method='ADJ').expand() == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
@XFAIL # dotprodsimp is not on by default in this function
def test_issue_17247_expression_blowup_24():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.inv(method='CH') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
@XFAIL # dotprodsimp is not on by default in this function
def test_issue_17247_expression_blowup_25():
M = SparseMatrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.inv(method='LDL') == Matrix(S('''[
[-26194832/3470993 - 31733264*I/3470993, 156352/3470993 + 10325632*I/3470993, 0, -7741283181072/3306971225785 + 2999007604624*I/3306971225785],
[4408224/3470993 - 9675328*I/3470993, -2422272/3470993 + 1523712*I/3470993, 0, -1824666489984/3306971225785 - 1401091949952*I/3306971225785],
[-26406945676288/22270005630769 + 10245925485056*I/22270005630769, 7453523312640/22270005630769 + 1601616519168*I/22270005630769, 633088/6416033 - 140288*I/6416033, 872209227109521408/21217636514687010905 + 6066405081802389504*I/21217636514687010905],
[0, 0, 0, -11328/952745 + 87616*I/952745]]'''))
def test_issue_17247_expression_blowup_26():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64, -9/32 - I/16, 183/256 - 97*I/128],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512, -219/128 + 115*I/256, 6301/4096 - 6609*I/1024],
[ 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64, 1/4 - 5*I/16, 65/128 + 87*I/64],
[ -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128, 85/256 - 33*I/16, 805/128 + 2415*I/512],
[ 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16, 1/4 + I/2, -129/64 - 9*I/64],
[ 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128, 125/64 + 87*I/64, -2063/256 + 541*I/128],
[ -2, 17/4 - 13*I/2, 1 + I, -19/4 + 5*I/4, 1/2 - I, 9/4 + 55*I/16, -3/4, 45/32 - 37*I/16],
[ 1/4 + 13*I/4, -825/64 - 147*I/32, 21/8 + I, -537/64 + 143*I/16, -5/8 - 39*I/16, 2473/256 + 137*I/64, -149/64 + 49*I/32, -177/128 - 1369*I/128]]'''))
assert M.rank() == 4
def test_issue_17247_expression_blowup_27():
M = Matrix([
[ 0, 1 - x, x + 1, 1 - x],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 1 - x],
[ 0, 0, 1 - x, 0]])
P, J = M.jordan_form()
assert P.expand() == Matrix(S('''[
[ 0, 4*x/(x**2 - 2*x + 1), -(-17*x**4 + 12*sqrt(2)*x**4 - 4*sqrt(2)*x**3 + 6*x**3 - 6*x - 4*sqrt(2)*x + 12*sqrt(2) + 17)/(-7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 + 8*x**3 - 2*x**2 + 8*x + 6*sqrt(2)*x - 5*sqrt(2) - 7), -(12*sqrt(2)*x**4 + 17*x**4 - 6*x**3 - 4*sqrt(2)*x**3 - 4*sqrt(2)*x + 6*x - 17 + 12*sqrt(2))/(7*x**4 + 5*sqrt(2)*x**4 - 6*sqrt(2)*x**3 - 8*x**3 + 2*x**2 - 8*x + 6*sqrt(2)*x - 5*sqrt(2) + 7)],
[x - 1, x/(x - 1) + 1/(x - 1), (-7*x**3 + 5*sqrt(2)*x**3 - x**2 + sqrt(2)*x**2 - sqrt(2)*x - x - 5*sqrt(2) - 7)/(-3*x**3 + 2*sqrt(2)*x**3 - 2*sqrt(2)*x**2 + 3*x**2 + 2*sqrt(2)*x + 3*x - 3 - 2*sqrt(2)), (7*x**3 + 5*sqrt(2)*x**3 + x**2 + sqrt(2)*x**2 - sqrt(2)*x + x - 5*sqrt(2) + 7)/(2*sqrt(2)*x**3 + 3*x**3 - 3*x**2 - 2*sqrt(2)*x**2 - 3*x + 2*sqrt(2)*x - 2*sqrt(2) + 3)],
[ 0, 1, -(-3*x**2 + 2*sqrt(2)*x**2 + 2*x - 3 - 2*sqrt(2))/(-x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x + 1 + sqrt(2)), -(2*sqrt(2)*x**2 + 3*x**2 - 2*x - 2*sqrt(2) + 3)/(x**2 + sqrt(2)*x**2 - 2*sqrt(2)*x - 1 + sqrt(2))],
[1 - x, 0, 1, 1]]''')).expand()
assert J == Matrix(S('''[
[0, 1, 0, 0],
[0, 0, 0, 0],
[0, 0, x - sqrt(2)*(x - 1) + 1, 0],
[0, 0, 0, x + sqrt(2)*(x - 1) + 1]]'''))
def test_issue_17247_expression_blowup_28():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.singular_values() == S('''[
sqrt(14609315/131072 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) + 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2 + sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 + sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2),
sqrt(14609315/131072 - sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))/2 - sqrt(64789115132571/2147483648 - 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3) - 76627253330829751075/(35184372088832*sqrt(64789115132571/4294967296 + 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)) + 2*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3))) - 3546944054712886603889144627/(110680464442257309696*(25895222463957462655758224991455280215303/633825300114114700748351602688 + sqrt(1213909058710955930446995195883114969038524625997915131236390724543989220134670)*I/22282920707136844948184236032)**(1/3)))/2)]''')
def test_issue_17247_expression_blowup_29():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.gauss_jordan_solve(ones(4, 1)) == (Matrix(S('''[
[ -32549314808672/3306971225785 - 17397006745216*I/3306971225785],
[ 67439348256/3306971225785 - 9167503335872*I/3306971225785],
[-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905],
[ -11328/952745 + 87616*I/952745]]''')), Matrix(0, 1, []))
@XFAIL # dotprodsimp is not on by default in this function
def test_issue_17247_expression_blowup_30():
M = Matrix(S('''[
[ -3/4, 45/32 - 37*I/16, 0, 0],
[-149/64 + 49*I/32, -177/128 - 1369*I/128, 0, -2063/256 + 541*I/128],
[ 0, 9/4 + 55*I/16, 2473/256 + 137*I/64, 0],
[ 0, 0, 0, -177/128 - 1369*I/128]]'''))
assert M.cholesky_solve(ones(4, 1)) == Matrix(S('''[
[ -32549314808672/3306971225785 - 17397006745216*I/3306971225785],
[ 67439348256/3306971225785 - 9167503335872*I/3306971225785],
[-15091965363354518272/21217636514687010905 + 16890163109293858304*I/21217636514687010905],
[ -11328/952745 + 87616*I/952745]]'''))
# This test is commented out because without dotprodsimp this calculation hangs.
# @XFAIL # dotprodsimp is not on by default in this function
# def test_issue_17247_expression_blowup_31():
# M = Matrix([
# [x + 1, 1 - x, 0, 0],
# [1 - x, x + 1, 0, x + 1],
# [ 0, 1 - x, x + 1, 0],
# [ 0, 0, 0, x + 1]])
# assert M.LDLsolve(ones(4, 1)) == Matrix([
# [(x + 1)/(4*x)],
# [(x - 1)/(4*x)],
# [(x + 1)/(4*x)],
# [ 1/(x + 1)]])
@XFAIL # dotprodsimp is not on by default in this function
def test_issue_17247_expression_blowup_32():
M = Matrix([
[x + 1, 1 - x, 0, 0],
[1 - x, x + 1, 0, x + 1],
[ 0, 1 - x, x + 1, 0],
[ 0, 0, 0, x + 1]])
assert M.LUsolve(ones(4, 1)) == Matrix([
[(x + 1)/(4*x)],
[(x - 1)/(4*x)],
[(x + 1)/(4*x)],
[ 1/(x + 1)]])
def test_issue_16823():
# This still needs to be fixed if not using dotprodsimp.
M = Matrix(S('''[
[1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I,15/128-3/32*I,19/256+551/1024*I],
[21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I,129/256-549/512*I,42533/16384+29103/8192*I],
[-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I,3/64+13/64*I,-23/32-59/256*I],
[1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I,119/128+143/128*I,-10879/2048+4343/4096*I],
[-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I,-9/32-1/16*I,183/256-97/128*I],
[1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I,-219/128+115/256*I,6301/4096-6609/1024*I],
[-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I,1/4-5/16*I,65/128+87/64*I],
[-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I,85/256-33/16*I,805/128+2415/512*I],
[0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I,1/4+1/2*I,-129/64-9/64*I],
[1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I,125/64+87/64*I,-2063/256+541/128*I],
[0,-4*I,0,-6,-4,9-5*I,-4*I,27/2+6*I,-2,17/4-13/2*I,1+I,-19/4+5/4*I,1/2-I,9/4+55/16*I,-3/4,45/32-37/16*I],
[0,1/4+1/2*I,1,-9/4+3*I,-2*I,119/8+29/4*I,1/4+5/2*I,-23/8-57/16*I,1/4+13/4*I,-825/64-147/32*I,21/8+I,-537/64+143/16*I,-5/8-39/16*I,2473/256+137/64*I,-149/64+49/32*I,-177/128-1369/128*I]]'''))
assert M.rank() == 8
def test_issue_18531():
# solve_linear_system still needs fixing but the rref works.
M = Matrix([
[1, 1, 1, 1, 1, 0, 1, 0, 0],
[1 + sqrt(2), -1 + sqrt(2), 1 - sqrt(2), -sqrt(2) - 1, 1, 1, -1, 1, 1],
[-5 + 2*sqrt(2), -5 - 2*sqrt(2), -5 - 2*sqrt(2), -5 + 2*sqrt(2), -7, 2, -7, -2, 0],
[-3*sqrt(2) - 1, 1 - 3*sqrt(2), -1 + 3*sqrt(2), 1 + 3*sqrt(2), -7, -5, 7, -5, 3],
[7 - 4*sqrt(2), 4*sqrt(2) + 7, 4*sqrt(2) + 7, 7 - 4*sqrt(2), 7, -12, 7, 12, 0],
[-1 + 3*sqrt(2), 1 + 3*sqrt(2), -3*sqrt(2) - 1, 1 - 3*sqrt(2), 7, -5, -7, -5, 3],
[-3 + 2*sqrt(2), -3 - 2*sqrt(2), -3 - 2*sqrt(2), -3 + 2*sqrt(2), -1, 2, -1, -2, 0],
[1 - sqrt(2), -sqrt(2) - 1, 1 + sqrt(2), -1 + sqrt(2), -1, 1, 1, 1, 1]
])
assert M.rref() == (Matrix([
[1, 0, 0, 0, 0, 0, 0, 0, 1/2],
[0, 1, 0, 0, 0, 0, 0, 0, -1/2],
[0, 0, 1, 0, 0, 0, 0, 0, 1/2],
[0, 0, 0, 1, 0, 0, 0, 0, -1/2],
[0, 0, 0, 0, 1, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 1, 0, 0, -1/2],
[0, 0, 0, 0, 0, 0, 1, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 1, -1/2]]), (0, 1, 2, 3, 4, 5, 6, 7))
def test_creation():
raises(ValueError, lambda: Matrix(5, 5, range(20)))
raises(ValueError, lambda: Matrix(5, -1, []))
raises(IndexError, lambda: Matrix((1, 2))[2])
with raises(IndexError):
Matrix((1, 2))[1:2] = 5
with raises(IndexError):
Matrix((1, 2))[3] = 5
assert Matrix() == Matrix([]) == Matrix([[]]) == Matrix(0, 0, [])
# anything can go into a matrix (laplace_transform uses tuples)
assert Matrix([[[], ()]]).tolist() == [[[], ()]]
assert Matrix([[[], ()]]).T.tolist() == [[[]], [()]]
a = Matrix([[x, 0], [0, 0]])
m = a
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
b = Matrix(2, 2, [x, 0, 0, 0])
m = b
assert m.cols == m.rows
assert m.cols == 2
assert m[:] == [x, 0, 0, 0]
assert a == b
assert Matrix(b) == b
c23 = Matrix(2, 3, range(1, 7))
c13 = Matrix(1, 3, range(7, 10))
c = Matrix([c23, c13])
assert c.cols == 3
assert c.rows == 3
assert c[:] == [1, 2, 3, 4, 5, 6, 7, 8, 9]
assert Matrix(eye(2)) == eye(2)
assert ImmutableMatrix(ImmutableMatrix(eye(2))) == ImmutableMatrix(eye(2))
assert ImmutableMatrix(c) == c.as_immutable()
assert Matrix(ImmutableMatrix(c)) == ImmutableMatrix(c).as_mutable()
assert c is not Matrix(c)
dat = [[ones(3,2), ones(3,3)*2], [ones(2,3)*3, ones(2,2)*4]]
M = Matrix(dat)
assert M == Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
assert M.tolist() != dat
# keep block form if evaluate=False
assert Matrix(dat, evaluate=False).tolist() == dat
A = MatrixSymbol("A", 2, 2)
dat = [ones(2), A]
assert Matrix(dat) == Matrix([
[ 1, 1],
[ 1, 1],
[A[0, 0], A[0, 1]],
[A[1, 0], A[1, 1]]])
assert Matrix(dat, evaluate=False).tolist() == [[i] for i in dat]
# 0-dim tolerance
assert Matrix([ones(2), ones(0)]) == Matrix([ones(2)])
raises(ValueError, lambda: Matrix([ones(2), ones(0, 3)]))
raises(ValueError, lambda: Matrix([ones(2), ones(3, 0)]))
def test_irregular_block():
assert Matrix.irregular(3, ones(2,1), ones(3,3)*2, ones(2,2)*3,
ones(1,1)*4, ones(2,2)*5, ones(1,2)*6, ones(1,2)*7) == Matrix([
[1, 2, 2, 2, 3, 3],
[1, 2, 2, 2, 3, 3],
[4, 2, 2, 2, 5, 5],
[6, 6, 7, 7, 5, 5]])
def test_tolist():
lst = [[S.One, S.Half, x*y, S.Zero], [x, y, z, x**2], [y, -S.One, z*x, 3]]
m = Matrix(lst)
assert m.tolist() == lst
def test_as_mutable():
assert zeros(0, 3).as_mutable() == zeros(0, 3)
assert zeros(0, 3).as_immutable() == ImmutableMatrix(zeros(0, 3))
assert zeros(3, 0).as_immutable() == ImmutableMatrix(zeros(3, 0))
def test_slicing():
m0 = eye(4)
assert m0[:3, :3] == eye(3)
assert m0[2:4, 0:2] == zeros(2)
m1 = Matrix(3, 3, lambda i, j: i + j)
assert m1[0, :] == Matrix(1, 3, (0, 1, 2))
assert m1[1:3, 1] == Matrix(2, 1, (2, 3))
m2 = Matrix([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11], [12, 13, 14, 15]])
assert m2[:, -1] == Matrix(4, 1, [3, 7, 11, 15])
assert m2[-2:, :] == Matrix([[8, 9, 10, 11], [12, 13, 14, 15]])
def test_submatrix_assignment():
m = zeros(4)
m[2:4, 2:4] = eye(2)
assert m == Matrix(((0, 0, 0, 0),
(0, 0, 0, 0),
(0, 0, 1, 0),
(0, 0, 0, 1)))
m[:2, :2] = eye(2)
assert m == eye(4)
m[:, 0] = Matrix(4, 1, (1, 2, 3, 4))
assert m == Matrix(((1, 0, 0, 0),
(2, 1, 0, 0),
(3, 0, 1, 0),
(4, 0, 0, 1)))
m[:, :] = zeros(4)
assert m == zeros(4)
m[:, :] = [(1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)]
assert m == Matrix(((1, 2, 3, 4),
(5, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
m[:2, 0] = [0, 0]
assert m == Matrix(((0, 2, 3, 4),
(0, 6, 7, 8),
(9, 10, 11, 12),
(13, 14, 15, 16)))
def test_extract():
m = Matrix(4, 3, lambda i, j: i*3 + j)
assert m.extract([0, 1, 3], [0, 1]) == Matrix(3, 2, [0, 1, 3, 4, 9, 10])
assert m.extract([0, 3], [0, 0, 2]) == Matrix(2, 3, [0, 0, 2, 9, 9, 11])
assert m.extract(range(4), range(3)) == m
raises(IndexError, lambda: m.extract([4], [0]))
raises(IndexError, lambda: m.extract([0], [3]))
def test_reshape():
m0 = eye(3)
assert m0.reshape(1, 9) == Matrix(1, 9, (1, 0, 0, 0, 1, 0, 0, 0, 1))
m1 = Matrix(3, 4, lambda i, j: i + j)
assert m1.reshape(
4, 3) == Matrix(((0, 1, 2), (3, 1, 2), (3, 4, 2), (3, 4, 5)))
assert m1.reshape(2, 6) == Matrix(((0, 1, 2, 3, 1, 2), (3, 4, 2, 3, 4, 5)))
def test_applyfunc():
m0 = eye(3)
assert m0.applyfunc(lambda x: 2*x) == eye(3)*2
assert m0.applyfunc(lambda x: 0) == zeros(3)
def test_expand():
m0 = Matrix([[x*(x + y), 2], [((x + y)*y)*x, x*(y + x*(x + y))]])
# Test if expand() returns a matrix
m1 = m0.expand()
assert m1 == Matrix(
[[x*y + x**2, 2], [x*y**2 + y*x**2, x*y + y*x**2 + x**3]])
a = Symbol('a', real=True)
assert Matrix([exp(I*a)]).expand(complex=True) == \
Matrix([cos(a) + I*sin(a)])
assert Matrix([[0, 1, 2], [0, 0, -1], [0, 0, 0]]).exp() == Matrix([
[1, 1, Rational(3, 2)],
[0, 1, -1],
[0, 0, 1]]
)
def test_refine():
m0 = Matrix([[Abs(x)**2, sqrt(x**2)],
[sqrt(x**2)*Abs(y)**2, sqrt(y**2)*Abs(x)**2]])
m1 = m0.refine(Q.real(x) & Q.real(y))
assert m1 == Matrix([[x**2, Abs(x)], [y**2*Abs(x), x**2*Abs(y)]])
m1 = m0.refine(Q.positive(x) & Q.positive(y))
assert m1 == Matrix([[x**2, x], [x*y**2, x**2*y]])
m1 = m0.refine(Q.negative(x) & Q.negative(y))
assert m1 == Matrix([[x**2, -x], [-x*y**2, -x**2*y]])
def test_random():
M = randMatrix(3, 3)
M = randMatrix(3, 3, seed=3)
assert M == randMatrix(3, 3, seed=3)
M = randMatrix(3, 4, 0, 150)
M = randMatrix(3, seed=4, symmetric=True)
assert M == randMatrix(3, seed=4, symmetric=True)
S = M.copy()
S.simplify()
assert S == M # doesn't fail when elements are Numbers, not int
rng = random.Random(4)
assert M == randMatrix(3, symmetric=True, prng=rng)
# Ensure symmetry
for size in (10, 11): # Test odd and even
for percent in (100, 70, 30):
M = randMatrix(size, symmetric=True, percent=percent, prng=rng)
assert M == M.T
M = randMatrix(10, min=1, percent=70)
zero_count = 0
for i in range(M.shape[0]):
for j in range(M.shape[1]):
if M[i, j] == 0:
zero_count += 1
assert zero_count == 30
def test_LUsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[2, 1], [1, 0], [1, 0]]) # issue 14548
b = Matrix([3, 1, 1])
assert A.LUsolve(b) == Matrix([1, 1])
b = Matrix([3, 1, 2]) # inconsistent
raises(ValueError, lambda: A.LUsolve(b))
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4],
[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix([2, 1, -4])
b = A*x
soln = A.LUsolve(b)
assert soln == x
A = Matrix([[0, -1, 2], [5, 10, 7]]) # underdetermined
x = Matrix([-1, 2, 0])
b = A*x
raises(NotImplementedError, lambda: A.LUsolve(b))
A = Matrix(4, 4, lambda i, j: 1/(i+j+1) if i != 3 else 0)
b = Matrix.zeros(4, 1)
raises(NotImplementedError, lambda: A.LUsolve(b))
def test_QRsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.QRsolve(b)
assert soln == x
x = Matrix([[1, 2], [3, 4], [5, 6]])
b = A*x
soln = A.QRsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.QRsolve(b)
assert soln == x
x = Matrix([[7, 8], [9, 10], [11, 12]])
b = A*x
soln = A.QRsolve(b)
assert soln == x
def test_inverse():
A = eye(4)
assert A.inv() == eye(4)
assert A.inv(method="LU") == eye(4)
assert A.inv(method="ADJ") == eye(4)
assert A.inv(method="CH") == eye(4)
assert A.inv(method="LDL") == eye(4)
assert A.inv(method="QR") == eye(4)
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
Ainv = A.inv()
assert A*Ainv == eye(3)
assert A.inv(method="LU") == Ainv
assert A.inv(method="ADJ") == Ainv
assert A.inv(method="CH") == Ainv
assert A.inv(method="LDL") == Ainv
assert A.inv(method="QR") == Ainv
AA = Matrix([[0, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 0],
[1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0],
[1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0],
[1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1],
[0, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],
[1, 1, 0, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1],
[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1],
[1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0, 1, 1, 0],
[1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 0],
[0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1],
[1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 1, 1, 0],
[0, 1, 0, 0, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 1, 0, 0],
[1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0],
[0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1],
[0, 1, 0, 1, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
[1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1],
[0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 1, 0, 1, 1],
[0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0],
[0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 1, 0, 0, 1, 0]])
assert AA.inv(method="BLOCK") * AA == eye(AA.shape[0])
# test that immutability is not a problem
cls = ImmutableMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
cls = ImmutableSparseMatrix
m = cls([[48, 49, 31],
[ 9, 71, 94],
[59, 28, 65]])
assert all(type(m.inv(s)) is cls for s in 'GE ADJ LU CH LDL QR'.split())
def test_matrix_inverse_mod():
A = Matrix(2, 1, [1, 0])
raises(NonSquareMatrixError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 0, 0, 0])
raises(ValueError, lambda: A.inv_mod(2))
A = Matrix(2, 2, [1, 2, 3, 4])
Ai = Matrix(2, 2, [1, 1, 0, 1])
assert A.inv_mod(3) == Ai
A = Matrix(2, 2, [1, 0, 0, 1])
assert A.inv_mod(2) == A
A = Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])
raises(ValueError, lambda: A.inv_mod(5))
A = Matrix(3, 3, [5, 1, 3, 2, 6, 0, 2, 1, 1])
Ai = Matrix(3, 3, [6, 8, 0, 1, 5, 6, 5, 6, 4])
assert A.inv_mod(9) == Ai
A = Matrix(3, 3, [1, 6, -3, 4, 1, -5, 3, -5, 5])
Ai = Matrix(3, 3, [4, 3, 3, 1, 2, 5, 1, 5, 1])
assert A.inv_mod(6) == Ai
A = Matrix(3, 3, [1, 6, 1, 4, 1, 5, 3, 2, 5])
Ai = Matrix(3, 3, [6, 0, 3, 6, 6, 4, 1, 6, 1])
assert A.inv_mod(7) == Ai
def test_jacobian_hessian():
L = Matrix(1, 2, [x**2*y, 2*y**2 + x*y])
syms = [x, y]
assert L.jacobian(syms) == Matrix([[2*x*y, x**2], [y, 4*y + x]])
L = Matrix(1, 2, [x, x**2*y**3])
assert L.jacobian(syms) == Matrix([[1, 0], [2*x*y**3, x**2*3*y**2]])
f = x**2*y
syms = [x, y]
assert hessian(f, syms) == Matrix([[2*y, 2*x], [2*x, 0]])
f = x**2*y**3
assert hessian(f, syms) == \
Matrix([[2*y**3, 6*x*y**2], [6*x*y**2, 6*x**2*y]])
f = z + x*y**2
g = x**2 + 2*y**3
ans = Matrix([[0, 2*y],
[2*y, 2*x]])
assert ans == hessian(f, Matrix([x, y]))
assert ans == hessian(f, Matrix([x, y]).T)
assert hessian(f, (y, x), [g]) == Matrix([
[ 0, 6*y**2, 2*x],
[6*y**2, 2*x, 2*y],
[ 2*x, 2*y, 0]])
def test_nullspace():
# first test reduced row-ech form
R = Rational
M = Matrix([[5, 7, 2, 1],
[1, 6, 2, -1]])
out, tmp = M.rref()
assert out == Matrix([[1, 0, -R(2)/23, R(13)/23],
[0, 1, R(8)/23, R(-6)/23]])
M = Matrix([[-5, -1, 4, -3, -1],
[ 1, -1, -1, 1, 0],
[-1, 0, 0, 0, 0],
[ 4, 1, -4, 3, 1],
[-2, 0, 2, -2, -1]])
assert M*M.nullspace()[0] == Matrix(5, 1, [0]*5)
M = Matrix([[ 1, 3, 0, 2, 6, 3, 1],
[-2, -6, 0, -2, -8, 3, 1],
[ 3, 9, 0, 0, 6, 6, 2],
[-1, -3, 0, 1, 0, 9, 3]])
out, tmp = M.rref()
assert out == Matrix([[1, 3, 0, 0, 2, 0, 0],
[0, 0, 0, 1, 2, 0, 0],
[0, 0, 0, 0, 0, 1, R(1)/3],
[0, 0, 0, 0, 0, 0, 0]])
# now check the vectors
basis = M.nullspace()
assert basis[0] == Matrix([-3, 1, 0, 0, 0, 0, 0])
assert basis[1] == Matrix([0, 0, 1, 0, 0, 0, 0])
assert basis[2] == Matrix([-2, 0, 0, -2, 1, 0, 0])
assert basis[3] == Matrix([0, 0, 0, 0, 0, R(-1)/3, 1])
# issue 4797; just see that we can do it when rows > cols
M = Matrix([[1, 2], [2, 4], [3, 6]])
assert M.nullspace()
def test_columnspace():
M = Matrix([[ 1, 2, 0, 2, 5],
[-2, -5, 1, -1, -8],
[ 0, -3, 3, 4, 1],
[ 3, 6, 0, -7, 2]])
# now check the vectors
basis = M.columnspace()
assert basis[0] == Matrix([1, -2, 0, 3])
assert basis[1] == Matrix([2, -5, -3, 6])
assert basis[2] == Matrix([2, -1, 4, -7])
#check by columnspace definition
a, b, c, d, e = symbols('a b c d e')
X = Matrix([a, b, c, d, e])
for i in range(len(basis)):
eq=M*X-basis[i]
assert len(solve(eq, X)) != 0
#check if rank-nullity theorem holds
assert M.rank() == len(basis)
assert len(M.nullspace()) + len(M.columnspace()) == M.cols
def test_wronskian():
assert wronskian([cos(x), sin(x)], x) == cos(x)**2 + sin(x)**2
assert wronskian([exp(x), exp(2*x)], x) == exp(3*x)
assert wronskian([exp(x), x], x) == exp(x) - x*exp(x)
assert wronskian([1, x, x**2], x) == 2
w1 = -6*exp(x)*sin(x)*x + 6*cos(x)*exp(x)*x**2 - 6*exp(x)*cos(x)*x - \
exp(x)*cos(x)*x**3 + exp(x)*sin(x)*x**3
assert wronskian([exp(x), cos(x), x**3], x).expand() == w1
assert wronskian([exp(x), cos(x), x**3], x, method='berkowitz').expand() \
== w1
w2 = -x**3*cos(x)**2 - x**3*sin(x)**2 - 6*x*cos(x)**2 - 6*x*sin(x)**2
assert wronskian([sin(x), cos(x), x**3], x).expand() == w2
assert wronskian([sin(x), cos(x), x**3], x, method='berkowitz').expand() \
== w2
assert wronskian([], x) == 1
def test_definite():
# Examples from Gilbert Strang, "Introduction to Linear Algebra"
# Positive definite matrices
m = Matrix([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[5, 4], [4, 5]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Positive semidefinite matrices
m = Matrix([[2, -1, -1], [-1, 2, -1], [-1, -1, 2]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[1, 2], [2, 4]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Examples from Mathematica documentation
# Non-hermitian positive definite matrices
m = Matrix([[2, 3], [4, 8]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[1, 2*I], [-I, 4]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
# Symbolic matrices examples
a = Symbol('a', positive=True)
b = Symbol('b', negative=True)
m = Matrix([[a, 0, 0], [0, a, 0], [0, 0, a]])
assert m.is_positive_definite == True
assert m.is_positive_semidefinite == True
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == False
m = Matrix([[b, 0, 0], [0, b, 0], [0, 0, b]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == False
assert m.is_negative_definite == True
assert m.is_negative_semidefinite == True
assert m.is_indefinite == False
m = Matrix([[a, 0], [0, b]])
assert m.is_positive_definite == False
assert m.is_positive_semidefinite == False
assert m.is_negative_definite == False
assert m.is_negative_semidefinite == False
assert m.is_indefinite == True
def test_positive_definite():
# Test alternative algorithms for testing positive definitiveness.
m = Matrix([[2, -1, 0], [-1, 2, -1], [0, -1, 2]])
assert m._eval_is_positive_definite(method='eigen') == True
assert m._eval_is_positive_definite(method='LDL') == True
assert m._eval_is_positive_definite(method='CH') == True
m = Matrix([[5, 4], [4, 5]])
assert m._eval_is_positive_definite(method='eigen') == True
assert m._eval_is_positive_definite(method='LDL') == True
assert m._eval_is_positive_definite(method='CH') == True
m = Matrix([[2, -1, -1], [-1, 2, -1], [-1, -1, 2]])
assert m._eval_is_positive_definite(method='eigen') == False
assert m._eval_is_positive_definite(method='LDL') == False
assert m._eval_is_positive_definite(method='CH') == False
m = Matrix([[1, 2], [2, 4]])
assert m._eval_is_positive_definite(method='eigen') == False
assert m._eval_is_positive_definite(method='LDL') == False
assert m._eval_is_positive_definite(method='CH') == False
m = Matrix([[2, 3], [4, 8]])
assert m._eval_is_positive_definite(method='eigen') == True
assert m._eval_is_positive_definite(method='LDL') == True
assert m._eval_is_positive_definite(method='CH') == True
m = Matrix([[1, 2*I], [-I, 4]])
assert m._eval_is_positive_definite(method='eigen') == True
assert m._eval_is_positive_definite(method='LDL') == True
assert m._eval_is_positive_definite(method='CH') == True
a = Symbol('a', positive=True)
b = Symbol('b', negative=True)
m = Matrix([[a, 0, 0], [0, a, 0], [0, 0, a]])
assert m._eval_is_positive_definite(method='eigen') == True
assert m._eval_is_positive_definite(method='LDL') == True
assert m._eval_is_positive_definite(method='CH') == True
m = Matrix([[b, 0, 0], [0, b, 0], [0, 0, b]])
assert m._eval_is_positive_definite(method='eigen') == False
assert m._eval_is_positive_definite(method='LDL') == False
assert m._eval_is_positive_definite(method='CH') == False
m = Matrix([[a, 0], [0, b]])
assert m._eval_is_positive_definite(method='eigen') == False
assert m._eval_is_positive_definite(method='LDL') == False
assert m._eval_is_positive_definite(method='CH') == False
def test_subs():
assert Matrix([[1, x], [x, 4]]).subs(x, 5) == Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([[x, -1], [y, -2]]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs([(x, -1), (y, -2)]) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([[x, 2], [x + y, 4]]).subs({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
assert Matrix([x*y]).subs({x: y - 1, y: x - 1}, simultaneous=True) == \
Matrix([(x - 1)*(y - 1)])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).subs(1, 2)
def test_xreplace():
assert Matrix([[1, x], [x, 4]]).xreplace({x: 5}) == \
Matrix([[1, 5], [5, 4]])
assert Matrix([[x, 2], [x + y, 4]]).xreplace({x: -1, y: -2}) == \
Matrix([[-1, 2], [-3, 4]])
for cls in classes:
assert Matrix([[2, 0], [0, 2]]) == cls.eye(2).xreplace({1: 2})
def test_simplify():
n = Symbol('n')
f = Function('f')
M = Matrix([[ 1/x + 1/y, (x + x*y) / x ],
[ (f(x) + y*f(x))/f(x), 2 * (1/n - cos(n * pi)/n) / pi ]])
M.simplify()
assert M == Matrix([[ (x + y)/(x * y), 1 + y ],
[ 1 + y, 2*((1 - 1*cos(pi*n))/(pi*n)) ]])
eq = (1 + x)**2
M = Matrix([[eq]])
M.simplify()
assert M == Matrix([[eq]])
M.simplify(ratio=oo) == M
assert M == Matrix([[eq.simplify(ratio=oo)]])
def test_transpose():
M = Matrix([[1, 2, 3, 4, 5, 6, 7, 8, 9, 0],
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]])
assert M.T == Matrix( [ [1, 1],
[2, 2],
[3, 3],
[4, 4],
[5, 5],
[6, 6],
[7, 7],
[8, 8],
[9, 9],
[0, 0] ])
assert M.T.T == M
assert M.T == M.transpose()
def test_conjugate():
M = Matrix([[0, I, 5],
[1, 2, 0]])
assert M.T == Matrix([[0, 1],
[I, 2],
[5, 0]])
assert M.C == Matrix([[0, -I, 5],
[1, 2, 0]])
assert M.C == M.conjugate()
assert M.H == M.T.C
assert M.H == Matrix([[ 0, 1],
[-I, 2],
[ 5, 0]])
def test_conj_dirac():
raises(AttributeError, lambda: eye(3).D)
M = Matrix([[1, I, I, I],
[0, 1, I, I],
[0, 0, 1, I],
[0, 0, 0, 1]])
assert M.D == Matrix([[ 1, 0, 0, 0],
[-I, 1, 0, 0],
[-I, -I, -1, 0],
[-I, -I, I, -1]])
def test_trace():
M = Matrix([[1, 0, 0],
[0, 5, 0],
[0, 0, 8]])
assert M.trace() == 14
def test_shape():
M = Matrix([[x, 0, 0],
[0, y, 0]])
assert M.shape == (2, 3)
def test_col_row_op():
M = Matrix([[x, 0, 0],
[0, y, 0]])
M.row_op(1, lambda r, j: r + j + 1)
assert M == Matrix([[x, 0, 0],
[1, y + 2, 3]])
M.col_op(0, lambda c, j: c + y**j)
assert M == Matrix([[x + 1, 0, 0],
[1 + y, y + 2, 3]])
# neither row nor slice give copies that allow the original matrix to
# be changed
assert M.row(0) == Matrix([[x + 1, 0, 0]])
r1 = M.row(0)
r1[0] = 42
assert M[0, 0] == x + 1
r1 = M[0, :-1] # also testing negative slice
r1[0] = 42
assert M[0, 0] == x + 1
c1 = M.col(0)
assert c1 == Matrix([x + 1, 1 + y])
c1[0] = 0
assert M[0, 0] == x + 1
c1 = M[:, 0]
c1[0] = 42
assert M[0, 0] == x + 1
def test_zip_row_op():
for cls in classes[:2]: # XXX: immutable matrices don't support row ops
M = cls.eye(3)
M.zip_row_op(1, 0, lambda v, u: v + 2*u)
assert M == cls([[1, 0, 0],
[2, 1, 0],
[0, 0, 1]])
M = cls.eye(3)*2
M[0, 1] = -1
M.zip_row_op(1, 0, lambda v, u: v + 2*u); M
assert M == cls([[2, -1, 0],
[4, 0, 0],
[0, 0, 2]])
def test_issue_3950():
m = Matrix([1, 2, 3])
a = Matrix([1, 2, 3])
b = Matrix([2, 2, 3])
assert not (m in [])
assert not (m in [1])
assert m != 1
assert m == a
assert m != b
def test_issue_3981():
class Index1(object):
def __index__(self):
return 1
class Index2(object):
def __index__(self):
return 2
index1 = Index1()
index2 = Index2()
m = Matrix([1, 2, 3])
assert m[index2] == 3
m[index2] = 5
assert m[2] == 5
m = Matrix([[1, 2, 3], [4, 5, 6]])
assert m[index1, index2] == 6
assert m[1, index2] == 6
assert m[index1, 2] == 6
m[index1, index2] = 4
assert m[1, 2] == 4
m[1, index2] = 6
assert m[1, 2] == 6
m[index1, 2] = 8
assert m[1, 2] == 8
def test_evalf():
a = Matrix([sqrt(5), 6])
assert all(a.evalf()[i] == a[i].evalf() for i in range(2))
assert all(a.evalf(2)[i] == a[i].evalf(2) for i in range(2))
assert all(a.n(2)[i] == a[i].n(2) for i in range(2))
def test_is_symbolic():
a = Matrix([[x, x], [x, x]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3, 4], [5, 6, 7, 8]])
assert a.is_symbolic() is False
a = Matrix([[1, 2, 3, 4], [5, 6, x, 8]])
assert a.is_symbolic() is True
a = Matrix([[1, x, 3]])
assert a.is_symbolic() is True
a = Matrix([[1, 2, 3]])
assert a.is_symbolic() is False
a = Matrix([[1], [x], [3]])
assert a.is_symbolic() is True
a = Matrix([[1], [2], [3]])
assert a.is_symbolic() is False
def test_is_upper():
a = Matrix([[1, 2, 3]])
assert a.is_upper is True
a = Matrix([[1], [2], [3]])
assert a.is_upper is False
a = zeros(4, 2)
assert a.is_upper is True
def test_is_lower():
a = Matrix([[1, 2, 3]])
assert a.is_lower is False
a = Matrix([[1], [2], [3]])
assert a.is_lower is True
def test_is_nilpotent():
a = Matrix(4, 4, [0, 2, 1, 6, 0, 0, 1, 2, 0, 0, 0, 3, 0, 0, 0, 0])
assert a.is_nilpotent()
a = Matrix([[1, 0], [0, 1]])
assert not a.is_nilpotent()
a = Matrix([])
assert a.is_nilpotent()
def test_zeros_ones_fill():
n, m = 3, 5
a = zeros(n, m)
a.fill( 5 )
b = 5 * ones(n, m)
assert a == b
assert a.rows == b.rows == 3
assert a.cols == b.cols == 5
assert a.shape == b.shape == (3, 5)
assert zeros(2) == zeros(2, 2)
assert ones(2) == ones(2, 2)
assert zeros(2, 3) == Matrix(2, 3, [0]*6)
assert ones(2, 3) == Matrix(2, 3, [1]*6)
def test_empty_zeros():
a = zeros(0)
assert a == Matrix()
a = zeros(0, 2)
assert a.rows == 0
assert a.cols == 2
a = zeros(2, 0)
assert a.rows == 2
assert a.cols == 0
def test_issue_3749():
a = Matrix([[x**2, x*y], [x*sin(y), x*cos(y)]])
assert a.diff(x) == Matrix([[2*x, y], [sin(y), cos(y)]])
assert Matrix([
[x, -x, x**2],
[exp(x), 1/x - exp(-x), x + 1/x]]).limit(x, oo) == \
Matrix([[oo, -oo, oo], [oo, 0, oo]])
assert Matrix([
[(exp(x) - 1)/x, 2*x + y*x, x**x ],
[1/x, abs(x), abs(sin(x + 1))]]).limit(x, 0) == \
Matrix([[1, 0, 1], [oo, 0, sin(1)]])
assert a.integrate(x) == Matrix([
[Rational(1, 3)*x**3, y*x**2/2],
[x**2*sin(y)/2, x**2*cos(y)/2]])
def test_inv_iszerofunc():
A = eye(4)
A.col_swap(0, 1)
for method in "GE", "LU":
assert A.inv(method=method, iszerofunc=lambda x: x == 0) == \
A.inv(method="ADJ")
def test_jacobian_metrics():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi)])
Y = Matrix([rho, phi])
J = X.jacobian(Y)
assert J == X.jacobian(Y.T)
assert J == (X.T).jacobian(Y)
assert J == (X.T).jacobian(Y.T)
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(trigsimp)
assert g == Matrix([[1, 0], [0, rho**2]])
def test_jacobian2():
rho, phi = symbols("rho,phi")
X = Matrix([rho*cos(phi), rho*sin(phi), rho**2])
Y = Matrix([rho, phi])
J = Matrix([
[cos(phi), -rho*sin(phi)],
[sin(phi), rho*cos(phi)],
[ 2*rho, 0],
])
assert X.jacobian(Y) == J
def test_issue_4564():
X = Matrix([exp(x + y + z), exp(x + y + z), exp(x + y + z)])
Y = Matrix([x, y, z])
for i in range(1, 3):
for j in range(1, 3):
X_slice = X[:i, :]
Y_slice = Y[:j, :]
J = X_slice.jacobian(Y_slice)
assert J.rows == i
assert J.cols == j
for k in range(j):
assert J[:, k] == X_slice
def test_nonvectorJacobian():
X = Matrix([[exp(x + y + z), exp(x + y + z)],
[exp(x + y + z), exp(x + y + z)]])
raises(TypeError, lambda: X.jacobian(Matrix([x, y, z])))
X = X[0, :]
Y = Matrix([[x, y], [x, z]])
raises(TypeError, lambda: X.jacobian(Y))
raises(TypeError, lambda: X.jacobian(Matrix([ [x, y], [x, z] ])))
def test_vec():
m = Matrix([[1, 3], [2, 4]])
m_vec = m.vec()
assert m_vec.cols == 1
for i in range(4):
assert m_vec[i] == i + 1
def test_vech():
m = Matrix([[1, 2], [2, 3]])
m_vech = m.vech()
assert m_vech.cols == 1
for i in range(3):
assert m_vech[i] == i + 1
m_vech = m.vech(diagonal=False)
assert m_vech[0] == 2
m = Matrix([[1, x*(x + y)], [y*x + x**2, 1]])
m_vech = m.vech(diagonal=False)
assert m_vech[0] == x*(x + y)
m = Matrix([[1, x*(x + y)], [y*x, 1]])
m_vech = m.vech(diagonal=False, check_symmetry=False)
assert m_vech[0] == y*x
def test_vech_errors():
m = Matrix([[1, 3]])
raises(ShapeError, lambda: m.vech())
m = Matrix([[1, 3], [2, 4]])
raises(ValueError, lambda: m.vech())
raises(ShapeError, lambda: Matrix([ [1, 3] ]).vech())
raises(ValueError, lambda: Matrix([ [1, 3], [2, 4] ]).vech())
def test_diag():
# mostly tested in testcommonmatrix.py
assert diag([1, 2, 3]) == Matrix([1, 2, 3])
m = [1, 2, [3]]
raises(ValueError, lambda: diag(m))
assert diag(m, strict=False) == Matrix([1, 2, 3])
def test_get_diag_blocks1():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert a.get_diag_blocks() == [a]
assert b.get_diag_blocks() == [b]
assert c.get_diag_blocks() == [c]
def test_get_diag_blocks2():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
assert diag(a, b, b).get_diag_blocks() == [a, b, b]
assert diag(a, b, c).get_diag_blocks() == [a, b, c]
assert diag(a, c, b).get_diag_blocks() == [a, c, b]
assert diag(c, c, b).get_diag_blocks() == [c, c, b]
def test_inv_block():
a = Matrix([[1, 2], [2, 3]])
b = Matrix([[3, x], [y, 3]])
c = Matrix([[3, x, 3], [y, 3, z], [x, y, z]])
A = diag(a, b, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), b.inv())
A = diag(a, b, c)
assert A.inv(try_block_diag=True) == diag(a.inv(), b.inv(), c.inv())
A = diag(a, c, b)
assert A.inv(try_block_diag=True) == diag(a.inv(), c.inv(), b.inv())
A = diag(a, a, b, a, c, a)
assert A.inv(try_block_diag=True) == diag(
a.inv(), a.inv(), b.inv(), a.inv(), c.inv(), a.inv())
assert A.inv(try_block_diag=True, method="ADJ") == diag(
a.inv(method="ADJ"), a.inv(method="ADJ"), b.inv(method="ADJ"),
a.inv(method="ADJ"), c.inv(method="ADJ"), a.inv(method="ADJ"))
def test_creation_args():
"""
Check that matrix dimensions can be specified using any reasonable type
(see issue 4614).
"""
raises(ValueError, lambda: zeros(3, -1))
raises(TypeError, lambda: zeros(1, 2, 3, 4))
assert zeros(int(3)) == zeros(3)
assert zeros(Integer(3)) == zeros(3)
raises(ValueError, lambda: zeros(3.))
assert eye(int(3)) == eye(3)
assert eye(Integer(3)) == eye(3)
raises(ValueError, lambda: eye(3.))
assert ones(int(3), Integer(4)) == ones(3, 4)
raises(TypeError, lambda: Matrix(5))
raises(TypeError, lambda: Matrix(1, 2))
raises(ValueError, lambda: Matrix([1, [2]]))
def test_diagonal_symmetrical():
m = Matrix(2, 2, [0, 1, 1, 0])
assert not m.is_diagonal()
assert m.is_symmetric()
assert m.is_symmetric(simplify=False)
m = Matrix(2, 2, [1, 0, 0, 1])
assert m.is_diagonal()
m = diag(1, 2, 3)
assert m.is_diagonal()
assert m.is_symmetric()
m = Matrix(3, 3, [1, 0, 0, 0, 2, 0, 0, 0, 3])
assert m == diag(1, 2, 3)
m = Matrix(2, 3, zeros(2, 3))
assert not m.is_symmetric()
assert m.is_diagonal()
m = Matrix(((5, 0), (0, 6), (0, 0)))
assert m.is_diagonal()
m = Matrix(((5, 0, 0), (0, 6, 0)))
assert m.is_diagonal()
m = Matrix(3, 3, [1, x**2 + 2*x + 1, y, (x + 1)**2, 2, 0, y, 0, 3])
assert m.is_symmetric()
assert not m.is_symmetric(simplify=False)
assert m.expand().is_symmetric(simplify=False)
def test_diagonalization():
m = Matrix([[1, 2+I], [2-I, 3]])
assert m.is_diagonalizable()
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
assert not m.is_diagonalizable()
assert not m.is_symmetric()
raises(NonSquareMatrixError, lambda: m.diagonalize())
# diagonalizable
m = diag(1, 2, 3)
(P, D) = m.diagonalize()
assert P == eye(3)
assert D == m
m = Matrix(2, 2, [0, 1, 1, 0])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(2, 2, [1, 0, 0, 3])
assert m.is_symmetric()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == eye(2)
assert D == m
m = Matrix(2, 2, [1, 1, 0, 0])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
m = Matrix(3, 3, [1, 2, 0, 0, 3, 0, 2, -4, 2])
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
for i in P:
assert i.as_numer_denom()[1] == 1
m = Matrix(2, 2, [1, 0, 0, 0])
assert m.is_diagonal()
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
assert P == Matrix([[0, 1], [1, 0]])
# diagonalizable, complex only
m = Matrix(2, 2, [0, 1, -1, 0])
assert not m.is_diagonalizable(True)
raises(MatrixError, lambda: m.diagonalize(True))
assert m.is_diagonalizable()
(P, D) = m.diagonalize()
assert P.inv() * m * P == D
# not diagonalizable
m = Matrix(2, 2, [0, 1, 0, 0])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
m = Matrix(3, 3, [-3, 1, -3, 20, 3, 10, 2, -2, 4])
assert not m.is_diagonalizable()
raises(MatrixError, lambda: m.diagonalize())
# symbolic
a, b, c, d = symbols('a b c d')
m = Matrix(2, 2, [a, c, c, b])
assert m.is_symmetric()
assert m.is_diagonalizable()
def test_issue_15887():
# Mutable matrix should not use cache
a = MutableDenseMatrix([[0, 1], [1, 0]])
assert a.is_diagonalizable() is True
a[1, 0] = 0
assert a.is_diagonalizable() is False
a = MutableDenseMatrix([[0, 1], [1, 0]])
a.diagonalize()
a[1, 0] = 0
raises(MatrixError, lambda: a.diagonalize())
# Test deprecated cache and kwargs
with warns_deprecated_sympy():
a.is_diagonalizable(clear_cache=True)
with warns_deprecated_sympy():
a.is_diagonalizable(clear_subproducts=True)
def test_jordan_form():
m = Matrix(3, 2, [-3, 1, -3, 20, 3, 10])
raises(NonSquareMatrixError, lambda: m.jordan_form())
# diagonalizable
m = Matrix(3, 3, [7, -12, 6, 10, -19, 10, 12, -24, 13])
Jmust = Matrix(3, 3, [-1, 0, 0, 0, 1, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
assert Jmust == m.diagonalize()[1]
# m = Matrix(3, 3, [0, 6, 3, 1, 3, 1, -2, 2, 1])
# m.jordan_form() # very long
# m.jordan_form() #
# diagonalizable, complex only
# Jordan cells
# complexity: one of eigenvalues is zero
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
# The blocks are ordered according to the value of their eigenvalues,
# in order to make the matrix compatible with .diagonalize()
Jmust = Matrix(3, 3, [2, 1, 0, 0, 2, 0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
# complexity: all of eigenvalues are equal
m = Matrix(3, 3, [2, 6, -15, 1, 1, -5, 1, 2, -6])
# Jmust = Matrix(3, 3, [-1, 0, 0, 0, -1, 1, 0, 0, -1])
# same here see 1456ff
Jmust = Matrix(3, 3, [-1, 1, 0, 0, -1, 0, 0, 0, -1])
P, J = m.jordan_form()
assert Jmust == J
# complexity: two of eigenvalues are zero
m = Matrix(3, 3, [4, -5, 2, 5, -7, 3, 6, -9, 4])
Jmust = Matrix(3, 3, [0, 1, 0, 0, 0, 0, 0, 0, 1])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 5, -2, -3, -3, -1, 3, 3, 2, 1, -2, -3, -1, 1, 5, 5])
Jmust = Matrix(4, 4, [2, 1, 0, 0,
0, 2, 0, 0,
0, 0, 2, 1,
0, 0, 0, 2]
)
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [6, 2, -8, -6, -3, 2, 9, 6, 2, -2, -8, -6, -1, 0, 3, 4])
# Jmust = Matrix(4, 4, [2, 0, 0, 0, 0, 2, 1, 0, 0, 0, 2, 0, 0, 0, 0, -2])
# same here see 1456ff
Jmust = Matrix(4, 4, [-2, 0, 0, 0,
0, 2, 1, 0,
0, 0, 2, 0,
0, 0, 0, 2])
P, J = m.jordan_form()
assert Jmust == J
m = Matrix(4, 4, [5, 4, 2, 1, 0, 1, -1, -1, -1, -1, 3, 0, 1, 1, -1, 2])
assert not m.is_diagonalizable()
Jmust = Matrix(4, 4, [1, 0, 0, 0, 0, 2, 0, 0, 0, 0, 4, 1, 0, 0, 0, 4])
P, J = m.jordan_form()
assert Jmust == J
# checking for maximum precision to remain unchanged
m = Matrix([[Float('1.0', precision=110), Float('2.0', precision=110)],
[Float('3.14159265358979323846264338327', precision=110), Float('4.0', precision=110)]])
P, J = m.jordan_form()
for term in J._mat:
if isinstance(term, Float):
assert term._prec == 110
def test_jordan_form_complex_issue_9274():
A = Matrix([[ 2, 4, 1, 0],
[-4, 2, 0, 1],
[ 0, 0, 2, 4],
[ 0, 0, -4, 2]])
p = 2 - 4*I;
q = 2 + 4*I;
Jmust1 = Matrix([[p, 1, 0, 0],
[0, p, 0, 0],
[0, 0, q, 1],
[0, 0, 0, q]])
Jmust2 = Matrix([[q, 1, 0, 0],
[0, q, 0, 0],
[0, 0, p, 1],
[0, 0, 0, p]])
P, J = A.jordan_form()
assert J == Jmust1 or J == Jmust2
assert simplify(P*J*P.inv()) == A
def test_issue_10220():
# two non-orthogonal Jordan blocks with eigenvalue 1
M = Matrix([[1, 0, 0, 1],
[0, 1, 1, 0],
[0, 0, 1, 1],
[0, 0, 0, 1]])
P, J = M.jordan_form()
assert P == Matrix([[0, 1, 0, 1],
[1, 0, 0, 0],
[0, 1, 0, 0],
[0, 0, 1, 0]])
assert J == Matrix([
[1, 1, 0, 0],
[0, 1, 1, 0],
[0, 0, 1, 0],
[0, 0, 0, 1]])
def test_jordan_form_issue_15858():
A = Matrix([
[1, 1, 1, 0],
[-2, -1, 0, -1],
[0, 0, -1, -1],
[0, 0, 2, 1]])
(P, J) = A.jordan_form()
assert P.expand() == Matrix([
[ -I, -I/2, I, I/2],
[-1 + I, 0, -1 - I, 0],
[ 0, -S(1)/2 - I/2, 0, -S(1)/2 + I/2],
[ 0, 1, 0, 1]])
assert J == Matrix([
[-I, 1, 0, 0],
[0, -I, 0, 0],
[0, 0, I, 1],
[0, 0, 0, I]])
def test_Matrix_berkowitz_charpoly():
UA, K_i, K_w = symbols('UA K_i K_w')
A = Matrix([[-K_i - UA + K_i**2/(K_i + K_w), K_i*K_w/(K_i + K_w)],
[ K_i*K_w/(K_i + K_w), -K_w + K_w**2/(K_i + K_w)]])
charpoly = A.charpoly(x)
assert charpoly == \
Poly(x**2 + (K_i*UA + K_w*UA + 2*K_i*K_w)/(K_i + K_w)*x +
K_i*K_w*UA/(K_i + K_w), x, domain='ZZ(K_i,K_w,UA)')
assert type(charpoly) is PurePoly
A = Matrix([[1, 3], [2, 0]])
assert A.charpoly() == A.charpoly(x) == PurePoly(x**2 - x - 6)
A = Matrix([[1, 2], [x, 0]])
p = A.charpoly(x)
assert p.gen != x
assert p.as_expr().subs(p.gen, x) == x**2 - 3*x
def test_exp_jordan_block():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_exp_jblock() == Matrix([[exp(l)]])
m = Matrix.jordan_block(3, l)
assert m._eval_matrix_exp_jblock() == \
Matrix([
[exp(l), exp(l), exp(l)/2],
[0, exp(l), exp(l)],
[0, 0, exp(l)]])
def test_exp():
m = Matrix([[3, 4], [0, -2]])
m_exp = Matrix([[exp(3), -4*exp(-2)/5 + 4*exp(3)/5], [0, exp(-2)]])
assert m.exp() == m_exp
assert exp(m) == m_exp
m = Matrix([[1, 0], [0, 1]])
assert m.exp() == Matrix([[E, 0], [0, E]])
assert exp(m) == Matrix([[E, 0], [0, E]])
m = Matrix([[1, -1], [1, 1]])
assert m.exp() == Matrix([[E*cos(1), -E*sin(1)], [E*sin(1), E*cos(1)]])
def test_log():
l = Symbol('lamda')
m = Matrix.jordan_block(1, l)
assert m._eval_matrix_log_jblock() == Matrix([[log(l)]])
m = Matrix.jordan_block(4, l)
assert m._eval_matrix_log_jblock() == \
Matrix(
[
[log(l), 1/l, -1/(2*l**2), 1/(3*l**3)],
[0, log(l), 1/l, -1/(2*l**2)],
[0, 0, log(l), 1/l],
[0, 0, 0, log(l)]
]
)
m = Matrix(
[[0, 0, 1],
[0, 0, 0],
[-1, 0, 0]]
)
raises(MatrixError, lambda: m.log())
def test_has():
A = Matrix(((x, y), (2, 3)))
assert A.has(x)
assert not A.has(z)
assert A.has(Symbol)
A = A.subs(x, 2)
assert not A.has(x)
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero1():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=None indicates that no simplifications
# should be performed during the search.
x = Symbol('x')
column = Matrix(3, 1, [x, cos(x)**2 + sin(x)**2, S.Half])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column)
assert pivot_val == S.Half
def test_find_reasonable_pivot_naive_finds_guaranteed_nonzero2():
# Test if matrices._find_reasonable_pivot_naive()
# finds a guaranteed non-zero pivot when the
# some of the candidate pivots are symbolic expressions.
# Keyword argument: simpfunc=_simplify indicates that the search
# should attempt to simplify candidate pivots.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x**2,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert pivot_val == 1
def test_find_reasonable_pivot_naive_simplifies():
# Test if matrices._find_reasonable_pivot_naive()
# simplifies candidate pivots, and reports
# their offsets correctly.
x = Symbol('x')
column = Matrix(3, 1,
[x,
cos(x)**2+sin(x)**2+x,
cos(x)**2+sin(x)**2])
pivot_offset, pivot_val, pivot_assumed_nonzero, simplified =\
_find_reasonable_pivot_naive(column, simpfunc=_simplify)
assert len(simplified) == 2
assert simplified[0][0] == 1
assert simplified[0][1] == 1+x
assert simplified[1][0] == 2
assert simplified[1][1] == 1
def test_errors():
raises(ValueError, lambda: Matrix([[1, 2], [1]]))
raises(IndexError, lambda: Matrix([[1, 2]])[1.2, 5])
raises(IndexError, lambda: Matrix([[1, 2]])[1, 5.2])
raises(ValueError, lambda: randMatrix(3, c=4, symmetric=True))
raises(ValueError, lambda: Matrix([1, 2]).reshape(4, 6))
raises(ShapeError,
lambda: Matrix([[1, 2], [3, 4]]).copyin_matrix([1, 0], Matrix([1, 2])))
raises(TypeError, lambda: Matrix([[1, 2], [3, 4]]).copyin_list([0,
1], set([])))
raises(NonSquareMatrixError, lambda: Matrix([[1, 2, 3], [2, 3, 0]]).inv())
raises(ShapeError,
lambda: Matrix(1, 2, [1, 2]).row_join(Matrix([[1, 2], [3, 4]])))
raises(
ShapeError, lambda: Matrix([1, 2]).col_join(Matrix([[1, 2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).row_insert(1, Matrix([[1,
2], [3, 4]])))
raises(ShapeError, lambda: Matrix([1]).col_insert(1, Matrix([[1,
2], [3, 4]])))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).trace())
raises(TypeError, lambda: Matrix([1]).applyfunc(1))
raises(ShapeError, lambda: Matrix([1]).LUsolve(Matrix([[1, 2], [3, 4]])))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor(4, 5))
raises(ValueError, lambda: Matrix([[1, 2], [3, 4]]).minor_submatrix(4, 5))
raises(TypeError, lambda: Matrix([1, 2, 3]).cross(1))
raises(TypeError, lambda: Matrix([1, 2, 3]).dot(1))
raises(ShapeError, lambda: Matrix([1, 2, 3]).dot(Matrix([1, 2])))
raises(ShapeError, lambda: Matrix([1, 2]).dot([]))
raises(TypeError, lambda: Matrix([1, 2]).dot('a'))
with warns_deprecated_sympy():
Matrix([[1, 2], [3, 4]]).dot(Matrix([[4, 3], [1, 2]]))
raises(ShapeError, lambda: Matrix([1, 2]).dot([1, 2, 3]))
raises(NonSquareMatrixError, lambda: Matrix([1, 2, 3]).exp())
raises(ShapeError, lambda: Matrix([[1, 2], [3, 4]]).normalized())
raises(ValueError, lambda: Matrix([1, 2]).inv(method='not a method'))
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_GE())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_GE())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_ADJ())
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inverse_ADJ())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).inverse_LU())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).is_nilpotent())
raises(NonSquareMatrixError, lambda: Matrix([1, 2]).det())
raises(ValueError,
lambda: Matrix([[1, 2], [3, 4]]).det(method='Not a real method'))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc="Not function"))
raises(ValueError,
lambda: Matrix([[1, 2, 3, 4], [5, 6, 7, 8],
[9, 10, 11, 12], [13, 14, 15, 16]]).det(iszerofunc=False))
raises(ValueError,
lambda: hessian(Matrix([[1, 2], [3, 4]]), Matrix([[1, 2], [2, 1]])))
raises(ValueError, lambda: hessian(Matrix([[1, 2], [3, 4]]), []))
raises(ValueError, lambda: hessian(Symbol('x')**2, 'a'))
raises(IndexError, lambda: eye(3)[5, 2])
raises(IndexError, lambda: eye(3)[2, 5])
M = Matrix(((1, 2, 3, 4), (5, 6, 7, 8), (9, 10, 11, 12), (13, 14, 15, 16)))
raises(ValueError, lambda: M.det('method=LU_decomposition()'))
V = Matrix([[10, 10, 10]])
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.row_insert(4.7, V))
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(ValueError, lambda: M.col_insert(-4.2, V))
def test_len():
assert len(Matrix()) == 0
assert len(Matrix([[1, 2]])) == len(Matrix([[1], [2]])) == 2
assert len(Matrix(0, 2, lambda i, j: 0)) == \
len(Matrix(2, 0, lambda i, j: 0)) == 0
assert len(Matrix([[0, 1, 2], [3, 4, 5]])) == 6
assert Matrix([1]) == Matrix([[1]])
assert not Matrix()
assert Matrix() == Matrix([])
def test_integrate():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2)))
assert A.integrate(x) == \
Matrix(((x, 4*x, x**2/2), (x*y, 2*x, 4*x), (10*x, 5*x, x**3/3)))
assert A.integrate(y) == \
Matrix(((y, 4*y, x*y), (y**2/2, 2*y, 4*y), (10*y, 5*y, y*x**2)))
def test_limit():
A = Matrix(((1, 4, sin(x)/x), (y, 2, 4), (10, 5, x**2 + 1)))
assert A.limit(x, 0) == Matrix(((1, 4, 1), (y, 2, 4), (10, 5, 1)))
def test_diff():
A = MutableDenseMatrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
assert isinstance(A.diff(x), type(A))
assert A.diff(x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A.diff(y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A, x) == MutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A, y) == MutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
A_imm = A.as_immutable()
assert isinstance(A_imm.diff(x), type(A_imm))
assert A_imm.diff(x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert A_imm.diff(y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
assert diff(A_imm, x) == ImmutableDenseMatrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
assert diff(A_imm, y) == ImmutableDenseMatrix(((0, 0, 0), (1, 0, 0), (0, 0, 0)))
def test_diff_by_matrix():
# Derive matrix by matrix:
A = MutableDenseMatrix([[x, y], [z, t]])
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A, A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
A_imm = A.as_immutable()
assert A_imm.diff(A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
assert diff(A_imm, A_imm) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Derive a constant matrix:
assert A.diff(a) == MutableDenseMatrix([[0, 0], [0, 0]])
B = ImmutableDenseMatrix([a, b])
assert A.diff(B) == Array.zeros(2, 1, 2, 2)
assert A.diff(A) == Array([[[[1, 0], [0, 0]], [[0, 1], [0, 0]]], [[[0, 0], [1, 0]], [[0, 0], [0, 1]]]])
# Test diff with tuples:
dB = B.diff([[a, b]])
assert dB.shape == (2, 2, 1)
assert dB == Array([[[1], [0]], [[0], [1]]])
f = Function("f")
fxyz = f(x, y, z)
assert fxyz.diff([[x, y, z]]) == Array([fxyz.diff(x), fxyz.diff(y), fxyz.diff(z)])
assert fxyz.diff(([x, y, z], 2)) == Array([
[fxyz.diff(x, 2), fxyz.diff(x, y), fxyz.diff(x, z)],
[fxyz.diff(x, y), fxyz.diff(y, 2), fxyz.diff(y, z)],
[fxyz.diff(x, z), fxyz.diff(z, y), fxyz.diff(z, 2)],
])
expr = sin(x)*exp(y)
assert expr.diff([[x, y]]) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(y, ((x, y),)) == Array([cos(x)*exp(y), sin(x)*exp(y)])
assert expr.diff(x, ((x, y),)) == Array([-sin(x)*exp(y), cos(x)*exp(y)])
assert expr.diff(((y, x),), [[x, y]]) == Array([[cos(x)*exp(y), -sin(x)*exp(y)], [sin(x)*exp(y), cos(x)*exp(y)]])
# Test different notations:
fxyz.diff(x).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[0, 1, 0]
fxyz.diff(z).diff(y).diff(x) == fxyz.diff(((x, y, z),), 3)[2, 1, 0]
fxyz.diff([[x, y, z]], ((z, y, x),)) == Array([[fxyz.diff(i).diff(j) for i in (x, y, z)] for j in (z, y, x)])
# Test scalar derived by matrix remains matrix:
res = x.diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[1, 0]])
res = (x**3).diff(Matrix([[x, y]]))
assert isinstance(res, ImmutableDenseMatrix)
assert res == Matrix([[3*x**2, 0]])
def test_getattr():
A = Matrix(((1, 4, x), (y, 2, 4), (10, 5, x**2 + 1)))
raises(AttributeError, lambda: A.nonexistantattribute)
assert getattr(A, 'diff')(x) == Matrix(((0, 0, 1), (0, 0, 0), (0, 0, 2*x)))
def test_hessenberg():
A = Matrix([[3, 4, 1], [2, 4, 5], [0, 1, 2]])
assert A.is_upper_hessenberg
A = A.T
assert A.is_lower_hessenberg
A[0, -1] = 1
assert A.is_lower_hessenberg is False
A = Matrix([[3, 4, 1], [2, 4, 5], [3, 1, 2]])
assert not A.is_upper_hessenberg
A = zeros(5, 2)
assert A.is_upper_hessenberg
def test_cholesky():
raises(NonSquareMatrixError, lambda: Matrix((1, 2)).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: Matrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: Matrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert Matrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = Matrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = Matrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = Matrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
raises(NonSquareMatrixError, lambda: SparseMatrix((1, 2)).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky())
raises(ValueError, lambda: SparseMatrix(((5 + I, 0), (0, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 5), (5, 1))).cholesky())
raises(ValueError, lambda: SparseMatrix(((1, 2), (3, 4))).cholesky(hermitian=False))
assert SparseMatrix(((5 + I, 0), (0, 1))).cholesky(hermitian=False) == Matrix([
[sqrt(5 + I), 0], [0, 1]])
A = SparseMatrix(((1, 5), (5, 1)))
L = A.cholesky(hermitian=False)
assert L == Matrix([[1, 0], [5, 2*sqrt(6)*I]])
assert L*L.T == A
A = SparseMatrix(((25, 15, -5), (15, 18, 0), (-5, 0, 11)))
L = A.cholesky()
assert L * L.T == A
assert L.is_lower
assert L == Matrix([[5, 0, 0], [3, 3, 0], [-1, 1, 3]])
A = SparseMatrix(((4, -2*I, 2 + 2*I), (2*I, 2, -1 + I), (2 - 2*I, -1 - I, 11)))
assert A.cholesky() == Matrix(((2, 0, 0), (I, 1, 0), (1 - I, 0, 3)))
def test_cholesky_solve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix(((1, 5), (5, 1)))
x = Matrix((4, -3))
b = A*x
soln = A.cholesky_solve(b)
assert soln == x
A = Matrix(((9, 3*I), (-3*I, 5)))
x = Matrix((-2, 1))
b = A*x
soln = A.cholesky_solve(b)
assert expand_mul(soln) == x
A = Matrix(((9*I, 3), (-3 + I, 5)))
x = Matrix((2 + 3*I, -1))
b = A*x
soln = A.cholesky_solve(b)
assert expand_mul(soln) == x
a00, a01, a11, b0, b1 = symbols('a00, a01, a11, b0, b1')
A = Matrix(((a00, a01), (a01, a11)))
b = Matrix((b0, b1))
x = A.cholesky_solve(b)
assert simplify(A*x) == b
def test_LDLsolve():
A = Matrix([[2, 3, 5],
[3, 6, 2],
[8, 3, 6]])
x = Matrix(3, 1, [3, 7, 5])
b = A*x
soln = A.LDLsolve(b)
assert soln == x
A = Matrix([[0, -1, 2],
[5, 10, 7],
[8, 3, 4]])
x = Matrix(3, 1, [-1, 2, 5])
b = A*x
soln = A.LDLsolve(b)
assert soln == x
A = Matrix(((9, 3*I), (-3*I, 5)))
x = Matrix((-2, 1))
b = A*x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix(((9*I, 3), (-3 + I, 5)))
x = Matrix((2 + 3*I, -1))
b = A*x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix(((9, 3), (3, 9)))
x = Matrix((1, 1))
b = A * x
soln = A.LDLsolve(b)
assert expand_mul(soln) == x
A = Matrix([[-5, -3, -4], [-3, -7, 7]])
x = Matrix([[8], [7], [-2]])
b = A * x
raises(NotImplementedError, lambda: A.LDLsolve(b))
def test_lower_triangular_solve():
raises(NonSquareMatrixError,
lambda: Matrix([1, 0]).lower_triangular_solve(Matrix([0, 1])))
raises(ShapeError,
lambda: Matrix([[1, 0], [0, 1]]).lower_triangular_solve(Matrix([1])))
raises(ValueError,
lambda: Matrix([[2, 1], [1, 2]]).lower_triangular_solve(
Matrix([[1, 0], [0, 1]])))
A = Matrix([[1, 0], [0, 1]])
B = Matrix([[x, y], [y, x]])
C = Matrix([[4, 8], [2, 9]])
assert A.lower_triangular_solve(B) == B
assert A.lower_triangular_solve(C) == C
def test_upper_triangular_solve():
raises(NonSquareMatrixError,
lambda: Matrix([1, 0]).upper_triangular_solve(Matrix([0, 1])))
raises(ShapeError,
lambda: Matrix([[1, 0], [0, 1]]).upper_triangular_solve(Matrix([1])))
raises(TypeError,
lambda: Matrix([[2, 1], [1, 2]]).upper_triangular_solve(
Matrix([[1, 0], [0, 1]])))
A = Matrix([[1, 0], [0, 1]])
B = Matrix([[x, y], [y, x]])
C = Matrix([[2, 4], [3, 8]])
assert A.upper_triangular_solve(B) == B
assert A.upper_triangular_solve(C) == C
def test_diagonal_solve():
raises(TypeError, lambda: Matrix([1, 1]).diagonal_solve(Matrix([1])))
A = Matrix([[1, 0], [0, 1]])*2
B = Matrix([[x, y], [y, x]])
assert A.diagonal_solve(B) == B/2
A = Matrix([[1, 0], [1, 2]])
raises(TypeError, lambda: A.diagonal_solve(B))
def test_matrix_norm():
# Vector Tests
# Test columns and symbols
x = Symbol('x', real=True)
v = Matrix([cos(x), sin(x)])
assert trigsimp(v.norm(2)) == 1
assert v.norm(10) == Pow(cos(x)**10 + sin(x)**10, Rational(1, 10))
# Test Rows
A = Matrix([[5, Rational(3, 2)]])
assert A.norm() == Pow(25 + Rational(9, 4), S.Half)
assert A.norm(oo) == max(A._mat)
assert A.norm(-oo) == min(A._mat)
# Matrix Tests
# Intuitive test
A = Matrix([[1, 1], [1, 1]])
assert A.norm(2) == 2
assert A.norm(-2) == 0
assert A.norm('frobenius') == 2
assert eye(10).norm(2) == eye(10).norm(-2) == 1
assert A.norm(oo) == 2
# Test with Symbols and more complex entries
A = Matrix([[3, y, y], [x, S.Half, -pi]])
assert (A.norm('fro')
== sqrt(Rational(37, 4) + 2*abs(y)**2 + pi**2 + x**2))
# Check non-square
A = Matrix([[1, 2, -3], [4, 5, Rational(13, 2)]])
assert A.norm(2) == sqrt(Rational(389, 8) + sqrt(78665)/8)
assert A.norm(-2) is S.Zero
assert A.norm('frobenius') == sqrt(389)/2
# Test properties of matrix norms
# https://en.wikipedia.org/wiki/Matrix_norm#Definition
# Two matrices
A = Matrix([[1, 2], [3, 4]])
B = Matrix([[5, 5], [-2, 2]])
C = Matrix([[0, -I], [I, 0]])
D = Matrix([[1, 0], [0, -1]])
L = [A, B, C, D]
alpha = Symbol('alpha', real=True)
for order in ['fro', 2, -2]:
# Zero Check
assert zeros(3).norm(order) is S.Zero
# Check Triangle Inequality for all Pairs of Matrices
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert (dif >= 0)
# Scalar multiplication linearity
for M in [A, B, C, D]:
dif = simplify((alpha*M).norm(order) -
abs(alpha) * M.norm(order))
assert dif == 0
# Test Properties of Vector Norms
# https://en.wikipedia.org/wiki/Vector_norm
# Two column vectors
a = Matrix([1, 1 - 1*I, -3])
b = Matrix([S.Half, 1*I, 1])
c = Matrix([-1, -1, -1])
d = Matrix([3, 2, I])
e = Matrix([Integer(1e2), Rational(1, 1e2), 1])
L = [a, b, c, d, e]
alpha = Symbol('alpha', real=True)
for order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity, pi]:
# Zero Check
if order > 0:
assert Matrix([0, 0, 0]).norm(order) is S.Zero
# Triangle inequality on all pairs
if order >= 1: # Triangle InEq holds only for these norms
for X in L:
for Y in L:
dif = (X.norm(order) + Y.norm(order) -
(X + Y).norm(order))
assert simplify(dif >= 0) is S.true
# Linear to scalar multiplication
if order in [1, 2, -1, -2, S.Infinity, S.NegativeInfinity]:
for X in L:
dif = simplify((alpha*X).norm(order) -
(abs(alpha) * X.norm(order)))
assert dif == 0
# ord=1
M = Matrix(3, 3, [1, 3, 0, -2, -1, 0, 3, 9, 6])
assert M.norm(1) == 13
def test_condition_number():
x = Symbol('x', real=True)
A = eye(3)
A[0, 0] = 10
A[2, 2] = Rational(1, 10)
assert A.condition_number() == 100
A[1, 1] = x
assert A.condition_number() == Max(10, Abs(x)) / Min(Rational(1, 10), Abs(x))
M = Matrix([[cos(x), sin(x)], [-sin(x), cos(x)]])
Mc = M.condition_number()
assert all(Float(1.).epsilon_eq(Mc.subs(x, val).evalf()) for val in
[Rational(1, 5), S.Half, Rational(1, 10), pi/2, pi, pi*Rational(7, 4) ])
#issue 10782
assert Matrix([]).condition_number() == 0
def test_equality():
A = Matrix(((1, 2, 3), (4, 5, 6), (7, 8, 9)))
B = Matrix(((9, 8, 7), (6, 5, 4), (3, 2, 1)))
assert A == A[:, :]
assert not A != A[:, :]
assert not A == B
assert A != B
assert A != 10
assert not A == 10
# A SparseMatrix can be equal to a Matrix
C = SparseMatrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
D = Matrix(((1, 0, 0), (0, 1, 0), (0, 0, 1)))
assert C == D
assert not C != D
def test_col_join():
assert eye(3).col_join(Matrix([[7, 7, 7]])) == \
Matrix([[1, 0, 0],
[0, 1, 0],
[0, 0, 1],
[7, 7, 7]])
def test_row_insert():
r4 = Matrix([[4, 4, 4]])
for i in range(-4, 5):
l = [1, 0, 0]
l.insert(i, 4)
assert flatten(eye(3).row_insert(i, r4).col(0).tolist()) == l
def test_col_insert():
c4 = Matrix([4, 4, 4])
for i in range(-4, 5):
l = [0, 0, 0]
l.insert(i, 4)
assert flatten(zeros(3).col_insert(i, c4).row(0).tolist()) == l
def test_normalized():
assert Matrix([3, 4]).normalized() == \
Matrix([Rational(3, 5), Rational(4, 5)])
# Zero vector trivial cases
assert Matrix([0, 0, 0]).normalized() == Matrix([0, 0, 0])
# Machine precision error truncation trivial cases
m = Matrix([0,0,1.e-100])
assert m.normalized(
iszerofunc=lambda x: x.evalf(n=10, chop=True).is_zero
) == Matrix([0, 0, 0])
def test_print_nonzero():
assert capture(lambda: eye(3).print_nonzero()) == \
'[X ]\n[ X ]\n[ X]\n'
assert capture(lambda: eye(3).print_nonzero('.')) == \
'[. ]\n[ . ]\n[ .]\n'
def test_zeros_eye():
assert Matrix.eye(3) == eye(3)
assert Matrix.zeros(3) == zeros(3)
assert ones(3, 4) == Matrix(3, 4, [1]*12)
i = Matrix([[1, 0], [0, 1]])
z = Matrix([[0, 0], [0, 0]])
for cls in classes:
m = cls.eye(2)
assert i == m # but m == i will fail if m is immutable
assert i == eye(2, cls=cls)
assert type(m) == cls
m = cls.zeros(2)
assert z == m
assert z == zeros(2, cls=cls)
assert type(m) == cls
def test_is_zero():
assert Matrix().is_zero_matrix
assert Matrix([[0, 0], [0, 0]]).is_zero_matrix
assert zeros(3, 4).is_zero_matrix
assert not eye(3).is_zero_matrix
assert Matrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert SparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert ImmutableSparseMatrix([[x, 0], [0, 0]]).is_zero_matrix == None
assert Matrix([[x, 1], [0, 0]]).is_zero_matrix == False
a = Symbol('a', nonzero=True)
assert Matrix([[a, 0], [0, 0]]).is_zero_matrix == False
def test_rotation_matrices():
# This tests the rotation matrices by rotating about an axis and back.
theta = pi/3
r3_plus = rot_axis3(theta)
r3_minus = rot_axis3(-theta)
r2_plus = rot_axis2(theta)
r2_minus = rot_axis2(-theta)
r1_plus = rot_axis1(theta)
r1_minus = rot_axis1(-theta)
assert r3_minus*r3_plus*eye(3) == eye(3)
assert r2_minus*r2_plus*eye(3) == eye(3)
assert r1_minus*r1_plus*eye(3) == eye(3)
# Check the correctness of the trace of the rotation matrix
assert r1_plus.trace() == 1 + 2*cos(theta)
assert r2_plus.trace() == 1 + 2*cos(theta)
assert r3_plus.trace() == 1 + 2*cos(theta)
# Check that a rotation with zero angle doesn't change anything.
assert rot_axis1(0) == eye(3)
assert rot_axis2(0) == eye(3)
assert rot_axis3(0) == eye(3)
def test_DeferredVector():
assert str(DeferredVector("vector")[4]) == "vector[4]"
assert sympify(DeferredVector("d")) == DeferredVector("d")
raises(IndexError, lambda: DeferredVector("d")[-1])
assert str(DeferredVector("d")) == "d"
assert repr(DeferredVector("test")) == "DeferredVector('test')"
def test_DeferredVector_not_iterable():
assert not iterable(DeferredVector('X'))
def test_DeferredVector_Matrix():
raises(TypeError, lambda: Matrix(DeferredVector("V")))
def test_GramSchmidt():
R = Rational
m1 = Matrix(1, 2, [1, 2])
m2 = Matrix(1, 2, [2, 3])
assert GramSchmidt([m1, m2]) == \
[Matrix(1, 2, [1, 2]), Matrix(1, 2, [R(2)/5, R(-1)/5])]
assert GramSchmidt([m1.T, m2.T]) == \
[Matrix(2, 1, [1, 2]), Matrix(2, 1, [R(2)/5, R(-1)/5])]
# from wikipedia
assert GramSchmidt([Matrix([3, 1]), Matrix([2, 2])], True) == [
Matrix([3*sqrt(10)/10, sqrt(10)/10]),
Matrix([-sqrt(10)/10, 3*sqrt(10)/10])]
def test_casoratian():
assert casoratian([1, 2, 3, 4], 1) == 0
assert casoratian([1, 2, 3, 4], 1, zero=False) == 0
def test_zero_dimension_multiply():
assert (Matrix()*zeros(0, 3)).shape == (0, 3)
assert zeros(3, 0)*zeros(0, 3) == zeros(3, 3)
assert zeros(0, 3)*zeros(3, 0) == Matrix()
def test_slice_issue_2884():
m = Matrix(2, 2, range(4))
assert m[1, :] == Matrix([[2, 3]])
assert m[-1, :] == Matrix([[2, 3]])
assert m[:, 1] == Matrix([[1, 3]]).T
assert m[:, -1] == Matrix([[1, 3]]).T
raises(IndexError, lambda: m[2, :])
raises(IndexError, lambda: m[2, 2])
def test_slice_issue_3401():
assert zeros(0, 3)[:, -1].shape == (0, 1)
assert zeros(3, 0)[0, :] == Matrix(1, 0, [])
def test_copyin():
s = zeros(3, 3)
s[3] = 1
assert s[:, 0] == Matrix([0, 1, 0])
assert s[3] == 1
assert s[3: 4] == [1]
s[1, 1] = 42
assert s[1, 1] == 42
assert s[1, 1:] == Matrix([[42, 0]])
s[1, 1:] = Matrix([[5, 6]])
assert s[1, :] == Matrix([[1, 5, 6]])
s[1, 1:] = [[42, 43]]
assert s[1, :] == Matrix([[1, 42, 43]])
s[0, 0] = 17
assert s[:, :1] == Matrix([17, 1, 0])
s[0, 0] = [1, 1, 1]
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = Matrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
s[0, 0] = SparseMatrix([1, 1, 1])
assert s[:, 0] == Matrix([1, 1, 1])
def test_invertible_check():
# sometimes a singular matrix will have a pivot vector shorter than
# the number of rows in a matrix...
assert Matrix([[1, 2], [1, 2]]).rref() == (Matrix([[1, 2], [0, 0]]), (0,))
raises(ValueError, lambda: Matrix([[1, 2], [1, 2]]).inv())
m = Matrix([
[-1, -1, 0],
[ x, 1, 1],
[ 1, x, -1],
])
assert len(m.rref()[1]) != m.rows
# in addition, unless simplify=True in the call to rref, the identity
# matrix will be returned even though m is not invertible
assert m.rref()[0] != eye(3)
assert m.rref(simplify=signsimp)[0] != eye(3)
raises(ValueError, lambda: m.inv(method="ADJ"))
raises(ValueError, lambda: m.inv(method="GE"))
raises(ValueError, lambda: m.inv(method="LU"))
def test_issue_3959():
x, y = symbols('x, y')
e = x*y
assert e.subs(x, Matrix([3, 5, 3])) == Matrix([3, 5, 3])*y
def test_issue_5964():
assert str(Matrix([[1, 2], [3, 4]])) == 'Matrix([[1, 2], [3, 4]])'
def test_issue_7604():
x, y = symbols(u"x y")
assert sstr(Matrix([[x, 2*y], [y**2, x + 3]])) == \
'Matrix([\n[ x, 2*y],\n[y**2, x + 3]])'
def test_is_Identity():
assert eye(3).is_Identity
assert eye(3).as_immutable().is_Identity
assert not zeros(3).is_Identity
assert not ones(3).is_Identity
# issue 6242
assert not Matrix([[1, 0, 0]]).is_Identity
# issue 8854
assert SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1}).is_Identity
assert not SparseMatrix(2,3, range(6)).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1}).is_Identity
assert not SparseMatrix(3,3, {(0,0):1, (1,1):1, (2,2):1, (0,1):2, (0,2):3}).is_Identity
def test_dot():
assert ones(1, 3).dot(ones(3, 1)) == 3
assert ones(1, 3).dot([1, 1, 1]) == 3
assert Matrix([1, 2, 3]).dot(Matrix([1, 2, 3])) == 14
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I])) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=False) == -5 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True) == 13 + I
assert Matrix([1, 2, 3*I]).dot(Matrix([I, 2, 3*I]), hermitian=True, conjugate_convention="physics") == 13 - I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="right") == 4 + 8*I
assert Matrix([1, 2, 3*I]).dot(Matrix([4, 5*I, 6]), hermitian=True, conjugate_convention="left") == 4 - 8*I
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), hermitian=False, conjugate_convention="left") == -5
assert Matrix([I, 2*I]).dot(Matrix([I, 2*I]), conjugate_convention="left") == 5
raises(ValueError, lambda: Matrix([1, 2]).dot(Matrix([3, 4]), hermitian=True, conjugate_convention="test"))
def test_dual():
B_x, B_y, B_z, E_x, E_y, E_z = symbols(
'B_x B_y B_z E_x E_y E_z', real=True)
F = Matrix((
( 0, E_x, E_y, E_z),
(-E_x, 0, B_z, -B_y),
(-E_y, -B_z, 0, B_x),
(-E_z, B_y, -B_x, 0)
))
Fd = Matrix((
( 0, -B_x, -B_y, -B_z),
(B_x, 0, E_z, -E_y),
(B_y, -E_z, 0, E_x),
(B_z, E_y, -E_x, 0)
))
assert F.dual().equals(Fd)
assert eye(3).dual().equals(zeros(3))
assert F.dual().dual().equals(-F)
def test_anti_symmetric():
assert Matrix([1, 2]).is_anti_symmetric() is False
m = Matrix(3, 3, [0, x**2 + 2*x + 1, y, -(x + 1)**2, 0, x*y, -y, -x*y, 0])
assert m.is_anti_symmetric() is True
assert m.is_anti_symmetric(simplify=False) is False
assert m.is_anti_symmetric(simplify=lambda x: x) is False
# tweak to fail
m[2, 1] = -m[2, 1]
assert m.is_anti_symmetric() is False
# untweak
m[2, 1] = -m[2, 1]
m = m.expand()
assert m.is_anti_symmetric(simplify=False) is True
m[0, 0] = 1
assert m.is_anti_symmetric() is False
def test_normalize_sort_diogonalization():
A = Matrix(((1, 2), (2, 1)))
P, Q = A.diagonalize(normalize=True)
assert P*P.T == P.T*P == eye(P.cols)
P, Q = A.diagonalize(normalize=True, sort=True)
assert P*P.T == P.T*P == eye(P.cols)
assert P*Q*P.inv() == A
def test_issue_5321():
raises(ValueError, lambda: Matrix([[1, 2, 3], Matrix(0, 1, [])]))
def test_issue_5320():
assert Matrix.hstack(eye(2), 2*eye(2)) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
assert Matrix.vstack(eye(2), 2*eye(2)) == Matrix([
[1, 0],
[0, 1],
[2, 0],
[0, 2]
])
cls = SparseMatrix
assert cls.hstack(cls(eye(2)), cls(2*eye(2))) == Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2]
])
def test_issue_11944():
A = Matrix([[1]])
AIm = sympify(A)
assert Matrix.hstack(AIm, A) == Matrix([[1, 1]])
assert Matrix.vstack(AIm, A) == Matrix([[1], [1]])
def test_cross():
a = [1, 2, 3]
b = [3, 4, 5]
col = Matrix([-2, 4, -2])
row = col.T
def test(M, ans):
assert ans == M
assert type(M) == cls
for cls in classes:
A = cls(a)
B = cls(b)
test(A.cross(B), col)
test(A.cross(B.T), col)
test(A.T.cross(B.T), row)
test(A.T.cross(B), row)
raises(ShapeError, lambda:
Matrix(1, 2, [1, 1]).cross(Matrix(1, 2, [1, 1])))
def test_hash():
for cls in classes[-2:]:
s = {cls.eye(1), cls.eye(1)}
assert len(s) == 1 and s.pop() == cls.eye(1)
# issue 3979
for cls in classes[:2]:
assert not isinstance(cls.eye(1), Hashable)
@XFAIL
def test_issue_3979():
# when this passes, delete this and change the [1:2]
# to [:2] in the test_hash above for issue 3979
cls = classes[0]
raises(AttributeError, lambda: hash(cls.eye(1)))
def test_adjoint():
dat = [[0, I], [1, 0]]
ans = Matrix([[0, 1], [-I, 0]])
for cls in classes:
assert ans == cls(dat).adjoint()
def test_simplify_immutable():
from sympy import simplify, sin, cos
assert simplify(ImmutableMatrix([[sin(x)**2 + cos(x)**2]])) == \
ImmutableMatrix([[1]])
def test_rank():
from sympy.abc import x
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.rank() == 2
n = Matrix(3, 3, range(1, 10))
assert n.rank() == 2
p = zeros(3)
assert p.rank() == 0
def test_issue_11434():
ax, ay, bx, by, cx, cy, dx, dy, ex, ey, t0, t1 = \
symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
M = Matrix([[ax, ay, ax*t0, ay*t0, 0],
[bx, by, bx*t0, by*t0, 0],
[cx, cy, cx*t0, cy*t0, 1],
[dx, dy, dx*t0, dy*t0, 1],
[ex, ey, 2*ex*t1 - ex*t0, 2*ey*t1 - ey*t0, 0]])
assert M.rank() == 4
def test_rank_regression_from_so():
# see:
# https://stackoverflow.com/questions/19072700/why-does-sympy-give-me-the-wrong-answer-when-i-row-reduce-a-symbolic-matrix
nu, lamb = symbols('nu, lambda')
A = Matrix([[-3*nu, 1, 0, 0],
[ 3*nu, -2*nu - 1, 2, 0],
[ 0, 2*nu, (-1*nu) - lamb - 2, 3],
[ 0, 0, nu + lamb, -3]])
expected_reduced = Matrix([[1, 0, 0, 1/(nu**2*(-lamb - nu))],
[0, 1, 0, 3/(nu*(-lamb - nu))],
[0, 0, 1, 3/(-lamb - nu)],
[0, 0, 0, 0]])
expected_pivots = (0, 1, 2)
reduced, pivots = A.rref()
assert simplify(expected_reduced - reduced) == zeros(*A.shape)
assert pivots == expected_pivots
def test_replace():
from sympy import symbols, Function, Matrix
F, G = symbols('F, G', cls=Function)
K = Matrix(2, 2, lambda i, j: G(i+j))
M = Matrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G)
assert N == K
def test_replace_map():
from sympy import symbols, Function, Matrix
F, G = symbols('F, G', cls=Function)
K = Matrix(2, 2, [(G(0), {F(0): G(0)}), (G(1), {F(1): G(1)}), (G(1), {F(1)\
: G(1)}), (G(2), {F(2): G(2)})])
M = Matrix(2, 2, lambda i, j: F(i+j))
N = M.replace(F, G, True)
assert N == K
def test_atoms():
m = Matrix([[1, 2], [x, 1 - 1/x]])
assert m.atoms() == {S.One,S(2),S.NegativeOne, x}
assert m.atoms(Symbol) == {x}
def test_pinv():
# Pseudoinverse of an invertible matrix is the inverse.
A1 = Matrix([[a, b], [c, d]])
assert simplify(A1.pinv(method="RD")) == simplify(A1.inv())
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[13, 104], [2212, 3], [-3, 5]]),
Matrix([[1, 7, 9], [11, 17, 19]]),
Matrix([a, b])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Pinv with diagonalization makes expression too complicated.
for A in As:
A_pinv = simplify(A.pinv(method="ED"))
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# XXX Computing pinv using diagonalization makes an expression that
# is too complicated to simplify.
# A1 = Matrix([[a, b], [c, d]])
# assert simplify(A1.pinv(method="ED")) == simplify(A1.inv())
# so this is tested numerically at a fixed random point
from sympy.core.numbers import comp
q = A1.pinv(method="ED")
w = A1.inv()
reps = {a: -73633, b: 11362, c: 55486, d: 62570}
assert all(
comp(i.n(), j.n())
for i, j in zip(q.subs(reps), w.subs(reps))
)
def test_pinv_solve():
# Fully determined system (unique result, identical to other solvers).
A = Matrix([[1, 5], [7, 9]])
B = Matrix([12, 13])
assert A.pinv_solve(B) == A.cholesky_solve(B)
assert A.pinv_solve(B) == A.LDLsolve(B)
assert A.pinv_solve(B) == Matrix([sympify('-43/26'), sympify('71/26')])
assert A * A.pinv() * B == B
# Fully determined, with two-dimensional B matrix.
B = Matrix([[12, 13, 14], [15, 16, 17]])
assert A.pinv_solve(B) == A.cholesky_solve(B)
assert A.pinv_solve(B) == A.LDLsolve(B)
assert A.pinv_solve(B) == Matrix([[-33, -37, -41], [69, 75, 81]]) / 26
assert A * A.pinv() * B == B
# Underdetermined system (infinite results).
A = Matrix([[1, 0, 1], [0, 1, 1]])
B = Matrix([5, 7])
solution = A.pinv_solve(B)
w = {}
for s in solution.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert solution == Matrix([[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 1],
[w['w0_0']/3 + w['w1_0']/3 - w['w2_0']/3 + 3],
[-w['w0_0']/3 - w['w1_0']/3 + w['w2_0']/3 + 4]])
assert A * A.pinv() * B == B
# Overdetermined system (least squares results).
A = Matrix([[1, 0], [0, 0], [0, 1]])
B = Matrix([3, 2, 1])
assert A.pinv_solve(B) == Matrix([3, 1])
# Proof the solution is not exact.
assert A * A.pinv() * B != B
def test_pinv_rank_deficient():
# Test the four properties of the pseudoinverse for various matrices.
As = [Matrix([[1, 1, 1], [2, 2, 2]]),
Matrix([[1, 0], [0, 0]]),
Matrix([[1, 2], [2, 4], [3, 6]])]
for A in As:
A_pinv = A.pinv(method="RD")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
# Test solving with rank-deficient matrices.
A = Matrix([[1, 0], [0, 0]])
# Exact, non-unique solution.
B = Matrix([3, 0])
solution = A.pinv_solve(B)
w1 = solution.atoms(Symbol).pop()
assert w1.name == 'w1_0'
assert solution == Matrix([3, w1])
assert A * A.pinv() * B == B
# Least squares, non-unique solution.
B = Matrix([3, 1])
solution = A.pinv_solve(B)
w1 = solution.atoms(Symbol).pop()
assert w1.name == 'w1_0'
assert solution == Matrix([3, w1])
assert A * A.pinv() * B != B
@XFAIL
def test_pinv_rank_deficient_when_diagonalization_fails():
# Test the four properties of the pseudoinverse for matrices when
# diagonalization of A.H*A fails.
As = [Matrix([
[61, 89, 55, 20, 71, 0],
[62, 96, 85, 85, 16, 0],
[69, 56, 17, 4, 54, 0],
[10, 54, 91, 41, 71, 0],
[ 7, 30, 10, 48, 90, 0],
[0,0,0,0,0,0]])]
for A in As:
A_pinv = A.pinv(method="ED")
AAp = A * A_pinv
ApA = A_pinv * A
assert simplify(AAp * A) == A
assert simplify(ApA * A_pinv) == A_pinv
assert AAp.H == AAp
assert ApA.H == ApA
def test_gauss_jordan_solve():
# Square, full rank, unique solution
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 10]])
b = Matrix([3, 6, 9])
sol, params = A.gauss_jordan_solve(b)
assert sol == Matrix([[-1], [2], [0]])
assert params == Matrix(0, 1, [])
# Square, full rank, unique solution, B has more columns than rows
A = eye(3)
B = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
sol, params = A.gauss_jordan_solve(B)
assert sol == B
assert params == Matrix(0, 4, [])
# Square, reduced rank, parametrized solution
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
b = Matrix([3, 6, 9])
sol, params, freevar = A.gauss_jordan_solve(b, freevar=True)
w = {}
for s in sol.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert sol == Matrix([[w['tau0'] - 1], [-2*w['tau0'] + 2], [w['tau0']]])
assert params == Matrix([[w['tau0']]])
assert freevar == [2]
# Square, reduced rank, parametrized solution, B has two columns
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
B = Matrix([[3, 4], [6, 8], [9, 12]])
sol, params, freevar = A.gauss_jordan_solve(B, freevar=True)
w = {}
for s in sol.atoms(Symbol):
# Extract dummy symbols used in the solution.
w[s.name] = s
assert sol == Matrix([[w['tau0'] - 1, w['tau1'] - Rational(4, 3)],
[-2*w['tau0'] + 2, -2*w['tau1'] + Rational(8, 3)],
[w['tau0'], w['tau1']],])
assert params == Matrix([[w['tau0'], w['tau1']]])
assert freevar == [2]
# Square, reduced rank, parametrized solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[-2*w['tau0'] - 3*w['tau1']],
[w['tau0']], [w['tau1']]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
# Square, reduced rank, parametrized solution
A = Matrix([[0, 0, 0], [0, 0, 0], [0, 0, 0]])
b = Matrix([0, 0, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]])
assert params == Matrix([[w['tau0']], [w['tau1']], [w['tau2']]])
# Square, reduced rank, no solution
A = Matrix([[1, 2, 3], [2, 4, 6], [3, 6, 9]])
b = Matrix([0, 0, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, tall, full rank, unique solution
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
b = Matrix([0, 0, 1, 0])
sol, params = A.gauss_jordan_solve(b)
assert sol == Matrix([[Rational(-1, 2)], [0], [Rational(1, 6)]])
assert params == Matrix(0, 1, [])
# Rectangular, tall, full rank, unique solution, B has less columns than rows
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [1, 2], [0, 0]])
sol, params = A.gauss_jordan_solve(B)
assert sol == Matrix([[Rational(-1, 2), Rational(-2, 2)], [0, 0], [Rational(1, 6), Rational(2, 6)]])
assert params == Matrix(0, 2, [])
# Rectangular, tall, full rank, no solution
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
b = Matrix([0, 0, 0, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, tall, full rank, no solution, B has two columns (2nd has no solution)
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [1, 0], [0, 1]])
raises(ValueError, lambda: A.gauss_jordan_solve(B))
# Rectangular, tall, full rank, no solution, B has two columns (1st has no solution)
A = Matrix([[1, 5, 3], [2, 1, 6], [1, 7, 9], [1, 4, 3]])
B = Matrix([[0,0], [0, 0], [0, 1], [1, 0]])
raises(ValueError, lambda: A.gauss_jordan_solve(B))
# Rectangular, tall, reduced rank, parametrized solution
A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]])
b = Matrix([0, 0, 0, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[-3*w['tau0'] + 5], [-1], [w['tau0']]])
assert params == Matrix([[w['tau0']]])
# Rectangular, tall, reduced rank, no solution
A = Matrix([[1, 5, 3], [2, 10, 6], [3, 15, 9], [1, 4, 3]])
b = Matrix([0, 0, 1, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Rectangular, wide, full rank, parametrized solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 1, 12]])
b = Matrix([1, 1, 1])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[2*w['tau0'] - 1], [-3*w['tau0'] + 1], [0],
[w['tau0']]])
assert params == Matrix([[w['tau0']]])
# Rectangular, wide, reduced rank, parametrized solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]])
b = Matrix([0, 1, 0])
sol, params = A.gauss_jordan_solve(b)
w = {}
for s in sol.atoms(Symbol):
w[s.name] = s
assert sol == Matrix([[w['tau0'] + 2*w['tau1'] + S.Half],
[-2*w['tau0'] - 3*w['tau1'] - Rational(1, 4)],
[w['tau0']], [w['tau1']]])
assert params == Matrix([[w['tau0']], [w['tau1']]])
# watch out for clashing symbols
x0, x1, x2, _x0 = symbols('_tau0 _tau1 _tau2 tau1')
M = Matrix([[0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, _x0]])
A = M[:, :-1]
b = M[:, -1:]
sol, params = A.gauss_jordan_solve(b)
assert params == Matrix(3, 1, [x0, x1, x2])
assert sol == Matrix(5, 1, [x1, 0, x0, _x0, x2])
# Rectangular, wide, reduced rank, no solution
A = Matrix([[1, 2, 3, 4], [5, 6, 7, 8], [2, 4, 6, 8]])
b = Matrix([1, 1, 1])
raises(ValueError, lambda: A.gauss_jordan_solve(b))
# Test for immutable matrix
A = ImmutableMatrix([[1, 0], [0, 1]])
B = ImmutableMatrix([1, 2])
sol, params = A.gauss_jordan_solve(B)
assert sol == ImmutableMatrix([1, 2])
assert params == ImmutableMatrix(0, 1, [])
assert sol.__class__ == ImmutableDenseMatrix
assert params.__class__ == ImmutableDenseMatrix
def test_solve():
A = Matrix([[1,2], [2,4]])
b = Matrix([[3], [4]])
raises(ValueError, lambda: A.solve(b)) #no solution
b = Matrix([[ 4], [8]])
raises(ValueError, lambda: A.solve(b)) #infinite solution
def test_issue_7201():
assert ones(0, 1) + ones(0, 1) == Matrix(0, 1, [])
assert ones(1, 0) + ones(1, 0) == Matrix(1, 0, [])
def test_free_symbols():
for M in ImmutableMatrix, ImmutableSparseMatrix, Matrix, SparseMatrix:
assert M([[x], [0]]).free_symbols == {x}
def test_from_ndarray():
"""See issue 7465."""
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
assert Matrix(array([1, 2, 3])) == Matrix([1, 2, 3])
assert Matrix(array([[1, 2, 3]])) == Matrix([[1, 2, 3]])
assert Matrix(array([[1, 2, 3], [4, 5, 6]])) == \
Matrix([[1, 2, 3], [4, 5, 6]])
assert Matrix(array([x, y, z])) == Matrix([x, y, z])
raises(NotImplementedError, lambda: Matrix(array([[
[1, 2], [3, 4]], [[5, 6], [7, 8]]])))
def test_17522_numpy():
from sympy.matrices.common import _matrixify
try:
from numpy import array, matrix
except ImportError:
skip('NumPy must be available to test indexing matrixified NumPy ndarrays and matrices')
m = _matrixify(array([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_mpmath():
from sympy.matrices.common import _matrixify
try:
from mpmath import matrix
except ImportError:
skip('mpmath must be available to test indexing matrixified mpmath matrices')
m = _matrixify(matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_17522_scipy():
from sympy.matrices.common import _matrixify
try:
from scipy.sparse import csr_matrix
except ImportError:
skip('SciPy must be available to test indexing matrixified SciPy sparse matrices')
m = _matrixify(csr_matrix([[1, 2], [3, 4]]))
assert m[3] == 4
assert list(m) == [1, 2, 3, 4]
def test_hermitian():
a = Matrix([[1, I], [-I, 1]])
assert a.is_hermitian
a[0, 0] = 2*I
assert a.is_hermitian is False
a[0, 0] = x
assert a.is_hermitian is None
a[0, 1] = a[1, 0]*I
assert a.is_hermitian is False
def test_doit():
a = Matrix([[Add(x,x, evaluate=False)]])
assert a[0] != 2*x
assert a.doit() == Matrix([[2*x]])
def test_issue_9457_9467_9876():
# for row_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.row_del(1)
assert M == Matrix([[1, 2, 3], [3, 4, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.row_del(-2)
assert N == Matrix([[1, 2, 3], [3, 4, 5]])
O = Matrix([[1, 2, 3], [5, 6, 7], [9, 10, 11]])
O.row_del(-1)
assert O == Matrix([[1, 2, 3], [5, 6, 7]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.row_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.row_del(-10))
# for col_del(index)
M = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
M.col_del(1)
assert M == Matrix([[1, 3], [2, 4], [3, 5]])
N = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
N.col_del(-2)
assert N == Matrix([[1, 3], [2, 4], [3, 5]])
P = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: P.col_del(10))
Q = Matrix([[1, 2, 3], [2, 3, 4], [3, 4, 5]])
raises(IndexError, lambda: Q.col_del(-10))
def test_issue_9422():
x, y = symbols('x y', commutative=False)
a, b = symbols('a b')
M = eye(2)
M1 = Matrix(2, 2, [x, y, y, z])
assert y*x*M != x*y*M
assert b*a*M == a*b*M
assert x*M1 != M1*x
assert a*M1 == M1*a
assert y*x*M == Matrix([[y*x, 0], [0, y*x]])
def test_issue_10770():
M = Matrix([])
a = ['col_insert', 'row_join'], Matrix([9, 6, 3])
b = ['row_insert', 'col_join'], a[1].T
c = ['row_insert', 'col_insert'], Matrix([[1, 2], [3, 4]])
for ops, m in (a, b, c):
for op in ops:
f = getattr(M, op)
new = f(m) if 'join' in op else f(42, m)
assert new == m and id(new) != id(m)
def test_issue_10658():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A.extract([0, 1, 2], [True, True, False]) == \
Matrix([[1, 2], [4, 5], [7, 8]])
assert A.extract([0, 1, 2], [True, False, False]) == Matrix([[1], [4], [7]])
assert A.extract([True, False, False], [0, 1, 2]) == Matrix([[1, 2, 3]])
assert A.extract([True, False, True], [0, 1, 2]) == \
Matrix([[1, 2, 3], [7, 8, 9]])
assert A.extract([0, 1, 2], [False, False, False]) == Matrix(3, 0, [])
assert A.extract([False, False, False], [0, 1, 2]) == Matrix(0, 3, [])
assert A.extract([True, False, True], [False, True, False]) == \
Matrix([[2], [8]])
def test_opportunistic_simplification():
# this test relates to issue #10718, #9480, #11434
# issue #9480
m = Matrix([[-5 + 5*sqrt(2), -5], [-5*sqrt(2)/2 + 5, -5*sqrt(2)/2]])
assert m.rank() == 1
# issue #10781
m = Matrix([[3+3*sqrt(3)*I, -9],[4,-3+3*sqrt(3)*I]])
assert simplify(m.rref()[0] - Matrix([[1, -9/(3 + 3*sqrt(3)*I)], [0, 0]])) == zeros(2, 2)
# issue #11434
ax,ay,bx,by,cx,cy,dx,dy,ex,ey,t0,t1 = symbols('a_x a_y b_x b_y c_x c_y d_x d_y e_x e_y t_0 t_1')
m = Matrix([[ax,ay,ax*t0,ay*t0,0],[bx,by,bx*t0,by*t0,0],[cx,cy,cx*t0,cy*t0,1],[dx,dy,dx*t0,dy*t0,1],[ex,ey,2*ex*t1-ex*t0,2*ey*t1-ey*t0,0]])
assert m.rank() == 4
def test_partial_pivoting():
# example from https://en.wikipedia.org/wiki/Pivot_element
# partial pivoting with back substitution gives a perfect result
# naive pivoting give an error ~1e-13, so anything better than
# 1e-15 is good
mm=Matrix([[0.003 ,59.14, 59.17],[ 5.291, -6.13,46.78]])
assert (mm.rref()[0] - Matrix([[1.0, 0, 10.0], [ 0, 1.0, 1.0]])).norm() < 1e-15
# issue #11549
m_mixed = Matrix([[6e-17, 1.0, 4],[ -1.0, 0, 8],[ 0, 0, 1]])
m_float = Matrix([[6e-17, 1.0, 4.],[ -1.0, 0., 8.],[ 0., 0., 1.]])
m_inv = Matrix([[ 0, -1.0, 8.0],[1.0, 6.0e-17, -4.0],[ 0, 0, 1]])
# this example is numerically unstable and involves a matrix with a norm >= 8,
# this comparing the difference of the results with 1e-15 is numerically sound.
assert (m_mixed.inv() - m_inv).norm() < 1e-15
assert (m_float.inv() - m_inv).norm() < 1e-15
def test_iszero_substitution():
""" When doing numerical computations, all elements that pass
the iszerofunc test should be set to numerically zero if they
aren't already. """
# Matrix from issue #9060
m = Matrix([[0.9, -0.1, -0.2, 0],[-0.8, 0.9, -0.4, 0],[-0.1, -0.8, 0.6, 0]])
m_rref = m.rref(iszerofunc=lambda x: abs(x)<6e-15)[0]
m_correct = Matrix([[1.0, 0, -0.301369863013699, 0],[ 0, 1.0, -0.712328767123288, 0],[ 0, 0, 0, 0]])
m_diff = m_rref - m_correct
assert m_diff.norm() < 1e-15
# if a zero-substitution wasn't made, this entry will be -1.11022302462516e-16
assert m_rref[2,2] == 0
def test_issue_11238():
from sympy import Point
xx = 8*tan(pi*Rational(13, 45))/(tan(pi*Rational(13, 45)) + sqrt(3))
yy = (-8*sqrt(3)*tan(pi*Rational(13, 45))**2 + 24*tan(pi*Rational(13, 45)))/(-3 + tan(pi*Rational(13, 45))**2)
p1 = Point(0, 0)
p2 = Point(1, -sqrt(3))
p0 = Point(xx,yy)
m1 = Matrix([p1 - simplify(p0), p2 - simplify(p0)])
m2 = Matrix([p1 - p0, p2 - p0])
m3 = Matrix([simplify(p1 - p0), simplify(p2 - p0)])
# This system has expressions which are zero and
# cannot be easily proved to be such, so without
# numerical testing, these assertions will fail.
Z = lambda x: abs(x.n()) < 1e-20
assert m1.rank(simplify=True, iszerofunc=Z) == 1
assert m2.rank(simplify=True, iszerofunc=Z) == 1
assert m3.rank(simplify=True, iszerofunc=Z) == 1
def test_as_real_imag():
m1 = Matrix(2,2,[1,2,3,4])
m2 = m1*S.ImaginaryUnit
m3 = m1 + m2
for kls in classes:
a,b = kls(m3).as_real_imag()
assert list(a) == list(m1)
assert list(b) == list(m1)
def test_deprecated():
# Maintain tests for deprecated functions. We must capture
# the deprecation warnings. When the deprecated functionality is
# removed, the corresponding tests should be removed.
m = Matrix(3, 3, [0, 1, 0, -4, 4, 0, -2, 1, 2])
P, Jcells = m.jordan_cells()
assert Jcells[1] == Matrix(1, 1, [2])
assert Jcells[0] == Matrix(2, 2, [2, 1, 0, 2])
with warns_deprecated_sympy():
assert Matrix([[1,2],[3,4]]).dot(Matrix([[1,3],[4,5]])) == [10, 19, 14, 28]
def test_issue_14489():
from sympy import Mod
A = Matrix([-1, 1, 2])
B = Matrix([10, 20, -15])
assert Mod(A, 3) == Matrix([2, 1, 2])
assert Mod(B, 4) == Matrix([2, 0, 1])
def test_issue_14943():
# Test that __array__ accepts the optional dtype argument
try:
from numpy import array
except ImportError:
skip('NumPy must be available to test creating matrices from ndarrays')
M = Matrix([[1,2], [3,4]])
assert array(M, dtype=float).dtype.name == 'float64'
def test_case_6913():
m = MatrixSymbol('m', 1, 1)
a = Symbol("a")
a = m[0, 0]>0
assert str(a) == 'm[0, 0] > 0'
def test_issue_15872():
A = Matrix([[1, 1, 1, 0], [-2, -1, 0, -1], [0, 0, -1, -1], [0, 0, 2, 1]])
B = A - Matrix.eye(4) * I
assert B.rank() == 3
assert (B**2).rank() == 2
assert (B**3).rank() == 2
def test_issue_11948():
A = MatrixSymbol('A', 3, 3)
a = Wild('a')
assert A.match(a) == {a: A}
def test_gramschmidt_conjugate_dot():
vecs = [Matrix([1, I]), Matrix([1, -I])]
assert Matrix.orthogonalize(*vecs) == \
[Matrix([[1], [I]]), Matrix([[1], [-I]])]
mat = Matrix([[1, I], [1, -I]])
Q, R = mat.QRdecomposition()
assert Q * Q.H == Matrix.eye(2)
def test_issue_17827():
C = Matrix([
[3, 4, -1, 1],
[9, 12, -3, 3],
[0, 2, 1, 3],
[2, 3, 0, -2],
[0, 3, 3, -5],
[8, 15, 0, 6]
])
# Tests for row/col within valid range
D = C.elementary_row_op('n<->m', row1=2, row2=5)
E = C.elementary_row_op('n->n+km', row1=5, row2=3, k=-4)
F = C.elementary_row_op('n->kn', row=5, k=2)
assert(D[5, :] == Matrix([[0, 2, 1, 3]]))
assert(E[5, :] == Matrix([[0, 3, 0, 14]]))
assert(F[5, :] == Matrix([[16, 30, 0, 12]]))
# Tests for row/col out of range
raises(ValueError, lambda: C.elementary_row_op('n<->m', row1=2, row2=6))
raises(ValueError, lambda: C.elementary_row_op('n->kn', row=7, k=2))
raises(ValueError, lambda: C.elementary_row_op('n->n+km', row1=-1, row2=5, k=2))
def test_issue_8207():
a = Matrix(MatrixSymbol('a', 3, 1))
b = Matrix(MatrixSymbol('b', 3, 1))
c = a.dot(b)
d = diff(c, a[0, 0])
e = diff(d, a[0, 0])
assert d == b[0, 0]
assert e == 0
def test_func():
from sympy.simplify.simplify import nthroot
A = Matrix([[1, 2],[0, 3]])
assert A.analytic_func(sin(x*t), x) == Matrix([[sin(t), sin(3*t) - sin(t)], [0, sin(3*t)]])
A = Matrix([[2, 1],[1, 2]])
assert (pi * A / 6).analytic_func(cos(x), x) == Matrix([[sqrt(3)/4, -sqrt(3)/4], [-sqrt(3)/4, sqrt(3)/4]])
raises(ValueError, lambda : zeros(5).analytic_func(log(x), x))
raises(ValueError, lambda : (A*x).analytic_func(log(x), x))
A = Matrix([[0, -1, -2, 3], [0, -1, -2, 3], [0, 1, 0, -1], [0, 0, -1, 1]])
assert A.analytic_func(exp(x), x) == A.exp()
raises(ValueError, lambda : A.analytic_func(sqrt(x), x))
A = Matrix([[41, 12],[12, 34]])
assert simplify(A.analytic_func(sqrt(x), x)**2) == A
A = Matrix([[3, -12, 4], [-1, 0, -2], [-1, 5, -1]])
assert simplify(A.analytic_func(nthroot(x, 3), x)**3) == A
A = Matrix([[2, 0, 0, 0], [1, 2, 0, 0], [0, 1, 3, 0], [0, 0, 1, 3]])
assert A.analytic_func(exp(x), x) == A.exp()
A = Matrix([[0, 2, 1, 6], [0, 0, 1, 2], [0, 0, 0, 3], [0, 0, 0, 0]])
assert A.analytic_func(exp(x*t), x) == expand(simplify((A*t).exp()))
|
3c992e038aea75dc11c5249321df844f53cf43aef40843a4d606423e730464d8 | from __future__ import print_function, division
from sympy import Number
from sympy.core import Mul, Basic, sympify, S
from sympy.functions import adjoint
from sympy.strategies import (rm_id, unpack, typed, flatten, exhaust,
do_one, new)
from sympy.matrices.matrices import MatrixBase
from .inverse import Inverse
from .matexpr import \
MatrixExpr, ShapeError, Identity, ZeroMatrix, GenericIdentity
from .matpow import MatPow
from .transpose import transpose
from .permutation import PermutationMatrix
# XXX: MatMul should perhaps not subclass directly from Mul
class MatMul(MatrixExpr, Mul):
"""
A product of matrix expressions
Examples
========
>>> from sympy import MatMul, MatrixSymbol
>>> A = MatrixSymbol('A', 5, 4)
>>> B = MatrixSymbol('B', 4, 3)
>>> C = MatrixSymbol('C', 3, 6)
>>> MatMul(A, B, C)
A*B*C
"""
is_MatMul = True
identity = GenericIdentity()
def __new__(cls, *args, **kwargs):
check = kwargs.get('check', True)
if not args:
return cls.identity
# This must be removed aggressively in the constructor to avoid
# TypeErrors from GenericIdentity().shape
args = filter(lambda i: cls.identity != i, args)
args = list(map(sympify, args))
obj = Basic.__new__(cls, *args)
factor, matrices = obj.as_coeff_matrices()
if check:
validate(*matrices)
if not matrices:
# Should it be
#
# return Basic.__neq__(cls, factor, GenericIdentity()) ?
return factor
return obj
@property
def shape(self):
matrices = [arg for arg in self.args if arg.is_Matrix]
return (matrices[0].rows, matrices[-1].cols)
def _entry(self, i, j, expand=True, **kwargs):
from sympy import Dummy, Sum, Mul, ImmutableMatrix, Integer
coeff, matrices = self.as_coeff_matrices()
if len(matrices) == 1: # situation like 2*X, matmul is just X
return coeff * matrices[0][i, j]
indices = [None]*(len(matrices) + 1)
ind_ranges = [None]*(len(matrices) - 1)
indices[0] = i
indices[-1] = j
def f():
counter = 1
while True:
yield Dummy("i_%i" % counter)
counter += 1
dummy_generator = kwargs.get("dummy_generator", f())
for i in range(1, len(matrices)):
indices[i] = next(dummy_generator)
for i, arg in enumerate(matrices[:-1]):
ind_ranges[i] = arg.shape[1] - 1
matrices = [arg._entry(indices[i], indices[i+1], dummy_generator=dummy_generator) for i, arg in enumerate(matrices)]
expr_in_sum = Mul.fromiter(matrices)
if any(v.has(ImmutableMatrix) for v in matrices):
expand = True
result = coeff*Sum(
expr_in_sum,
*zip(indices[1:-1], [0]*len(ind_ranges), ind_ranges)
)
# Don't waste time in result.doit() if the sum bounds are symbolic
if not any(isinstance(v, (Integer, int)) for v in ind_ranges):
expand = False
return result.doit() if expand else result
def as_coeff_matrices(self):
scalars = [x for x in self.args if not x.is_Matrix]
matrices = [x for x in self.args if x.is_Matrix]
coeff = Mul(*scalars)
if coeff.is_commutative is False:
raise NotImplementedError("noncommutative scalars in MatMul are not supported.")
return coeff, matrices
def as_coeff_mmul(self):
coeff, matrices = self.as_coeff_matrices()
return coeff, MatMul(*matrices)
def _eval_transpose(self):
"""Transposition of matrix multiplication.
Notes
=====
The following rules are applied.
Transposition for matrix multiplied with another matrix:
`\\left(A B\\right)^{T} = B^{T} A^{T}`
Transposition for matrix multiplied with scalar:
`\\left(c A\\right)^{T} = c A^{T}`
References
==========
.. [1] https://en.wikipedia.org/wiki/Transpose
"""
coeff, matrices = self.as_coeff_matrices()
return MatMul(
coeff, *[transpose(arg) for arg in matrices[::-1]]).doit()
def _eval_adjoint(self):
return MatMul(*[adjoint(arg) for arg in self.args[::-1]]).doit()
def _eval_trace(self):
factor, mmul = self.as_coeff_mmul()
if factor != 1:
from .trace import trace
return factor * trace(mmul.doit())
else:
raise NotImplementedError("Can't simplify any further")
def _eval_determinant(self):
from sympy.matrices.expressions.determinant import Determinant
factor, matrices = self.as_coeff_matrices()
square_matrices = only_squares(*matrices)
return factor**self.rows * Mul(*list(map(Determinant, square_matrices)))
def _eval_inverse(self):
try:
return MatMul(*[
arg.inverse() if isinstance(arg, MatrixExpr) else arg**-1
for arg in self.args[::-1]]).doit()
except ShapeError:
return Inverse(self)
def doit(self, **kwargs):
deep = kwargs.get('deep', True)
if deep:
args = [arg.doit(**kwargs) for arg in self.args]
else:
args = self.args
# treat scalar*MatrixSymbol or scalar*MatPow separately
expr = canonicalize(MatMul(*args))
return expr
# Needed for partial compatibility with Mul
def args_cnc(self, **kwargs):
coeff_c = [x for x in self.args if x.is_commutative]
coeff_nc = [x for x in self.args if not x.is_commutative]
return [coeff_c, coeff_nc]
def _eval_derivative_matrix_lines(self, x):
from .transpose import Transpose
with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
lines = []
for ind in with_x_ind:
left_args = self.args[:ind]
right_args = self.args[ind+1:]
if right_args:
right_mat = MatMul.fromiter(right_args)
else:
right_mat = Identity(self.shape[1])
if left_args:
left_rev = MatMul.fromiter([Transpose(i).doit() if i.is_Matrix else i for i in reversed(left_args)])
else:
left_rev = Identity(self.shape[0])
d = self.args[ind]._eval_derivative_matrix_lines(x)
for i in d:
i.append_first(left_rev)
i.append_second(right_mat)
lines.append(i)
return lines
def validate(*matrices):
""" Checks for valid shapes for args of MatMul """
for i in range(len(matrices)-1):
A, B = matrices[i:i+2]
if A.cols != B.rows:
raise ShapeError("Matrices %s and %s are not aligned"%(A, B))
# Rules
def newmul(*args):
if args[0] == 1:
args = args[1:]
return new(MatMul, *args)
def any_zeros(mul):
if any([arg.is_zero or (arg.is_Matrix and arg.is_ZeroMatrix)
for arg in mul.args]):
matrices = [arg for arg in mul.args if arg.is_Matrix]
return ZeroMatrix(matrices[0].rows, matrices[-1].cols)
return mul
def merge_explicit(matmul):
""" Merge explicit MatrixBase arguments
>>> from sympy import MatrixSymbol, eye, Matrix, MatMul, pprint
>>> from sympy.matrices.expressions.matmul import merge_explicit
>>> A = MatrixSymbol('A', 2, 2)
>>> B = Matrix([[1, 1], [1, 1]])
>>> C = Matrix([[1, 2], [3, 4]])
>>> X = MatMul(A, B, C)
>>> pprint(X)
[1 1] [1 2]
A*[ ]*[ ]
[1 1] [3 4]
>>> pprint(merge_explicit(X))
[4 6]
A*[ ]
[4 6]
>>> X = MatMul(B, A, C)
>>> pprint(X)
[1 1] [1 2]
[ ]*A*[ ]
[1 1] [3 4]
>>> pprint(merge_explicit(X))
[1 1] [1 2]
[ ]*A*[ ]
[1 1] [3 4]
"""
if not any(isinstance(arg, MatrixBase) for arg in matmul.args):
return matmul
newargs = []
last = matmul.args[0]
for arg in matmul.args[1:]:
if isinstance(arg, (MatrixBase, Number)) and isinstance(last, (MatrixBase, Number)):
last = last * arg
else:
newargs.append(last)
last = arg
newargs.append(last)
return MatMul(*newargs)
def remove_ids(mul):
""" Remove Identities from a MatMul
This is a modified version of sympy.strategies.rm_id.
This is necesssary because MatMul may contain both MatrixExprs and Exprs
as args.
See Also
========
sympy.strategies.rm_id
"""
# Separate Exprs from MatrixExprs in args
factor, mmul = mul.as_coeff_mmul()
# Apply standard rm_id for MatMuls
result = rm_id(lambda x: x.is_Identity is True)(mmul)
if result != mmul:
return newmul(factor, *result.args) # Recombine and return
else:
return mul
def factor_in_front(mul):
factor, matrices = mul.as_coeff_matrices()
if factor != 1:
return newmul(factor, *matrices)
return mul
def combine_powers(mul):
"""Combine consecutive powers with the same base into one
e.g. A*A**2 -> A**3
This also cancels out the possible matrix inverses using the
knowledgebase of ``Inverse``.
e.g. Y * X * X.I -> Y
"""
factor, args = mul.as_coeff_matrices()
new_args = [args[0]]
for B in args[1:]:
A = new_args[-1]
if A.is_square == False or B.is_square == False:
new_args.append(B)
continue
if isinstance(A, MatPow):
A_base, A_exp = A.args
else:
A_base, A_exp = A, S.One
if isinstance(B, MatPow):
B_base, B_exp = B.args
else:
B_base, B_exp = B, S.One
if A_base == B_base:
new_exp = A_exp + B_exp
new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
elif not isinstance(B_base, MatrixBase) and \
A_base == B_base.inverse():
new_exp = A_exp - B_exp
new_args[-1] = MatPow(A_base, new_exp).doit(deep=False)
else:
new_args.append(B)
return newmul(factor, *new_args)
def combine_permutations(mul):
"""Refine products of permutation matrices as the products of cycles.
"""
args = mul.args
l = len(args)
if l < 2:
return mul
result = [args[0]]
for i in range(1, l):
A = result[-1]
B = args[i]
if isinstance(A, PermutationMatrix) and \
isinstance(B, PermutationMatrix):
cycle_1 = A.args[0]
cycle_2 = B.args[0]
result[-1] = PermutationMatrix(cycle_1 * cycle_2)
else:
result.append(B)
return MatMul(*result)
rules = (
any_zeros, remove_ids, combine_powers, unpack, rm_id(lambda x: x == 1),
merge_explicit, factor_in_front, flatten, combine_permutations)
canonicalize = exhaust(typed({MatMul: do_one(*rules)}))
def only_squares(*matrices):
"""factor matrices only if they are square"""
if matrices[0].rows != matrices[-1].cols:
raise RuntimeError("Invalid matrices being multiplied")
out = []
start = 0
for i, M in enumerate(matrices):
if M.cols == matrices[start].rows:
out.append(MatMul(*matrices[start:i+1]).doit())
start = i+1
return out
from sympy.assumptions.ask import ask, Q
from sympy.assumptions.refine import handlers_dict
def refine_MatMul(expr, assumptions):
"""
>>> from sympy import MatrixSymbol, Q, assuming, refine
>>> X = MatrixSymbol('X', 2, 2)
>>> expr = X * X.T
>>> print(expr)
X*X.T
>>> with assuming(Q.orthogonal(X)):
... print(refine(expr))
I
"""
newargs = []
exprargs = []
for args in expr.args:
if args.is_Matrix:
exprargs.append(args)
else:
newargs.append(args)
last = exprargs[0]
for arg in exprargs[1:]:
if arg == last.T and ask(Q.orthogonal(arg), assumptions):
last = Identity(arg.shape[0])
elif arg == last.conjugate() and ask(Q.unitary(arg), assumptions):
last = Identity(arg.shape[0])
else:
newargs.append(last)
last = arg
newargs.append(last)
return MatMul(*newargs)
handlers_dict['MatMul'] = refine_MatMul
|
7153178a5a8a5a2837a1cd9dc52fdcfbfe190abd2c5e82cb6873378732adb885 | from __future__ import print_function, division
from .matexpr import MatrixExpr, ShapeError, Identity, ZeroMatrix
from sympy.core import S
from sympy.core.sympify import _sympify
from sympy.matrices import MatrixBase
from .permutation import PermutationMatrix
class MatPow(MatrixExpr):
def __new__(cls, base, exp):
base = _sympify(base)
if not base.is_Matrix:
raise TypeError("Function parameter should be a matrix")
exp = _sympify(exp)
return super(MatPow, cls).__new__(cls, base, exp)
@property
def base(self):
return self.args[0]
@property
def exp(self):
return self.args[1]
@property
def shape(self):
return self.base.shape
def _entry(self, i, j, **kwargs):
from sympy.matrices.expressions import MatMul
A = self.doit()
if isinstance(A, MatPow):
# We still have a MatPow, make an explicit MatMul out of it.
if not A.base.is_square:
raise ShapeError("Power of non-square matrix %s" % A.base)
elif A.exp.is_Integer and A.exp.is_positive:
A = MatMul(*[A.base for k in range(A.exp)])
#elif A.exp.is_Integer and self.exp.is_negative:
# Note: possible future improvement: in principle we can take
# positive powers of the inverse, but carefully avoid recursion,
# perhaps by adding `_entry` to Inverse (as it is our subclass).
# T = A.base.as_explicit().inverse()
# A = MatMul(*[T for k in range(-A.exp)])
else:
# Leave the expression unevaluated:
from sympy.matrices.expressions.matexpr import MatrixElement
return MatrixElement(self, i, j)
return A._entry(i, j)
def doit(self, **kwargs):
from sympy.matrices.expressions import Inverse
deep = kwargs.get('deep', True)
if deep:
args = [arg.doit(**kwargs) for arg in self.args]
else:
args = self.args
base, exp = args
# combine all powers, e.g. (A**2)**3 = A**6
while isinstance(base, MatPow):
exp = exp*base.args[1]
base = base.args[0]
if exp.is_zero and base.is_square:
if isinstance(base, MatrixBase):
return base.func(Identity(base.shape[0]))
return Identity(base.shape[0])
elif isinstance(base, ZeroMatrix) and exp.is_negative:
raise ValueError("Matrix determinant is 0, not invertible.")
elif isinstance(base, (Identity, ZeroMatrix)):
return base
elif isinstance(base, PermutationMatrix):
return PermutationMatrix(base.args[0] ** exp).doit()
elif isinstance(base, MatrixBase):
if exp is S.One:
return base
return base**exp
# Note: just evaluate cases we know, return unevaluated on others.
# E.g., MatrixSymbol('x', n, m) to power 0 is not an error.
elif exp is S.NegativeOne and base.is_square:
return Inverse(base).doit(**kwargs)
elif exp is S.One:
return base
return MatPow(base, exp)
def _eval_transpose(self):
base, exp = self.args
return MatPow(base.T, exp)
def _eval_derivative(self, x):
from sympy import Pow
return Pow._eval_derivative(self, x)
def _eval_derivative_matrix_lines(self, x):
from sympy.core.expr import ExprBuilder
from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct
from .matmul import MatMul
from .inverse import Inverse
exp = self.exp
if self.base.shape == (1, 1) and not exp.has(x):
lr = self.base._eval_derivative_matrix_lines(x)
for i in lr:
subexpr = ExprBuilder(
CodegenArrayContraction,
[
ExprBuilder(
CodegenArrayTensorProduct,
[
Identity(1),
i._lines[0],
exp*self.base**(exp-1),
i._lines[1],
Identity(1),
]
),
(0, 3, 4), (5, 7, 8)
],
validator=CodegenArrayContraction._validate
)
i._first_pointer_parent = subexpr.args[0].args
i._first_pointer_index = 0
i._second_pointer_parent = subexpr.args[0].args
i._second_pointer_index = 4
i._lines = [subexpr]
return lr
if (exp > 0) == True:
newexpr = MatMul.fromiter([self.base for i in range(exp)])
elif (exp == -1) == True:
return Inverse(self.base)._eval_derivative_matrix_lines(x)
elif (exp < 0) == True:
newexpr = MatMul.fromiter([Inverse(self.base) for i in range(-exp)])
elif (exp == 0) == True:
return self.doit()._eval_derivative_matrix_lines(x)
else:
raise NotImplementedError("cannot evaluate %s derived by %s" % (self, x))
return newexpr._eval_derivative_matrix_lines(x)
|
221e2565c45463070a639d1cb2efb8e7119048183123efa8a8e0148fbd5077b0 | from __future__ import print_function, division
from typing import Any, Callable
from sympy.core.logic import FuzzyBool
from functools import wraps, reduce
import collections
from sympy.core import S, Symbol, Tuple, Integer, Basic, Expr, Eq, Mul, Add
from sympy.core.decorators import call_highest_priority
from sympy.core.compatibility import SYMPY_INTS, default_sort_key
from sympy.core.sympify import SympifyError, _sympify
from sympy.functions import conjugate, adjoint
from sympy.functions.special.tensor_functions import KroneckerDelta
from sympy.matrices import ShapeError
from sympy.simplify import simplify
from sympy.utilities.misc import filldedent
def _sympifyit(arg, retval=None):
# This version of _sympifyit sympifies MutableMatrix objects
def deco(func):
@wraps(func)
def __sympifyit_wrapper(a, b):
try:
b = _sympify(b)
return func(a, b)
except SympifyError:
return retval
return __sympifyit_wrapper
return deco
class MatrixExpr(Expr):
"""Superclass for Matrix Expressions
MatrixExprs represent abstract matrices, linear transformations represented
within a particular basis.
Examples
========
>>> from sympy import MatrixSymbol
>>> A = MatrixSymbol('A', 3, 3)
>>> y = MatrixSymbol('y', 3, 1)
>>> x = (A.T*A).I * A * y
See Also
========
MatrixSymbol, MatAdd, MatMul, Transpose, Inverse
"""
# Should not be considered iterable by the
# sympy.core.compatibility.iterable function. Subclass that actually are
# iterable (i.e., explicit matrices) should set this to True.
_iterable = False
_op_priority = 11.0
is_Matrix = True # type: bool
is_MatrixExpr = True # type: bool
is_Identity = None # type: FuzzyBool
is_Inverse = False
is_Transpose = False
is_ZeroMatrix = False
is_MatAdd = False
is_MatMul = False
is_commutative = False
is_number = False
is_symbol = False
is_scalar = False
def __new__(cls, *args, **kwargs):
args = map(_sympify, args)
return Basic.__new__(cls, *args, **kwargs)
# The following is adapted from the core Expr object
def __neg__(self):
return MatMul(S.NegativeOne, self).doit()
def __abs__(self):
raise NotImplementedError
@_sympifyit('other', NotImplemented)
@call_highest_priority('__radd__')
def __add__(self, other):
return MatAdd(self, other, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__add__')
def __radd__(self, other):
return MatAdd(other, self, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rsub__')
def __sub__(self, other):
return MatAdd(self, -other, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__sub__')
def __rsub__(self, other):
return MatAdd(other, -self, check=True).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __mul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rmul__')
def __matmul__(self, other):
return MatMul(self, other).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__mul__')
def __rmatmul__(self, other):
return MatMul(other, self).doit()
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rpow__')
def __pow__(self, other):
if not self.is_square:
raise ShapeError("Power of non-square matrix %s" % self)
elif self.is_Identity:
return self
elif other == S.Zero:
return Identity(self.rows)
elif other == S.One:
return self
return MatPow(self, other).doit(deep=False)
@_sympifyit('other', NotImplemented)
@call_highest_priority('__pow__')
def __rpow__(self, other):
raise NotImplementedError("Matrix Power not defined")
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rdiv__')
def __div__(self, other):
return self * other**S.NegativeOne
@_sympifyit('other', NotImplemented)
@call_highest_priority('__div__')
def __rdiv__(self, other):
raise NotImplementedError()
#return MatMul(other, Pow(self, S.NegativeOne))
__truediv__ = __div__ # type: Callable[[MatrixExpr, Any], Any]
__rtruediv__ = __rdiv__ # type: Callable[[MatrixExpr, Any], Any]
@property
def rows(self):
return self.shape[0]
@property
def cols(self):
return self.shape[1]
@property
def is_square(self):
return self.rows == self.cols
def _eval_conjugate(self):
from sympy.matrices.expressions.adjoint import Adjoint
from sympy.matrices.expressions.transpose import Transpose
return Adjoint(Transpose(self))
def as_real_imag(self, deep=True, **hints):
from sympy import I
real = S.Half * (self + self._eval_conjugate())
im = (self - self._eval_conjugate())/(2*I)
return (real, im)
def _eval_inverse(self):
from sympy.matrices.expressions.inverse import Inverse
return Inverse(self)
def _eval_transpose(self):
return Transpose(self)
def _eval_power(self, exp):
return MatPow(self, exp)
def _eval_simplify(self, **kwargs):
if self.is_Atom:
return self
else:
return self.func(*[simplify(x, **kwargs) for x in self.args])
def _eval_adjoint(self):
from sympy.matrices.expressions.adjoint import Adjoint
return Adjoint(self)
def _eval_derivative_array(self, x):
if isinstance(x, MatrixExpr):
return _matrix_derivative(self, x)
else:
return self._eval_derivative(x)
def _eval_derivative_n_times(self, x, n):
return Basic._eval_derivative_n_times(self, x, n)
def _visit_eval_derivative_scalar(self, x):
# `x` is a scalar:
if x.has(self):
return _matrix_derivative(x, self)
else:
return ZeroMatrix(*self.shape)
def _visit_eval_derivative_array(self, x):
if x.has(self):
return _matrix_derivative(x, self)
else:
from sympy import Derivative
return Derivative(x, self)
def _accept_eval_derivative(self, s):
from sympy import MatrixBase, NDimArray
if isinstance(s, (MatrixBase, NDimArray, MatrixExpr)):
return s._visit_eval_derivative_array(self)
else:
return s._visit_eval_derivative_scalar(self)
@classmethod
def _check_dim(cls, dim):
"""Helper function to check invalid matrix dimensions"""
from sympy.solvers.solvers import check_assumptions
ok = check_assumptions(dim, integer=True, nonnegative=True)
if ok is False:
raise ValueError(
"The dimension specification {} should be "
"a nonnegative integer.".format(dim))
def _entry(self, i, j, **kwargs):
raise NotImplementedError(
"Indexing not implemented for %s" % self.__class__.__name__)
def adjoint(self):
return adjoint(self)
def as_coeff_Mul(self, rational=False):
"""Efficiently extract the coefficient of a product. """
return S.One, self
def conjugate(self):
return conjugate(self)
def transpose(self):
from sympy.matrices.expressions.transpose import transpose
return transpose(self)
@property
def T(self):
'''Matrix transposition'''
return self.transpose()
def inverse(self):
return self._eval_inverse()
def inv(self):
return self.inverse()
@property
def I(self):
return self.inverse()
def valid_index(self, i, j):
def is_valid(idx):
return isinstance(idx, (int, Integer, Symbol, Expr))
return (is_valid(i) and is_valid(j) and
(self.rows is None or
(0 <= i) != False and (i < self.rows) != False) and
(0 <= j) != False and (j < self.cols) != False)
def __getitem__(self, key):
if not isinstance(key, tuple) and isinstance(key, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, key, (0, None, 1))
if isinstance(key, tuple) and len(key) == 2:
i, j = key
if isinstance(i, slice) or isinstance(j, slice):
from sympy.matrices.expressions.slice import MatrixSlice
return MatrixSlice(self, i, j)
i, j = _sympify(i), _sympify(j)
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid indices (%s, %s)" % (i, j))
elif isinstance(key, (SYMPY_INTS, Integer)):
# row-wise decomposition of matrix
rows, cols = self.shape
# allow single indexing if number of columns is known
if not isinstance(cols, Integer):
raise IndexError(filldedent('''
Single indexing is only supported when the number
of columns is known.'''))
key = _sympify(key)
i = key // cols
j = key % cols
if self.valid_index(i, j) != False:
return self._entry(i, j)
else:
raise IndexError("Invalid index %s" % key)
elif isinstance(key, (Symbol, Expr)):
raise IndexError(filldedent('''
Only integers may be used when addressing the matrix
with a single index.'''))
raise IndexError("Invalid index, wanted %s[i,j]" % self)
def as_explicit(self):
"""
Returns a dense Matrix with elements represented explicitly
Returns an object of type ImmutableDenseMatrix.
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.as_explicit()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_mutable: returns mutable Matrix type
"""
from sympy.matrices.immutable import ImmutableDenseMatrix
return ImmutableDenseMatrix([[ self[i, j]
for j in range(self.cols)]
for i in range(self.rows)])
def as_mutable(self):
"""
Returns a dense, mutable matrix with elements represented explicitly
Examples
========
>>> from sympy import Identity
>>> I = Identity(3)
>>> I
I
>>> I.shape
(3, 3)
>>> I.as_mutable()
Matrix([
[1, 0, 0],
[0, 1, 0],
[0, 0, 1]])
See Also
========
as_explicit: returns ImmutableDenseMatrix
"""
return self.as_explicit().as_mutable()
def __array__(self):
from numpy import empty
a = empty(self.shape, dtype=object)
for i in range(self.rows):
for j in range(self.cols):
a[i, j] = self[i, j]
return a
def equals(self, other):
"""
Test elementwise equality between matrices, potentially of different
types
>>> from sympy import Identity, eye
>>> Identity(3).equals(eye(3))
True
"""
return self.as_explicit().equals(other)
def canonicalize(self):
return self
def as_coeff_mmul(self):
return 1, MatMul(self)
@staticmethod
def from_index_summation(expr, first_index=None, last_index=None, dimensions=None):
r"""
Parse expression of matrices with explicitly summed indices into a
matrix expression without indices, if possible.
This transformation expressed in mathematical notation:
`\sum_{j=0}^{N-1} A_{i,j} B_{j,k} \Longrightarrow \mathbf{A}\cdot \mathbf{B}`
Optional parameter ``first_index``: specify which free index to use as
the index starting the expression.
Examples
========
>>> from sympy import MatrixSymbol, MatrixExpr, Sum, Symbol
>>> from sympy.abc import i, j, k, l, N
>>> A = MatrixSymbol("A", N, N)
>>> B = MatrixSymbol("B", N, N)
>>> expr = Sum(A[i, j]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B
Transposition is detected:
>>> expr = Sum(A[j, i]*B[j, k], (j, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A.T*B
Detect the trace:
>>> expr = Sum(A[i, i], (i, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
Trace(A)
More complicated expressions:
>>> expr = Sum(A[i, j]*B[k, j]*A[l, k], (j, 0, N-1), (k, 0, N-1))
>>> MatrixExpr.from_index_summation(expr)
A*B.T*A.T
"""
from sympy import Sum, Mul, Add, MatMul, transpose, trace
from sympy.strategies.traverse import bottom_up
def remove_matelement(expr, i1, i2):
def repl_match(pos):
def func(x):
if not isinstance(x, MatrixElement):
return False
if x.args[pos] != i1:
return False
if x.args[3-pos] == 0:
if x.args[0].shape[2-pos] == 1:
return True
else:
return False
return True
return func
expr = expr.replace(repl_match(1),
lambda x: x.args[0])
expr = expr.replace(repl_match(2),
lambda x: transpose(x.args[0]))
# Make sure that all Mul are transformed to MatMul and that they
# are flattened:
rule = bottom_up(lambda x: reduce(lambda a, b: a*b, x.args) if isinstance(x, (Mul, MatMul)) else x)
return rule(expr)
def recurse_expr(expr, index_ranges={}):
if expr.is_Mul:
nonmatargs = []
pos_arg = []
pos_ind = []
dlinks = {}
link_ind = []
counter = 0
args_ind = []
for arg in expr.args:
retvals = recurse_expr(arg, index_ranges)
assert isinstance(retvals, list)
if isinstance(retvals, list):
for i in retvals:
args_ind.append(i)
else:
args_ind.append(retvals)
for arg_symbol, arg_indices in args_ind:
if arg_indices is None:
nonmatargs.append(arg_symbol)
continue
if isinstance(arg_symbol, MatrixElement):
arg_symbol = arg_symbol.args[0]
pos_arg.append(arg_symbol)
pos_ind.append(arg_indices)
link_ind.append([None]*len(arg_indices))
for i, ind in enumerate(arg_indices):
if ind in dlinks:
other_i = dlinks[ind]
link_ind[counter][i] = other_i
link_ind[other_i[0]][other_i[1]] = (counter, i)
dlinks[ind] = (counter, i)
counter += 1
counter2 = 0
lines = {}
while counter2 < len(link_ind):
for i, e in enumerate(link_ind):
if None in e:
line_start_index = (i, e.index(None))
break
cur_ind_pos = line_start_index
cur_line = []
index1 = pos_ind[cur_ind_pos[0]][cur_ind_pos[1]]
while True:
d, r = cur_ind_pos
if pos_arg[d] != 1:
if r % 2 == 1:
cur_line.append(transpose(pos_arg[d]))
else:
cur_line.append(pos_arg[d])
next_ind_pos = link_ind[d][1-r]
counter2 += 1
# Mark as visited, there will be no `None` anymore:
link_ind[d] = (-1, -1)
if next_ind_pos is None:
index2 = pos_ind[d][1-r]
lines[(index1, index2)] = cur_line
break
cur_ind_pos = next_ind_pos
lines = {k: MatMul.fromiter(v) if len(v) != 1 else v[0] for k, v in lines.items()}
return [(Mul.fromiter(nonmatargs), None)] + [
(MatrixElement(a, i, j), (i, j)) for (i, j), a in lines.items()
]
elif expr.is_Add:
res = [recurse_expr(i) for i in expr.args]
d = collections.defaultdict(list)
for res_addend in res:
scalar = 1
for elem, indices in res_addend:
if indices is None:
scalar = elem
continue
indices = tuple(sorted(indices, key=default_sort_key))
d[indices].append(scalar*remove_matelement(elem, *indices))
scalar = 1
return [(MatrixElement(Add.fromiter(v), *k), k) for k, v in d.items()]
elif isinstance(expr, KroneckerDelta):
i1, i2 = expr.args
if dimensions is not None:
identity = Identity(dimensions[0])
else:
identity = S.One
return [(MatrixElement(identity, i1, i2), (i1, i2))]
elif isinstance(expr, MatrixElement):
matrix_symbol, i1, i2 = expr.args
if i1 in index_ranges:
r1, r2 = index_ranges[i1]
if r1 != 0 or matrix_symbol.shape[0] != r2+1:
raise ValueError("index range mismatch: {0} vs. (0, {1})".format(
(r1, r2), matrix_symbol.shape[0]))
if i2 in index_ranges:
r1, r2 = index_ranges[i2]
if r1 != 0 or matrix_symbol.shape[1] != r2+1:
raise ValueError("index range mismatch: {0} vs. (0, {1})".format(
(r1, r2), matrix_symbol.shape[1]))
if (i1 == i2) and (i1 in index_ranges):
return [(trace(matrix_symbol), None)]
return [(MatrixElement(matrix_symbol, i1, i2), (i1, i2))]
elif isinstance(expr, Sum):
return recurse_expr(
expr.args[0],
index_ranges={i[0]: i[1:] for i in expr.args[1:]}
)
else:
return [(expr, None)]
retvals = recurse_expr(expr)
factors, indices = zip(*retvals)
retexpr = Mul.fromiter(factors)
if len(indices) == 0 or list(set(indices)) == [None]:
return retexpr
if first_index is None:
for i in indices:
if i is not None:
ind0 = i
break
return remove_matelement(retexpr, *ind0)
else:
return remove_matelement(retexpr, first_index, last_index)
def applyfunc(self, func):
from .applyfunc import ElementwiseApplyFunction
return ElementwiseApplyFunction(func, self)
def _eval_Eq(self, other):
if not isinstance(other, MatrixExpr):
return False
if self.shape != other.shape:
return False
if (self - other).is_ZeroMatrix:
return True
return Eq(self, other, evaluate=False)
def get_postprocessor(cls):
def _postprocessor(expr):
# To avoid circular imports, we can't have MatMul/MatAdd on the top level
mat_class = {Mul: MatMul, Add: MatAdd}[cls]
nonmatrices = []
matrices = []
for term in expr.args:
if isinstance(term, MatrixExpr):
matrices.append(term)
else:
nonmatrices.append(term)
if not matrices:
return cls._from_args(nonmatrices)
if nonmatrices:
if cls == Mul:
for i in range(len(matrices)):
if not matrices[i].is_MatrixExpr:
# If one of the matrices explicit, absorb the scalar into it
# (doit will combine all explicit matrices into one, so it
# doesn't matter which)
matrices[i] = matrices[i].__mul__(cls._from_args(nonmatrices))
nonmatrices = []
break
else:
# Maintain the ability to create Add(scalar, matrix) without
# raising an exception. That way different algorithms can
# replace matrix expressions with non-commutative symbols to
# manipulate them like non-commutative scalars.
return cls._from_args(nonmatrices + [mat_class(*matrices).doit(deep=False)])
if mat_class == MatAdd:
return mat_class(*matrices).doit(deep=False)
return mat_class(cls._from_args(nonmatrices), *matrices).doit(deep=False)
return _postprocessor
Basic._constructor_postprocessor_mapping[MatrixExpr] = {
"Mul": [get_postprocessor(Mul)],
"Add": [get_postprocessor(Add)],
}
def _matrix_derivative(expr, x):
from sympy import Derivative
lines = expr._eval_derivative_matrix_lines(x)
parts = [i.build() for i in lines]
from sympy.codegen.array_utils import recognize_matrix_expression
parts = [[recognize_matrix_expression(j).doit() for j in i] for i in parts]
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return (1, 1)
def get_rank(parts):
return sum([j not in (1, None) for i in parts for j in _get_shape(i)])
ranks = [get_rank(i) for i in parts]
rank = ranks[0]
def contract_one_dims(parts):
if len(parts) == 1:
return parts[0]
else:
p1, p2 = parts[:2]
if p2.is_Matrix:
p2 = p2.T
if p1 == Identity(1):
pbase = p2
elif p2 == Identity(1):
pbase = p1
else:
pbase = p1*p2
if len(parts) == 2:
return pbase
else: # len(parts) > 2
if pbase.is_Matrix:
raise ValueError("")
return pbase*Mul.fromiter(parts[2:])
if rank <= 2:
return Add.fromiter([contract_one_dims(i) for i in parts])
return Derivative(expr, x)
class MatrixElement(Expr):
parent = property(lambda self: self.args[0])
i = property(lambda self: self.args[1])
j = property(lambda self: self.args[2])
_diff_wrt = True
is_symbol = True
is_commutative = True
def __new__(cls, name, n, m):
n, m = map(_sympify, (n, m))
from sympy import MatrixBase
if isinstance(name, (MatrixBase,)):
if n.is_Integer and m.is_Integer:
return name[n, m]
if isinstance(name, str):
name = Symbol(name)
name = _sympify(name)
obj = Expr.__new__(cls, name, n, m)
return obj
def doit(self, **kwargs):
deep = kwargs.get('deep', True)
if deep:
args = [arg.doit(**kwargs) for arg in self.args]
else:
args = self.args
return args[0][args[1], args[2]]
@property
def indices(self):
return self.args[1:]
def _eval_derivative(self, v):
from sympy import Sum, symbols, Dummy
if not isinstance(v, MatrixElement):
from sympy import MatrixBase
if isinstance(self.parent, MatrixBase):
return self.parent.diff(v)[self.i, self.j]
return S.Zero
M = self.args[0]
m, n = self.parent.shape
if M == v.args[0]:
return KroneckerDelta(self.args[1], v.args[1], (0, m-1)) * \
KroneckerDelta(self.args[2], v.args[2], (0, n-1))
if isinstance(M, Inverse):
i, j = self.args[1:]
i1, i2 = symbols("z1, z2", cls=Dummy)
Y = M.args[0]
r1, r2 = Y.shape
return -Sum(M[i, i1]*Y[i1, i2].diff(v)*M[i2, j], (i1, 0, r1-1), (i2, 0, r2-1))
if self.has(v.args[0]):
return None
return S.Zero
class MatrixSymbol(MatrixExpr):
"""Symbolic representation of a Matrix object
Creates a SymPy Symbol to represent a Matrix. This matrix has a shape and
can be included in Matrix Expressions
Examples
========
>>> from sympy import MatrixSymbol, Identity
>>> A = MatrixSymbol('A', 3, 4) # A 3 by 4 Matrix
>>> B = MatrixSymbol('B', 4, 3) # A 4 by 3 Matrix
>>> A.shape
(3, 4)
>>> 2*A*B + Identity(3)
I + 2*A*B
"""
is_commutative = False
is_symbol = True
_diff_wrt = True
def __new__(cls, name, n, m):
n, m = _sympify(n), _sympify(m)
cls._check_dim(m)
cls._check_dim(n)
if isinstance(name, str):
name = Symbol(name)
obj = Basic.__new__(cls, name, n, m)
return obj
def _hashable_content(self):
return (self.name, self.shape)
@property
def shape(self):
return self.args[1:3]
@property
def name(self):
return self.args[0].name
def _eval_subs(self, old, new):
# only do substitutions in shape
shape = Tuple(*self.shape)._subs(old, new)
return MatrixSymbol(self.args[0], *shape)
def __call__(self, *args):
raise TypeError("%s object is not callable" % self.__class__)
def _entry(self, i, j, **kwargs):
return MatrixElement(self, i, j)
@property
def free_symbols(self):
return set((self,))
def doit(self, **hints):
if hints.get('deep', True):
return type(self)(self.args[0], self.args[1].doit(**hints),
self.args[2].doit(**hints))
else:
return self
def _eval_simplify(self, **kwargs):
return self
def _eval_derivative(self, x):
# x is a scalar:
return ZeroMatrix(self.shape[0], self.shape[1])
def _eval_derivative_matrix_lines(self, x):
if self != x:
first = ZeroMatrix(x.shape[0], self.shape[0]) if self.shape[0] != 1 else S.Zero
second = ZeroMatrix(x.shape[1], self.shape[1]) if self.shape[1] != 1 else S.Zero
return [_LeftRightArgs(
[first, second],
)]
else:
first = Identity(self.shape[0]) if self.shape[0] != 1 else S.One
second = Identity(self.shape[1]) if self.shape[1] != 1 else S.One
return [_LeftRightArgs(
[first, second],
)]
class Identity(MatrixExpr):
"""The Matrix Identity I - multiplicative identity
Examples
========
>>> from sympy.matrices import Identity, MatrixSymbol
>>> A = MatrixSymbol('A', 3, 5)
>>> I = Identity(3)
>>> I*A
A
"""
is_Identity = True
def __new__(cls, n):
n = _sympify(n)
cls._check_dim(n)
return super(Identity, cls).__new__(cls, n)
@property
def rows(self):
return self.args[0]
@property
def cols(self):
return self.args[0]
@property
def shape(self):
return (self.args[0], self.args[0])
@property
def is_square(self):
return True
def _eval_transpose(self):
return self
def _eval_trace(self):
return self.rows
def _eval_inverse(self):
return self
def conjugate(self):
return self
def _entry(self, i, j, **kwargs):
eq = Eq(i, j)
if eq is S.true:
return S.One
elif eq is S.false:
return S.Zero
return KroneckerDelta(i, j, (0, self.cols-1))
def _eval_determinant(self):
return S.One
class GenericIdentity(Identity):
"""
An identity matrix without a specified shape
This exists primarily so MatMul() with no arguments can return something
meaningful.
"""
def __new__(cls):
# super(Identity, cls) instead of super(GenericIdentity, cls) because
# Identity.__new__ doesn't have the same signature
return super(Identity, cls).__new__(cls)
@property
def rows(self):
raise TypeError("GenericIdentity does not have a specified shape")
@property
def cols(self):
raise TypeError("GenericIdentity does not have a specified shape")
@property
def shape(self):
raise TypeError("GenericIdentity does not have a specified shape")
# Avoid Matrix.__eq__ which might call .shape
def __eq__(self, other):
return isinstance(other, GenericIdentity)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return super(GenericIdentity, self).__hash__()
class ZeroMatrix(MatrixExpr):
"""The Matrix Zero 0 - additive identity
Examples
========
>>> from sympy import MatrixSymbol, ZeroMatrix
>>> A = MatrixSymbol('A', 3, 5)
>>> Z = ZeroMatrix(3, 5)
>>> A + Z
A
>>> Z*A.T
0
"""
is_ZeroMatrix = True
def __new__(cls, m, n):
m, n = _sympify(m), _sympify(n)
cls._check_dim(m)
cls._check_dim(n)
return super(ZeroMatrix, cls).__new__(cls, m, n)
@property
def shape(self):
return (self.args[0], self.args[1])
@_sympifyit('other', NotImplemented)
@call_highest_priority('__rpow__')
def __pow__(self, other):
if other != 1 and not self.is_square:
raise ShapeError("Power of non-square matrix %s" % self)
if other == 0:
return Identity(self.rows)
if other < 1:
raise ValueError("Matrix det == 0; not invertible.")
return self
def _eval_transpose(self):
return ZeroMatrix(self.cols, self.rows)
def _eval_trace(self):
return S.Zero
def _eval_determinant(self):
return S.Zero
def conjugate(self):
return self
def _entry(self, i, j, **kwargs):
return S.Zero
def __nonzero__(self):
return False
__bool__ = __nonzero__
class GenericZeroMatrix(ZeroMatrix):
"""
A zero matrix without a specified shape
This exists primarily so MatAdd() with no arguments can return something
meaningful.
"""
def __new__(cls):
# super(ZeroMatrix, cls) instead of super(GenericZeroMatrix, cls)
# because ZeroMatrix.__new__ doesn't have the same signature
return super(ZeroMatrix, cls).__new__(cls)
@property
def rows(self):
raise TypeError("GenericZeroMatrix does not have a specified shape")
@property
def cols(self):
raise TypeError("GenericZeroMatrix does not have a specified shape")
@property
def shape(self):
raise TypeError("GenericZeroMatrix does not have a specified shape")
# Avoid Matrix.__eq__ which might call .shape
def __eq__(self, other):
return isinstance(other, GenericZeroMatrix)
def __ne__(self, other):
return not (self == other)
def __hash__(self):
return super(GenericZeroMatrix, self).__hash__()
class OneMatrix(MatrixExpr):
"""
Matrix whose all entries are ones.
"""
def __new__(cls, m, n):
m, n = _sympify(m), _sympify(n)
cls._check_dim(m)
cls._check_dim(n)
obj = super(OneMatrix, cls).__new__(cls, m, n)
return obj
@property
def shape(self):
return self._args
def as_explicit(self):
from sympy import ImmutableDenseMatrix
return ImmutableDenseMatrix.ones(*self.shape)
def _eval_transpose(self):
return OneMatrix(self.cols, self.rows)
def _eval_trace(self):
return S.One*self.rows
def _eval_determinant(self):
condition = Eq(self.shape[0], 1) & Eq(self.shape[1], 1)
if condition == True:
return S.One
elif condition == False:
return S.Zero
else:
from sympy import Determinant
return Determinant(self)
def conjugate(self):
return self
def _entry(self, i, j, **kwargs):
return S.One
def matrix_symbols(expr):
return [sym for sym in expr.free_symbols if sym.is_Matrix]
class _LeftRightArgs(object):
r"""
Helper class to compute matrix derivatives.
The logic: when an expression is derived by a matrix `X_{mn}`, two lines of
matrix multiplications are created: the one contracted to `m` (first line),
and the one contracted to `n` (second line).
Transposition flips the side by which new matrices are connected to the
lines.
The trace connects the end of the two lines.
"""
def __init__(self, lines, higher=S.One):
self._lines = [i for i in lines]
self._first_pointer_parent = self._lines
self._first_pointer_index = 0
self._first_line_index = 0
self._second_pointer_parent = self._lines
self._second_pointer_index = 1
self._second_line_index = 1
self.higher = higher
@property
def first_pointer(self):
return self._first_pointer_parent[self._first_pointer_index]
@first_pointer.setter
def first_pointer(self, value):
self._first_pointer_parent[self._first_pointer_index] = value
@property
def second_pointer(self):
return self._second_pointer_parent[self._second_pointer_index]
@second_pointer.setter
def second_pointer(self, value):
self._second_pointer_parent[self._second_pointer_index] = value
def __repr__(self):
built = [self._build(i) for i in self._lines]
return "_LeftRightArgs(lines=%s, higher=%s)" % (
built,
self.higher,
)
def transpose(self):
self._first_pointer_parent, self._second_pointer_parent = self._second_pointer_parent, self._first_pointer_parent
self._first_pointer_index, self._second_pointer_index = self._second_pointer_index, self._first_pointer_index
self._first_line_index, self._second_line_index = self._second_line_index, self._first_line_index
return self
@staticmethod
def _build(expr):
from sympy.core.expr import ExprBuilder
if isinstance(expr, ExprBuilder):
return expr.build()
if isinstance(expr, list):
if len(expr) == 1:
return expr[0]
else:
return expr[0](*[_LeftRightArgs._build(i) for i in expr[1]])
else:
return expr
def build(self):
data = [self._build(i) for i in self._lines]
if self.higher != 1:
data += [self._build(self.higher)]
data = [i.doit() for i in data]
return data
def matrix_form(self):
if self.first != 1 and self.higher != 1:
raise ValueError("higher dimensional array cannot be represented")
def _get_shape(elem):
if isinstance(elem, MatrixExpr):
return elem.shape
return (None, None)
if _get_shape(self.first)[1] != _get_shape(self.second)[1]:
# Remove one-dimensional identity matrices:
# (this is needed by `a.diff(a)` where `a` is a vector)
if _get_shape(self.second) == (1, 1):
return self.first*self.second[0, 0]
if _get_shape(self.first) == (1, 1):
return self.first[1, 1]*self.second.T
raise ValueError("incompatible shapes")
if self.first != 1:
return self.first*self.second.T
else:
return self.higher
def rank(self):
"""
Number of dimensions different from trivial (warning: not related to
matrix rank).
"""
rank = 0
if self.first != 1:
rank += sum([i != 1 for i in self.first.shape])
if self.second != 1:
rank += sum([i != 1 for i in self.second.shape])
if self.higher != 1:
rank += 2
return rank
def _multiply_pointer(self, pointer, other):
from sympy.core.expr import ExprBuilder
from sympy.codegen.array_utils import CodegenArrayContraction, CodegenArrayTensorProduct
subexpr = ExprBuilder(
CodegenArrayContraction,
[
ExprBuilder(
CodegenArrayTensorProduct,
[
pointer,
other
]
),
(1, 2)
],
validator=CodegenArrayContraction._validate
)
return subexpr
def append_first(self, other):
self.first_pointer *= other
def append_second(self, other):
self.second_pointer *= other
def __hash__(self):
return hash((self.first, self.second))
def __eq__(self, other):
if not isinstance(other, _LeftRightArgs):
return False
return (self.first == other.first) and (self.second == other.second)
def _make_matrix(x):
from sympy import ImmutableDenseMatrix
if isinstance(x, MatrixExpr):
return x
return ImmutableDenseMatrix([[x]])
from .matmul import MatMul
from .matadd import MatAdd
from .matpow import MatPow
from .transpose import Transpose
from .inverse import Inverse
|
91e3a0b808f7df51989d66dcea069d1828cc2c22ca82416df1805ca5e75437c1 | from __future__ import print_function, division
from sympy.core.sympify import _sympify
from sympy.matrices.expressions import MatrixExpr
from sympy import S, I, sqrt, exp
class DFT(MatrixExpr):
""" Discrete Fourier Transform """
def __new__(cls, n):
n = _sympify(n)
cls._check_dim(n)
obj = super(DFT, cls).__new__(cls, n)
return obj
n = property(lambda self: self.args[0]) # type: ignore
shape = property(lambda self: (self.n, self.n))
def _entry(self, i, j, **kwargs):
w = exp(-2*S.Pi*I/self.n)
return w**(i*j) / sqrt(self.n)
def _eval_inverse(self):
return IDFT(self.n)
class IDFT(DFT):
""" Inverse Discrete Fourier Transform """
def _entry(self, i, j, **kwargs):
w = exp(-2*S.Pi*I/self.n)
return w**(-i*j) / sqrt(self.n)
def _eval_inverse(self):
return DFT(self.n)
|
87bda7668229436416f1c67ec435d76c3176062993a031a2ebe1522c1842bd54 | """Implementation of the Kronecker product"""
from __future__ import division, print_function
from sympy.core import Mul, prod, sympify
from sympy.functions import adjoint
from sympy.matrices.expressions.matexpr import MatrixExpr, ShapeError, Identity
from sympy.matrices.expressions.transpose import transpose
from sympy.matrices.matrices import MatrixBase
from sympy.strategies import (
canon, condition, distribute, do_one, exhaust, flatten, typed, unpack)
from sympy.strategies.traverse import bottom_up
from sympy.utilities import sift
from .matadd import MatAdd
from .matmul import MatMul
from .matpow import MatPow
def kronecker_product(*matrices):
"""
The Kronecker product of two or more arguments.
This computes the explicit Kronecker product for subclasses of
``MatrixBase`` i.e. explicit matrices. Otherwise, a symbolic
``KroneckerProduct`` object is returned.
Examples
========
For ``MatrixSymbol`` arguments a ``KroneckerProduct`` object is returned.
Elements of this matrix can be obtained by indexing, or for MatrixSymbols
with known dimension the explicit matrix can be obtained with
``.as_explicit()``
>>> from sympy.matrices import kronecker_product, MatrixSymbol
>>> A = MatrixSymbol('A', 2, 2)
>>> B = MatrixSymbol('B', 2, 2)
>>> kronecker_product(A)
A
>>> kronecker_product(A, B)
KroneckerProduct(A, B)
>>> kronecker_product(A, B)[0, 1]
A[0, 0]*B[0, 1]
>>> kronecker_product(A, B).as_explicit()
Matrix([
[A[0, 0]*B[0, 0], A[0, 0]*B[0, 1], A[0, 1]*B[0, 0], A[0, 1]*B[0, 1]],
[A[0, 0]*B[1, 0], A[0, 0]*B[1, 1], A[0, 1]*B[1, 0], A[0, 1]*B[1, 1]],
[A[1, 0]*B[0, 0], A[1, 0]*B[0, 1], A[1, 1]*B[0, 0], A[1, 1]*B[0, 1]],
[A[1, 0]*B[1, 0], A[1, 0]*B[1, 1], A[1, 1]*B[1, 0], A[1, 1]*B[1, 1]]])
For explicit matrices the Kronecker product is returned as a Matrix
>>> from sympy.matrices import Matrix, kronecker_product
>>> sigma_x = Matrix([
... [0, 1],
... [1, 0]])
...
>>> Isigma_y = Matrix([
... [0, 1],
... [-1, 0]])
...
>>> kronecker_product(sigma_x, Isigma_y)
Matrix([
[ 0, 0, 0, 1],
[ 0, 0, -1, 0],
[ 0, 1, 0, 0],
[-1, 0, 0, 0]])
See Also
========
KroneckerProduct
"""
if not matrices:
raise TypeError("Empty Kronecker product is undefined")
validate(*matrices)
if len(matrices) == 1:
return matrices[0]
else:
return KroneckerProduct(*matrices).doit()
class KroneckerProduct(MatrixExpr):
"""
The Kronecker product of two or more arguments.
The Kronecker product is a non-commutative product of matrices.
Given two matrices of dimension (m, n) and (s, t) it produces a matrix
of dimension (m s, n t).
This is a symbolic object that simply stores its argument without
evaluating it. To actually compute the product, use the function
``kronecker_product()`` or call the the ``.doit()`` or ``.as_explicit()``
methods.
>>> from sympy.matrices import KroneckerProduct, MatrixSymbol
>>> A = MatrixSymbol('A', 5, 5)
>>> B = MatrixSymbol('B', 5, 5)
>>> isinstance(KroneckerProduct(A, B), KroneckerProduct)
True
"""
is_KroneckerProduct = True
def __new__(cls, *args, **kwargs):
args = list(map(sympify, args))
if all(a.is_Identity for a in args):
ret = Identity(prod(a.rows for a in args))
if all(isinstance(a, MatrixBase) for a in args):
return ret.as_explicit()
else:
return ret
check = kwargs.get('check', True)
if check:
validate(*args)
return super(KroneckerProduct, cls).__new__(cls, *args)
@property
def shape(self):
rows, cols = self.args[0].shape
for mat in self.args[1:]:
rows *= mat.rows
cols *= mat.cols
return (rows, cols)
def _entry(self, i, j, **kwargs):
result = 1
for mat in reversed(self.args):
i, m = divmod(i, mat.rows)
j, n = divmod(j, mat.cols)
result *= mat[m, n]
return result
def _eval_adjoint(self):
return KroneckerProduct(*list(map(adjoint, self.args))).doit()
def _eval_conjugate(self):
return KroneckerProduct(*[a.conjugate() for a in self.args]).doit()
def _eval_transpose(self):
return KroneckerProduct(*list(map(transpose, self.args))).doit()
def _eval_trace(self):
from .trace import trace
return prod(trace(a) for a in self.args)
def _eval_determinant(self):
from .determinant import det, Determinant
if not all(a.is_square for a in self.args):
return Determinant(self)
m = self.rows
return prod(det(a)**(m/a.rows) for a in self.args)
def _eval_inverse(self):
try:
return KroneckerProduct(*[a.inverse() for a in self.args])
except ShapeError:
from sympy.matrices.expressions.inverse import Inverse
return Inverse(self)
def structurally_equal(self, other):
'''Determine whether two matrices have the same Kronecker product structure
Examples
========
>>> from sympy import KroneckerProduct, MatrixSymbol, symbols
>>> m, n = symbols(r'm, n', integer=True)
>>> A = MatrixSymbol('A', m, m)
>>> B = MatrixSymbol('B', n, n)
>>> C = MatrixSymbol('C', m, m)
>>> D = MatrixSymbol('D', n, n)
>>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(C, D))
True
>>> KroneckerProduct(A, B).structurally_equal(KroneckerProduct(D, C))
False
>>> KroneckerProduct(A, B).structurally_equal(C)
False
'''
# Inspired by BlockMatrix
return (isinstance(other, KroneckerProduct)
and self.shape == other.shape
and len(self.args) == len(other.args)
and all(a.shape == b.shape for (a, b) in zip(self.args, other.args)))
def has_matching_shape(self, other):
'''Determine whether two matrices have the appropriate structure to bring matrix
multiplication inside the KroneckerProdut
Examples
========
>>> from sympy import KroneckerProduct, MatrixSymbol, symbols
>>> m, n = symbols(r'm, n', integer=True)
>>> A = MatrixSymbol('A', m, n)
>>> B = MatrixSymbol('B', n, m)
>>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(B, A))
True
>>> KroneckerProduct(A, B).has_matching_shape(KroneckerProduct(A, B))
False
>>> KroneckerProduct(A, B).has_matching_shape(A)
False
'''
return (isinstance(other, KroneckerProduct)
and self.cols == other.rows
and len(self.args) == len(other.args)
and all(a.cols == b.rows for (a, b) in zip(self.args, other.args)))
def _eval_expand_kroneckerproduct(self, **hints):
return flatten(canon(typed({KroneckerProduct: distribute(KroneckerProduct, MatAdd)}))(self))
def _kronecker_add(self, other):
if self.structurally_equal(other):
return self.__class__(*[a + b for (a, b) in zip(self.args, other.args)])
else:
return self + other
def _kronecker_mul(self, other):
if self.has_matching_shape(other):
return self.__class__(*[a*b for (a, b) in zip(self.args, other.args)])
else:
return self * other
def doit(self, **kwargs):
deep = kwargs.get('deep', True)
if deep:
args = [arg.doit(**kwargs) for arg in self.args]
else:
args = self.args
return canonicalize(KroneckerProduct(*args))
def validate(*args):
if not all(arg.is_Matrix for arg in args):
raise TypeError("Mix of Matrix and Scalar symbols")
# rules
def extract_commutative(kron):
c_part = []
nc_part = []
for arg in kron.args:
c, nc = arg.args_cnc()
c_part.extend(c)
nc_part.append(Mul._from_args(nc))
c_part = Mul(*c_part)
if c_part != 1:
return c_part*KroneckerProduct(*nc_part)
return kron
def matrix_kronecker_product(*matrices):
"""Compute the Kronecker product of a sequence of SymPy Matrices.
This is the standard Kronecker product of matrices [1].
Parameters
==========
matrices : tuple of MatrixBase instances
The matrices to take the Kronecker product of.
Returns
=======
matrix : MatrixBase
The Kronecker product matrix.
Examples
========
>>> from sympy import Matrix
>>> from sympy.matrices.expressions.kronecker import (
... matrix_kronecker_product)
>>> m1 = Matrix([[1,2],[3,4]])
>>> m2 = Matrix([[1,0],[0,1]])
>>> matrix_kronecker_product(m1, m2)
Matrix([
[1, 0, 2, 0],
[0, 1, 0, 2],
[3, 0, 4, 0],
[0, 3, 0, 4]])
>>> matrix_kronecker_product(m2, m1)
Matrix([
[1, 2, 0, 0],
[3, 4, 0, 0],
[0, 0, 1, 2],
[0, 0, 3, 4]])
References
==========
[1] https://en.wikipedia.org/wiki/Kronecker_product
"""
# Make sure we have a sequence of Matrices
if not all(isinstance(m, MatrixBase) for m in matrices):
raise TypeError(
'Sequence of Matrices expected, got: %s' % repr(matrices)
)
# Pull out the first element in the product.
matrix_expansion = matrices[-1]
# Do the kronecker product working from right to left.
for mat in reversed(matrices[:-1]):
rows = mat.rows
cols = mat.cols
# Go through each row appending kronecker product to.
# running matrix_expansion.
for i in range(rows):
start = matrix_expansion*mat[i*cols]
# Go through each column joining each item
for j in range(cols - 1):
start = start.row_join(
matrix_expansion*mat[i*cols + j + 1]
)
# If this is the first element, make it the start of the
# new row.
if i == 0:
next = start
else:
next = next.col_join(start)
matrix_expansion = next
MatrixClass = max(matrices, key=lambda M: M._class_priority).__class__
if isinstance(matrix_expansion, MatrixClass):
return matrix_expansion
else:
return MatrixClass(matrix_expansion)
def explicit_kronecker_product(kron):
# Make sure we have a sequence of Matrices
if not all(isinstance(m, MatrixBase) for m in kron.args):
return kron
return matrix_kronecker_product(*kron.args)
rules = (unpack,
explicit_kronecker_product,
flatten,
extract_commutative)
canonicalize = exhaust(condition(lambda x: isinstance(x, KroneckerProduct),
do_one(*rules)))
def _kronecker_dims_key(expr):
if isinstance(expr, KroneckerProduct):
return tuple(a.shape for a in expr.args)
else:
return (0,)
def kronecker_mat_add(expr):
from functools import reduce
args = sift(expr.args, _kronecker_dims_key)
nonkrons = args.pop((0,), None)
if not args:
return expr
krons = [reduce(lambda x, y: x._kronecker_add(y), group)
for group in args.values()]
if not nonkrons:
return MatAdd(*krons)
else:
return MatAdd(*krons) + nonkrons
def kronecker_mat_mul(expr):
# modified from block matrix code
factor, matrices = expr.as_coeff_matrices()
i = 0
while i < len(matrices) - 1:
A, B = matrices[i:i+2]
if isinstance(A, KroneckerProduct) and isinstance(B, KroneckerProduct):
matrices[i] = A._kronecker_mul(B)
matrices.pop(i+1)
else:
i += 1
return factor*MatMul(*matrices)
def kronecker_mat_pow(expr):
if isinstance(expr.base, KroneckerProduct):
return KroneckerProduct(*[MatPow(a, expr.exp) for a in expr.base.args])
else:
return expr
def combine_kronecker(expr):
"""Combine KronekeckerProduct with expression.
If possible write operations on KroneckerProducts of compatible shapes
as a single KroneckerProduct.
Examples
========
>>> from sympy.matrices.expressions import MatrixSymbol, KroneckerProduct, combine_kronecker
>>> from sympy import symbols
>>> m, n = symbols(r'm, n', integer=True)
>>> A = MatrixSymbol('A', m, n)
>>> B = MatrixSymbol('B', n, m)
>>> combine_kronecker(KroneckerProduct(A, B)*KroneckerProduct(B, A))
KroneckerProduct(A*B, B*A)
>>> combine_kronecker(KroneckerProduct(A, B)+KroneckerProduct(B.T, A.T))
KroneckerProduct(A + B.T, B + A.T)
>>> combine_kronecker(KroneckerProduct(A, B)**m)
KroneckerProduct(A**m, B**m)
"""
def haskron(expr):
return isinstance(expr, MatrixExpr) and expr.has(KroneckerProduct)
rule = exhaust(
bottom_up(exhaust(condition(haskron, typed(
{MatAdd: kronecker_mat_add,
MatMul: kronecker_mat_mul,
MatPow: kronecker_mat_pow})))))
result = rule(expr)
doit = getattr(result, 'doit', None)
if doit is not None:
return doit()
else:
return result
|
0a34d849c261dc8af266597cc261571ec2ad6d306d29736cb6f2f95efea64d7c | from __future__ import print_function, division
from sympy.core import Mul, sympify
from sympy.matrices.expressions.matexpr import (
MatrixExpr, ShapeError, OneMatrix, ZeroMatrix
)
from sympy.strategies import (
unpack, flatten, condition, exhaust, rm_id, sort
)
def hadamard_product(*matrices):
"""
Return the elementwise (aka Hadamard) product of matrices.
Examples
========
>>> from sympy.matrices import hadamard_product, MatrixSymbol
>>> A = MatrixSymbol('A', 2, 3)
>>> B = MatrixSymbol('B', 2, 3)
>>> hadamard_product(A)
A
>>> hadamard_product(A, B)
HadamardProduct(A, B)
>>> hadamard_product(A, B)[0, 1]
A[0, 1]*B[0, 1]
"""
if not matrices:
raise TypeError("Empty Hadamard product is undefined")
validate(*matrices)
if len(matrices) == 1:
return matrices[0]
else:
matrices = [i for i in matrices if not i.is_Identity]
return HadamardProduct(*matrices).doit()
class HadamardProduct(MatrixExpr):
"""
Elementwise product of matrix expressions
Examples
========
Hadamard product for matrix symbols:
>>> from sympy.matrices import hadamard_product, HadamardProduct, MatrixSymbol
>>> A = MatrixSymbol('A', 5, 5)
>>> B = MatrixSymbol('B', 5, 5)
>>> isinstance(hadamard_product(A, B), HadamardProduct)
True
Notes
=====
This is a symbolic object that simply stores its argument without
evaluating it. To actually compute the product, use the function
``hadamard_product()`` or ``HadamardProduct.doit``
"""
is_HadamardProduct = True
def __new__(cls, *args, **kwargs):
args = list(map(sympify, args))
check = kwargs.get('check', True)
if check:
validate(*args)
return super(HadamardProduct, cls).__new__(cls, *args)
@property
def shape(self):
return self.args[0].shape
def _entry(self, i, j, **kwargs):
return Mul(*[arg._entry(i, j, **kwargs) for arg in self.args])
def _eval_transpose(self):
from sympy.matrices.expressions.transpose import transpose
return HadamardProduct(*list(map(transpose, self.args)))
def doit(self, **ignored):
expr = self.func(*[i.doit(**ignored) for i in self.args])
# Check for explicit matrices:
from sympy import MatrixBase
from sympy.matrices.immutable import ImmutableMatrix
explicit = [i for i in expr.args if isinstance(i, MatrixBase)]
if explicit:
remainder = [i for i in expr.args if i not in explicit]
expl_mat = ImmutableMatrix([
Mul.fromiter(i) for i in zip(*explicit)
]).reshape(*self.shape)
expr = HadamardProduct(*([expl_mat] + remainder))
return canonicalize(expr)
def _eval_derivative(self, x):
from sympy import Add
terms = []
args = list(self.args)
for i in range(len(args)):
factors = args[:i] + [args[i].diff(x)] + args[i+1:]
terms.append(hadamard_product(*factors))
return Add.fromiter(terms)
def _eval_derivative_matrix_lines(self, x):
from sympy.core.expr import ExprBuilder
from sympy.codegen.array_utils import CodegenArrayDiagonal, CodegenArrayTensorProduct
from sympy.matrices.expressions.matexpr import _make_matrix
with_x_ind = [i for i, arg in enumerate(self.args) if arg.has(x)]
lines = []
for ind in with_x_ind:
left_args = self.args[:ind]
right_args = self.args[ind+1:]
d = self.args[ind]._eval_derivative_matrix_lines(x)
hadam = hadamard_product(*(right_args + left_args))
diagonal = [(0, 2), (3, 4)]
diagonal = [e for j, e in enumerate(diagonal) if self.shape[j] != 1]
for i in d:
l1 = i._lines[i._first_line_index]
l2 = i._lines[i._second_line_index]
subexpr = ExprBuilder(
CodegenArrayDiagonal,
[
ExprBuilder(
CodegenArrayTensorProduct,
[
ExprBuilder(_make_matrix, [l1]),
hadam,
ExprBuilder(_make_matrix, [l2]),
]
),
*diagonal],
)
i._first_pointer_parent = subexpr.args[0].args[0].args
i._first_pointer_index = 0
i._second_pointer_parent = subexpr.args[0].args[2].args
i._second_pointer_index = 0
i._lines = [subexpr]
lines.append(i)
return lines
def validate(*args):
if not all(arg.is_Matrix for arg in args):
raise TypeError("Mix of Matrix and Scalar symbols")
A = args[0]
for B in args[1:]:
if A.shape != B.shape:
raise ShapeError("Matrices %s and %s are not aligned" % (A, B))
# TODO Implement algorithm for rewriting Hadamard product as diagonal matrix
# if matmul identy matrix is multiplied.
def canonicalize(x):
"""Canonicalize the Hadamard product ``x`` with mathematical properties.
Examples
========
>>> from sympy.matrices.expressions import MatrixSymbol, HadamardProduct
>>> from sympy.matrices.expressions import OneMatrix, ZeroMatrix
>>> from sympy.matrices.expressions.hadamard import canonicalize
>>> from sympy import init_printing
>>> init_printing(use_unicode=False)
>>> A = MatrixSymbol('A', 2, 2)
>>> B = MatrixSymbol('B', 2, 2)
>>> C = MatrixSymbol('C', 2, 2)
Hadamard product associativity:
>>> X = HadamardProduct(A, HadamardProduct(B, C))
>>> X
A.*(B.*C)
>>> canonicalize(X)
A.*B.*C
Hadamard product commutativity:
>>> X = HadamardProduct(A, B)
>>> Y = HadamardProduct(B, A)
>>> X
A.*B
>>> Y
B.*A
>>> canonicalize(X)
A.*B
>>> canonicalize(Y)
A.*B
Hadamard product identity:
>>> X = HadamardProduct(A, OneMatrix(2, 2))
>>> X
A.*1
>>> canonicalize(X)
A
Absorbing element of Hadamard product:
>>> X = HadamardProduct(A, ZeroMatrix(2, 2))
>>> X
A.*0
>>> canonicalize(X)
0
Rewriting to Hadamard Power
>>> X = HadamardProduct(A, A, A)
>>> X
A.*A.*A
>>> canonicalize(X)
.3
A
Notes
=====
As the Hadamard product is associative, nested products can be flattened.
The Hadamard product is commutative so that factors can be sorted for
canonical form.
A matrix of only ones is an identity for Hadamard product,
so every matrices of only ones can be removed.
Any zero matrix will make the whole product a zero matrix.
Duplicate elements can be collected and rewritten as HadamardPower
References
==========
.. [1] https://en.wikipedia.org/wiki/Hadamard_product_(matrices)
"""
from sympy.core.compatibility import default_sort_key
# Associativity
rule = condition(
lambda x: isinstance(x, HadamardProduct),
flatten
)
fun = exhaust(rule)
x = fun(x)
# Identity
fun = condition(
lambda x: isinstance(x, HadamardProduct),
rm_id(lambda x: isinstance(x, OneMatrix))
)
x = fun(x)
# Absorbing by Zero Matrix
def absorb(x):
if any(isinstance(c, ZeroMatrix) for c in x.args):
return ZeroMatrix(*x.shape)
else:
return x
fun = condition(
lambda x: isinstance(x, HadamardProduct),
absorb
)
x = fun(x)
# Rewriting with HadamardPower
if isinstance(x, HadamardProduct):
from collections import Counter
tally = Counter(x.args)
new_arg = []
for base, exp in tally.items():
if exp == 1:
new_arg.append(base)
else:
new_arg.append(HadamardPower(base, exp))
x = HadamardProduct(*new_arg)
# Commutativity
fun = condition(
lambda x: isinstance(x, HadamardProduct),
sort(default_sort_key)
)
x = fun(x)
# Unpacking
x = unpack(x)
return x
def hadamard_power(base, exp):
base = sympify(base)
exp = sympify(exp)
if exp == 1:
return base
if not base.is_Matrix:
return base**exp
if exp.is_Matrix:
raise ValueError("cannot raise expression to a matrix")
return HadamardPower(base, exp)
class HadamardPower(MatrixExpr):
r"""
Elementwise power of matrix expressions
Parameters
==========
base : scalar or matrix
exp : scalar or matrix
Notes
=====
There are four definitions for the hadamard power which can be used.
Let's consider `A, B` as `(m, n)` matrices, and `a, b` as scalars.
Matrix raised to a scalar exponent:
.. math::
A^{\circ b} = \begin{bmatrix}
A_{0, 0}^b & A_{0, 1}^b & \cdots & A_{0, n-1}^b \\
A_{1, 0}^b & A_{1, 1}^b & \cdots & A_{1, n-1}^b \\
\vdots & \vdots & \ddots & \vdots \\
A_{m-1, 0}^b & A_{m-1, 1}^b & \cdots & A_{m-1, n-1}^b
\end{bmatrix}
Scalar raised to a matrix exponent:
.. math::
a^{\circ B} = \begin{bmatrix}
a^{B_{0, 0}} & a^{B_{0, 1}} & \cdots & a^{B_{0, n-1}} \\
a^{B_{1, 0}} & a^{B_{1, 1}} & \cdots & a^{B_{1, n-1}} \\
\vdots & \vdots & \ddots & \vdots \\
a^{B_{m-1, 0}} & a^{B_{m-1, 1}} & \cdots & a^{B_{m-1, n-1}}
\end{bmatrix}
Matrix raised to a matrix exponent:
.. math::
A^{\circ B} = \begin{bmatrix}
A_{0, 0}^{B_{0, 0}} & A_{0, 1}^{B_{0, 1}} &
\cdots & A_{0, n-1}^{B_{0, n-1}} \\
A_{1, 0}^{B_{1, 0}} & A_{1, 1}^{B_{1, 1}} &
\cdots & A_{1, n-1}^{B_{1, n-1}} \\
\vdots & \vdots &
\ddots & \vdots \\
A_{m-1, 0}^{B_{m-1, 0}} & A_{m-1, 1}^{B_{m-1, 1}} &
\cdots & A_{m-1, n-1}^{B_{m-1, n-1}}
\end{bmatrix}
Scalar raised to a scalar exponent:
.. math::
a^{\circ b} = a^b
"""
def __new__(cls, base, exp):
base = sympify(base)
exp = sympify(exp)
if base.is_scalar and exp.is_scalar:
return base ** exp
if base.is_Matrix and exp.is_Matrix and base.shape != exp.shape:
raise ValueError(
'The shape of the base {} and '
'the shape of the exponent {} do not match.'
.format(base.shape, exp.shape)
)
obj = super(HadamardPower, cls).__new__(cls, base, exp)
return obj
@property
def base(self):
return self._args[0]
@property
def exp(self):
return self._args[1]
@property
def shape(self):
if self.base.is_Matrix:
return self.base.shape
return self.exp.shape
def _entry(self, i, j, **kwargs):
base = self.base
exp = self.exp
if base.is_Matrix:
a = base._entry(i, j, **kwargs)
elif base.is_scalar:
a = base
else:
raise ValueError(
'The base {} must be a scalar or a matrix.'.format(base))
if exp.is_Matrix:
b = exp._entry(i, j, **kwargs)
elif exp.is_scalar:
b = exp
else:
raise ValueError(
'The exponent {} must be a scalar or a matrix.'.format(exp))
return a ** b
def _eval_transpose(self):
from sympy.matrices.expressions.transpose import transpose
return HadamardPower(transpose(self.base), self.exp)
def _eval_derivative(self, x):
from sympy import log
dexp = self.exp.diff(x)
logbase = self.base.applyfunc(log)
dlbase = logbase.diff(x)
return hadamard_product(
dexp*logbase + self.exp*dlbase,
self
)
def _eval_derivative_matrix_lines(self, x):
from sympy.codegen.array_utils import CodegenArrayTensorProduct
from sympy.codegen.array_utils import CodegenArrayDiagonal
from sympy.core.expr import ExprBuilder
from sympy.matrices.expressions.matexpr import _make_matrix
lr = self.base._eval_derivative_matrix_lines(x)
for i in lr:
diagonal = [(1, 2), (3, 4)]
diagonal = [e for j, e in enumerate(diagonal) if self.base.shape[j] != 1]
l1 = i._lines[i._first_line_index]
l2 = i._lines[i._second_line_index]
subexpr = ExprBuilder(
CodegenArrayDiagonal,
[
ExprBuilder(
CodegenArrayTensorProduct,
[
ExprBuilder(_make_matrix, [l1]),
self.exp*hadamard_power(self.base, self.exp-1),
ExprBuilder(_make_matrix, [l2]),
]
),
*diagonal],
validator=CodegenArrayDiagonal._validate
)
i._first_pointer_parent = subexpr.args[0].args[0].args
i._first_pointer_index = 0
i._first_line_index = 0
i._second_pointer_parent = subexpr.args[0].args[2].args
i._second_pointer_index = 0
i._second_line_index = 0
i._lines = [subexpr]
return lr
|
f5ea5a8cf9d11d39f32c923853ef60c05a5e4c4b45ca6a103dac7a94cf1e207d | from __future__ import print_function, division
from sympy import ask, Q
from sympy.core import Basic, Add
from sympy.strategies import typed, exhaust, condition, do_one, unpack
from sympy.strategies.traverse import bottom_up
from sympy.utilities import sift
from sympy.utilities.misc import filldedent
from sympy.matrices.expressions.matexpr import MatrixExpr, ZeroMatrix, Identity
from sympy.matrices.expressions.matmul import MatMul
from sympy.matrices.expressions.matadd import MatAdd
from sympy.matrices.expressions.matpow import MatPow
from sympy.matrices.expressions.transpose import Transpose, transpose
from sympy.matrices.expressions.trace import Trace
from sympy.matrices.expressions.determinant import det, Determinant
from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions.inverse import Inverse
from sympy.matrices import Matrix, ShapeError
from sympy.functions.elementary.complexes import re, im
class BlockMatrix(MatrixExpr):
"""A BlockMatrix is a Matrix comprised of other matrices.
The submatrices are stored in a SymPy Matrix object but accessed as part of
a Matrix Expression
>>> from sympy import (MatrixSymbol, BlockMatrix, symbols,
... Identity, ZeroMatrix, block_collapse)
>>> n,m,l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m ,m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
>>> print(B)
Matrix([
[X, Z],
[0, Y]])
>>> C = BlockMatrix([[Identity(n), Z]])
>>> print(C)
Matrix([[I, Z]])
>>> print(block_collapse(C*B))
Matrix([[X, Z + Z*Y]])
Some matrices might be comprised of rows of blocks with
the matrices in each row having the same height and the
rows all having the same total number of columns but
not having the same number of columns for each matrix
in each row. In this case, the matrix is not a block
matrix and should be instantiated by Matrix.
>>> from sympy import ones, Matrix
>>> dat = [
... [ones(3,2), ones(3,3)*2],
... [ones(2,3)*3, ones(2,2)*4]]
...
>>> BlockMatrix(dat)
Traceback (most recent call last):
...
ValueError:
Although this matrix is comprised of blocks, the blocks do not fill
the matrix in a size-symmetric fashion. To create a full matrix from
these arguments, pass them directly to Matrix.
>>> Matrix(dat)
Matrix([
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[1, 1, 2, 2, 2],
[3, 3, 3, 4, 4],
[3, 3, 3, 4, 4]])
See Also
========
sympy.matrices.matrices.MatrixBase.irregular
"""
def __new__(cls, *args, **kwargs):
from sympy.matrices.immutable import ImmutableDenseMatrix
from sympy.utilities.iterables import is_sequence
isMat = lambda i: getattr(i, 'is_Matrix', False)
if len(args) != 1 or \
not is_sequence(args[0]) or \
len(set([isMat(r) for r in args[0]])) != 1:
raise ValueError(filldedent('''
expecting a sequence of 1 or more rows
containing Matrices.'''))
rows = args[0] if args else []
if not isMat(rows):
if rows and isMat(rows[0]):
rows = [rows] # rows is not list of lists or []
# regularity check
# same number of matrices in each row
blocky = ok = len(set([len(r) for r in rows])) == 1
if ok:
# same number of rows for each matrix in a row
for r in rows:
ok = len(set([i.rows for i in r])) == 1
if not ok:
break
blocky = ok
# same number of cols for each matrix in each col
for c in range(len(rows[0])):
ok = len(set([rows[i][c].cols
for i in range(len(rows))])) == 1
if not ok:
break
if not ok:
# same total cols in each row
ok = len(set([
sum([i.cols for i in r]) for r in rows])) == 1
if blocky and ok:
raise ValueError(filldedent('''
Although this matrix is comprised of blocks,
the blocks do not fill the matrix in a
size-symmetric fashion. To create a full matrix
from these arguments, pass them directly to
Matrix.'''))
raise ValueError(filldedent('''
When there are not the same number of rows in each
row's matrices or there are not the same number of
total columns in each row, the matrix is not a
block matrix. If this matrix is known to consist of
blocks fully filling a 2-D space then see
Matrix.irregular.'''))
mat = ImmutableDenseMatrix(rows, evaluate=False)
obj = Basic.__new__(cls, mat)
return obj
@property
def shape(self):
numrows = numcols = 0
M = self.blocks
for i in range(M.shape[0]):
numrows += M[i, 0].shape[0]
for i in range(M.shape[1]):
numcols += M[0, i].shape[1]
return (numrows, numcols)
@property
def blockshape(self):
return self.blocks.shape
@property
def blocks(self):
return self.args[0]
@property
def rowblocksizes(self):
return [self.blocks[i, 0].rows for i in range(self.blockshape[0])]
@property
def colblocksizes(self):
return [self.blocks[0, i].cols for i in range(self.blockshape[1])]
def structurally_equal(self, other):
return (isinstance(other, BlockMatrix)
and self.shape == other.shape
and self.blockshape == other.blockshape
and self.rowblocksizes == other.rowblocksizes
and self.colblocksizes == other.colblocksizes)
def _blockmul(self, other):
if (isinstance(other, BlockMatrix) and
self.colblocksizes == other.rowblocksizes):
return BlockMatrix(self.blocks*other.blocks)
return self * other
def _blockadd(self, other):
if (isinstance(other, BlockMatrix)
and self.structurally_equal(other)):
return BlockMatrix(self.blocks + other.blocks)
return self + other
def _eval_transpose(self):
# Flip all the individual matrices
matrices = [transpose(matrix) for matrix in self.blocks]
# Make a copy
M = Matrix(self.blockshape[0], self.blockshape[1], matrices)
# Transpose the block structure
M = M.transpose()
return BlockMatrix(M)
def _eval_trace(self):
if self.rowblocksizes == self.colblocksizes:
return Add(*[Trace(self.blocks[i, i])
for i in range(self.blockshape[0])])
raise NotImplementedError(
"Can't perform trace of irregular blockshape")
def _eval_determinant(self):
if self.blockshape == (2, 2):
[[A, B],
[C, D]] = self.blocks.tolist()
if ask(Q.invertible(A)):
return det(A)*det(D - C*A.I*B)
elif ask(Q.invertible(D)):
return det(D)*det(A - B*D.I*C)
return Determinant(self)
def as_real_imag(self):
real_matrices = [re(matrix) for matrix in self.blocks]
real_matrices = Matrix(self.blockshape[0], self.blockshape[1], real_matrices)
im_matrices = [im(matrix) for matrix in self.blocks]
im_matrices = Matrix(self.blockshape[0], self.blockshape[1], im_matrices)
return (real_matrices, im_matrices)
def transpose(self):
"""Return transpose of matrix.
Examples
========
>>> from sympy import MatrixSymbol, BlockMatrix, ZeroMatrix
>>> from sympy.abc import l, m, n
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m ,m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m,n), Y]])
>>> B.transpose()
Matrix([
[X.T, 0],
[Z.T, Y.T]])
>>> _.transpose()
Matrix([
[X, Z],
[0, Y]])
"""
return self._eval_transpose()
def _entry(self, i, j, **kwargs):
# Find row entry
for row_block, numrows in enumerate(self.rowblocksizes):
if (i < numrows) != False:
break
else:
i -= numrows
for col_block, numcols in enumerate(self.colblocksizes):
if (j < numcols) != False:
break
else:
j -= numcols
return self.blocks[row_block, col_block][i, j]
@property
def is_Identity(self):
if self.blockshape[0] != self.blockshape[1]:
return False
for i in range(self.blockshape[0]):
for j in range(self.blockshape[1]):
if i==j and not self.blocks[i, j].is_Identity:
return False
if i!=j and not self.blocks[i, j].is_ZeroMatrix:
return False
return True
@property
def is_structurally_symmetric(self):
return self.rowblocksizes == self.colblocksizes
def equals(self, other):
if self == other:
return True
if (isinstance(other, BlockMatrix) and self.blocks == other.blocks):
return True
return super(BlockMatrix, self).equals(other)
class BlockDiagMatrix(BlockMatrix):
"""
A BlockDiagMatrix is a BlockMatrix with matrices only along the diagonal
>>> from sympy import MatrixSymbol, BlockDiagMatrix, symbols, Identity
>>> n, m, l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m ,m)
>>> BlockDiagMatrix(X, Y)
Matrix([
[X, 0],
[0, Y]])
See Also
========
sympy.matrices.dense.diag
"""
def __new__(cls, *mats):
return Basic.__new__(BlockDiagMatrix, *mats)
@property
def diag(self):
return self.args
@property
def blocks(self):
from sympy.matrices.immutable import ImmutableDenseMatrix
mats = self.args
data = [[mats[i] if i == j else ZeroMatrix(mats[i].rows, mats[j].cols)
for j in range(len(mats))]
for i in range(len(mats))]
return ImmutableDenseMatrix(data, evaluate=False)
@property
def shape(self):
return (sum(block.rows for block in self.args),
sum(block.cols for block in self.args))
@property
def blockshape(self):
n = len(self.args)
return (n, n)
@property
def rowblocksizes(self):
return [block.rows for block in self.args]
@property
def colblocksizes(self):
return [block.cols for block in self.args]
def _eval_inverse(self, expand='ignored'):
return BlockDiagMatrix(*[mat.inverse() for mat in self.args])
def _eval_transpose(self):
return BlockDiagMatrix(*[mat.transpose() for mat in self.args])
def _blockmul(self, other):
if (isinstance(other, BlockDiagMatrix) and
self.colblocksizes == other.rowblocksizes):
return BlockDiagMatrix(*[a*b for a, b in zip(self.args, other.args)])
else:
return BlockMatrix._blockmul(self, other)
def _blockadd(self, other):
if (isinstance(other, BlockDiagMatrix) and
self.blockshape == other.blockshape and
self.rowblocksizes == other.rowblocksizes and
self.colblocksizes == other.colblocksizes):
return BlockDiagMatrix(*[a + b for a, b in zip(self.args, other.args)])
else:
return BlockMatrix._blockadd(self, other)
def block_collapse(expr):
"""Evaluates a block matrix expression
>>> from sympy import MatrixSymbol, BlockMatrix, symbols, \
Identity, Matrix, ZeroMatrix, block_collapse
>>> n,m,l = symbols('n m l')
>>> X = MatrixSymbol('X', n, n)
>>> Y = MatrixSymbol('Y', m ,m)
>>> Z = MatrixSymbol('Z', n, m)
>>> B = BlockMatrix([[X, Z], [ZeroMatrix(m, n), Y]])
>>> print(B)
Matrix([
[X, Z],
[0, Y]])
>>> C = BlockMatrix([[Identity(n), Z]])
>>> print(C)
Matrix([[I, Z]])
>>> print(block_collapse(C*B))
Matrix([[X, Z + Z*Y]])
"""
from sympy.strategies.util import expr_fns
hasbm = lambda expr: isinstance(expr, MatrixExpr) and expr.has(BlockMatrix)
conditioned_rl = condition(
hasbm,
typed(
{MatAdd: do_one(bc_matadd, bc_block_plus_ident),
MatMul: do_one(bc_matmul, bc_dist),
MatPow: bc_matmul,
Transpose: bc_transpose,
Inverse: bc_inverse,
BlockMatrix: do_one(bc_unpack, deblock)}
)
)
rule = exhaust(
bottom_up(
exhaust(conditioned_rl),
fns=expr_fns
)
)
result = rule(expr)
doit = getattr(result, 'doit', None)
if doit is not None:
return doit()
else:
return result
def bc_unpack(expr):
if expr.blockshape == (1, 1):
return expr.blocks[0, 0]
return expr
def bc_matadd(expr):
args = sift(expr.args, lambda M: isinstance(M, BlockMatrix))
blocks = args[True]
if not blocks:
return expr
nonblocks = args[False]
block = blocks[0]
for b in blocks[1:]:
block = block._blockadd(b)
if nonblocks:
return MatAdd(*nonblocks) + block
else:
return block
def bc_block_plus_ident(expr):
idents = [arg for arg in expr.args if arg.is_Identity]
if not idents:
return expr
blocks = [arg for arg in expr.args if isinstance(arg, BlockMatrix)]
if (blocks and all(b.structurally_equal(blocks[0]) for b in blocks)
and blocks[0].is_structurally_symmetric):
block_id = BlockDiagMatrix(*[Identity(k)
for k in blocks[0].rowblocksizes])
return MatAdd(block_id * len(idents), *blocks).doit()
return expr
def bc_dist(expr):
""" Turn a*[X, Y] into [a*X, a*Y] """
factor, mat = expr.as_coeff_mmul()
if factor == 1:
return expr
unpacked = unpack(mat)
if isinstance(unpacked, BlockDiagMatrix):
B = unpacked.diag
new_B = [factor * mat for mat in B]
return BlockDiagMatrix(*new_B)
elif isinstance(unpacked, BlockMatrix):
B = unpacked.blocks
new_B = [
[factor * B[i, j] for j in range(B.cols)] for i in range(B.rows)]
return BlockMatrix(new_B)
return unpacked
def bc_matmul(expr):
if isinstance(expr, MatPow):
if expr.args[1].is_Integer:
factor, matrices = (1, [expr.args[0]]*expr.args[1])
else:
return expr
else:
factor, matrices = expr.as_coeff_matrices()
i = 0
while (i+1 < len(matrices)):
A, B = matrices[i:i+2]
if isinstance(A, BlockMatrix) and isinstance(B, BlockMatrix):
matrices[i] = A._blockmul(B)
matrices.pop(i+1)
elif isinstance(A, BlockMatrix):
matrices[i] = A._blockmul(BlockMatrix([[B]]))
matrices.pop(i+1)
elif isinstance(B, BlockMatrix):
matrices[i] = BlockMatrix([[A]])._blockmul(B)
matrices.pop(i+1)
else:
i+=1
return MatMul(factor, *matrices).doit()
def bc_transpose(expr):
collapse = block_collapse(expr.arg)
return collapse._eval_transpose()
def bc_inverse(expr):
if isinstance(expr.arg, BlockDiagMatrix):
return expr._eval_inverse()
expr2 = blockinverse_1x1(expr)
if expr != expr2:
return expr2
return blockinverse_2x2(Inverse(reblock_2x2(expr.arg)))
def blockinverse_1x1(expr):
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (1, 1):
mat = Matrix([[expr.arg.blocks[0].inverse()]])
return BlockMatrix(mat)
return expr
def blockinverse_2x2(expr):
if isinstance(expr.arg, BlockMatrix) and expr.arg.blockshape == (2, 2):
# Cite: The Matrix Cookbook Section 9.1.3
[[A, B],
[C, D]] = expr.arg.blocks.tolist()
return BlockMatrix([[ (A - B*D.I*C).I, (-A).I*B*(D - C*A.I*B).I],
[-(D - C*A.I*B).I*C*A.I, (D - C*A.I*B).I]])
else:
return expr
def deblock(B):
""" Flatten a BlockMatrix of BlockMatrices """
if not isinstance(B, BlockMatrix) or not B.blocks.has(BlockMatrix):
return B
wrap = lambda x: x if isinstance(x, BlockMatrix) else BlockMatrix([[x]])
bb = B.blocks.applyfunc(wrap) # everything is a block
from sympy import Matrix
try:
MM = Matrix(0, sum(bb[0, i].blocks.shape[1] for i in range(bb.shape[1])), [])
for row in range(0, bb.shape[0]):
M = Matrix(bb[row, 0].blocks)
for col in range(1, bb.shape[1]):
M = M.row_join(bb[row, col].blocks)
MM = MM.col_join(M)
return BlockMatrix(MM)
except ShapeError:
return B
def reblock_2x2(B):
""" Reblock a BlockMatrix so that it has 2x2 blocks of block matrices """
if not isinstance(B, BlockMatrix) or not all(d > 2 for d in B.blocks.shape):
return B
BM = BlockMatrix # for brevity's sake
return BM([[ B.blocks[0, 0], BM(B.blocks[0, 1:])],
[BM(B.blocks[1:, 0]), BM(B.blocks[1:, 1:])]])
def bounds(sizes):
""" Convert sequence of numbers into pairs of low-high pairs
>>> from sympy.matrices.expressions.blockmatrix import bounds
>>> bounds((1, 10, 50))
[(0, 1), (1, 11), (11, 61)]
"""
low = 0
rv = []
for size in sizes:
rv.append((low, low + size))
low += size
return rv
def blockcut(expr, rowsizes, colsizes):
""" Cut a matrix expression into Blocks
>>> from sympy import ImmutableMatrix, blockcut
>>> M = ImmutableMatrix(4, 4, range(16))
>>> B = blockcut(M, (1, 3), (1, 3))
>>> type(B).__name__
'BlockMatrix'
>>> ImmutableMatrix(B.blocks[0, 1])
Matrix([[1, 2, 3]])
"""
rowbounds = bounds(rowsizes)
colbounds = bounds(colsizes)
return BlockMatrix([[MatrixSlice(expr, rowbound, colbound)
for colbound in colbounds]
for rowbound in rowbounds])
|
8dea59c3bc822a047b16d744616d96e097fe5d2d019a1500c5e061a2d97877a1 | from sympy.matrices.expressions import MatrixSymbol, MatAdd, MatPow, MatMul
from sympy.matrices.expressions.matexpr import GenericZeroMatrix, ZeroMatrix
from sympy.matrices import eye, ImmutableMatrix
from sympy.core import Add, Basic, S
from sympy.testing.pytest import XFAIL, raises
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
def test_sort_key():
assert MatAdd(Y, X).doit().args == (X, Y)
def test_matadd_sympify():
assert isinstance(MatAdd(eye(1), eye(1)).args[0], Basic)
def test_matadd_of_matrices():
assert MatAdd(eye(2), 4*eye(2), eye(2)).doit() == ImmutableMatrix(6*eye(2))
def test_doit_args():
A = ImmutableMatrix([[1, 2], [3, 4]])
B = ImmutableMatrix([[2, 3], [4, 5]])
assert MatAdd(A, MatPow(B, 2)).doit() == A + B**2
assert MatAdd(A, MatMul(A, B)).doit() == A + A*B
assert (MatAdd(A, X, MatMul(A, B), Y, MatAdd(2*A, B)).doit() ==
MatAdd(3*A + A*B + B, X, Y))
def test_generic_identity():
assert MatAdd.identity == GenericZeroMatrix()
assert MatAdd.identity != S.Zero
def test_zero_matrix_add():
assert Add(ZeroMatrix(2, 2), ZeroMatrix(2, 2)) == ZeroMatrix(2, 2)
@XFAIL
def test_matrix_add_with_scalar():
raises(TypeError, lambda: Add(0, ZeroMatrix(2, 2)))
|
85ce9bb318a45e511a8e8da6dab5cc88f607092a0c2552035e59bf145a8d7908 | from sympy.core import I, symbols, Basic, Mul, S
from sympy.functions import adjoint, transpose
from sympy.matrices import (Identity, Inverse, Matrix, MatrixSymbol, ZeroMatrix,
eye, ImmutableMatrix)
from sympy.matrices.expressions import Adjoint, Transpose, det, MatPow
from sympy.matrices.expressions.matexpr import GenericIdentity
from sympy.matrices.expressions.matmul import (factor_in_front, remove_ids,
MatMul, combine_powers, any_zeros, unpack, only_squares)
from sympy.strategies import null_safe
from sympy import refine, Q, Symbol
from sympy.testing.pytest import XFAIL
n, m, l, k = symbols('n m l k', integer=True)
x = symbols('x')
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
E = MatrixSymbol('E', m, n)
def test_adjoint():
assert adjoint(A*B) == Adjoint(B)*Adjoint(A)
assert adjoint(2*A*B) == 2*Adjoint(B)*Adjoint(A)
assert adjoint(2*I*C) == -2*I*Adjoint(C)
M = Matrix(2, 2, [1, 2 + I, 3, 4])
MA = Matrix(2, 2, [1, 3, 2 - I, 4])
assert adjoint(M) == MA
assert adjoint(2*M) == 2*MA
assert adjoint(MatMul(2, M)) == MatMul(2, MA).doit()
def test_transpose():
assert transpose(A*B) == Transpose(B)*Transpose(A)
assert transpose(2*A*B) == 2*Transpose(B)*Transpose(A)
assert transpose(2*I*C) == 2*I*Transpose(C)
M = Matrix(2, 2, [1, 2 + I, 3, 4])
MT = Matrix(2, 2, [1, 3, 2 + I, 4])
assert transpose(M) == MT
assert transpose(2*M) == 2*MT
assert transpose(x*M) == x*MT
assert transpose(MatMul(2, M)) == MatMul(2, MT).doit()
def test_factor_in_front():
assert factor_in_front(MatMul(A, 2, B, evaluate=False)) ==\
MatMul(2, A, B, evaluate=False)
def test_remove_ids():
assert remove_ids(MatMul(A, Identity(m), B, evaluate=False)) == \
MatMul(A, B, evaluate=False)
assert null_safe(remove_ids)(MatMul(Identity(n), evaluate=False)) == \
MatMul(Identity(n), evaluate=False)
def test_combine_powers():
assert combine_powers(MatMul(D, Inverse(D), D, evaluate=False)) == \
MatMul(Identity(n), D, evaluate=False)
def test_any_zeros():
assert any_zeros(MatMul(A, ZeroMatrix(m, k), evaluate=False)) == \
ZeroMatrix(n, k)
def test_unpack():
assert unpack(MatMul(A, evaluate=False)) == A
x = MatMul(A, B)
assert unpack(x) == x
def test_only_squares():
assert only_squares(C) == [C]
assert only_squares(C, D) == [C, D]
assert only_squares(C, A, A.T, D) == [C, A*A.T, D]
def test_determinant():
assert det(2*C) == 2**n*det(C)
assert det(2*C*D) == 2**n*det(C)*det(D)
assert det(3*C*A*A.T*D) == 3**n*det(C)*det(A*A.T)*det(D)
def test_doit():
assert MatMul(C, 2, D).args == (C, 2, D)
assert MatMul(C, 2, D).doit().args == (2, C, D)
assert MatMul(C, Transpose(D*C)).args == (C, Transpose(D*C))
assert MatMul(C, Transpose(D*C)).doit(deep=True).args == (C, C.T, D.T)
def test_doit_drills_down():
X = ImmutableMatrix([[1, 2], [3, 4]])
Y = ImmutableMatrix([[2, 3], [4, 5]])
assert MatMul(X, MatPow(Y, 2)).doit() == X*Y**2
assert MatMul(C, Transpose(D*C)).doit().args == (C, C.T, D.T)
def test_doit_deep_false_still_canonical():
assert (MatMul(C, Transpose(D*C), 2).doit(deep=False).args ==
(2, C, Transpose(D*C)))
def test_matmul_scalar_Matrix_doit():
# Issue 9053
X = Matrix([[1, 2], [3, 4]])
assert MatMul(2, X).doit() == 2*X
def test_matmul_sympify():
assert isinstance(MatMul(eye(1), eye(1)).args[0], Basic)
def test_collapse_MatrixBase():
A = Matrix([[1, 1], [1, 1]])
B = Matrix([[1, 2], [3, 4]])
assert MatMul(A, B).doit() == ImmutableMatrix([[4, 6], [4, 6]])
def test_refine():
assert refine(C*C.T*D, Q.orthogonal(C)).doit() == D
kC = k*C
assert refine(kC*C.T, Q.orthogonal(C)).doit() == k*Identity(n)
assert refine(kC* kC.T, Q.orthogonal(C)).doit() == (k**2)*Identity(n)
def test_matmul_no_matrices():
assert MatMul(1) == 1
assert MatMul(n, m) == n*m
assert not isinstance(MatMul(n, m), MatMul)
def test_matmul_args_cnc():
assert MatMul(n, A, A.T).args_cnc() == [[n], [A, A.T]]
assert MatMul(A, A.T).args_cnc() == [[], [A, A.T]]
@XFAIL
def test_matmul_args_cnc_symbols():
# Not currently supported
a, b = symbols('a b', commutative=False)
assert MatMul(n, a, b, A, A.T).args_cnc() == [[n], [a, b, A, A.T]]
assert MatMul(n, a, A, b, A.T).args_cnc() == [[n], [a, A, b, A.T]]
def test_issue_12950():
M = Matrix([[Symbol("x")]]) * MatrixSymbol("A", 1, 1)
assert MatrixSymbol("A", 1, 1).as_explicit()[0]*Symbol('x') == M.as_explicit()[0]
def test_construction_with_Mul():
assert Mul(C, D) == MatMul(C, D)
assert Mul(D, C) == MatMul(D, C)
def test_generic_identity():
assert MatMul.identity == GenericIdentity()
assert MatMul.identity != S.One
|
e7b31c84a764f261ff1b95f240bca73c57511db6f3f2ba7284ae58753bdd607b | from sympy.matrices.expressions.blockmatrix import (
block_collapse, bc_matmul, bc_block_plus_ident, BlockDiagMatrix,
BlockMatrix, bc_dist, bc_matadd, bc_transpose, bc_inverse,
blockcut, reblock_2x2, deblock)
from sympy.matrices.expressions import (MatrixSymbol, Identity,
Inverse, trace, Transpose, det, ZeroMatrix)
from sympy.matrices import (
Matrix, ImmutableMatrix, ImmutableSparseMatrix)
from sympy.core import Tuple, symbols, Expr
from sympy.functions import transpose
i, j, k, l, m, n, p = symbols('i:n, p', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
G = MatrixSymbol('G', n, n)
H = MatrixSymbol('H', n, n)
b1 = BlockMatrix([[G, H]])
b2 = BlockMatrix([[G], [H]])
def test_bc_matmul():
assert bc_matmul(H*b1*b2*G) == BlockMatrix([[(H*G*G + H*H*H)*G]])
def test_bc_matadd():
assert bc_matadd(BlockMatrix([[G, H]]) + BlockMatrix([[H, H]])) == \
BlockMatrix([[G+H, H+H]])
def test_bc_transpose():
assert bc_transpose(Transpose(BlockMatrix([[A, B], [C, D]]))) == \
BlockMatrix([[A.T, C.T], [B.T, D.T]])
def test_bc_dist_diag():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', m, m)
C = MatrixSymbol('C', l, l)
X = BlockDiagMatrix(A, B, C)
assert bc_dist(X+X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
def test_block_plus_ident():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', m, m)
X = BlockMatrix([[A, B], [C, D]])
assert bc_block_plus_ident(X+Identity(m+n)) == \
BlockDiagMatrix(Identity(n), Identity(m)) + X
def test_BlockMatrix():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, k)
C = MatrixSymbol('C', l, m)
D = MatrixSymbol('D', l, k)
M = MatrixSymbol('M', m + k, p)
N = MatrixSymbol('N', l + n, k + m)
X = BlockMatrix(Matrix([[A, B], [C, D]]))
assert X.__class__(*X.args) == X
# block_collapse does nothing on normal inputs
E = MatrixSymbol('E', n, m)
assert block_collapse(A + 2*E) == A + 2*E
F = MatrixSymbol('F', m, m)
assert block_collapse(E.T*A*F) == E.T*A*F
assert X.shape == (l + n, k + m)
assert X.blockshape == (2, 2)
assert transpose(X) == BlockMatrix(Matrix([[A.T, C.T], [B.T, D.T]]))
assert transpose(X).shape == X.shape[::-1]
# Test that BlockMatrices and MatrixSymbols can still mix
assert (X*M).is_MatMul
assert X._blockmul(M).is_MatMul
assert (X*M).shape == (n + l, p)
assert (X + N).is_MatAdd
assert X._blockadd(N).is_MatAdd
assert (X + N).shape == X.shape
E = MatrixSymbol('E', m, 1)
F = MatrixSymbol('F', k, 1)
Y = BlockMatrix(Matrix([[E], [F]]))
assert (X*Y).shape == (l + n, 1)
assert block_collapse(X*Y).blocks[0, 0] == A*E + B*F
assert block_collapse(X*Y).blocks[1, 0] == C*E + D*F
# block_collapse passes down into container objects, transposes, and inverse
assert block_collapse(transpose(X*Y)) == transpose(block_collapse(X*Y))
assert block_collapse(Tuple(X*Y, 2*X)) == (
block_collapse(X*Y), block_collapse(2*X))
# Make sure that MatrixSymbols will enter 1x1 BlockMatrix if it simplifies
Ab = BlockMatrix([[A]])
Z = MatrixSymbol('Z', *A.shape)
assert block_collapse(Ab + Z) == A + Z
def test_block_collapse_explicit_matrices():
A = Matrix([[1, 2], [3, 4]])
assert block_collapse(BlockMatrix([[A]])) == A
A = ImmutableSparseMatrix([[1, 2], [3, 4]])
assert block_collapse(BlockMatrix([[A]])) == A
def test_issue_17624():
a = MatrixSymbol("a", 2, 2)
z = ZeroMatrix(2, 2)
b = BlockMatrix([[a, z], [z, z]])
assert block_collapse(b * b) == BlockMatrix([[a**2, z], [z, z]])
assert block_collapse(b * b * b) == BlockMatrix([[a**3, z], [z, z]])
def test_issue_18618():
A = Matrix([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
assert A == Matrix(BlockDiagMatrix(A))
def test_BlockMatrix_trace():
A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
X = BlockMatrix([[A, B], [C, D]])
assert trace(X) == trace(A) + trace(D)
def test_BlockMatrix_Determinant():
A, B, C, D = [MatrixSymbol(s, 3, 3) for s in 'ABCD']
X = BlockMatrix([[A, B], [C, D]])
from sympy import assuming, Q
with assuming(Q.invertible(A)):
assert det(X) == det(A) * det(D - C*A.I*B)
assert isinstance(det(X), Expr)
def test_squareBlockMatrix():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, n)
D = MatrixSymbol('D', m, m)
X = BlockMatrix([[A, B], [C, D]])
Y = BlockMatrix([[A]])
assert X.is_square
Q = X + Identity(m + n)
assert (block_collapse(Q) ==
BlockMatrix([[A + Identity(n), B], [C, D + Identity(m)]]))
assert (X + MatrixSymbol('Q', n + m, n + m)).is_MatAdd
assert (X * MatrixSymbol('Q', n + m, n + m)).is_MatMul
assert block_collapse(Y.I) == A.I
assert block_collapse(X.inverse()) == BlockMatrix([
[(-B*D.I*C + A).I, -A.I*B*(D + -C*A.I*B).I],
[-(D - C*A.I*B).I*C*A.I, (D - C*A.I*B).I]])
assert isinstance(X.inverse(), Inverse)
assert not X.is_Identity
Z = BlockMatrix([[Identity(n), B], [C, D]])
assert not Z.is_Identity
def test_BlockDiagMatrix():
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', m, m)
C = MatrixSymbol('C', l, l)
M = MatrixSymbol('M', n + m + l, n + m + l)
X = BlockDiagMatrix(A, B, C)
Y = BlockDiagMatrix(A, 2*B, 3*C)
assert X.blocks[1, 1] == B
assert X.shape == (n + m + l, n + m + l)
assert all(X.blocks[i, j].is_ZeroMatrix if i != j else X.blocks[i, j] in [A, B, C]
for i in range(3) for j in range(3))
assert X.__class__(*X.args) == X
assert isinstance(block_collapse(X.I * X), Identity)
assert bc_matmul(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
assert block_collapse(X*X) == BlockDiagMatrix(A*A, B*B, C*C)
#XXX: should be == ??
assert block_collapse(X + X).equals(BlockDiagMatrix(2*A, 2*B, 2*C))
assert block_collapse(X*Y) == BlockDiagMatrix(A*A, 2*B*B, 3*C*C)
assert block_collapse(X + Y) == BlockDiagMatrix(2*A, 3*B, 4*C)
# Ensure that BlockDiagMatrices can still interact with normal MatrixExprs
assert (X*(2*M)).is_MatMul
assert (X + (2*M)).is_MatAdd
assert (X._blockmul(M)).is_MatMul
assert (X._blockadd(M)).is_MatAdd
def test_blockcut():
A = MatrixSymbol('A', n, m)
B = blockcut(A, (n/2, n/2), (m/2, m/2))
assert A[i, j] == B[i, j]
assert B == BlockMatrix([[A[:n/2, :m/2], A[:n/2, m/2:]],
[A[n/2:, :m/2], A[n/2:, m/2:]]])
M = ImmutableMatrix(4, 4, range(16))
B = blockcut(M, (2, 2), (2, 2))
assert M == ImmutableMatrix(B)
B = blockcut(M, (1, 3), (2, 2))
assert ImmutableMatrix(B.blocks[0, 1]) == ImmutableMatrix([[2, 3]])
def test_reblock_2x2():
B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), 2, 2)
for j in range(3)]
for i in range(3)])
assert B.blocks.shape == (3, 3)
BB = reblock_2x2(B)
assert BB.blocks.shape == (2, 2)
assert B.shape == BB.shape
assert B.as_explicit() == BB.as_explicit()
def test_deblock():
B = BlockMatrix([[MatrixSymbol('A_%d%d'%(i,j), n, n)
for j in range(4)]
for i in range(4)])
assert deblock(reblock_2x2(B)) == B
def test_block_collapse_type():
bm1 = BlockDiagMatrix(ImmutableMatrix([1]), ImmutableMatrix([2]))
bm2 = BlockDiagMatrix(ImmutableMatrix([3]), ImmutableMatrix([4]))
assert bm1.T.__class__ == BlockDiagMatrix
assert block_collapse(bm1 - bm2).__class__ == BlockDiagMatrix
assert block_collapse(Inverse(bm1)).__class__ == BlockDiagMatrix
assert block_collapse(Transpose(bm1)).__class__ == BlockDiagMatrix
assert bc_transpose(Transpose(bm1)).__class__ == BlockDiagMatrix
assert bc_inverse(Inverse(bm1)).__class__ == BlockDiagMatrix
|
ffbbf631512981fbbb87baeb5686581a536baa87f8c6b42f841d9a5d1b65ffdf | from sympy.core import symbols, Lambda
from sympy.functions import KroneckerDelta
from sympy.matrices import Matrix
from sympy.matrices.expressions import FunctionMatrix, MatrixExpr, Identity
from sympy.testing.pytest import raises
def test_funcmatrix_creation():
i, j, k = symbols('i j k')
assert FunctionMatrix(2, 2, Lambda((i, j), 0))
assert FunctionMatrix(0, 0, Lambda((i, j), 0))
raises(ValueError, lambda: FunctionMatrix(-1, 0, Lambda((i, j), 0)))
raises(ValueError, lambda: FunctionMatrix(2.0, 0, Lambda((i, j), 0)))
raises(ValueError, lambda: FunctionMatrix(2j, 0, Lambda((i, j), 0)))
raises(ValueError, lambda: FunctionMatrix(0, -1, Lambda((i, j), 0)))
raises(ValueError, lambda: FunctionMatrix(0, 2.0, Lambda((i, j), 0)))
raises(ValueError, lambda: FunctionMatrix(0, 2j, Lambda((i, j), 0)))
raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda(i, 0)))
raises(ValueError, lambda: FunctionMatrix(2, 2, lambda i, j: 0))
raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda((i,), 0)))
raises(ValueError, lambda: FunctionMatrix(2, 2, Lambda((i, j, k), 0)))
raises(ValueError, lambda: FunctionMatrix(2, 2, i+j))
assert FunctionMatrix(2, 2, "lambda i, j: 0") == \
FunctionMatrix(2, 2, Lambda((i, j), 0))
m = FunctionMatrix(2, 2, KroneckerDelta)
assert m.as_explicit() == Identity(2).as_explicit()
assert m.args[2] == Lambda((i, j), KroneckerDelta(i, j))
n = symbols('n')
assert FunctionMatrix(n, n, Lambda((i, j), 0))
n = symbols('n', integer=False)
raises(ValueError, lambda: FunctionMatrix(n, n, Lambda((i, j), 0)))
n = symbols('n', negative=True)
raises(ValueError, lambda: FunctionMatrix(n, n, Lambda((i, j), 0)))
def test_funcmatrix():
i, j = symbols('i,j')
X = FunctionMatrix(3, 3, Lambda((i, j), i - j))
assert X[1, 1] == 0
assert X[1, 2] == -1
assert X.shape == (3, 3)
assert X.rows == X.cols == 3
assert Matrix(X) == Matrix(3, 3, lambda i, j: i - j)
assert isinstance(X*X + X, MatrixExpr)
def test_replace_issue():
X = FunctionMatrix(3, 3, KroneckerDelta)
assert X.replace(lambda x: True, lambda x: x) == X
|
f726f71d71e54a1e29a2c05d4222b6aa40e36ed96beedb8728b487ce67c2777f | from sympy.testing.pytest import raises
from sympy.core import symbols, pi, S
from sympy.matrices import Identity, MatrixSymbol, ImmutableMatrix, ZeroMatrix
from sympy.matrices.expressions import MatPow, MatAdd, MatMul
from sympy.matrices.expressions.matexpr import ShapeError
n, m, l, k = symbols('n m l k', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
E = MatrixSymbol('E', m, n)
def test_entry():
from sympy.concrete import Sum
assert MatPow(A, 1)[0, 0] == A[0, 0]
assert MatPow(C, 0)[0, 0] == 1
assert MatPow(C, 0)[0, 1] == 0
assert isinstance(MatPow(C, 2)[0, 0], Sum)
def test_as_explicit_symbol():
X = MatrixSymbol('X', 2, 2)
assert MatPow(X, 0).as_explicit() == ImmutableMatrix(Identity(2))
assert MatPow(X, 1).as_explicit() == X.as_explicit()
assert MatPow(X, 2).as_explicit() == (X.as_explicit())**2
def test_as_explicit_nonsquare_symbol():
X = MatrixSymbol('X', 2, 3)
assert MatPow(X, 1).as_explicit() == X.as_explicit()
for r in [0, 2, S.Half, S.Pi]:
raises(ShapeError, lambda: MatPow(X, r).as_explicit())
def test_as_explicit():
A = ImmutableMatrix([[1, 2], [3, 4]])
assert MatPow(A, 0).as_explicit() == ImmutableMatrix(Identity(2))
assert MatPow(A, 1).as_explicit() == A
assert MatPow(A, 2).as_explicit() == A**2
assert MatPow(A, -1).as_explicit() == A.inv()
assert MatPow(A, -2).as_explicit() == (A.inv())**2
# less expensive than testing on a 2x2
A = ImmutableMatrix([4]);
assert MatPow(A, S.Half).as_explicit() == A**S.Half
def test_as_explicit_nonsquare():
A = ImmutableMatrix([[1, 2, 3], [4, 5, 6]])
assert MatPow(A, 1).as_explicit() == A
raises(ShapeError, lambda: MatPow(A, 0).as_explicit())
raises(ShapeError, lambda: MatPow(A, 2).as_explicit())
raises(ShapeError, lambda: MatPow(A, -1).as_explicit())
raises(ValueError, lambda: MatPow(A, pi).as_explicit())
def test_doit_nonsquare_MatrixSymbol():
assert MatPow(A, 1).doit() == A
for r in [0, 2, -1, pi]:
assert MatPow(A, r).doit() == MatPow(A, r)
def test_doit_square_MatrixSymbol_symsize():
assert MatPow(C, 0).doit() == Identity(n)
assert MatPow(C, 1).doit() == C
for r in [2, pi]:
assert MatPow(C, r).doit() == MatPow(C, r)
def test_doit_with_MatrixBase():
X = ImmutableMatrix([[1, 2], [3, 4]])
assert MatPow(X, 0).doit() == ImmutableMatrix(Identity(2))
assert MatPow(X, 1).doit() == X
assert MatPow(X, 2).doit() == X**2
assert MatPow(X, -1).doit() == X.inv()
assert MatPow(X, -2).doit() == (X.inv())**2
# less expensive than testing on a 2x2
assert MatPow(ImmutableMatrix([4]), S.Half).doit() == ImmutableMatrix([2])
X = ImmutableMatrix([[0, 2], [0, 4]]) # det() == 0
raises(ValueError, lambda: MatPow(X,-1).doit())
raises(ValueError, lambda: MatPow(X,-2).doit())
def test_doit_nonsquare():
X = ImmutableMatrix([[1, 2, 3], [4, 5, 6]])
assert MatPow(X, 1).doit() == X
raises(ShapeError, lambda: MatPow(X, 0).doit())
raises(ShapeError, lambda: MatPow(X, 2).doit())
raises(ShapeError, lambda: MatPow(X, -1).doit())
raises(ShapeError, lambda: MatPow(X, pi).doit())
def test_doit_equals_pow(): #17179
X = ImmutableMatrix ([[1,0],[0,1]])
assert MatPow(X, n).doit() == X**n == X
def test_doit_nested_MatrixExpr():
X = ImmutableMatrix([[1, 2], [3, 4]])
Y = ImmutableMatrix([[2, 3], [4, 5]])
assert MatPow(MatMul(X, Y), 2).doit() == (X*Y)**2
assert MatPow(MatAdd(X, Y), 2).doit() == (X + Y)**2
def test_identity_power():
k = Identity(n)
assert MatPow(k, 4).doit() == k
assert MatPow(k, n).doit() == k
assert MatPow(k, -3).doit() == k
assert MatPow(k, 0).doit() == k
l = Identity(3)
assert MatPow(l, n).doit() == l
assert MatPow(l, -1).doit() == l
assert MatPow(l, 0).doit() == l
def test_zero_power():
z1 = ZeroMatrix(n, n)
assert MatPow(z1, 3).doit() == z1
raises(ValueError, lambda:MatPow(z1, -1).doit())
assert MatPow(z1, 0).doit() == Identity(n)
assert MatPow(z1, n).doit() == z1
raises(ValueError, lambda:MatPow(z1, -2).doit())
z2 = ZeroMatrix(4, 4)
assert MatPow(z2, n).doit() == z2
raises(ValueError, lambda:MatPow(z2, -3).doit())
assert MatPow(z2, 2).doit() == z2
assert MatPow(z2, 0).doit() == Identity(4)
raises(ValueError, lambda:MatPow(z2, -1).doit())
def test_transpose_power():
from sympy.matrices.expressions.transpose import Transpose as TP
assert (C*D).T**5 == ((C*D)**5).T == (D.T * C.T)**5
assert ((C*D).T**5).T == (C*D)**5
assert (C.T.I.T)**7 == C**-7
assert (C.T**l).T**k == C**(l*k)
assert ((E.T * A.T)**5).T == (A*E)**5
assert ((A*E).T**5).T**7 == (A*E)**35
assert TP(TP(C**2 * D**3)**5).doit() == (C**2 * D**3)**5
assert ((D*C)**-5).T**-5 == ((D*C)**25).T
assert (((D*C)**l).T**k).T == (D*C)**(l*k)
|
e3291699da52c7a26fb1081b2190093736e2f97d3b6fb70e43597e60378efa2f | from sympy.combinatorics import Permutation
from sympy.core.expr import unchanged
from sympy.matrices import Matrix
from sympy.matrices.expressions import \
MatMul, BlockDiagMatrix, Determinant, Inverse
from sympy.matrices.expressions.matexpr import \
MatrixSymbol, Identity, ZeroMatrix, OneMatrix
from sympy.matrices.expressions.permutation import \
MatrixPermute, PermutationMatrix
from sympy.testing.pytest import raises
from sympy import Symbol
def test_PermutationMatrix_basic():
p = Permutation([1, 0])
assert unchanged(PermutationMatrix, p)
raises(ValueError, lambda: PermutationMatrix((0, 1, 2)))
assert PermutationMatrix(p).as_explicit() == Matrix([[0, 1], [1, 0]])
assert isinstance(PermutationMatrix(p)*MatrixSymbol('A', 2, 2), MatMul)
def test_PermutationMatrix_matmul():
p = Permutation([1, 2, 0])
P = PermutationMatrix(p)
M = Matrix([[0, 1, 2], [3, 4, 5], [6, 7, 8]])
assert (P*M).as_explicit() == P.as_explicit()*M
assert (M*P).as_explicit() == M*P.as_explicit()
P1 = PermutationMatrix(Permutation([1, 2, 0]))
P2 = PermutationMatrix(Permutation([2, 1, 0]))
P3 = PermutationMatrix(Permutation([1, 0, 2]))
assert P1*P2 == P3
def test_PermutationMatrix_matpow():
p1 = Permutation([1, 2, 0])
P1 = PermutationMatrix(p1)
p2 = Permutation([2, 0, 1])
P2 = PermutationMatrix(p2)
assert P1**2 == P2
assert P1**3 == Identity(3)
def test_PermutationMatrix_identity():
p = Permutation([0, 1])
assert PermutationMatrix(p).is_Identity
p = Permutation([1, 0])
assert not PermutationMatrix(p).is_Identity
def test_PermutationMatrix_determinant():
P = PermutationMatrix(Permutation([0, 1, 2]))
assert Determinant(P).doit() == 1
P = PermutationMatrix(Permutation([0, 2, 1]))
assert Determinant(P).doit() == -1
P = PermutationMatrix(Permutation([2, 0, 1]))
assert Determinant(P).doit() == 1
def test_PermutationMatrix_inverse():
P = PermutationMatrix(Permutation(0, 1, 2))
assert Inverse(P).doit() == PermutationMatrix(Permutation(0, 2, 1))
def test_PermutationMatrix_rewrite_BlockDiagMatrix():
P = PermutationMatrix(Permutation([0, 1, 2, 3, 4, 5]))
P0 = PermutationMatrix(Permutation([0]))
assert P.rewrite(BlockDiagMatrix) == \
BlockDiagMatrix(P0, P0, P0, P0, P0, P0)
P = PermutationMatrix(Permutation([0, 1, 3, 2, 4, 5]))
P10 = PermutationMatrix(Permutation(0, 1))
assert P.rewrite(BlockDiagMatrix) == \
BlockDiagMatrix(P0, P0, P10, P0, P0)
P = PermutationMatrix(Permutation([1, 0, 3, 2, 5, 4]))
assert P.rewrite(BlockDiagMatrix) == \
BlockDiagMatrix(P10, P10, P10)
P = PermutationMatrix(Permutation([0, 4, 3, 2, 1, 5]))
P3210 = PermutationMatrix(Permutation([3, 2, 1, 0]))
assert P.rewrite(BlockDiagMatrix) == \
BlockDiagMatrix(P0, P3210, P0)
P = PermutationMatrix(Permutation([0, 4, 2, 3, 1, 5]))
P3120 = PermutationMatrix(Permutation([3, 1, 2, 0]))
assert P.rewrite(BlockDiagMatrix) == \
BlockDiagMatrix(P0, P3120, P0)
P = PermutationMatrix(Permutation(0, 3)(1, 4)(2, 5))
assert P.rewrite(BlockDiagMatrix) == BlockDiagMatrix(P)
def test_MartrixPermute_basic():
p = Permutation(0, 1)
P = PermutationMatrix(p)
A = MatrixSymbol('A', 2, 2)
raises(ValueError, lambda: MatrixPermute(Symbol('x'), p))
raises(ValueError, lambda: MatrixPermute(A, Symbol('x')))
assert MatrixPermute(A, P) == MatrixPermute(A, p)
raises(ValueError, lambda: MatrixPermute(A, p, 2))
pp = Permutation(0, 1, size=3)
assert MatrixPermute(A, pp) == MatrixPermute(A, p)
pp = Permutation(0, 1, 2)
raises(ValueError, lambda: MatrixPermute(A, pp))
def test_MatrixPermute_shape():
p = Permutation(0, 1)
A = MatrixSymbol('A', 2, 3)
assert MatrixPermute(A, p).shape == (2, 3)
def test_MatrixPermute_explicit():
p = Permutation(0, 1, 2)
A = MatrixSymbol('A', 3, 3)
AA = A.as_explicit()
assert MatrixPermute(A, p, 0).as_explicit() == \
AA.permute(p, orientation='rows')
assert MatrixPermute(A, p, 1).as_explicit() == \
AA.permute(p, orientation='cols')
def test_MatrixPermute_rewrite_MatMul():
p = Permutation(0, 1, 2)
A = MatrixSymbol('A', 3, 3)
assert MatrixPermute(A, p, 0).rewrite(MatMul).as_explicit() == \
MatrixPermute(A, p, 0).as_explicit()
assert MatrixPermute(A, p, 1).rewrite(MatMul).as_explicit() == \
MatrixPermute(A, p, 1).as_explicit()
def test_MatrixPermute_doit():
p = Permutation(0, 1, 2)
A = MatrixSymbol('A', 3, 3)
assert MatrixPermute(A, p).doit() == MatrixPermute(A, p)
p = Permutation(0, size=3)
A = MatrixSymbol('A', 3, 3)
assert MatrixPermute(A, p).doit().as_explicit() == \
MatrixPermute(A, p).as_explicit()
p = Permutation(0, 1, 2)
A = Identity(3)
assert MatrixPermute(A, p, 0).doit().as_explicit() == \
MatrixPermute(A, p, 0).as_explicit()
assert MatrixPermute(A, p, 1).doit().as_explicit() == \
MatrixPermute(A, p, 1).as_explicit()
A = ZeroMatrix(3, 3)
assert MatrixPermute(A, p).doit() == A
A = OneMatrix(3, 3)
assert MatrixPermute(A, p).doit() == A
A = MatrixSymbol('A', 4, 4)
p1 = Permutation(0, 1, 2, 3)
p2 = Permutation(0, 2, 3, 1)
expr = MatrixPermute(MatrixPermute(A, p1, 0), p2, 0)
assert expr.as_explicit() == expr.doit().as_explicit()
expr = MatrixPermute(MatrixPermute(A, p1, 1), p2, 1)
assert expr.as_explicit() == expr.doit().as_explicit()
|
e951d0d206cce47ec4301d99fc90b7651f700ffcb36d47c062969e368bd0e511 | from sympy.core import S, symbols
from sympy.matrices import eye, Matrix, ShapeError
from sympy.matrices.expressions import (
Identity, MatrixExpr, MatrixSymbol, Determinant,
det, ZeroMatrix, Transpose
)
from sympy.matrices.expressions.matexpr import OneMatrix
from sympy.testing.pytest import raises
from sympy import refine, Q
n = symbols('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', 3, 4)
def test_det():
assert isinstance(Determinant(A), Determinant)
assert not isinstance(Determinant(A), MatrixExpr)
raises(ShapeError, lambda: Determinant(C))
assert det(eye(3)) == 1
assert det(Matrix(3, 3, [1, 3, 2, 4, 1, 3, 2, 5, 2])) == 17
A / det(A) # Make sure this is possible
raises(TypeError, lambda: Determinant(S.One))
assert Determinant(A).arg is A
def test_eval_determinant():
assert det(Identity(n)) == 1
assert det(ZeroMatrix(n, n)) == 0
assert det(OneMatrix(n, n)) == Determinant(OneMatrix(n, n))
assert det(OneMatrix(1, 1)) == 1
assert det(OneMatrix(2, 2)) == 0
assert det(Transpose(A)) == det(A)
def test_refine():
assert refine(det(A), Q.orthogonal(A)) == 1
assert refine(det(A), Q.singular(A)) == 0
|
c8ec8d2829aa140c45b6b36309d0e6db2429079baaae92f5c611de508d0c469b | from sympy import (KroneckerDelta, diff, Piecewise, Sum, Dummy, factor,
expand, zeros, gcd_terms, Eq, Symbol)
from sympy.core import S, symbols, Add, Mul, SympifyError, Rational
from sympy.core.expr import unchanged
from sympy.functions import transpose, sin, cos, sqrt, cbrt, exp
from sympy.simplify import simplify
from sympy.matrices import (Identity, ImmutableMatrix, Inverse, MatAdd, MatMul,
MatPow, Matrix, MatrixExpr, MatrixSymbol, ShapeError, ZeroMatrix,
SparseMatrix, Transpose, Adjoint)
from sympy.matrices.expressions.matexpr import (MatrixElement,
GenericZeroMatrix, GenericIdentity, OneMatrix)
from sympy.testing.pytest import raises, XFAIL
n, m, l, k, p = symbols('n m l k p', integer=True)
x = symbols('x')
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
E = MatrixSymbol('E', m, n)
w = MatrixSymbol('w', n, 1)
def test_matrix_symbol_creation():
assert MatrixSymbol('A', 2, 2)
assert MatrixSymbol('A', 0, 0)
raises(ValueError, lambda: MatrixSymbol('A', -1, 2))
raises(ValueError, lambda: MatrixSymbol('A', 2.0, 2))
raises(ValueError, lambda: MatrixSymbol('A', 2j, 2))
raises(ValueError, lambda: MatrixSymbol('A', 2, -1))
raises(ValueError, lambda: MatrixSymbol('A', 2, 2.0))
raises(ValueError, lambda: MatrixSymbol('A', 2, 2j))
n = symbols('n')
assert MatrixSymbol('A', n, n)
n = symbols('n', integer=False)
raises(ValueError, lambda: MatrixSymbol('A', n, n))
n = symbols('n', negative=True)
raises(ValueError, lambda: MatrixSymbol('A', n, n))
def test_zero_matrix_creation():
assert unchanged(ZeroMatrix, 2, 2)
assert unchanged(ZeroMatrix, 0, 0)
raises(ValueError, lambda: ZeroMatrix(-1, 2))
raises(ValueError, lambda: ZeroMatrix(2.0, 2))
raises(ValueError, lambda: ZeroMatrix(2j, 2))
raises(ValueError, lambda: ZeroMatrix(2, -1))
raises(ValueError, lambda: ZeroMatrix(2, 2.0))
raises(ValueError, lambda: ZeroMatrix(2, 2j))
n = symbols('n')
assert unchanged(ZeroMatrix, n, n)
n = symbols('n', integer=False)
raises(ValueError, lambda: ZeroMatrix(n, n))
n = symbols('n', negative=True)
raises(ValueError, lambda: ZeroMatrix(n, n))
def test_one_matrix_creation():
assert OneMatrix(2, 2)
assert OneMatrix(0, 0)
raises(ValueError, lambda: OneMatrix(-1, 2))
raises(ValueError, lambda: OneMatrix(2.0, 2))
raises(ValueError, lambda: OneMatrix(2j, 2))
raises(ValueError, lambda: OneMatrix(2, -1))
raises(ValueError, lambda: OneMatrix(2, 2.0))
raises(ValueError, lambda: OneMatrix(2, 2j))
n = symbols('n')
assert OneMatrix(n, n)
n = symbols('n', integer=False)
raises(ValueError, lambda: OneMatrix(n, n))
n = symbols('n', negative=True)
raises(ValueError, lambda: OneMatrix(n, n))
def test_identity_matrix_creation():
assert Identity(2)
assert Identity(0)
raises(ValueError, lambda: Identity(-1))
raises(ValueError, lambda: Identity(2.0))
raises(ValueError, lambda: Identity(2j))
n = symbols('n')
assert Identity(n)
n = symbols('n', integer=False)
raises(ValueError, lambda: Identity(n))
n = symbols('n', negative=True)
raises(ValueError, lambda: Identity(n))
def test_shape():
assert A.shape == (n, m)
assert (A*B).shape == (n, l)
raises(ShapeError, lambda: B*A)
def test_matexpr():
assert (x*A).shape == A.shape
assert (x*A).__class__ == MatMul
assert 2*A - A - A == ZeroMatrix(*A.shape)
assert (A*B).shape == (n, l)
def test_subs():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', m, l)
assert A.subs(n, m).shape == (m, m)
assert (A*B).subs(B, C) == A*C
assert (A*B).subs(l, n).is_square
def test_ZeroMatrix():
A = MatrixSymbol('A', n, m)
Z = ZeroMatrix(n, m)
assert A + Z == A
assert A*Z.T == ZeroMatrix(n, n)
assert Z*A.T == ZeroMatrix(n, n)
assert A - A == ZeroMatrix(*A.shape)
assert not Z
assert transpose(Z) == ZeroMatrix(m, n)
assert Z.conjugate() == Z
assert ZeroMatrix(n, n)**0 == Identity(n)
with raises(ShapeError):
Z**0
with raises(ShapeError):
Z**2
def test_ZeroMatrix_doit():
Znn = ZeroMatrix(Add(n, n, evaluate=False), n)
assert isinstance(Znn.rows, Add)
assert Znn.doit() == ZeroMatrix(2*n, n)
assert isinstance(Znn.doit().rows, Mul)
def test_OneMatrix():
A = MatrixSymbol('A', n, m)
a = MatrixSymbol('a', n, 1)
U = OneMatrix(n, m)
assert U.shape == (n, m)
assert isinstance(A + U, Add)
assert transpose(U) == OneMatrix(m, n)
assert U.conjugate() == U
assert OneMatrix(n, n) ** 0 == Identity(n)
with raises(ShapeError):
U ** 0
with raises(ShapeError):
U ** 2
with raises(ShapeError):
a + U
U = OneMatrix(n, n)
assert U[1, 2] == 1
U = OneMatrix(2, 3)
assert U.as_explicit() == ImmutableMatrix.ones(2, 3)
def test_OneMatrix_doit():
Unn = OneMatrix(Add(n, n, evaluate=False), n)
assert isinstance(Unn.rows, Add)
assert Unn.doit() == OneMatrix(2 * n, n)
assert isinstance(Unn.doit().rows, Mul)
def test_Identity():
A = MatrixSymbol('A', n, m)
i, j = symbols('i j')
In = Identity(n)
Im = Identity(m)
assert A*Im == A
assert In*A == A
assert transpose(In) == In
assert In.inverse() == In
assert In.conjugate() == In
assert In[i, j] != 0
assert Sum(In[i, j], (i, 0, n-1), (j, 0, n-1)).subs(n,3).doit() == 3
assert Sum(Sum(In[i, j], (i, 0, n-1)), (j, 0, n-1)).subs(n,3).doit() == 3
# If range exceeds the limit `(0, n-1)`, do not remove `Piecewise`:
expr = Sum(In[i, j], (i, 0, n-1))
assert expr.doit() == 1
expr = Sum(In[i, j], (i, 0, n-2))
assert expr.doit().dummy_eq(
Piecewise(
(1, (j >= 0) & (j <= n-2)),
(0, True)
)
)
expr = Sum(In[i, j], (i, 1, n-1))
assert expr.doit().dummy_eq(
Piecewise(
(1, (j >= 1) & (j <= n-1)),
(0, True)
)
)
def test_Identity_doit():
Inn = Identity(Add(n, n, evaluate=False))
assert isinstance(Inn.rows, Add)
assert Inn.doit() == Identity(2*n)
assert isinstance(Inn.doit().rows, Mul)
def test_addition():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, m)
assert isinstance(A + B, MatAdd)
assert (A + B).shape == A.shape
assert isinstance(A - A + 2*B, MatMul)
raises(ShapeError, lambda: A + B.T)
raises(TypeError, lambda: A + 1)
raises(TypeError, lambda: 5 + A)
raises(TypeError, lambda: 5 - A)
assert A + ZeroMatrix(n, m) - A == ZeroMatrix(n, m)
with raises(TypeError):
ZeroMatrix(n,m) + S.Zero
def test_multiplication():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
assert (2*A*B).shape == (n, l)
assert (A*0*B) == ZeroMatrix(n, l)
raises(ShapeError, lambda: B*A)
assert (2*A).shape == A.shape
assert A * ZeroMatrix(m, m) * B == ZeroMatrix(n, l)
assert C * Identity(n) * C.I == Identity(n)
assert B/2 == S.Half*B
raises(NotImplementedError, lambda: 2/B)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
assert Identity(n) * (A + B) == A + B
assert A**2*A == A**3
assert A**2*(A.I)**3 == A.I
assert A**3*(A.I)**2 == A
def test_MatPow():
A = MatrixSymbol('A', n, n)
AA = MatPow(A, 2)
assert AA.exp == 2
assert AA.base == A
assert (A**n).exp == n
assert A**0 == Identity(n)
assert A**1 == A
assert A**2 == AA
assert A**-1 == Inverse(A)
assert (A**-1)**-1 == A
assert (A**2)**3 == A**6
assert A**S.Half == sqrt(A)
assert A**Rational(1, 3) == cbrt(A)
raises(ShapeError, lambda: MatrixSymbol('B', 3, 2)**2)
def test_MatrixSymbol():
n, m, t = symbols('n,m,t')
X = MatrixSymbol('X', n, m)
assert X.shape == (n, m)
raises(TypeError, lambda: MatrixSymbol('X', n, m)(t)) # issue 5855
assert X.doit() == X
def test_dense_conversion():
X = MatrixSymbol('X', 2, 2)
assert ImmutableMatrix(X) == ImmutableMatrix(2, 2, lambda i, j: X[i, j])
assert Matrix(X) == Matrix(2, 2, lambda i, j: X[i, j])
def test_free_symbols():
assert (C*D).free_symbols == set((C, D))
def test_zero_matmul():
assert isinstance(S.Zero * MatrixSymbol('X', 2, 2), MatrixExpr)
def test_matadd_simplify():
A = MatrixSymbol('A', 1, 1)
assert simplify(MatAdd(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
MatAdd(A, Matrix([[1]]))
def test_matmul_simplify():
A = MatrixSymbol('A', 1, 1)
assert simplify(MatMul(A, ImmutableMatrix([[sin(x)**2 + cos(x)**2]]))) == \
MatMul(A, Matrix([[1]]))
def test_invariants():
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
X = MatrixSymbol('X', n, n)
objs = [Identity(n), ZeroMatrix(m, n), A, MatMul(A, B), MatAdd(A, A),
Transpose(A), Adjoint(A), Inverse(X), MatPow(X, 2), MatPow(X, -1),
MatPow(X, 0)]
for obj in objs:
assert obj == obj.__class__(*obj.args)
def test_indexing():
A = MatrixSymbol('A', n, m)
A[1, 2]
A[l, k]
A[l+1, k+1]
def test_single_indexing():
A = MatrixSymbol('A', 2, 3)
assert A[1] == A[0, 1]
assert A[int(1)] == A[0, 1]
assert A[3] == A[1, 0]
assert list(A[:2, :2]) == [A[0, 0], A[0, 1], A[1, 0], A[1, 1]]
raises(IndexError, lambda: A[6])
raises(IndexError, lambda: A[n])
B = MatrixSymbol('B', n, m)
raises(IndexError, lambda: B[1])
B = MatrixSymbol('B', n, 3)
assert B[3] == B[1, 0]
def test_MatrixElement_commutative():
assert A[0, 1]*A[1, 0] == A[1, 0]*A[0, 1]
def test_MatrixSymbol_determinant():
A = MatrixSymbol('A', 4, 4)
assert A.as_explicit().det() == A[0, 0]*A[1, 1]*A[2, 2]*A[3, 3] - \
A[0, 0]*A[1, 1]*A[2, 3]*A[3, 2] - A[0, 0]*A[1, 2]*A[2, 1]*A[3, 3] + \
A[0, 0]*A[1, 2]*A[2, 3]*A[3, 1] + A[0, 0]*A[1, 3]*A[2, 1]*A[3, 2] - \
A[0, 0]*A[1, 3]*A[2, 2]*A[3, 1] - A[0, 1]*A[1, 0]*A[2, 2]*A[3, 3] + \
A[0, 1]*A[1, 0]*A[2, 3]*A[3, 2] + A[0, 1]*A[1, 2]*A[2, 0]*A[3, 3] - \
A[0, 1]*A[1, 2]*A[2, 3]*A[3, 0] - A[0, 1]*A[1, 3]*A[2, 0]*A[3, 2] + \
A[0, 1]*A[1, 3]*A[2, 2]*A[3, 0] + A[0, 2]*A[1, 0]*A[2, 1]*A[3, 3] - \
A[0, 2]*A[1, 0]*A[2, 3]*A[3, 1] - A[0, 2]*A[1, 1]*A[2, 0]*A[3, 3] + \
A[0, 2]*A[1, 1]*A[2, 3]*A[3, 0] + A[0, 2]*A[1, 3]*A[2, 0]*A[3, 1] - \
A[0, 2]*A[1, 3]*A[2, 1]*A[3, 0] - A[0, 3]*A[1, 0]*A[2, 1]*A[3, 2] + \
A[0, 3]*A[1, 0]*A[2, 2]*A[3, 1] + A[0, 3]*A[1, 1]*A[2, 0]*A[3, 2] - \
A[0, 3]*A[1, 1]*A[2, 2]*A[3, 0] - A[0, 3]*A[1, 2]*A[2, 0]*A[3, 1] + \
A[0, 3]*A[1, 2]*A[2, 1]*A[3, 0]
def test_MatrixElement_diff():
assert (A[3, 0]*A[0, 0]).diff(A[0, 0]) == A[3, 0]
def test_MatrixElement_doit():
u = MatrixSymbol('u', 2, 1)
v = ImmutableMatrix([3, 5])
assert u[0, 0].subs(u, v).doit() == v[0, 0]
def test_identity_powers():
M = Identity(n)
assert MatPow(M, 3).doit() == M**3
assert M**n == M
assert MatPow(M, 0).doit() == M**2
assert M**-2 == M
assert MatPow(M, -2).doit() == M**0
N = Identity(3)
assert MatPow(N, 2).doit() == N**n
assert MatPow(N, 3).doit() == N
assert MatPow(N, -2).doit() == N**4
assert MatPow(N, 2).doit() == N**0
def test_Zero_power():
z1 = ZeroMatrix(n, n)
assert z1**4 == z1
raises(ValueError, lambda:z1**-2)
assert z1**0 == Identity(n)
assert MatPow(z1, 2).doit() == z1**2
raises(ValueError, lambda:MatPow(z1, -2).doit())
z2 = ZeroMatrix(3, 3)
assert MatPow(z2, 4).doit() == z2**4
raises(ValueError, lambda:z2**-3)
assert z2**3 == MatPow(z2, 3).doit()
assert z2**0 == Identity(3)
raises(ValueError, lambda:MatPow(z2, -1).doit())
def test_matrixelement_diff():
dexpr = diff((D*w)[k,0], w[p,0])
assert w[k, p].diff(w[k, p]) == 1
assert w[k, p].diff(w[0, 0]) == KroneckerDelta(0, k, (0, n-1))*KroneckerDelta(0, p, (0, 0))
_i_1 = Dummy("_i_1")
assert dexpr.dummy_eq(Sum(KroneckerDelta(_i_1, p, (0, n-1))*D[k, _i_1], (_i_1, 0, n - 1)))
assert dexpr.doit() == D[k, p]
def test_MatrixElement_with_values():
x, y, z, w = symbols("x y z w")
M = Matrix([[x, y], [z, w]])
i, j = symbols("i, j")
Mij = M[i, j]
assert isinstance(Mij, MatrixElement)
Ms = SparseMatrix([[2, 3], [4, 5]])
msij = Ms[i, j]
assert isinstance(msij, MatrixElement)
for oi, oj in [(0, 0), (0, 1), (1, 0), (1, 1)]:
assert Mij.subs({i: oi, j: oj}) == M[oi, oj]
assert msij.subs({i: oi, j: oj}) == Ms[oi, oj]
A = MatrixSymbol("A", 2, 2)
assert A[0, 0].subs(A, M) == x
assert A[i, j].subs(A, M) == M[i, j]
assert M[i, j].subs(M, A) == A[i, j]
assert isinstance(M[3*i - 2, j], MatrixElement)
assert M[3*i - 2, j].subs({i: 1, j: 0}) == M[1, 0]
assert isinstance(M[i, 0], MatrixElement)
assert M[i, 0].subs(i, 0) == M[0, 0]
assert M[0, i].subs(i, 1) == M[0, 1]
assert M[i, j].diff(x) == Matrix([[1, 0], [0, 0]])[i, j]
raises(ValueError, lambda: M[i, 2])
raises(ValueError, lambda: M[i, -1])
raises(ValueError, lambda: M[2, i])
raises(ValueError, lambda: M[-1, i])
def test_inv():
B = MatrixSymbol('B', 3, 3)
assert B.inv() == B**-1
@XFAIL
def test_factor_expand():
A = MatrixSymbol("A", n, n)
B = MatrixSymbol("B", n, n)
expr1 = (A + B)*(C + D)
expr2 = A*C + B*C + A*D + B*D
assert expr1 != expr2
assert expand(expr1) == expr2
assert factor(expr2) == expr1
expr = B**(-1)*(A**(-1)*B**(-1) - A**(-1)*C*B**(-1))**(-1)*A**(-1)
I = Identity(n)
# Ideally we get the first, but we at least don't want a wrong answer
assert factor(expr) in [I - C, B**-1*(A**-1*(I - C)*B**-1)**-1*A**-1]
def test_issue_2749():
A = MatrixSymbol("A", 5, 2)
assert (A.T * A).I.as_explicit() == Matrix([[(A.T * A).I[0, 0], (A.T * A).I[0, 1]], \
[(A.T * A).I[1, 0], (A.T * A).I[1, 1]]])
def test_issue_2750():
x = MatrixSymbol('x', 1, 1)
assert (x.T*x).as_explicit()**-1 == Matrix([[x[0, 0]**(-2)]])
def test_issue_7842():
A = MatrixSymbol('A', 3, 1)
B = MatrixSymbol('B', 2, 1)
assert Eq(A, B) == False
assert Eq(A[1,0], B[1, 0]).func is Eq
A = ZeroMatrix(2, 3)
B = ZeroMatrix(2, 3)
assert Eq(A, B) == True
def test_generic_zero_matrix():
z = GenericZeroMatrix()
A = MatrixSymbol("A", n, n)
assert z == z
assert z != A
assert A != z
assert z.is_ZeroMatrix
raises(TypeError, lambda: z.shape)
raises(TypeError, lambda: z.rows)
raises(TypeError, lambda: z.cols)
assert MatAdd() == z
assert MatAdd(z, A) == MatAdd(A)
# Make sure it is hashable
hash(z)
def test_generic_identity():
I = GenericIdentity()
A = MatrixSymbol("A", n, n)
assert I == I
assert I != A
assert A != I
assert I.is_Identity
assert I**-1 == I
raises(TypeError, lambda: I.shape)
raises(TypeError, lambda: I.rows)
raises(TypeError, lambda: I.cols)
assert MatMul() == I
assert MatMul(I, A) == MatMul(A)
# Make sure it is hashable
hash(I)
def test_MatMul_postprocessor():
z = zeros(2)
z1 = ZeroMatrix(2, 2)
assert Mul(0, z) == Mul(z, 0) in [z, z1]
M = Matrix([[1, 2], [3, 4]])
Mx = Matrix([[x, 2*x], [3*x, 4*x]])
assert Mul(x, M) == Mul(M, x) == Mx
A = MatrixSymbol("A", 2, 2)
assert Mul(A, M) == MatMul(A, M)
assert Mul(M, A) == MatMul(M, A)
# Scalars should be absorbed into constant matrices
a = Mul(x, M, A)
b = Mul(M, x, A)
c = Mul(M, A, x)
assert a == b == c == MatMul(Mx, A)
a = Mul(x, A, M)
b = Mul(A, x, M)
c = Mul(A, M, x)
assert a == b == c == MatMul(A, Mx)
assert Mul(M, M) == M**2
assert Mul(A, M, M) == MatMul(A, M**2)
assert Mul(M, M, A) == MatMul(M**2, A)
assert Mul(M, A, M) == MatMul(M, A, M)
assert Mul(A, x, M, M, x) == MatMul(A, Mx**2)
@XFAIL
def test_MatAdd_postprocessor_xfail():
# This is difficult to get working because of the way that Add processes
# its args.
z = zeros(2)
assert Add(z, S.NaN) == Add(S.NaN, z)
def test_MatAdd_postprocessor():
# Some of these are nonsensical, but we do not raise errors for Add
# because that breaks algorithms that want to replace matrices with dummy
# symbols.
z = zeros(2)
assert Add(0, z) == Add(z, 0) == z
a = Add(S.Infinity, z)
assert a == Add(z, S.Infinity)
assert isinstance(a, Add)
assert a.args == (S.Infinity, z)
a = Add(S.ComplexInfinity, z)
assert a == Add(z, S.ComplexInfinity)
assert isinstance(a, Add)
assert a.args == (S.ComplexInfinity, z)
a = Add(z, S.NaN)
# assert a == Add(S.NaN, z) # See the XFAIL above
assert isinstance(a, Add)
assert a.args == (S.NaN, z)
M = Matrix([[1, 2], [3, 4]])
a = Add(x, M)
assert a == Add(M, x)
assert isinstance(a, Add)
assert a.args == (x, M)
A = MatrixSymbol("A", 2, 2)
assert Add(A, M) == Add(M, A) == A + M
# Scalars should be absorbed into constant matrices (producing an error)
a = Add(x, M, A)
assert a == Add(M, x, A) == Add(M, A, x) == Add(x, A, M) == Add(A, x, M) == Add(A, M, x)
assert isinstance(a, Add)
assert a.args == (x, A + M)
assert Add(M, M) == 2*M
assert Add(M, A, M) == Add(M, M, A) == Add(A, M, M) == A + 2*M
a = Add(A, x, M, M, x)
assert isinstance(a, Add)
assert a.args == (2*x, A + 2*M)
def test_simplify_matrix_expressions():
# Various simplification functions
assert type(gcd_terms(C*D + D*C)) == MatAdd
a = gcd_terms(2*C*D + 4*D*C)
assert type(a) == MatMul
assert a.args == (2, (C*D + 2*D*C))
def test_exp():
A = MatrixSymbol('A', 2, 2)
B = MatrixSymbol('B', 2, 2)
expr1 = exp(A)*exp(B)
expr2 = exp(B)*exp(A)
assert expr1 != expr2
assert expr1 - expr2 != 0
assert not isinstance(expr1, exp)
assert not isinstance(expr2, exp)
def test_invalid_args():
raises(SympifyError, lambda: MatrixSymbol(1, 2, 'A'))
def test_matrixsymbol_from_symbol():
# The label should be preserved during doit and subs
A_label = Symbol('A', complex=True)
A = MatrixSymbol(A_label, 2, 2)
A_1 = A.doit()
A_2 = A.subs(2, 3)
assert A_1.args == A.args
assert A_2.args[0] == A.args[0]
|
96c120746904ae103035ac12f88463eab0a50f8c5cf0bfc4a6623594b72a0428 | from sympy import (symbols, MatrixSymbol, MatPow, BlockMatrix, KroneckerDelta,
Identity, ZeroMatrix, ImmutableMatrix, eye, Sum, Dummy, trace,
Symbol)
from sympy.testing.pytest import raises
from sympy.matrices.expressions.matexpr import MatrixElement, MatrixExpr
k, l, m, n = symbols('k l m n', integer=True)
i, j = symbols('i j', integer=True)
W = MatrixSymbol('W', k, l)
X = MatrixSymbol('X', l, m)
Y = MatrixSymbol('Y', l, m)
Z = MatrixSymbol('Z', m, n)
X1 = MatrixSymbol('X1', m, m)
X2 = MatrixSymbol('X2', m, m)
X3 = MatrixSymbol('X3', m, m)
X4 = MatrixSymbol('X4', m, m)
A = MatrixSymbol('A', 2, 2)
B = MatrixSymbol('B', 2, 2)
x = MatrixSymbol('x', 1, 2)
y = MatrixSymbol('x', 2, 1)
def test_symbolic_indexing():
x12 = X[1, 2]
assert all(s in str(x12) for s in ['1', '2', X.name])
# We don't care about the exact form of this. We do want to make sure
# that all of these features are present
def test_add_index():
assert (X + Y)[i, j] == X[i, j] + Y[i, j]
def test_mul_index():
assert (A*y)[0, 0] == A[0, 0]*y[0, 0] + A[0, 1]*y[1, 0]
assert (A*B).as_mutable() == (A.as_mutable() * B.as_mutable())
X = MatrixSymbol('X', n, m)
Y = MatrixSymbol('Y', m, k)
result = (X*Y)[4,2]
expected = Sum(X[4, i]*Y[i, 2], (i, 0, m - 1))
assert result.args[0].dummy_eq(expected.args[0], i)
assert result.args[1][1:] == expected.args[1][1:]
def test_pow_index():
Q = MatPow(A, 2)
assert Q[0, 0] == A[0, 0]**2 + A[0, 1]*A[1, 0]
n = symbols("n")
Q2 = A**n
assert Q2[0, 0] == MatrixElement(Q2, 0, 0)
def test_transpose_index():
assert X.T[i, j] == X[j, i]
def test_Identity_index():
I = Identity(3)
assert I[0, 0] == I[1, 1] == I[2, 2] == 1
assert I[1, 0] == I[0, 1] == I[2, 1] == 0
assert I[i, 0].delta_range == (0, 2)
raises(IndexError, lambda: I[3, 3])
def test_block_index():
I = Identity(3)
Z = ZeroMatrix(3, 3)
B = BlockMatrix([[I, I], [I, I]])
e3 = ImmutableMatrix(eye(3))
BB = BlockMatrix([[e3, e3], [e3, e3]])
assert B[0, 0] == B[3, 0] == B[0, 3] == B[3, 3] == 1
assert B[4, 3] == B[5, 1] == 0
BB = BlockMatrix([[e3, e3], [e3, e3]])
assert B.as_explicit() == BB.as_explicit()
BI = BlockMatrix([[I, Z], [Z, I]])
assert BI.as_explicit().equals(eye(6))
def test_slicing():
A.as_explicit()[0, :] # does not raise an error
def test_errors():
raises(IndexError, lambda: Identity(2)[1, 2, 3, 4, 5])
raises(IndexError, lambda: Identity(2)[[1, 2, 3, 4, 5]])
def test_matrix_expression_to_indices():
i, j = symbols("i, j")
i1, i2, i3 = symbols("i_1:4")
def replace_dummies(expr):
repl = {i: Symbol(i.name) for i in expr.atoms(Dummy)}
return expr.xreplace(repl)
expr = W*X*Z
assert replace_dummies(expr._entry(i, j)) == \
Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
expr = Z.T*X.T*W.T
assert replace_dummies(expr._entry(i, j)) == \
Sum(W[j, i2]*X[i2, i1]*Z[i1, i], (i1, 0, m-1), (i2, 0, l-1))
assert MatrixExpr.from_index_summation(expr._entry(i, j), i) == expr
expr = W*X*Z + W*Y*Z
assert replace_dummies(expr._entry(i, j)) == \
Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
expr = 2*W*X*Z + 3*W*Y*Z
assert replace_dummies(expr._entry(i, j)) == \
2*Sum(W[i, i1]*X[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1)) +\
3*Sum(W[i, i1]*Y[i1, i2]*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
expr = W*(X + Y)*Z
assert replace_dummies(expr._entry(i, j)) == \
Sum(W[i, i1]*(X[i1, i2] + Y[i1, i2])*Z[i2, j], (i1, 0, l-1), (i2, 0, m-1))
assert MatrixExpr.from_index_summation(expr._entry(i, j)) == expr
expr = A*B**2*A
#assert replace_dummies(expr._entry(i, j)) == \
# Sum(A[i, i1]*B[i1, i2]*B[i2, i3]*A[i3, j], (i1, 0, 1), (i2, 0, 1), (i3, 0, 1))
# Check that different dummies are used in sub-multiplications:
expr = (X1*X2 + X2*X1)*X3
assert replace_dummies(expr._entry(i, j)) == \
Sum((Sum(X1[i, i2] * X2[i2, i1], (i2, 0, m - 1)) + Sum(X1[i3, i1] * X2[i, i3], (i3, 0, m - 1))) * X3[
i1, j], (i1, 0, m - 1))
def test_matrix_expression_from_index_summation():
from sympy.abc import a,b,c,d
A = MatrixSymbol("A", k, k)
B = MatrixSymbol("B", k, k)
C = MatrixSymbol("C", k, k)
w1 = MatrixSymbol("w1", k, 1)
i0, i1, i2, i3, i4 = symbols("i0:5", cls=Dummy)
expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1))
assert MatrixExpr.from_index_summation(expr, a) == W*X*Z
expr = Sum(W.T[b,a]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m-1))
assert MatrixExpr.from_index_summation(expr, a) == W*X*Z
expr = Sum(A[b, a]*B[b, c]*C[c, d], (b, 0, k-1), (c, 0, k-1))
assert MatrixSymbol.from_index_summation(expr, a) == A.T*B*C
expr = Sum(A[b, a]*B[c, b]*C[c, d], (b, 0, k-1), (c, 0, k-1))
assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C
expr = Sum(C[c, d]*A[b, a]*B[c, b], (b, 0, k-1), (c, 0, k-1))
assert MatrixSymbol.from_index_summation(expr, a) == A.T*B.T*C
expr = Sum(A[a, b] + B[a, b], (a, 0, k-1), (b, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == A + B
expr = Sum((A[a, b] + B[a, b])*C[b, c], (b, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == (A+B)*C
expr = Sum((A[a, b] + B[b, a])*C[b, c], (b, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == (A+B.T)*C
expr = Sum(A[a, b]*A[b, c]*A[c, d], (b, 0, k-1), (c, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == A**3
expr = Sum(A[a, b]*A[b, c]*B[c, d], (b, 0, k-1), (c, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == A**2*B
# Parse the trace of a matrix:
expr = Sum(A[a, a], (a, 0, k-1))
assert MatrixExpr.from_index_summation(expr, None) == trace(A)
expr = Sum(A[a, a]*B[b, c]*C[c, d], (a, 0, k-1), (c, 0, k-1))
assert MatrixExpr.from_index_summation(expr, b) == trace(A)*B*C
# Check wrong sum ranges (should raise an exception):
## Case 1: 0 to m instead of 0 to m-1
expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 0, m))
raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a))
## Case 2: 1 to m-1 instead of 0 to m-1
expr = Sum(W[a,b]*X[b,c]*Z[c,d], (b, 0, l-1), (c, 1, m-1))
raises(ValueError, lambda: MatrixExpr.from_index_summation(expr, a))
# Parse nested sums:
expr = Sum(A[a, b]*Sum(B[b, c]*C[c, d], (c, 0, k-1)), (b, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == A*B*C
# Test Kronecker delta:
expr = Sum(A[a, b]*KroneckerDelta(b, c)*B[c, d], (b, 0, k-1), (c, 0, k-1))
assert MatrixExpr.from_index_summation(expr, a) == A*B
expr = Sum(KroneckerDelta(i1, m)*KroneckerDelta(i2, n)*A[i, i1]*A[j, i2], (i1, 0, k-1), (i2, 0, k-1))
assert MatrixExpr.from_index_summation(expr, m) == A.T*A[j, n]
# Test numbered indices:
expr = Sum(A[i1, i2]*w1[i2, 0], (i2, 0, k-1))
assert MatrixExpr.from_index_summation(expr, i1) == A*w1
expr = Sum(A[i1, i2]*B[i2, 0], (i2, 0, k-1))
assert MatrixExpr.from_index_summation(expr, i1) == MatrixElement(A*B, i1, 0)
|
664bf637aa113e6d3eb0de0f170b1516b33963faafe31da05aa410403f3a8416 | from sympy.core.expr import unchanged
from sympy.core.mul import Mul
from sympy.matrices import Matrix
from sympy.matrices.expressions.matexpr import MatrixSymbol
from sympy.matrices.expressions.dotproduct import DotProduct
from sympy.testing.pytest import raises
A = Matrix(3, 1, [1, 2, 3])
B = Matrix(3, 1, [1, 3, 5])
C = Matrix(4, 1, [1, 2, 4, 5])
D = Matrix(2, 2, [1, 2, 3, 4])
def test_docproduct():
assert DotProduct(A, B).doit() == 22
assert DotProduct(A.T, B).doit() == 22
assert DotProduct(A, B.T).doit() == 22
assert DotProduct(A.T, B.T).doit() == 22
raises(TypeError, lambda: DotProduct(1, A))
raises(TypeError, lambda: DotProduct(A, 1))
raises(TypeError, lambda: DotProduct(A, D))
raises(TypeError, lambda: DotProduct(D, A))
raises(TypeError, lambda: DotProduct(B, C).doit())
def test_dotproduct_symbolic():
A = MatrixSymbol('A', 3, 1)
B = MatrixSymbol('B', 3, 1)
dot = DotProduct(A, B)
assert dot.is_scalar == True
assert unchanged(Mul, 2, dot)
# XXX Fix forced evaluation for arithmetics with matrix expressions
assert dot * A == (A[0, 0]*B[0, 0] + A[1, 0]*B[1, 0] + A[2, 0]*B[2, 0])*A
|
0bb386010413cf4619c5909aee0d26f3fd01aaaf2368f45adb6247552a8aeed6 | from sympy.matrices.expressions.slice import MatrixSlice
from sympy.matrices.expressions import MatrixSymbol
from sympy.abc import a, b, c, d, k, l, m, n
from sympy.testing.pytest import raises, XFAIL
from sympy.functions.elementary.integers import floor
from sympy.assumptions import assuming, Q
X = MatrixSymbol('X', n, m)
Y = MatrixSymbol('Y', m, k)
def test_shape():
B = MatrixSlice(X, (a, b), (c, d))
assert B.shape == (b - a, d - c)
def test_entry():
B = MatrixSlice(X, (a, b), (c, d))
assert B[0,0] == X[a, c]
assert B[k,l] == X[a+k, c+l]
raises(IndexError, lambda : MatrixSlice(X, 1, (2, 5))[1, 0])
assert X[1::2, :][1, 3] == X[1+2, 3]
assert X[:, 1::2][3, 1] == X[3, 1+2]
def test_on_diag():
assert not MatrixSlice(X, (a, b), (c, d)).on_diag
assert MatrixSlice(X, (a, b), (a, b)).on_diag
def test_inputs():
assert MatrixSlice(X, 1, (2, 5)) == MatrixSlice(X, (1, 2), (2, 5))
assert MatrixSlice(X, 1, (2, 5)).shape == (1, 3)
def test_slicing():
assert X[1:5, 2:4] == MatrixSlice(X, (1, 5), (2, 4))
assert X[1, 2:4] == MatrixSlice(X, 1, (2, 4))
assert X[1:5, :].shape == (4, X.shape[1])
assert X[:, 1:5].shape == (X.shape[0], 4)
assert X[::2, ::2].shape == (floor(n/2), floor(m/2))
assert X[2, :] == MatrixSlice(X, 2, (0, m))
assert X[k, :] == MatrixSlice(X, k, (0, m))
def test_exceptions():
X = MatrixSymbol('x', 10, 20)
raises(IndexError, lambda: X[0:12, 2])
raises(IndexError, lambda: X[0:9, 22])
raises(IndexError, lambda: X[-1:5, 2])
@XFAIL
def test_symmetry():
X = MatrixSymbol('x', 10, 10)
Y = X[:5, 5:]
with assuming(Q.symmetric(X)):
assert Y.T == X[5:, :5]
def test_slice_of_slice():
X = MatrixSymbol('x', 10, 10)
assert X[2, :][:, 3][0, 0] == X[2, 3]
assert X[:5, :5][:4, :4] == X[:4, :4]
assert X[1:5, 2:6][1:3, 2] == X[2:4, 4]
assert X[1:9:2, 2:6][1:3, 2] == X[3:7:2, 4]
def test_negative_index():
X = MatrixSymbol('x', 10, 10)
assert X[-1, :] == X[9, :]
|
e2e15f2833082fd5582ae8ee01bb584bda2def9adda8f19585e1c8802d5ffaa3 | from sympy import S, I, ask, Q, Abs, simplify, exp, sqrt
from sympy.core.symbol import symbols
from sympy.matrices.expressions.fourier import DFT, IDFT
from sympy.matrices import det, Matrix, Identity
from sympy.testing.pytest import raises
def test_dft_creation():
assert DFT(2)
assert DFT(0)
raises(ValueError, lambda: DFT(-1))
raises(ValueError, lambda: DFT(2.0))
raises(ValueError, lambda: DFT(2 + 1j))
n = symbols('n')
assert DFT(n)
n = symbols('n', integer=False)
raises(ValueError, lambda: DFT(n))
n = symbols('n', negative=True)
raises(ValueError, lambda: DFT(n))
def test_dft():
n, i, j = symbols('n i j')
assert DFT(4).shape == (4, 4)
assert ask(Q.unitary(DFT(4)))
assert Abs(simplify(det(Matrix(DFT(4))))) == 1
assert DFT(n)*IDFT(n) == Identity(n)
assert DFT(n)[i, j] == exp(-2*S.Pi*I/n)**(i*j) / sqrt(n)
|
5e7279076384d1bcee39b3f9032da6fbe63f3ec83995863a85727151d3c8e997 | from sympy.matrices.expressions import MatrixSymbol
from sympy.matrices.expressions.diagonal import DiagonalMatrix, DiagonalOf, DiagMatrix, diagonalize_vector
from sympy import Symbol, ask, Q, KroneckerDelta, Identity, Matrix, MatMul
from sympy.testing.pytest import raises
n = Symbol('n')
m = Symbol('m')
def test_DiagonalMatrix():
x = MatrixSymbol('x', n, m)
D = DiagonalMatrix(x)
assert D.diagonal_length is None
assert D.shape == (n, m)
x = MatrixSymbol('x', n, n)
D = DiagonalMatrix(x)
assert D.diagonal_length == n
assert D.shape == (n, n)
assert D[1, 2] == 0
assert D[1, 1] == x[1, 1]
i = Symbol('i')
j = Symbol('j')
x = MatrixSymbol('x', 3, 3)
ij = DiagonalMatrix(x)[i, j]
assert ij != 0
assert ij.subs({i:0, j:0}) == x[0, 0]
assert ij.subs({i:0, j:1}) == 0
assert ij.subs({i:1, j:1}) == x[1, 1]
assert ask(Q.diagonal(D)) # affirm that D is diagonal
x = MatrixSymbol('x', n, 3)
D = DiagonalMatrix(x)
assert D.diagonal_length == 3
assert D.shape == (n, 3)
assert D[2, m] == KroneckerDelta(2, m)*x[2, m]
assert D[3, m] == 0
raises(IndexError, lambda: D[m, 3])
x = MatrixSymbol('x', 3, n)
D = DiagonalMatrix(x)
assert D.diagonal_length == 3
assert D.shape == (3, n)
assert D[m, 2] == KroneckerDelta(m, 2)*x[m, 2]
assert D[m, 3] == 0
raises(IndexError, lambda: D[3, m])
x = MatrixSymbol('x', n, m)
D = DiagonalMatrix(x)
assert D.diagonal_length is None
assert D.shape == (n, m)
assert D[m, 4] != 0
x = MatrixSymbol('x', 3, 4)
assert [DiagonalMatrix(x)[i] for i in range(12)] == [
x[0, 0], 0, 0, 0, 0, x[1, 1], 0, 0, 0, 0, x[2, 2], 0]
# shape is retained, issue 12427
assert (
DiagonalMatrix(MatrixSymbol('x', 3, 4))*
DiagonalMatrix(MatrixSymbol('x', 4, 2))).shape == (3, 2)
def test_DiagonalOf():
x = MatrixSymbol('x', n, n)
d = DiagonalOf(x)
assert d.shape == (n, 1)
assert d.diagonal_length == n
assert d[2, 0] == d[2] == x[2, 2]
x = MatrixSymbol('x', n, m)
d = DiagonalOf(x)
assert d.shape == (None, 1)
assert d.diagonal_length is None
assert d[2, 0] == d[2] == x[2, 2]
d = DiagonalOf(MatrixSymbol('x', 4, 3))
assert d.shape == (3, 1)
d = DiagonalOf(MatrixSymbol('x', n, 3))
assert d.shape == (3, 1)
d = DiagonalOf(MatrixSymbol('x', 3, n))
assert d.shape == (3, 1)
x = MatrixSymbol('x', n, m)
assert [DiagonalOf(x)[i] for i in range(4)] ==[
x[0, 0], x[1, 1], x[2, 2], x[3, 3]]
def test_DiagMatrix():
x = MatrixSymbol('x', n, 1)
d = DiagMatrix(x)
assert d.shape == (n, n)
assert d[0, 1] == 0
assert d[0, 0] == x[0, 0]
a = MatrixSymbol('a', 1, 1)
d = diagonalize_vector(a)
assert isinstance(d, MatrixSymbol)
assert a == d
assert diagonalize_vector(Identity(3)) == Identity(3)
assert DiagMatrix(Identity(3)).doit() == Identity(3)
assert isinstance(DiagMatrix(Identity(3)), DiagMatrix)
# A diagonal matrix is equal to its transpose:
assert DiagMatrix(x).T == DiagMatrix(x)
assert diagonalize_vector(x.T) == DiagMatrix(x)
dx = DiagMatrix(x)
assert dx[0, 0] == x[0, 0]
assert dx[1, 1] == x[1, 0]
assert dx[0, 1] == 0
assert dx[0, m] == x[0, 0]*KroneckerDelta(0, m)
z = MatrixSymbol('z', 1, n)
dz = DiagMatrix(z)
assert dz[0, 0] == z[0, 0]
assert dz[1, 1] == z[0, 1]
assert dz[0, 1] == 0
assert dz[0, m] == z[0, m]*KroneckerDelta(0, m)
v = MatrixSymbol('v', 3, 1)
dv = DiagMatrix(v)
assert dv.as_explicit() == Matrix([
[v[0, 0], 0, 0],
[0, v[1, 0], 0],
[0, 0, v[2, 0]],
])
v = MatrixSymbol('v', 1, 3)
dv = DiagMatrix(v)
assert dv.as_explicit() == Matrix([
[v[0, 0], 0, 0],
[0, v[0, 1], 0],
[0, 0, v[0, 2]],
])
dv = DiagMatrix(3*v)
assert dv.args == (3*v,)
assert dv.doit() == 3*DiagMatrix(v)
assert isinstance(dv.doit(), MatMul)
a = MatrixSymbol("a", 3, 1).as_explicit()
expr = DiagMatrix(a)
result = Matrix([
[a[0, 0], 0, 0],
[0, a[1, 0], 0],
[0, 0, a[2, 0]],
])
assert expr.doit() == result
expr = DiagMatrix(a.T)
assert expr.doit() == result
|
85c2ce1878e0da7405b81ffc3e99af7ac71a25449daa83584b0c8c9f2fd53cb9 | from sympy.core.symbol import symbols, Dummy
from sympy.matrices.expressions.applyfunc import ElementwiseApplyFunction
from sympy import Matrix, Lambda, MatrixSymbol, exp, MatMul, sin, simplify
from sympy.testing.pytest import raises
from sympy.matrices.common import ShapeError
X = MatrixSymbol("X", 3, 3)
Y = MatrixSymbol("Y", 3, 3)
k = symbols("k")
Xk = MatrixSymbol("X", k, k)
Xd = X.as_explicit()
x, y, z, t = symbols("x y z t")
def test_applyfunc_matrix():
x = Dummy('x')
double = Lambda(x, x**2)
expr = ElementwiseApplyFunction(double, Xd)
assert isinstance(expr, ElementwiseApplyFunction)
assert expr.doit() == Xd.applyfunc(lambda x: x**2)
assert expr.shape == (3, 3)
assert expr.func(*expr.args) == expr
assert simplify(expr) == expr
assert expr[0, 0] == double(Xd[0, 0])
expr = ElementwiseApplyFunction(double, X)
assert isinstance(expr, ElementwiseApplyFunction)
assert isinstance(expr.doit(), ElementwiseApplyFunction)
assert expr == X.applyfunc(double)
assert expr.func(*expr.args) == expr
expr = ElementwiseApplyFunction(exp, X*Y)
assert expr.expr == X*Y
assert expr.function == Lambda(x, exp(x))
assert expr == (X*Y).applyfunc(exp)
assert expr.func(*expr.args) == expr
assert isinstance(X*expr, MatMul)
assert (X*expr).shape == (3, 3)
Z = MatrixSymbol("Z", 2, 3)
assert (Z*expr).shape == (2, 3)
expr = ElementwiseApplyFunction(exp, Z.T)*ElementwiseApplyFunction(exp, Z)
assert expr.shape == (3, 3)
expr = ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z.T)
assert expr.shape == (2, 2)
raises(ShapeError, lambda: ElementwiseApplyFunction(exp, Z)*ElementwiseApplyFunction(exp, Z))
M = Matrix([[x, y], [z, t]])
expr = ElementwiseApplyFunction(sin, M)
assert isinstance(expr, ElementwiseApplyFunction)
assert expr.function == Lambda(x, sin(x))
assert expr.expr == M
assert expr.doit() == M.applyfunc(sin)
assert expr.doit() == Matrix([[sin(x), sin(y)], [sin(z), sin(t)]])
assert expr.func(*expr.args) == expr
expr = ElementwiseApplyFunction(double, Xk)
assert expr.doit() == expr
assert expr.subs(k, 2).shape == (2, 2)
assert (expr*expr).shape == (k, k)
M = MatrixSymbol("M", k, t)
expr2 = M.T*expr*M
assert isinstance(expr2, MatMul)
assert expr2.args[1] == expr
assert expr2.shape == (t, t)
expr3 = expr*M
assert expr3.shape == (k, t)
raises(ShapeError, lambda: M*expr)
expr1 = ElementwiseApplyFunction(lambda x: x+1, Xk)
expr2 = ElementwiseApplyFunction(lambda x: x, Xk)
assert expr1 != expr2
def test_applyfunc_entry():
af = X.applyfunc(sin)
assert af[0, 0] == sin(X[0, 0])
af = Xd.applyfunc(sin)
assert af[0, 0] == sin(X[0, 0])
def test_applyfunc_as_explicit():
af = X.applyfunc(sin)
assert af.as_explicit() == Matrix([
[sin(X[0, 0]), sin(X[0, 1]), sin(X[0, 2])],
[sin(X[1, 0]), sin(X[1, 1]), sin(X[1, 2])],
[sin(X[2, 0]), sin(X[2, 1]), sin(X[2, 2])],
])
|
7437f31335a6e451f29503d16a6ec6226ebebbf104f6883401111cd53c453f7c | from sympy.core import symbols, S
from sympy.matrices.expressions import MatrixSymbol, Inverse, MatPow
from sympy.matrices import eye, Identity, ShapeError
from sympy.testing.pytest import raises
from sympy import refine, Q
n, m, l = symbols('n m l', integer=True)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', m, l)
C = MatrixSymbol('C', n, n)
D = MatrixSymbol('D', n, n)
E = MatrixSymbol('E', m, n)
def test_inverse():
raises(ShapeError, lambda: Inverse(A))
raises(ShapeError, lambda: Inverse(A*B))
assert Inverse(C).args == (C, S.NegativeOne)
assert Inverse(C).shape == (n, n)
assert Inverse(A*E).shape == (n, n)
assert Inverse(E*A).shape == (m, m)
assert Inverse(C).inverse() == C
assert isinstance(Inverse(Inverse(C)), Inverse)
assert Inverse(*Inverse(E*A).args) == Inverse(E*A)
assert C.inverse().inverse() == C
assert C.inverse()*C == Identity(C.rows)
assert Identity(n).inverse() == Identity(n)
assert (3*Identity(n)).inverse() == Identity(n)/3
# Simplifies Muls if possible (i.e. submatrices are square)
assert (C*D).inverse() == D.I*C.I
# But still works when not possible
assert isinstance((A*E).inverse(), Inverse)
assert Inverse(C*D).doit(inv_expand=False) == Inverse(C*D)
assert Inverse(eye(3)).doit() == eye(3)
assert Inverse(eye(3)).doit(deep=False) == eye(3)
def test_refine():
assert refine(C.I, Q.orthogonal(C)) == C.T
def test_inverse_matpow_canonicalization():
A = MatrixSymbol('A', 3, 3)
assert Inverse(MatPow(A, 3)).doit() == MatPow(Inverse(A), 3).doit()
|
32b391a2571992682b96c33b2ec3ca01778157e93312b30673365f547b9b43ca | from sympy.core import Lambda, S, symbols
from sympy.concrete import Sum
from sympy.functions import adjoint, conjugate, transpose
from sympy.matrices import eye, Matrix, ShapeError, ImmutableMatrix
from sympy.matrices.expressions import (
Adjoint, Identity, FunctionMatrix, MatrixExpr, MatrixSymbol, Trace,
ZeroMatrix, trace, MatPow, MatAdd, MatMul
)
from sympy.matrices.expressions.matexpr import OneMatrix
from sympy.testing.pytest import raises
n = symbols('n', integer=True)
A = MatrixSymbol('A', n, n)
B = MatrixSymbol('B', n, n)
C = MatrixSymbol('C', 3, 4)
def test_Trace():
assert isinstance(Trace(A), Trace)
assert not isinstance(Trace(A), MatrixExpr)
raises(ShapeError, lambda: Trace(C))
assert trace(eye(3)) == 3
assert trace(Matrix(3, 3, [1, 2, 3, 4, 5, 6, 7, 8, 9])) == 15
assert adjoint(Trace(A)) == trace(Adjoint(A))
assert conjugate(Trace(A)) == trace(Adjoint(A))
assert transpose(Trace(A)) == Trace(A)
A / Trace(A) # Make sure this is possible
# Some easy simplifications
assert trace(Identity(5)) == 5
assert trace(ZeroMatrix(5, 5)) == 0
assert trace(OneMatrix(1, 1)) == 1
assert trace(OneMatrix(2, 2)) == 2
assert trace(OneMatrix(n, n)) == n
assert trace(2*A*B) == 2*Trace(A*B)
assert trace(A.T) == trace(A)
i, j = symbols('i j')
F = FunctionMatrix(3, 3, Lambda((i, j), i + j))
assert trace(F) == (0 + 0) + (1 + 1) + (2 + 2)
raises(TypeError, lambda: Trace(S.One))
assert Trace(A).arg is A
assert str(trace(A)) == str(Trace(A).doit())
assert Trace(A).is_commutative is True
def test_Trace_A_plus_B():
assert trace(A + B) == Trace(A) + Trace(B)
assert Trace(A + B).arg == MatAdd(A, B)
assert Trace(A + B).doit() == Trace(A) + Trace(B)
def test_Trace_MatAdd_doit():
# See issue #9028
X = ImmutableMatrix([[1, 2, 3]]*3)
Y = MatrixSymbol('Y', 3, 3)
q = MatAdd(X, 2*X, Y, -3*Y)
assert Trace(q).arg == q
assert Trace(q).doit() == 18 - 2*Trace(Y)
def test_Trace_MatPow_doit():
X = Matrix([[1, 2], [3, 4]])
assert Trace(X).doit() == 5
q = MatPow(X, 2)
assert Trace(q).arg == q
assert Trace(q).doit() == 29
def test_Trace_MutableMatrix_plus():
# See issue #9043
X = Matrix([[1, 2], [3, 4]])
assert Trace(X) + Trace(X) == 2*Trace(X)
def test_Trace_doit_deep_False():
X = Matrix([[1, 2], [3, 4]])
q = MatPow(X, 2)
assert Trace(q).doit(deep=False).arg == q
q = MatAdd(X, 2*X)
assert Trace(q).doit(deep=False).arg == q
q = MatMul(X, 2*X)
assert Trace(q).doit(deep=False).arg == q
def test_trace_constant_factor():
# Issue 9052: gave 2*Trace(MatMul(A)) instead of 2*Trace(A)
assert trace(2*A) == 2*Trace(A)
X = ImmutableMatrix([[1, 2], [3, 4]])
assert trace(MatMul(2, X)) == 10
def test_rewrite():
assert isinstance(trace(A).rewrite(Sum), Sum)
|
5bb9b284cb87eb757b15403288e7e5e64e5afe72caed8d9216aeda48b6256cef | from sympy import Identity, OneMatrix, ZeroMatrix, Matrix, MatAdd
from sympy.core import symbols
from sympy.testing.pytest import raises
from sympy.matrices import ShapeError, MatrixSymbol
from sympy.matrices.expressions import (HadamardProduct, hadamard_product, HadamardPower, hadamard_power)
n, m, k = symbols('n,m,k')
Z = MatrixSymbol('Z', n, n)
A = MatrixSymbol('A', n, m)
B = MatrixSymbol('B', n, m)
C = MatrixSymbol('C', m, k)
def test_HadamardProduct():
assert HadamardProduct(A, B, A).shape == A.shape
raises(ShapeError, lambda: HadamardProduct(A, B.T))
raises(TypeError, lambda: HadamardProduct(A, n))
raises(TypeError, lambda: HadamardProduct(A, 1))
assert HadamardProduct(A, 2*B, -A)[1, 1] == \
-2 * A[1, 1] * B[1, 1] * A[1, 1]
mix = HadamardProduct(Z*A, B)*C
assert mix.shape == (n, k)
assert set(HadamardProduct(A, B, A).T.args) == set((A.T, A.T, B.T))
def test_HadamardProduct_isnt_commutative():
assert HadamardProduct(A, B) != HadamardProduct(B, A)
def test_mixed_indexing():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
Z = MatrixSymbol('Z', 2, 2)
assert (X*HadamardProduct(Y, Z))[0, 0] == \
X[0, 0]*Y[0, 0]*Z[0, 0] + X[0, 1]*Y[1, 0]*Z[1, 0]
def test_canonicalize():
X = MatrixSymbol('X', 2, 2)
Y = MatrixSymbol('Y', 2, 2)
expr = HadamardProduct(X, check=False)
assert isinstance(expr, HadamardProduct)
expr2 = expr.doit() # unpack is called
assert isinstance(expr2, MatrixSymbol)
Z = ZeroMatrix(2, 2)
U = OneMatrix(2, 2)
assert HadamardProduct(Z, X).doit() == Z
assert HadamardProduct(U, X, X, U).doit() == HadamardPower(X, 2)
assert HadamardProduct(X, U, Y).doit() == HadamardProduct(X, Y)
assert HadamardProduct(X, Z, U, Y).doit() == Z
def test_hadamard():
m, n, p = symbols('m, n, p', integer=True)
A = MatrixSymbol('A', m, n)
B = MatrixSymbol('B', m, n)
C = MatrixSymbol('C', m, p)
X = MatrixSymbol('X', m, m)
I = Identity(m)
with raises(TypeError):
hadamard_product()
assert hadamard_product(A) == A
assert isinstance(hadamard_product(A, B), HadamardProduct)
assert hadamard_product(A, B).doit() == hadamard_product(A, B)
with raises(ShapeError):
hadamard_product(A, C)
hadamard_product(A, I)
assert hadamard_product(X, I) == X
assert isinstance(hadamard_product(X, I), MatrixSymbol)
a = MatrixSymbol("a", k, 1)
expr = MatAdd(ZeroMatrix(k, 1), OneMatrix(k, 1))
expr = HadamardProduct(expr, a)
assert expr.doit() == a
def test_hadamard_product_with_explicit_mat():
A = MatrixSymbol("A", 3, 3).as_explicit()
B = MatrixSymbol("B", 3, 3).as_explicit()
X = MatrixSymbol("X", 3, 3)
expr = hadamard_product(A, B)
ret = Matrix([i*j for i, j in zip(A, B)]).reshape(3, 3)
assert expr == ret
expr = hadamard_product(A, X, B)
assert expr == HadamardProduct(ret, X)
def test_hadamard_power():
m, n, p = symbols('m, n, p', integer=True)
A = MatrixSymbol('A', m, n)
assert hadamard_power(A, 1) == A
assert isinstance(hadamard_power(A, 2), HadamardPower)
assert hadamard_power(A, n).T == hadamard_power(A.T, n)
assert hadamard_power(A, n)[0, 0] == A[0, 0]**n
assert hadamard_power(m, n) == m**n
raises(ValueError, lambda: hadamard_power(A, A))
def test_hadamard_power_explicit():
from sympy.matrices import Matrix
A = MatrixSymbol('A', 2, 2)
B = MatrixSymbol('B', 2, 2)
a, b = symbols('a b')
assert HadamardPower(a, b) == a**b
assert HadamardPower(a, B).as_explicit() == \
Matrix([
[a**B[0, 0], a**B[0, 1]],
[a**B[1, 0], a**B[1, 1]]])
assert HadamardPower(A, b).as_explicit() == \
Matrix([
[A[0, 0]**b, A[0, 1]**b],
[A[1, 0]**b, A[1, 1]**b]])
assert HadamardPower(A, B).as_explicit() == \
Matrix([
[A[0, 0]**B[0, 0], A[0, 1]**B[0, 1]],
[A[1, 0]**B[1, 0], A[1, 1]**B[1, 1]]])
|
d2f9b606821ba4dcdb1e5d627e8af62a6b62d516bc5c41e8d92a8e1290093847 | from sympy import Min, Max, Set, Lambda, symbols, S, oo
from sympy.core import Basic, Expr, Integer
from sympy.core.numbers import Infinity, NegativeInfinity, Zero
from sympy.multipledispatch import dispatch
from sympy.sets import Interval, FiniteSet, Union, ImageSet
_x, _y = symbols("x y")
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_pow(x, y): # noqa:F811
return None
@dispatch(Set, Set) # type: ignore # noqa:F811
def _set_pow(x, y): # noqa:F811
return ImageSet(Lambda((_x, _y), (_x ** _y)), x, y)
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_pow(x, y): # noqa:F811
return x**y
@dispatch(Interval, Zero) # type: ignore # noqa:F811
def _set_pow(x, z): # noqa:F811
return FiniteSet(S.One)
@dispatch(Interval, Integer) # type: ignore # noqa:F811
def _set_pow(x, exponent): # noqa:F811
"""
Powers in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
s1 = x.start**exponent
s2 = x.end**exponent
if ((s2 > s1) if exponent > 0 else (x.end > -x.start)) == True:
left_open = x.left_open
right_open = x.right_open
# TODO: handle unevaluated condition.
sleft = s2
else:
# TODO: `s2 > s1` could be unevaluated.
left_open = x.right_open
right_open = x.left_open
sleft = s1
if x.start.is_positive:
return Interval(
Min(s1, s2),
Max(s1, s2), left_open, right_open)
elif x.end.is_negative:
return Interval(
Min(s1, s2),
Max(s1, s2), left_open, right_open)
# Case where x.start < 0 and x.end > 0:
if exponent.is_odd:
if exponent.is_negative:
if x.start.is_zero:
return Interval(s2, oo, x.right_open)
if x.end.is_zero:
return Interval(-oo, s1, True, x.left_open)
return Union(Interval(-oo, s1, True, x.left_open), Interval(s2, oo, x.right_open))
else:
return Interval(s1, s2, x.left_open, x.right_open)
elif exponent.is_even:
if exponent.is_negative:
if x.start.is_zero:
return Interval(s2, oo, x.right_open)
if x.end.is_zero:
return Interval(s1, oo, x.left_open)
return Interval(0, oo)
else:
return Interval(S.Zero, sleft, S.Zero not in x, left_open)
@dispatch(Interval, Infinity) # type: ignore # noqa:F811
def _set_pow(b, e): # noqa:F811
# TODO: add logic for open intervals?
if b.start.is_nonnegative:
if b.end < 1:
return FiniteSet(S.Zero)
if b.start > 1:
return FiniteSet(S.Infinity)
return Interval(0, oo)
elif b.end.is_negative:
if b.start > -1:
return FiniteSet(S.Zero)
if b.end < -1:
return FiniteSet(-oo, oo)
return Interval(-oo, oo)
else:
if b.start > -1:
if b.end < 1:
return FiniteSet(S.Zero)
return Interval(0, oo)
return Interval(-oo, oo)
@dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811
def _set_pow(b, e): # noqa:F811
from sympy.sets.setexpr import set_div
return _set_pow(set_div(S.One, b), oo)
|
c354e95dbb1d7d1158d48314f78dd2e485f6a2300b8a80abc7012eb188ed3fe7 | from sympy import (S, Dummy, Lambda, symbols, Interval, Intersection, Set,
EmptySet, FiniteSet, Union, ComplexRegion)
from sympy.multipledispatch import dispatch
from sympy.sets.conditionset import ConditionSet
from sympy.sets.fancysets import (Integers, Naturals, Reals, Range,
ImageSet, Rationals)
from sympy.sets.sets import UniversalSet, imageset, ProductSet
@dispatch(ConditionSet, ConditionSet) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return None
@dispatch(ConditionSet, Set) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return ConditionSet(a.sym, a.condition, Intersection(a.base_set, b))
@dispatch(Naturals, Integers) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a
@dispatch(Naturals, Naturals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a if a is S.Naturals else b
@dispatch(Interval, Naturals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return intersection_sets(b, a)
@dispatch(ComplexRegion, Set) # type: ignore # noqa:F811
def intersection_sets(self, other): # noqa:F811
if other.is_ComplexRegion:
# self in rectangular form
if (not self.polar) and (not other.polar):
return ComplexRegion(Intersection(self.sets, other.sets))
# self in polar form
elif self.polar and other.polar:
r1, theta1 = self.a_interval, self.b_interval
r2, theta2 = other.a_interval, other.b_interval
new_r_interval = Intersection(r1, r2)
new_theta_interval = Intersection(theta1, theta2)
# 0 and 2*Pi means the same
if ((2*S.Pi in theta1 and S.Zero in theta2) or
(2*S.Pi in theta2 and S.Zero in theta1)):
new_theta_interval = Union(new_theta_interval,
FiniteSet(0))
return ComplexRegion(new_r_interval*new_theta_interval,
polar=True)
if other.is_subset(S.Reals):
new_interval = []
x = symbols("x", cls=Dummy, real=True)
# self in rectangular form
if not self.polar:
for element in self.psets:
if S.Zero in element.args[1]:
new_interval.append(element.args[0])
new_interval = Union(*new_interval)
return Intersection(new_interval, other)
# self in polar form
elif self.polar:
for element in self.psets:
if S.Zero in element.args[1]:
new_interval.append(element.args[0])
if S.Pi in element.args[1]:
new_interval.append(ImageSet(Lambda(x, -x), element.args[0]))
if S.Zero in element.args[0]:
new_interval.append(FiniteSet(0))
new_interval = Union(*new_interval)
return Intersection(new_interval, other)
@dispatch(Integers, Reals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a
@dispatch(Range, Interval) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
from sympy.functions.elementary.integers import floor, ceiling
if not all(i.is_number for i in b.args[:2]):
return
# In case of null Range, return an EmptySet.
if a.size == 0:
return S.EmptySet
# trim down to self's size, and represent
# as a Range with step 1.
start = ceiling(max(b.inf, a.inf))
if start not in b:
start += 1
end = floor(min(b.sup, a.sup))
if end not in b:
end -= 1
return intersection_sets(a, Range(start, end + 1))
@dispatch(Range, Naturals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return intersection_sets(a, Interval(b.inf, S.Infinity))
@dispatch(Range, Range) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
from sympy.solvers.diophantine.diophantine import diop_linear
from sympy.core.numbers import ilcm
from sympy import sign
# non-overlap quick exits
if not b:
return S.EmptySet
if not a:
return S.EmptySet
if b.sup < a.inf:
return S.EmptySet
if b.inf > a.sup:
return S.EmptySet
# work with finite end at the start
r1 = a
if r1.start.is_infinite:
r1 = r1.reversed
r2 = b
if r2.start.is_infinite:
r2 = r2.reversed
# If both ends are infinite then it means that one Range is just the set
# of all integers (the step must be 1).
if r1.start.is_infinite:
return b
if r2.start.is_infinite:
return a
# this equation represents the values of the Range;
# it's a linear equation
eq = lambda r, i: r.start + i*r.step
# we want to know when the two equations might
# have integer solutions so we use the diophantine
# solver
va, vb = diop_linear(eq(r1, Dummy('a')) - eq(r2, Dummy('b')))
# check for no solution
no_solution = va is None and vb is None
if no_solution:
return S.EmptySet
# there is a solution
# -------------------
# find the coincident point, c
a0 = va.as_coeff_Add()[0]
c = eq(r1, a0)
# find the first point, if possible, in each range
# since c may not be that point
def _first_finite_point(r1, c):
if c == r1.start:
return c
# st is the signed step we need to take to
# get from c to r1.start
st = sign(r1.start - c)*step
# use Range to calculate the first point:
# we want to get as close as possible to
# r1.start; the Range will not be null since
# it will at least contain c
s1 = Range(c, r1.start + st, st)[-1]
if s1 == r1.start:
pass
else:
# if we didn't hit r1.start then, if the
# sign of st didn't match the sign of r1.step
# we are off by one and s1 is not in r1
if sign(r1.step) != sign(st):
s1 -= st
if s1 not in r1:
return
return s1
# calculate the step size of the new Range
step = abs(ilcm(r1.step, r2.step))
s1 = _first_finite_point(r1, c)
if s1 is None:
return S.EmptySet
s2 = _first_finite_point(r2, c)
if s2 is None:
return S.EmptySet
# replace the corresponding start or stop in
# the original Ranges with these points; the
# result must have at least one point since
# we know that s1 and s2 are in the Ranges
def _updated_range(r, first):
st = sign(r.step)*step
if r.start.is_finite:
rv = Range(first, r.stop, st)
else:
rv = Range(r.start, first + st, st)
return rv
r1 = _updated_range(a, s1)
r2 = _updated_range(b, s2)
# work with them both in the increasing direction
if sign(r1.step) < 0:
r1 = r1.reversed
if sign(r2.step) < 0:
r2 = r2.reversed
# return clipped Range with positive step; it
# can't be empty at this point
start = max(r1.start, r2.start)
stop = min(r1.stop, r2.stop)
return Range(start, stop, step)
@dispatch(Range, Integers) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a
@dispatch(ImageSet, Set) # type: ignore # noqa:F811
def intersection_sets(self, other): # noqa:F811
from sympy.solvers.diophantine import diophantine
# Only handle the straight-forward univariate case
if (len(self.lamda.variables) > 1
or self.lamda.signature != self.lamda.variables):
return None
base_set = self.base_sets[0]
# Intersection between ImageSets with Integers as base set
# For {f(n) : n in Integers} & {g(m) : m in Integers} we solve the
# diophantine equations f(n)=g(m).
# If the solutions for n are {h(t) : t in Integers} then we return
# {f(h(t)) : t in integers}.
# If the solutions for n are {n_1, n_2, ..., n_k} then we return
# {f(n_i) : 1 <= i <= k}.
if base_set is S.Integers:
gm = None
if isinstance(other, ImageSet) and other.base_sets == (S.Integers,):
gm = other.lamda.expr
var = other.lamda.variables[0]
# Symbol of second ImageSet lambda must be distinct from first
m = Dummy('m')
gm = gm.subs(var, m)
elif other is S.Integers:
m = gm = Dummy('m')
if gm is not None:
fn = self.lamda.expr
n = self.lamda.variables[0]
try:
solns = list(diophantine(fn - gm, syms=(n, m), permute=True))
except (TypeError, NotImplementedError):
# TypeError if equation not polynomial with rational coeff.
# NotImplementedError if correct format but no solver.
return
# 3 cases are possible for solns:
# - empty set,
# - one or more parametric (infinite) solutions,
# - a finite number of (non-parametric) solution couples.
# Among those, there is one type of solution set that is
# not helpful here: multiple parametric solutions.
if len(solns) == 0:
return EmptySet
elif any(not isinstance(s, int) and s.free_symbols
for tupl in solns for s in tupl):
if len(solns) == 1:
soln, solm = solns[0]
(t,) = soln.free_symbols
expr = fn.subs(n, soln.subs(t, n)).expand()
return imageset(Lambda(n, expr), S.Integers)
else:
return
else:
return FiniteSet(*(fn.subs(n, s[0]) for s in solns))
if other == S.Reals:
from sympy.solvers.solveset import solveset_real
from sympy.core.function import expand_complex
f = self.lamda.expr
n = self.lamda.variables[0]
n_ = Dummy(n.name, real=True)
f_ = f.subs(n, n_)
re, im = f_.as_real_imag()
im = expand_complex(im)
re = re.subs(n_, n)
im = im.subs(n_, n)
ifree = im.free_symbols
lam = Lambda(n, re)
if not im:
# allow re-evaluation
# of self in this case to make
# the result canonical
pass
elif im.is_zero is False:
return S.EmptySet
elif ifree != {n}:
return None
else:
# univarite imaginary part in same variable
base_set = base_set.intersect(solveset_real(im, n))
return imageset(lam, base_set)
elif isinstance(other, Interval):
from sympy.solvers.solveset import (invert_real, invert_complex,
solveset)
f = self.lamda.expr
n = self.lamda.variables[0]
new_inf, new_sup = None, None
new_lopen, new_ropen = other.left_open, other.right_open
if f.is_real:
inverter = invert_real
else:
inverter = invert_complex
g1, h1 = inverter(f, other.inf, n)
g2, h2 = inverter(f, other.sup, n)
if all(isinstance(i, FiniteSet) for i in (h1, h2)):
if g1 == n:
if len(h1) == 1:
new_inf = h1.args[0]
if g2 == n:
if len(h2) == 1:
new_sup = h2.args[0]
# TODO: Design a technique to handle multiple-inverse
# functions
# Any of the new boundary values cannot be determined
if any(i is None for i in (new_sup, new_inf)):
return
range_set = S.EmptySet
if all(i.is_real for i in (new_sup, new_inf)):
# this assumes continuity of underlying function
# however fixes the case when it is decreasing
if new_inf > new_sup:
new_inf, new_sup = new_sup, new_inf
new_interval = Interval(new_inf, new_sup, new_lopen, new_ropen)
range_set = base_set.intersect(new_interval)
else:
if other.is_subset(S.Reals):
solutions = solveset(f, n, S.Reals)
if not isinstance(range_set, (ImageSet, ConditionSet)):
range_set = solutions.intersect(other)
else:
return
if range_set is S.EmptySet:
return S.EmptySet
elif isinstance(range_set, Range) and range_set.size is not S.Infinity:
range_set = FiniteSet(*list(range_set))
if range_set is not None:
return imageset(Lambda(n, f), range_set)
return
else:
return
@dispatch(ProductSet, ProductSet) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
if len(b.args) != len(a.args):
return S.EmptySet
return ProductSet(*(i.intersect(j) for i, j in zip(a.sets, b.sets)))
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
# handle (-oo, oo)
infty = S.NegativeInfinity, S.Infinity
if a == Interval(*infty):
l, r = a.left, a.right
if l.is_real or l in infty or r.is_real or r in infty:
return b
# We can't intersect [0,3] with [x,6] -- we don't know if x>0 or x<0
if not a._is_comparable(b):
return None
empty = False
if a.start <= b.end and b.start <= a.end:
# Get topology right.
if a.start < b.start:
start = b.start
left_open = b.left_open
elif a.start > b.start:
start = a.start
left_open = a.left_open
else:
start = a.start
left_open = a.left_open or b.left_open
if a.end < b.end:
end = a.end
right_open = a.right_open
elif a.end > b.end:
end = b.end
right_open = b.right_open
else:
end = a.end
right_open = a.right_open or b.right_open
if end - start == 0 and (left_open or right_open):
empty = True
else:
empty = True
if empty:
return S.EmptySet
return Interval(start, end, left_open, right_open)
@dispatch(type(EmptySet), Set) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return S.EmptySet
@dispatch(UniversalSet, Set) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return b
@dispatch(FiniteSet, FiniteSet) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return FiniteSet(*(a._elements & b._elements))
@dispatch(FiniteSet, Set) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
try:
return FiniteSet(*[el for el in a if el in b])
except TypeError:
return None # could not evaluate `el in b` due to symbolic ranges.
@dispatch(Set, Set) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return None
@dispatch(Integers, Rationals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a
@dispatch(Naturals, Rationals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a
@dispatch(Rationals, Reals) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return a
def _intlike_interval(a, b):
try:
from sympy.functions.elementary.integers import floor, ceiling
if b._inf is S.NegativeInfinity and b._sup is S.Infinity:
return a
s = Range(max(a.inf, ceiling(b.left)), floor(b.right) + 1)
return intersection_sets(s, b) # take out endpoints if open interval
except ValueError:
return None
@dispatch(Integers, Interval) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return _intlike_interval(a, b)
@dispatch(Naturals, Interval) # type: ignore # noqa:F811
def intersection_sets(a, b): # noqa:F811
return _intlike_interval(a, b)
|
6dcc4c753b41f8ecf9dd90bf1182eb197ad0e13fef1f90a33e7890e4fe6f6fa7 |
from sympy import symbols, S, oo
from sympy.core import Basic, Expr
from sympy.core.numbers import Infinity, NegativeInfinity
from sympy.multipledispatch import dispatch
from sympy.sets import Interval, FiniteSet
# XXX: The functions in this module are clearly not tested and are broken in a
# number of ways.
_x, _y = symbols("x y")
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
return x+y
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
"""
Additions in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
return Interval(x.start + y.start, x.end + y.end,
x.left_open or y.left_open, x.right_open or y.right_open)
@dispatch(Interval, Infinity) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
if x.start is S.NegativeInfinity:
return Interval(-oo, oo)
return FiniteSet({S.Infinity})
@dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811
def _set_add(x, y): # noqa:F811
if x.end is S.Infinity:
return Interval(-oo, oo)
return FiniteSet({S.NegativeInfinity})
@dispatch(Basic, Basic) # type: ignore
def _set_sub(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
return x-y
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
"""
Subtractions in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
return Interval(x.start - y.end, x.end - y.start,
x.left_open or y.right_open, x.right_open or y.left_open)
@dispatch(Interval, Infinity) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
if x.start is S.NegativeInfinity:
return Interval(-oo, oo)
return FiniteSet(-oo)
@dispatch(Interval, NegativeInfinity) # type: ignore # noqa:F811
def _set_sub(x, y): # noqa:F811
if x.start is S.NegativeInfinity:
return Interval(-oo, oo)
return FiniteSet(-oo)
|
e9547782ecbdb4706f9cac4b96fe3247105af5acc4479e4c4bb75fbbbaed755b | from sympy import (Interval, Intersection, Set, EmptySet, S, sympify,
FiniteSet, Union, ComplexRegion, ProductSet)
from sympy.multipledispatch import dispatch
from sympy.sets.fancysets import (Naturals, Naturals0, Integers, Rationals,
Reals)
from sympy.sets.sets import UniversalSet
@dispatch(Naturals0, Naturals) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(Rationals, Naturals) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(Rationals, Naturals0) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(Reals, Naturals) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(Reals, Naturals0) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(Reals, Rationals) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(Integers, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
intersect = Intersection(a, b)
if intersect == a:
return b
elif intersect == b:
return a
@dispatch(ComplexRegion, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
if b.is_subset(S.Reals):
# treat a subset of reals as a complex region
b = ComplexRegion.from_real(b)
if b.is_ComplexRegion:
# a in rectangular form
if (not a.polar) and (not b.polar):
return ComplexRegion(Union(a.sets, b.sets))
# a in polar form
elif a.polar and b.polar:
return ComplexRegion(Union(a.sets, b.sets), polar=True)
return None
@dispatch(type(EmptySet), Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return b
@dispatch(UniversalSet, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return a
@dispatch(ProductSet, ProductSet) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
if b.is_subset(a):
return a
if len(b.sets) != len(a.sets):
return None
if len(a.sets) == 2:
a1, a2 = a.sets
b1, b2 = b.sets
if a1 == b1:
return a1 * Union(a2, b2)
if a2 == b2:
return Union(a1, b1) * a2
return None
@dispatch(ProductSet, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
if b.is_subset(a):
return a
return None
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
if a._is_comparable(b):
from sympy.functions.elementary.miscellaneous import Min, Max
# Non-overlapping intervals
end = Min(a.end, b.end)
start = Max(a.start, b.start)
if (end < start or
(end == start and (end not in a and end not in b))):
return None
else:
start = Min(a.start, b.start)
end = Max(a.end, b.end)
left_open = ((a.start != start or a.left_open) and
(b.start != start or b.left_open))
right_open = ((a.end != end or a.right_open) and
(b.end != end or b.right_open))
return Interval(start, end, left_open, right_open)
@dispatch(Interval, UniversalSet) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return S.UniversalSet
@dispatch(Interval, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
# If I have open end points and these endpoints are contained in b
# But only in case, when endpoints are finite. Because
# interval does not contain oo or -oo.
open_left_in_b_and_finite = (a.left_open and
sympify(b.contains(a.start)) is S.true and
a.start.is_finite)
open_right_in_b_and_finite = (a.right_open and
sympify(b.contains(a.end)) is S.true and
a.end.is_finite)
if open_left_in_b_and_finite or open_right_in_b_and_finite:
# Fill in my end points and return
open_left = a.left_open and a.start not in b
open_right = a.right_open and a.end not in b
new_a = Interval(a.start, a.end, open_left, open_right)
return set((new_a, b))
return None
@dispatch(FiniteSet, FiniteSet) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return FiniteSet(*(a._elements | b._elements))
@dispatch(FiniteSet, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
# If `b` set contains one of my elements, remove it from `a`
if any(b.contains(x) == True for x in a):
return set((
FiniteSet(*[x for x in a if b.contains(x) != True]), b))
return None
@dispatch(Set, Set) # type: ignore # noqa:F811
def union_sets(a, b): # noqa:F811
return None
|
10e43952a6ec8da2e502ab991847022c071a3dda6ac64635d895c70723922d36 | from sympy import Set, symbols, exp, log, S, Wild, Dummy, oo
from sympy.core import Expr, Add
from sympy.core.function import Lambda, _coeff_isneg, FunctionClass
from sympy.logic.boolalg import true
from sympy.multipledispatch import dispatch
from sympy.sets import (imageset, Interval, FiniteSet, Union, ImageSet,
EmptySet, Intersection, Range)
from sympy.sets.fancysets import Integers, Naturals, Reals
from sympy.functions.elementary.exponential import match_real_imag
_x, _y = symbols("x y")
FunctionUnion = (FunctionClass, Lambda)
@dispatch(FunctionClass, Set) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return None
@dispatch(FunctionUnion, FiniteSet) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return FiniteSet(*map(f, x))
@dispatch(Lambda, Interval) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
from sympy.functions.elementary.miscellaneous import Min, Max
from sympy.solvers.solveset import solveset
from sympy.core.function import diff, Lambda
from sympy.series import limit
from sympy.calculus.singularities import singularities
from sympy.sets import Complement
# TODO: handle functions with infinitely many solutions (eg, sin, tan)
# TODO: handle multivariate functions
expr = f.expr
if len(expr.free_symbols) > 1 or len(f.variables) != 1:
return
var = f.variables[0]
if not var.is_real:
if expr.subs(var, Dummy(real=True)).is_real is False:
return
if expr.is_Piecewise:
result = S.EmptySet
domain_set = x
for (p_expr, p_cond) in expr.args:
if p_cond is true:
intrvl = domain_set
else:
intrvl = p_cond.as_set()
intrvl = Intersection(domain_set, intrvl)
if p_expr.is_Number:
image = FiniteSet(p_expr)
else:
image = imageset(Lambda(var, p_expr), intrvl)
result = Union(result, image)
# remove the part which has been `imaged`
domain_set = Complement(domain_set, intrvl)
if domain_set is S.EmptySet:
break
return result
if not x.start.is_comparable or not x.end.is_comparable:
return
try:
sing = [i for i in singularities(expr, var)
if i.is_real and i in x]
except NotImplementedError:
return
if x.left_open:
_start = limit(expr, var, x.start, dir="+")
elif x.start not in sing:
_start = f(x.start)
if x.right_open:
_end = limit(expr, var, x.end, dir="-")
elif x.end not in sing:
_end = f(x.end)
if len(sing) == 0:
solns = list(solveset(diff(expr, var), var))
extr = [_start, _end] + [f(i) for i in solns
if i.is_real and i in x]
start, end = Min(*extr), Max(*extr)
left_open, right_open = False, False
if _start <= _end:
# the minimum or maximum value can occur simultaneously
# on both the edge of the interval and in some interior
# point
if start == _start and start not in solns:
left_open = x.left_open
if end == _end and end not in solns:
right_open = x.right_open
else:
if start == _end and start not in solns:
left_open = x.right_open
if end == _start and end not in solns:
right_open = x.left_open
return Interval(start, end, left_open, right_open)
else:
return imageset(f, Interval(x.start, sing[0],
x.left_open, True)) + \
Union(*[imageset(f, Interval(sing[i], sing[i + 1], True, True))
for i in range(0, len(sing) - 1)]) + \
imageset(f, Interval(sing[-1], x.end, True, x.right_open))
@dispatch(FunctionClass, Interval) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
if f == exp:
return Interval(exp(x.start), exp(x.end), x.left_open, x.right_open)
elif f == log:
return Interval(log(x.start), log(x.end), x.left_open, x.right_open)
return ImageSet(Lambda(_x, f(_x)), x)
@dispatch(FunctionUnion, Union) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return Union(*(imageset(f, arg) for arg in x.args))
@dispatch(FunctionUnion, Intersection) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
from sympy.sets.sets import is_function_invertible_in_set
# If the function is invertible, intersect the maps of the sets.
if is_function_invertible_in_set(f, x):
return Intersection(*(imageset(f, arg) for arg in x.args))
else:
return ImageSet(Lambda(_x, f(_x)), x)
@dispatch(FunctionUnion, type(EmptySet)) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return x
@dispatch(FunctionUnion, Set) # type: ignore # noqa:F811
def _set_function(f, x): # noqa:F811
return ImageSet(Lambda(_x, f(_x)), x)
@dispatch(FunctionUnion, Range) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
from sympy.core.function import expand_mul
if not self:
return S.EmptySet
if not isinstance(f.expr, Expr):
return
if self.size == 1:
return FiniteSet(f(self[0]))
if f is S.IdentityFunction:
return self
x = f.variables[0]
expr = f.expr
# handle f that is linear in f's variable
if x not in expr.free_symbols or x in expr.diff(x).free_symbols:
return
if self.start.is_finite:
F = f(self.step*x + self.start) # for i in range(len(self))
else:
F = f(-self.step*x + self[-1])
F = expand_mul(F)
if F != expr:
return imageset(x, F, Range(self.size))
@dispatch(FunctionUnion, Integers) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
expr = f.expr
if not isinstance(expr, Expr):
return
n = f.variables[0]
if expr == abs(n):
return S.Naturals0
# f(x) + c and f(-x) + c cover the same integers
# so choose the form that has the fewest negatives
c = f(0)
fx = f(n) - c
f_x = f(-n) - c
neg_count = lambda e: sum(_coeff_isneg(_) for _ in Add.make_args(e))
if neg_count(f_x) < neg_count(fx):
expr = f_x + c
a = Wild('a', exclude=[n])
b = Wild('b', exclude=[n])
match = expr.match(a*n + b)
if match and match[a]:
# canonical shift
a, b = match[a], match[b]
if a in [1, -1]:
# drop integer addends in b
nonint = []
for bi in Add.make_args(b):
if not bi.is_integer:
nonint.append(bi)
b = Add(*nonint)
if b.is_number and a.is_real:
# avoid Mod for complex numbers, #11391
br, bi = match_real_imag(b)
if br and br.is_comparable and a.is_comparable:
br %= a
b = br + S.ImaginaryUnit*bi
elif b.is_number and a.is_imaginary:
br, bi = match_real_imag(b)
ai = a/S.ImaginaryUnit
if bi and bi.is_comparable and ai.is_comparable:
bi %= ai
b = br + S.ImaginaryUnit*bi
expr = a*n + b
if expr != f.expr:
return ImageSet(Lambda(n, expr), S.Integers)
@dispatch(FunctionUnion, Naturals) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
expr = f.expr
if not isinstance(expr, Expr):
return
x = f.variables[0]
if not expr.free_symbols - {x}:
if expr == abs(x):
if self is S.Naturals:
return self
return S.Naturals0
step = expr.coeff(x)
c = expr.subs(x, 0)
if c.is_Integer and step.is_Integer and expr == step*x + c:
if self is S.Naturals:
c += step
if step > 0:
if step == 1:
if c == 0:
return S.Naturals0
elif c == 1:
return S.Naturals
return Range(c, oo, step)
return Range(c, -oo, step)
@dispatch(FunctionUnion, Reals) # type: ignore # noqa:F811
def _set_function(f, self): # noqa:F811
expr = f.expr
if not isinstance(expr, Expr):
return
return _set_function(f, Interval(-oo, oo))
|
e82c1bd2623c96ef402500a5ab553fc6b42673b04a031f1062f1f7a61ee21cc9 | from sympy import S, Symbol
from sympy.core.logic import fuzzy_and, fuzzy_bool, fuzzy_not, fuzzy_or
from sympy.core.relational import Eq
from sympy.sets.sets import FiniteSet, Interval, Set, Union
from sympy.sets.fancysets import Complexes, Reals, Range, Rationals
from sympy.multipledispatch import dispatch
_inf_sets = [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals, S.Complexes]
@dispatch(Set, Set) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return None
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
# This is correct but can be made more comprehensive...
if fuzzy_bool(a.start < b.start):
return False
if fuzzy_bool(a.end > b.end):
return False
if (b.left_open and not a.left_open and fuzzy_bool(Eq(a.start, b.start))):
return False
if (b.right_open and not a.right_open and fuzzy_bool(Eq(a.end, b.end))):
return False
@dispatch(Interval, FiniteSet) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_fs): # noqa:F811
# An Interval can only be a subset of a finite set if it is finite
# which can only happen if it has zero measure.
if fuzzy_not(a_interval.measure.is_zero):
return False
@dispatch(Interval, Union) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_u): # noqa:F811
if all(isinstance(s, (Interval, FiniteSet)) for s in b_u.args):
intervals = [s for s in b_u.args if isinstance(s, Interval)]
if all(fuzzy_bool(a_interval.start < s.start) for s in intervals):
return False
if all(fuzzy_bool(a_interval.end > s.end) for s in intervals):
return False
if a_interval.measure.is_nonzero:
no_overlap = lambda s1, s2: fuzzy_or([
fuzzy_bool(s1.end <= s2.start),
fuzzy_bool(s1.start >= s2.end),
])
if all(no_overlap(s, a_interval) for s in intervals):
return False
@dispatch(Range, Range) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
if a.step == b.step == 1:
return fuzzy_and([fuzzy_bool(a.start >= b.start),
fuzzy_bool(a.stop <= b.stop)])
@dispatch(Range, Interval) # type: ignore # noqa:F811
def is_subset_sets(a_range, b_interval): # noqa:F811
if a_range.step.is_positive:
if b_interval.left_open and a_range.inf.is_finite:
cond_left = a_range.inf > b_interval.left
else:
cond_left = a_range.inf >= b_interval.left
if b_interval.right_open and a_range.sup.is_finite:
cond_right = a_range.sup < b_interval.right
else:
cond_right = a_range.sup <= b_interval.right
return fuzzy_and([cond_left, cond_right])
@dispatch(Range, FiniteSet) # type: ignore # noqa:F811
def is_subset_sets(a_range, b_finiteset): # noqa:F811
try:
a_size = a_range.size
except ValueError:
# symbolic Range of unknown size
return None
if a_size > len(b_finiteset):
return False
elif any(arg.has(Symbol) for arg in a_range.args):
return fuzzy_and(b_finiteset.contains(x) for x in a_range)
else:
# Checking A \ B == EmptySet is more efficient than repeated naive
# membership checks on an arbitrary FiniteSet.
a_set = set(a_range)
b_remaining = len(b_finiteset)
# Symbolic expressions and numbers of unknown type (integer or not) are
# all counted as "candidates", i.e. *potentially* matching some a in
# a_range.
cnt_candidate = 0
for b in b_finiteset:
if b.is_Integer:
a_set.discard(b)
elif fuzzy_not(b.is_integer):
pass
else:
cnt_candidate += 1
b_remaining -= 1
if len(a_set) > b_remaining + cnt_candidate:
return False
if len(a_set) == 0:
return True
return None
@dispatch(Interval, Range) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_range): # noqa:F811
if a_interval.measure.is_extended_nonzero:
return False
@dispatch(Interval, Rationals) # type: ignore # noqa:F811
def is_subset_sets(a_interval, b_rationals): # noqa:F811
if a_interval.measure.is_extended_nonzero:
return False
@dispatch(Range, Complexes) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return True
@dispatch(Complexes, Interval) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(Complexes, Range) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(Complexes, Rationals) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
@dispatch(Rationals, Reals) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return True
@dispatch(Rationals, Range) # type: ignore # noqa:F811
def is_subset_sets(a, b): # noqa:F811
return False
|
f57de7d5abbb2d75d4ab838921b39b025f996ae30f028fde84bc8dcef22babc9 | from sympy import Set, symbols
from sympy.core import Basic, Expr
from sympy.multipledispatch import dispatch
from sympy.sets import Interval
_x, _y = symbols("x y")
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
return None
@dispatch(Set, Set) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
return x*y
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_mul(x, y): # noqa:F811
"""
Multiplications in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
# TODO: some intervals containing 0 and oo will fail as 0*oo returns nan.
comvals = (
(x.start * y.start, bool(x.left_open or y.left_open)),
(x.start * y.end, bool(x.left_open or y.right_open)),
(x.end * y.start, bool(x.right_open or y.left_open)),
(x.end * y.end, bool(x.right_open or y.right_open)),
)
# TODO: handle symbolic intervals
minval, minopen = min(comvals)
maxval, maxopen = max(comvals)
return Interval(
minval,
maxval,
minopen,
maxopen
)
@dispatch(Basic, Basic) # type: ignore # noqa:F811
def _set_div(x, y): # noqa:F811
return None
@dispatch(Expr, Expr) # type: ignore # noqa:F811
def _set_div(x, y): # noqa:F811
return x/y
@dispatch(Set, Set) # type: ignore # noqa:F811 # noqa:F811
def _set_div(x, y): # noqa:F811
return None
@dispatch(Interval, Interval) # type: ignore # noqa:F811
def _set_div(x, y): # noqa:F811
"""
Divisions in interval arithmetic
https://en.wikipedia.org/wiki/Interval_arithmetic
"""
from sympy.sets.setexpr import set_mul
from sympy import oo
if (y.start*y.end).is_negative:
return Interval(-oo, oo)
if y.start == 0:
s2 = oo
else:
s2 = 1/y.start
if y.end == 0:
s1 = -oo
else:
s1 = 1/y.end
return set_mul(x, Interval(s1, s2, y.right_open, y.left_open))
|
786cce62e164b4381dce9751ded594de4ff01ddac92754d73012ff4d2e16922d | from sympy.sets import (ConditionSet, Intersection, FiniteSet,
EmptySet, Union, Contains)
from sympy import (Symbol, Eq, S, Abs, sin, pi, Interval,
And, Mod, oo, Function)
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
w = Symbol('w')
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
L = Symbol('lambda')
f = Function('f')
def test_CondSet():
sin_sols_principal = ConditionSet(x, Eq(sin(x), 0),
Interval(0, 2*pi, False, True))
assert pi in sin_sols_principal
assert pi/2 not in sin_sols_principal
assert 3*pi not in sin_sols_principal
assert 5 in ConditionSet(x, x**2 > 4, S.Reals)
assert 1 not in ConditionSet(x, x**2 > 4, S.Reals)
# in this case, 0 is not part of the base set so
# it can't be in any subset selected by the condition
assert 0 not in ConditionSet(x, y > 5, Interval(1, 7))
# since 'in' requires a true/false, the following raises
# an error because the given value provides no information
# for the condition to evaluate (since the condition does
# not depend on the dummy symbol): the result is `y > 5`.
# In this case, ConditionSet is just acting like
# Piecewise((Interval(1, 7), y > 5), (S.EmptySet, True)).
raises(TypeError, lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7)))
assert isinstance(ConditionSet(x, x < 1, {x, y}).base_set, FiniteSet)
raises(TypeError, lambda: ConditionSet(x, x + 1, {x, y}))
raises(TypeError, lambda: ConditionSet(x, x, 1))
I = S.Integers
C = ConditionSet
assert C(x, x < 1, C(x, x < 2, I)
) == C(x, (x < 1) & (x < 2), I)
assert C(y, y < 1, C(x, y < 2, I)
) == C(x, (x < 1) & (y < 2), I)
assert C(y, y < 1, C(x, x < 2, I)
) == C(y, (y < 1) & (y < 2), I)
assert C(y, y < 1, C(x, y < x, I)
) == C(x, (x < 1) & (y < x), I)
assert C(y, x < 1, C(x, y < x, I)
) == C(L, (x < 1) & (y < L), I)
c = C(y, x < 1, C(x, L < y, I))
assert c == C(c.sym, (L < y) & (x < 1), I)
assert c.sym not in (x, y, L)
c = C(y, x < 1, C(x, y < x, FiniteSet(L)))
assert c == C(L, And(x < 1, y < L), FiniteSet(L))
def test_CondSet_intersect():
input_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 4, False, False))
other_domain = Interval(0, 3, False, False)
output_conditionset = ConditionSet(x, x**2 > 4, Interval(1, 3, False, False))
assert Intersection(input_conditionset, other_domain) == output_conditionset
def test_issue_9849():
assert ConditionSet(x, Eq(x, x), S.Naturals) == S.Naturals
assert ConditionSet(x, Eq(Abs(sin(x)), -1), S.Naturals) == S.EmptySet
def test_simplified_FiniteSet_in_CondSet():
assert ConditionSet(x, And(x < 1, x > -3), FiniteSet(0, 1, 2)) == FiniteSet(0)
assert ConditionSet(x, x < 0, FiniteSet(0, 1, 2)) == EmptySet
assert ConditionSet(x, And(x < -3), EmptySet) == EmptySet
y = Symbol('y')
assert (ConditionSet(x, And(x > 0), FiniteSet(-1, 0, 1, y)) ==
Union(FiniteSet(1), ConditionSet(x, And(x > 0), FiniteSet(y))))
assert (ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(1, 4, 2, y)) ==
Union(FiniteSet(1, 4), ConditionSet(x, Eq(Mod(x, 3), 1), FiniteSet(y))))
def test_free_symbols():
assert ConditionSet(x, Eq(y, 0), FiniteSet(z)
).free_symbols == {y, z}
assert ConditionSet(x, Eq(x, 0), FiniteSet(z)
).free_symbols == {z}
assert ConditionSet(x, Eq(x, 0), FiniteSet(x, z)
).free_symbols == {x, z}
def test_subs_CondSet():
s = FiniteSet(z, y)
c = ConditionSet(x, x < 2, s)
# you can only replace sym with a symbol that is not in
# the free symbols
assert c.subs(x, 1) == c
assert c.subs(x, y) == ConditionSet(y, y < 2, s)
# double subs needed to change dummy if the base set
# also contains the dummy
orig = ConditionSet(y, y < 2, s)
base = orig.subs(y, w)
and_dummy = base.subs(y, w)
assert base == ConditionSet(y, y < 2, {w, z})
assert and_dummy == ConditionSet(w, w < 2, {w, z})
assert c.subs(x, w) == ConditionSet(w, w < 2, s)
assert ConditionSet(x, x < y, s
).subs(y, w) == ConditionSet(x, x < w, s.subs(y, w))
# if the user uses assumptions that cause the condition
# to evaluate, that can't be helped from SymPy's end
n = Symbol('n', negative=True)
assert ConditionSet(n, 0 < n, S.Integers) is S.EmptySet
p = Symbol('p', positive=True)
assert ConditionSet(n, n < y, S.Integers
).subs(n, x) == ConditionSet(x, x < y, S.Integers)
nc = Symbol('nc', commutative=False)
raises(ValueError, lambda: ConditionSet(
x, x < p, S.Integers).subs(x, nc))
raises(ValueError, lambda: ConditionSet(
x, x < p, S.Integers).subs(x, n))
raises(ValueError, lambda: ConditionSet(
x + 1, x < 1, S.Integers))
raises(ValueError, lambda: ConditionSet(
x + 1, x < 1, s))
assert ConditionSet(
n, n < x, Interval(0, oo)).subs(x, p) == Interval(0, oo)
assert ConditionSet(
n, n < x, Interval(-oo, 0)).subs(x, p) == S.EmptySet
assert ConditionSet(f(x), f(x) < 1, {w, z}
).subs(f(x), y) == ConditionSet(y, y < 1, {w, z})
def test_subs_CondSet_tebr():
with warns_deprecated_sympy():
assert ConditionSet((x, y), {x + 1, x + y}, S.Reals) == \
ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)
c = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)
assert c.subs(x, z) == c
def test_dummy_eq():
C = ConditionSet
I = S.Integers
c = C(x, x < 1, I)
assert c.dummy_eq(C(y, y < 1, I))
assert c.dummy_eq(1) == False
assert c.dummy_eq(C(x, x < 1, S.Reals)) == False
raises(ValueError, lambda: c.dummy_eq(C(x, x < 1, S.Reals), z))
c1 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)
c2 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Reals)
c3 = ConditionSet((x, y), Eq(x + 1, 0) & Eq(x + y, 0), S.Complexes)
assert c1.dummy_eq(c2)
assert c1.dummy_eq(c3) is False
assert c.dummy_eq(c1) is False
assert c1.dummy_eq(c) is False
def test_contains():
assert 6 in ConditionSet(x, x > 5, Interval(1, 7))
assert (8 in ConditionSet(x, y > 5, Interval(1, 7))) is False
# `in` should give True or False; in this case there is not
# enough information for that result
raises(TypeError,
lambda: 6 in ConditionSet(x, y > 5, Interval(1, 7)))
assert ConditionSet(x, y > 5, Interval(1, 7)
).contains(6) == (y > 5)
assert ConditionSet(x, y > 5, Interval(1, 7)
).contains(8) is S.false
assert ConditionSet(x, y > 5, Interval(1, 7)
).contains(w) == And(Contains(w, Interval(1, 7)), y > 5)
@XFAIL
def test_failing_contains():
# XXX This may have to return unevaluated Contains object
# because 1/0 should not be defined for 1 and 0 in the context of
# reals, but there is a nonsensical evaluation to ComplexInfinity
# and the comparison is giving an error.
assert ConditionSet(x, 1/x >= 0, S.Reals).contains(0) == \
Contains(0, ConditionSet(x, 1/x >= 0, S.Reals), evaluate=False)
|
27fa526da5586d528fc625b1dd38eda9429729b9021642489413a65acc45dc7d | from sympy.sets.setexpr import SetExpr
from sympy.sets import Interval, FiniteSet, Intersection, ImageSet, Union
from sympy import (Expr, Set, exp, log, cos, Symbol, Min, Max, S, oo, I,
symbols, Lambda, Dummy, Rational)
a, x = symbols("a, x")
_d = Dummy("d")
def test_setexpr():
se = SetExpr(Interval(0, 1))
assert isinstance(se.set, Set)
assert isinstance(se, Expr)
def test_scalar_funcs():
assert SetExpr(Interval(0, 1)).set == Interval(0, 1)
a, b = Symbol('a', real=True), Symbol('b', real=True)
a, b = 1, 2
# TODO: add support for more functions in the future:
for f in [exp, log]:
input_se = f(SetExpr(Interval(a, b)))
output = input_se.set
expected = Interval(Min(f(a), f(b)), Max(f(a), f(b)))
assert output == expected
def test_Add_Mul():
assert (SetExpr(Interval(0, 1)) + 1).set == Interval(1, 2)
assert (SetExpr(Interval(0, 1))*2).set == Interval(0, 2)
def test_Pow():
assert (SetExpr(Interval(0, 2))**2).set == Interval(0, 4)
def test_compound():
assert (exp(SetExpr(Interval(0, 1))*2 + 1)).set == \
Interval(exp(1), exp(3))
def test_Interval_Interval():
assert (SetExpr(Interval(1, 2)) + SetExpr(Interval(10, 20))).set == \
Interval(11, 22)
assert (SetExpr(Interval(1, 2))*SetExpr(Interval(10, 20))).set == \
Interval(10, 40)
def test_FiniteSet_FiniteSet():
assert (SetExpr(FiniteSet(1, 2, 3)) + SetExpr(FiniteSet(1, 2))).set == \
FiniteSet(2, 3, 4, 5)
assert (SetExpr(FiniteSet(1, 2, 3))*SetExpr(FiniteSet(1, 2))).set == \
FiniteSet(1, 2, 3, 4, 6)
def test_Interval_FiniteSet():
assert (SetExpr(FiniteSet(1, 2)) + SetExpr(Interval(0, 10))).set == \
Interval(1, 12)
def test_Many_Sets():
assert (SetExpr(Interval(0, 1)) +
SetExpr(Interval(2, 3)) +
SetExpr(FiniteSet(10, 11, 12))).set == Interval(12, 16)
def test_same_setexprs_are_not_identical():
a = SetExpr(FiniteSet(0, 1))
b = SetExpr(FiniteSet(0, 1))
assert (a + b).set == FiniteSet(0, 1, 2)
# Cannont detect the set being the same:
# assert (a + a).set == FiniteSet(0, 2)
def test_Interval_arithmetic():
i12cc = SetExpr(Interval(1, 2))
i12lo = SetExpr(Interval.Lopen(1, 2))
i12ro = SetExpr(Interval.Ropen(1, 2))
i12o = SetExpr(Interval.open(1, 2))
n23cc = SetExpr(Interval(-2, 3))
n23lo = SetExpr(Interval.Lopen(-2, 3))
n23ro = SetExpr(Interval.Ropen(-2, 3))
n23o = SetExpr(Interval.open(-2, 3))
n3n2cc = SetExpr(Interval(-3, -2))
assert i12cc + i12cc == SetExpr(Interval(2, 4))
assert i12cc - i12cc == SetExpr(Interval(-1, 1))
assert i12cc*i12cc == SetExpr(Interval(1, 4))
assert i12cc/i12cc == SetExpr(Interval(S.Half, 2))
assert i12cc**2 == SetExpr(Interval(1, 4))
assert i12cc**3 == SetExpr(Interval(1, 8))
assert i12lo + i12ro == SetExpr(Interval.open(2, 4))
assert i12lo - i12ro == SetExpr(Interval.Lopen(-1, 1))
assert i12lo*i12ro == SetExpr(Interval.open(1, 4))
assert i12lo/i12ro == SetExpr(Interval.Lopen(S.Half, 2))
assert i12lo + i12lo == SetExpr(Interval.Lopen(2, 4))
assert i12lo - i12lo == SetExpr(Interval.open(-1, 1))
assert i12lo*i12lo == SetExpr(Interval.Lopen(1, 4))
assert i12lo/i12lo == SetExpr(Interval.open(S.Half, 2))
assert i12lo + i12cc == SetExpr(Interval.Lopen(2, 4))
assert i12lo - i12cc == SetExpr(Interval.Lopen(-1, 1))
assert i12lo*i12cc == SetExpr(Interval.Lopen(1, 4))
assert i12lo/i12cc == SetExpr(Interval.Lopen(S.Half, 2))
assert i12lo + i12o == SetExpr(Interval.open(2, 4))
assert i12lo - i12o == SetExpr(Interval.open(-1, 1))
assert i12lo*i12o == SetExpr(Interval.open(1, 4))
assert i12lo/i12o == SetExpr(Interval.open(S.Half, 2))
assert i12lo**2 == SetExpr(Interval.Lopen(1, 4))
assert i12lo**3 == SetExpr(Interval.Lopen(1, 8))
assert i12ro + i12ro == SetExpr(Interval.Ropen(2, 4))
assert i12ro - i12ro == SetExpr(Interval.open(-1, 1))
assert i12ro*i12ro == SetExpr(Interval.Ropen(1, 4))
assert i12ro/i12ro == SetExpr(Interval.open(S.Half, 2))
assert i12ro + i12cc == SetExpr(Interval.Ropen(2, 4))
assert i12ro - i12cc == SetExpr(Interval.Ropen(-1, 1))
assert i12ro*i12cc == SetExpr(Interval.Ropen(1, 4))
assert i12ro/i12cc == SetExpr(Interval.Ropen(S.Half, 2))
assert i12ro + i12o == SetExpr(Interval.open(2, 4))
assert i12ro - i12o == SetExpr(Interval.open(-1, 1))
assert i12ro*i12o == SetExpr(Interval.open(1, 4))
assert i12ro/i12o == SetExpr(Interval.open(S.Half, 2))
assert i12ro**2 == SetExpr(Interval.Ropen(1, 4))
assert i12ro**3 == SetExpr(Interval.Ropen(1, 8))
assert i12o + i12lo == SetExpr(Interval.open(2, 4))
assert i12o - i12lo == SetExpr(Interval.open(-1, 1))
assert i12o*i12lo == SetExpr(Interval.open(1, 4))
assert i12o/i12lo == SetExpr(Interval.open(S.Half, 2))
assert i12o + i12ro == SetExpr(Interval.open(2, 4))
assert i12o - i12ro == SetExpr(Interval.open(-1, 1))
assert i12o*i12ro == SetExpr(Interval.open(1, 4))
assert i12o/i12ro == SetExpr(Interval.open(S.Half, 2))
assert i12o + i12cc == SetExpr(Interval.open(2, 4))
assert i12o - i12cc == SetExpr(Interval.open(-1, 1))
assert i12o*i12cc == SetExpr(Interval.open(1, 4))
assert i12o/i12cc == SetExpr(Interval.open(S.Half, 2))
assert i12o**2 == SetExpr(Interval.open(1, 4))
assert i12o**3 == SetExpr(Interval.open(1, 8))
assert n23cc + n23cc == SetExpr(Interval(-4, 6))
assert n23cc - n23cc == SetExpr(Interval(-5, 5))
assert n23cc*n23cc == SetExpr(Interval(-6, 9))
assert n23cc/n23cc == SetExpr(Interval.open(-oo, oo))
assert n23cc + n23ro == SetExpr(Interval.Ropen(-4, 6))
assert n23cc - n23ro == SetExpr(Interval.Lopen(-5, 5))
assert n23cc*n23ro == SetExpr(Interval.Ropen(-6, 9))
assert n23cc/n23ro == SetExpr(Interval.Lopen(-oo, oo))
assert n23cc + n23lo == SetExpr(Interval.Lopen(-4, 6))
assert n23cc - n23lo == SetExpr(Interval.Ropen(-5, 5))
assert n23cc*n23lo == SetExpr(Interval(-6, 9))
assert n23cc/n23lo == SetExpr(Interval.open(-oo, oo))
assert n23cc + n23o == SetExpr(Interval.open(-4, 6))
assert n23cc - n23o == SetExpr(Interval.open(-5, 5))
assert n23cc*n23o == SetExpr(Interval.open(-6, 9))
assert n23cc/n23o == SetExpr(Interval.open(-oo, oo))
assert n23cc**2 == SetExpr(Interval(0, 9))
assert n23cc**3 == SetExpr(Interval(-8, 27))
n32cc = SetExpr(Interval(-3, 2))
n32lo = SetExpr(Interval.Lopen(-3, 2))
n32ro = SetExpr(Interval.Ropen(-3, 2))
assert n32cc*n32lo == SetExpr(Interval.Ropen(-6, 9))
assert n32cc*n32cc == SetExpr(Interval(-6, 9))
assert n32lo*n32cc == SetExpr(Interval.Ropen(-6, 9))
assert n32cc*n32ro == SetExpr(Interval(-6, 9))
assert n32lo*n32ro == SetExpr(Interval.Ropen(-6, 9))
assert n32cc/n32lo == SetExpr(Interval.Ropen(-oo, oo))
assert i12cc/n32lo == SetExpr(Interval.Ropen(-oo, oo))
assert n3n2cc**2 == SetExpr(Interval(4, 9))
assert n3n2cc**3 == SetExpr(Interval(-27, -8))
assert n23cc + i12cc == SetExpr(Interval(-1, 5))
assert n23cc - i12cc == SetExpr(Interval(-4, 2))
assert n23cc*i12cc == SetExpr(Interval(-4, 6))
assert n23cc/i12cc == SetExpr(Interval(-2, 3))
def test_SetExpr_Intersection():
x, y, z, w = symbols("x y z w")
set1 = Interval(x, y)
set2 = Interval(w, z)
inter = Intersection(set1, set2)
se = SetExpr(inter)
assert exp(se).set == Intersection(
ImageSet(Lambda(x, exp(x)), set1),
ImageSet(Lambda(x, exp(x)), set2))
assert cos(se).set == ImageSet(Lambda(x, cos(x)), inter)
def test_SetExpr_Interval_div():
# TODO: some expressions cannot be calculated due to bugs (currently
# commented):
assert SetExpr(Interval(-3, -2))/SetExpr(Interval(-2, 1)) == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(2, 3))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-3, -2))/SetExpr(Interval(0, 4)) == SetExpr(Interval(-oo, Rational(-1, 2)))
assert SetExpr(Interval(2, 4))/SetExpr(Interval(-3, 0)) == SetExpr(Interval(-oo, Rational(-2, 3)))
assert SetExpr(Interval(2, 4))/SetExpr(Interval(0, 3)) == SetExpr(Interval(Rational(2, 3), oo))
# assert SetExpr(Interval(0, 1))/SetExpr(Interval(0, 1)) == SetExpr(Interval(0, oo))
# assert SetExpr(Interval(-1, 0))/SetExpr(Interval(0, 1)) == SetExpr(Interval(-oo, 0))
assert SetExpr(Interval(-1, 2))/SetExpr(Interval(-2, 2)) == SetExpr(Interval(-oo, oo))
assert 1/SetExpr(Interval(-1, 2)) == SetExpr(Union(Interval(-oo, -1), Interval(S.Half, oo)))
assert 1/SetExpr(Interval(0, 2)) == SetExpr(Interval(S.Half, oo))
assert (-1)/SetExpr(Interval(0, 2)) == SetExpr(Interval(-oo, Rational(-1, 2)))
# assert 1/SetExpr(Interval(-oo, 0)) == SetExpr(Interval.open(-oo, 0))
assert 1/SetExpr(Interval(-1, 0)) == SetExpr(Interval(-oo, -1))
# assert (-2)/SetExpr(Interval(-oo, 0)) == SetExpr(Interval(0, oo))
# assert 1/SetExpr(Interval(-oo, -1)) == SetExpr(Interval(-1, 0))
# assert SetExpr(Interval(1, 2))/a == Mul(SetExpr(Interval(1, 2)), 1/a, evaluate=False)
# assert SetExpr(Interval(1, 2))/0 == SetExpr(Interval(1, 2))*zoo
# assert SetExpr(Interval(1, oo))/oo == SetExpr(Interval(0, oo))
# assert SetExpr(Interval(1, oo))/(-oo) == SetExpr(Interval(-oo, 0))
# assert SetExpr(Interval(-oo, -1))/oo == SetExpr(Interval(-oo, 0))
# assert SetExpr(Interval(-oo, -1))/(-oo) == SetExpr(Interval(0, oo))
# assert SetExpr(Interval(-oo, oo))/oo == SetExpr(Interval(-oo, oo))
# assert SetExpr(Interval(-oo, oo))/(-oo) == SetExpr(Interval(-oo, oo))
# assert SetExpr(Interval(-1, oo))/oo == SetExpr(Interval(0, oo))
# assert SetExpr(Interval(-1, oo))/(-oo) == SetExpr(Interval(-oo, 0))
# assert SetExpr(Interval(-oo, 1))/oo == SetExpr(Interval(-oo, 0))
# assert SetExpr(Interval(-oo, 1))/(-oo) == SetExpr(Interval(0, oo))
def test_SetExpr_Interval_pow():
assert SetExpr(Interval(0, 2))**2 == SetExpr(Interval(0, 4))
assert SetExpr(Interval(-1, 1))**2 == SetExpr(Interval(0, 1))
assert SetExpr(Interval(1, 2))**2 == SetExpr(Interval(1, 4))
assert SetExpr(Interval(-1, 2))**3 == SetExpr(Interval(-1, 8))
assert SetExpr(Interval(-1, 1))**0 == SetExpr(FiniteSet(1))
#assert SetExpr(Interval(1, 2))**Rational(5, 2) == SetExpr(Interval(1, 4*sqrt(2)))
#assert SetExpr(Interval(-1, 2))**Rational(1, 3) == SetExpr(Interval(-1, 2**Rational(1, 3)))
#assert SetExpr(Interval(0, 2))**S.Half == SetExpr(Interval(0, sqrt(2)))
#assert SetExpr(Interval(-4, 2))**Rational(2, 3) == SetExpr(Interval(0, 2*2**Rational(1, 3)))
#assert SetExpr(Interval(-1, 5))**S.Half == SetExpr(Interval(0, sqrt(5)))
#assert SetExpr(Interval(-oo, 2))**S.Half == SetExpr(Interval(0, sqrt(2)))
#assert SetExpr(Interval(-2, 3))**(Rational(-1, 4)) == SetExpr(Interval(0, oo))
assert SetExpr(Interval(1, 5))**(-2) == SetExpr(Interval(Rational(1, 25), 1))
assert SetExpr(Interval(-1, 3))**(-2) == SetExpr(Interval(0, oo))
assert SetExpr(Interval(0, 2))**(-2) == SetExpr(Interval(Rational(1, 4), oo))
assert SetExpr(Interval(-1, 2))**(-3) == SetExpr(Union(Interval(-oo, -1), Interval(Rational(1, 8), oo)))
assert SetExpr(Interval(-3, -2))**(-3) == SetExpr(Interval(Rational(-1, 8), Rational(-1, 27)))
assert SetExpr(Interval(-3, -2))**(-2) == SetExpr(Interval(Rational(1, 9), Rational(1, 4)))
#assert SetExpr(Interval(0, oo))**S.Half == SetExpr(Interval(0, oo))
#assert SetExpr(Interval(-oo, -1))**Rational(1, 3) == SetExpr(Interval(-oo, -1))
#assert SetExpr(Interval(-2, 3))**(Rational(-1, 3)) == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-oo, 0))**(-2) == SetExpr(Interval.open(0, oo))
assert SetExpr(Interval(-2, 0))**(-2) == SetExpr(Interval(Rational(1, 4), oo))
assert SetExpr(Interval(Rational(1, 3), S.Half))**oo == SetExpr(FiniteSet(0))
assert SetExpr(Interval(0, S.Half))**oo == SetExpr(FiniteSet(0))
assert SetExpr(Interval(S.Half, 1))**oo == SetExpr(Interval(0, oo))
assert SetExpr(Interval(0, 1))**oo == SetExpr(Interval(0, oo))
assert SetExpr(Interval(2, 3))**oo == SetExpr(FiniteSet(oo))
assert SetExpr(Interval(1, 2))**oo == SetExpr(Interval(0, oo))
assert SetExpr(Interval(S.Half, 3))**oo == SetExpr(Interval(0, oo))
assert SetExpr(Interval(Rational(-1, 3), Rational(-1, 4)))**oo == SetExpr(FiniteSet(0))
assert SetExpr(Interval(-1, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-3, -2))**oo == SetExpr(FiniteSet(-oo, oo))
assert SetExpr(Interval(-2, -1))**oo == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-2, Rational(-1, 2)))**oo == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(Rational(-1, 2), S.Half))**oo == SetExpr(FiniteSet(0))
assert SetExpr(Interval(Rational(-1, 2), 1))**oo == SetExpr(Interval(0, oo))
assert SetExpr(Interval(Rational(-2, 3), 2))**oo == SetExpr(Interval(0, oo))
assert SetExpr(Interval(-1, 1))**oo == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-1, S.Half))**oo == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-1, 2))**oo == SetExpr(Interval(-oo, oo))
assert SetExpr(Interval(-2, S.Half))**oo == SetExpr(Interval(-oo, oo))
assert (SetExpr(Interval(1, 2))**x).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**x), Interval(1, 2))))
assert SetExpr(Interval(2, 3))**(-oo) == SetExpr(FiniteSet(0))
assert SetExpr(Interval(0, 2))**(-oo) == SetExpr(Interval(0, oo))
assert (SetExpr(Interval(-1, 2))**(-oo)).dummy_eq(SetExpr(ImageSet(Lambda(_d, _d**(-oo)), Interval(-1, 2))))
def test_SetExpr_Integers():
assert SetExpr(S.Integers) + 1 == SetExpr(S.Integers)
assert SetExpr(S.Integers) + I == SetExpr(ImageSet(Lambda(_d, _d + I), S.Integers))
assert SetExpr(S.Integers)*(-1) == SetExpr(S.Integers)
assert SetExpr(S.Integers)*2 == SetExpr(ImageSet(Lambda(_d, 2*_d), S.Integers))
assert SetExpr(S.Integers)*I == SetExpr(ImageSet(Lambda(_d, I*_d), S.Integers))
# issue #18050:
assert SetExpr(S.Integers)._eval_func(Lambda(x, I*x + 1)) == SetExpr(
ImageSet(Lambda(_d, I*_d + 1), S.Integers))
# needs improvement:
assert SetExpr(S.Integers)*I + 1 == SetExpr(
ImageSet(Lambda(x, x + 1), ImageSet(Lambda(_d, _d*I), S.Integers)))
|
4e1a6a62903eeab7d7751d7647e8f65a2190829eaece402761223f510a20dbef | from sympy.core.expr import unchanged
from sympy.core.singleton import S
from sympy.core.symbol import Symbol
from sympy.sets.contains import Contains
from sympy.sets.fancysets import Interval
from sympy.sets.powerset import PowerSet
from sympy.sets.sets import FiniteSet
from sympy.testing.pytest import raises, XFAIL
def test_powerset_creation():
assert unchanged(PowerSet, FiniteSet(1, 2))
assert unchanged(PowerSet, S.EmptySet)
raises(ValueError, lambda: PowerSet(123))
assert unchanged(PowerSet, S.Reals)
assert unchanged(PowerSet, S.Integers)
def test_powerset_rewrite_FiniteSet():
assert PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet) == \
FiniteSet(S.EmptySet, FiniteSet(1), FiniteSet(2), FiniteSet(1, 2))
assert PowerSet(S.EmptySet).rewrite(FiniteSet) == FiniteSet(S.EmptySet)
assert PowerSet(S.Naturals).rewrite(FiniteSet) == PowerSet(S.Naturals)
def test_finiteset_rewrite_powerset():
assert FiniteSet(S.EmptySet).rewrite(PowerSet) == PowerSet(S.EmptySet)
assert FiniteSet(
S.EmptySet, FiniteSet(1),
FiniteSet(2), FiniteSet(1, 2)).rewrite(PowerSet) == \
PowerSet(FiniteSet(1, 2))
assert FiniteSet(1, 2, 3).rewrite(PowerSet) == FiniteSet(1, 2, 3)
def test_powerset__contains__():
subset_series = [
S.EmptySet,
FiniteSet(1, 2),
S.Naturals,
S.Naturals0,
S.Integers,
S.Rationals,
S.Reals,
S.Complexes]
l = len(subset_series)
for i in range(l):
for j in range(l):
if i <= j:
assert subset_series[i] in \
PowerSet(subset_series[j], evaluate=False)
else:
assert subset_series[i] not in \
PowerSet(subset_series[j], evaluate=False)
@XFAIL
def test_failing_powerset__contains__():
# XXX These are failing when evaluate=True,
# but using unevaluated PowerSet works fine.
assert FiniteSet(1, 2) not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Naturals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Naturals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
assert S.Naturals0 not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Naturals0 not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
assert S.Integers not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Integers not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
assert S.Rationals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Rationals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
assert S.Reals not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Reals not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
assert S.Complexes not in PowerSet(S.EmptySet).rewrite(FiniteSet)
assert S.Complexes not in PowerSet(FiniteSet(1, 2)).rewrite(FiniteSet)
def test_powerset__len__():
A = PowerSet(S.EmptySet, evaluate=False)
assert len(A) == 1
A = PowerSet(A, evaluate=False)
assert len(A) == 2
A = PowerSet(A, evaluate=False)
assert len(A) == 4
A = PowerSet(A, evaluate=False)
assert len(A) == 16
def test_powerset__iter__():
a = PowerSet(FiniteSet(1, 2)).__iter__()
assert next(a) == S.EmptySet
assert next(a) == FiniteSet(1)
assert next(a) == FiniteSet(2)
assert next(a) == FiniteSet(1, 2)
a = PowerSet(S.Naturals).__iter__()
assert next(a) == S.EmptySet
assert next(a) == FiniteSet(1)
assert next(a) == FiniteSet(2)
assert next(a) == FiniteSet(1, 2)
assert next(a) == FiniteSet(3)
assert next(a) == FiniteSet(1, 3)
assert next(a) == FiniteSet(2, 3)
assert next(a) == FiniteSet(1, 2, 3)
def test_powerset_contains():
A = PowerSet(FiniteSet(1), evaluate=False)
assert A.contains(2) == Contains(2, A)
x = Symbol('x')
A = PowerSet(FiniteSet(x), evaluate=False)
assert A.contains(FiniteSet(1)) == Contains(FiniteSet(1), A)
def test_powerset_method():
# EmptySet
A = FiniteSet()
pset = A.powerset()
assert len(pset) == 1
assert pset == FiniteSet(S.EmptySet)
# FiniteSets
A = FiniteSet(1, 2)
pset = A.powerset()
assert len(pset) == 2**len(A)
assert pset == FiniteSet(FiniteSet(), FiniteSet(1),
FiniteSet(2), A)
# Not finite sets
A = Interval(0, 1)
assert A.powerset() == PowerSet(A)
|
e3190f0254b9615f56650abb7dcbd06242a40fe244b19c0be2dd227ede35f5f1 | from sympy import Symbol, Contains, S, Interval, FiniteSet, oo, Eq
from sympy.core.expr import unchanged
from sympy.testing.pytest import raises
def test_contains_basic():
raises(TypeError, lambda: Contains(S.Integers, 1))
assert Contains(2, S.Integers) is S.true
assert Contains(-2, S.Naturals) is S.false
i = Symbol('i', integer=True)
assert Contains(i, S.Naturals) == Contains(i, S.Naturals, evaluate=False)
def test_issue_6194():
x = Symbol('x')
assert unchanged(Contains, x, Interval(0, 1))
assert Interval(0, 1).contains(x) == (S.Zero <= x) & (x <= 1)
assert Contains(x, FiniteSet(0)) != S.false
assert Contains(x, Interval(1, 1)) != S.false
assert Contains(x, S.Integers) != S.false
def test_issue_10326():
assert Contains(oo, Interval(-oo, oo)) == False
assert Contains(-oo, Interval(-oo, oo)) == False
def test_binary_symbols():
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
assert Contains(x, FiniteSet(y, Eq(z, True))
).binary_symbols == set([y, z])
def test_as_set():
x = Symbol('x')
y = Symbol('y')
# Contains is a BooleanFunction whose value depends on an arg's
# containment in a Set -- rewriting as a Set is not yet implemented
raises(NotImplementedError, lambda:
Contains(x, FiniteSet(y)).as_set())
|
352bea70335b45e588dbd3a55b31108f7ca253f74f40daa55a3481e1ab2aa3af | from sympy.core.expr import unchanged
from sympy.sets.fancysets import (ImageSet, Range, normalize_theta_set,
ComplexRegion)
from sympy.sets.sets import (FiniteSet, Interval, imageset, Union,
Intersection, ProductSet, Contains)
from sympy.simplify.simplify import simplify
from sympy import (S, Symbol, Lambda, symbols, cos, sin, pi, oo, Basic,
Rational, sqrt, tan, log, exp, Abs, I, Tuple, eye,
Dummy, floor, And, Eq)
from sympy.utilities.iterables import cartes
from sympy.testing.pytest import XFAIL, raises
from sympy.abc import x, y, t
import itertools
def test_naturals():
N = S.Naturals
assert 5 in N
assert -5 not in N
assert 5.5 not in N
ni = iter(N)
a, b, c, d = next(ni), next(ni), next(ni), next(ni)
assert (a, b, c, d) == (1, 2, 3, 4)
assert isinstance(a, Basic)
assert N.intersect(Interval(-5, 5)) == Range(1, 6)
assert N.intersect(Interval(-5, 5, True, True)) == Range(1, 5)
assert N.boundary == N
assert N.is_open == False
assert N.is_closed == True
assert N.inf == 1
assert N.sup is oo
assert not N.contains(oo)
for s in (S.Naturals0, S.Naturals):
assert s.intersection(S.Reals) is s
assert s.is_subset(S.Reals)
assert N.as_relational(x) == And(Eq(floor(x), x), x >= 1, x < oo)
def test_naturals0():
N = S.Naturals0
assert 0 in N
assert -1 not in N
assert next(iter(N)) == 0
assert not N.contains(oo)
assert N.contains(sin(x)) == Contains(sin(x), N)
def test_integers():
Z = S.Integers
assert 5 in Z
assert -5 in Z
assert 5.5 not in Z
assert not Z.contains(oo)
assert not Z.contains(-oo)
zi = iter(Z)
a, b, c, d = next(zi), next(zi), next(zi), next(zi)
assert (a, b, c, d) == (0, 1, -1, 2)
assert isinstance(a, Basic)
assert Z.intersect(Interval(-5, 5)) == Range(-5, 6)
assert Z.intersect(Interval(-5, 5, True, True)) == Range(-4, 5)
assert Z.intersect(Interval(5, S.Infinity)) == Range(5, S.Infinity)
assert Z.intersect(Interval.Lopen(5, S.Infinity)) == Range(6, S.Infinity)
assert Z.inf is -oo
assert Z.sup is oo
assert Z.boundary == Z
assert Z.is_open == False
assert Z.is_closed == True
assert Z.as_relational(x) == And(Eq(floor(x), x), -oo < x, x < oo)
def test_ImageSet():
raises(ValueError, lambda: ImageSet(x, S.Integers))
assert ImageSet(Lambda(x, 1), S.Integers) == FiniteSet(1)
assert ImageSet(Lambda(x, y), S.Integers) == {y}
assert ImageSet(Lambda(x, 1), S.EmptySet) == S.EmptySet
empty = Intersection(FiniteSet(log(2)/pi), S.Integers)
assert unchanged(ImageSet, Lambda(x, 1), empty) # issue #17471
squares = ImageSet(Lambda(x, x**2), S.Naturals)
assert 4 in squares
assert 5 not in squares
assert FiniteSet(*range(10)).intersect(squares) == FiniteSet(1, 4, 9)
assert 16 not in squares.intersect(Interval(0, 10))
si = iter(squares)
a, b, c, d = next(si), next(si), next(si), next(si)
assert (a, b, c, d) == (1, 4, 9, 16)
harmonics = ImageSet(Lambda(x, 1/x), S.Naturals)
assert Rational(1, 5) in harmonics
assert Rational(.25) in harmonics
assert 0.25 not in harmonics
assert Rational(.3) not in harmonics
assert (1, 2) not in harmonics
assert harmonics.is_iterable
assert imageset(x, -x, Interval(0, 1)) == Interval(-1, 0)
assert ImageSet(Lambda(x, x**2), Interval(0, 2)).doit() == Interval(0, 4)
assert ImageSet(Lambda((x, y), 2*x), {4}, {3}).doit() == FiniteSet(8)
assert (ImageSet(Lambda((x, y), x+y), {1, 2, 3}, {10, 20, 30}).doit() ==
FiniteSet(11, 12, 13, 21, 22, 23, 31, 32, 33))
c = Interval(1, 3) * Interval(1, 3)
assert Tuple(2, 6) in ImageSet(Lambda(((x, y),), (x, 2*y)), c)
assert Tuple(2, S.Half) in ImageSet(Lambda(((x, y),), (x, 1/y)), c)
assert Tuple(2, -2) not in ImageSet(Lambda(((x, y),), (x, y**2)), c)
assert Tuple(2, -2) in ImageSet(Lambda(((x, y),), (x, -2)), c)
c3 = ProductSet(Interval(3, 7), Interval(8, 11), Interval(5, 9))
assert Tuple(8, 3, 9) in ImageSet(Lambda(((t, y, x),), (y, t, x)), c3)
assert Tuple(Rational(1, 8), 3, 9) in ImageSet(Lambda(((t, y, x),), (1/y, t, x)), c3)
assert 2/pi not in ImageSet(Lambda(((x, y),), 2/x), c)
assert 2/S(100) not in ImageSet(Lambda(((x, y),), 2/x), c)
assert Rational(2, 3) in ImageSet(Lambda(((x, y),), 2/x), c)
S1 = imageset(lambda x, y: x + y, S.Integers, S.Naturals)
assert S1.base_pset == ProductSet(S.Integers, S.Naturals)
assert S1.base_sets == (S.Integers, S.Naturals)
# Passing a set instead of a FiniteSet shouldn't raise
assert unchanged(ImageSet, Lambda(x, x**2), {1, 2, 3})
S2 = ImageSet(Lambda(((x, y),), x+y), {(1, 2), (3, 4)})
assert 3 in S2.doit()
# FIXME: This doesn't yet work:
#assert 3 in S2
assert S2._contains(3) is None
raises(TypeError, lambda: ImageSet(Lambda(x, x**2), 1))
def test_image_is_ImageSet():
assert isinstance(imageset(x, sqrt(sin(x)), Range(5)), ImageSet)
def test_halfcircle():
r, th = symbols('r, theta', real=True)
L = Lambda(((r, th),), (r*cos(th), r*sin(th)))
halfcircle = ImageSet(L, Interval(0, 1)*Interval(0, pi))
assert (1, 0) in halfcircle
assert (0, -1) not in halfcircle
assert (0, 0) in halfcircle
assert halfcircle._contains((r, 0)) is None
# This one doesn't work:
#assert (r, 2*pi) not in halfcircle
assert not halfcircle.is_iterable
def test_ImageSet_iterator_not_injective():
L = Lambda(x, x - x % 2) # produces 0, 2, 2, 4, 4, 6, 6, ...
evens = ImageSet(L, S.Naturals)
i = iter(evens)
# No repeats here
assert (next(i), next(i), next(i), next(i)) == (0, 2, 4, 6)
def test_inf_Range_len():
raises(ValueError, lambda: len(Range(0, oo, 2)))
assert Range(0, oo, 2).size is S.Infinity
assert Range(0, -oo, -2).size is S.Infinity
assert Range(oo, 0, -2).size is S.Infinity
assert Range(-oo, 0, 2).size is S.Infinity
def test_Range_set():
empty = Range(0)
assert Range(5) == Range(0, 5) == Range(0, 5, 1)
r = Range(10, 20, 2)
assert 12 in r
assert 8 not in r
assert 11 not in r
assert 30 not in r
assert list(Range(0, 5)) == list(range(5))
assert list(Range(5, 0, -1)) == list(range(5, 0, -1))
assert Range(5, 15).sup == 14
assert Range(5, 15).inf == 5
assert Range(15, 5, -1).sup == 15
assert Range(15, 5, -1).inf == 6
assert Range(10, 67, 10).sup == 60
assert Range(60, 7, -10).inf == 10
assert len(Range(10, 38, 10)) == 3
assert Range(0, 0, 5) == empty
assert Range(oo, oo, 1) == empty
assert Range(oo, 1, 1) == empty
assert Range(-oo, 1, -1) == empty
assert Range(1, oo, -1) == empty
assert Range(1, -oo, 1) == empty
assert Range(1, -4, oo) == empty
assert Range(1, -4, -oo) == Range(1, 2)
assert Range(1, 4, oo) == Range(1, 2)
assert Range(-oo, oo).size == oo
assert Range(oo, -oo, -1).size == oo
raises(ValueError, lambda: Range(-oo, oo, 2))
raises(ValueError, lambda: Range(x, pi, y))
raises(ValueError, lambda: Range(x, y, 0))
assert 5 in Range(0, oo, 5)
assert -5 in Range(-oo, 0, 5)
assert oo not in Range(0, oo)
ni = symbols('ni', integer=False)
assert ni not in Range(oo)
u = symbols('u', integer=None)
assert Range(oo).contains(u) is not False
inf = symbols('inf', infinite=True)
assert inf not in Range(-oo, oo)
raises(ValueError, lambda: Range(0, oo, 2)[-1])
raises(ValueError, lambda: Range(0, -oo, -2)[-1])
assert Range(-oo, 1, 1)[-1] is S.Zero
assert Range(oo, 1, -1)[-1] == 2
assert inf not in Range(oo)
inf = symbols('inf', infinite=True)
assert inf not in Range(oo)
assert Range(-oo, 1, 1)[-1] is S.Zero
assert Range(oo, 1, -1)[-1] == 2
assert Range(1, 10, 1)[-1] == 9
assert all(i.is_Integer for i in Range(0, -1, 1))
it = iter(Range(-oo, 0, 2))
raises(TypeError, lambda: next(it))
assert empty.intersect(S.Integers) == empty
assert Range(-1, 10, 1).intersect(S.Integers) == Range(-1, 10, 1)
assert Range(-1, 10, 1).intersect(S.Naturals) == Range(1, 10, 1)
assert Range(-1, 10, 1).intersect(S.Naturals0) == Range(0, 10, 1)
# test slicing
assert Range(1, 10, 1)[5] == 6
assert Range(1, 12, 2)[5] == 11
assert Range(1, 10, 1)[-1] == 9
assert Range(1, 10, 3)[-1] == 7
raises(ValueError, lambda: Range(oo,0,-1)[1:3:0])
raises(ValueError, lambda: Range(oo,0,-1)[:1])
raises(ValueError, lambda: Range(1, oo)[-2])
raises(ValueError, lambda: Range(-oo, 1)[2])
raises(IndexError, lambda: Range(10)[-20])
raises(IndexError, lambda: Range(10)[20])
raises(ValueError, lambda: Range(2, -oo, -2)[2:2:0])
assert Range(2, -oo, -2)[2:2:2] == empty
assert Range(2, -oo, -2)[:2:2] == Range(2, -2, -4)
raises(ValueError, lambda: Range(-oo, 4, 2)[:2:2])
assert Range(-oo, 4, 2)[::-2] == Range(2, -oo, -4)
raises(ValueError, lambda: Range(-oo, 4, 2)[::2])
assert Range(oo, 2, -2)[::] == Range(oo, 2, -2)
assert Range(-oo, 4, 2)[:-2:-2] == Range(2, 0, -4)
assert Range(-oo, 4, 2)[:-2:2] == Range(-oo, 0, 4)
raises(ValueError, lambda: Range(-oo, 4, 2)[:0:-2])
raises(ValueError, lambda: Range(-oo, 4, 2)[:2:-2])
assert Range(-oo, 4, 2)[-2::-2] == Range(0, -oo, -4)
raises(ValueError, lambda: Range(-oo, 4, 2)[-2:0:-2])
raises(ValueError, lambda: Range(-oo, 4, 2)[0::2])
assert Range(oo, 2, -2)[0::] == Range(oo, 2, -2)
raises(ValueError, lambda: Range(-oo, 4, 2)[0:-2:2])
assert Range(oo, 2, -2)[0:-2:] == Range(oo, 6, -2)
raises(ValueError, lambda: Range(oo, 2, -2)[0:2:])
raises(ValueError, lambda: Range(-oo, 4, 2)[2::-1])
assert Range(-oo, 4, 2)[-2::2] == Range(0, 4, 4)
assert Range(oo, 0, -2)[-10:0:2] == empty
raises(ValueError, lambda: Range(oo, 0, -2)[-10:10:2])
raises(ValueError, lambda: Range(oo, 0, -2)[0::-2])
assert Range(oo, 0, -2)[0:-4:-2] == empty
assert Range(oo, 0, -2)[:0:2] == empty
raises(ValueError, lambda: Range(oo, 0, -2)[:1:-1])
# test empty Range
assert Range(x, x, y) == empty
assert empty.reversed == empty
assert 0 not in empty
assert list(empty) == []
assert len(empty) == 0
assert empty.size is S.Zero
assert empty.intersect(FiniteSet(0)) is S.EmptySet
assert bool(empty) is False
raises(IndexError, lambda: empty[0])
assert empty[:0] == empty
raises(NotImplementedError, lambda: empty.inf)
raises(NotImplementedError, lambda: empty.sup)
AB = [None] + list(range(12))
for R in [
Range(1, 10),
Range(1, 10, 2),
]:
r = list(R)
for a, b, c in cartes(AB, AB, [-3, -1, None, 1, 3]):
for reverse in range(2):
r = list(reversed(r))
R = R.reversed
result = list(R[a:b:c])
ans = r[a:b:c]
txt = ('\n%s[%s:%s:%s] = %s -> %s' % (
R, a, b, c, result, ans))
check = ans == result
assert check, txt
assert Range(1, 10, 1).boundary == Range(1, 10, 1)
for r in (Range(1, 10, 2), Range(1, oo, 2)):
rev = r.reversed
assert r.inf == rev.inf and r.sup == rev.sup
assert r.step == -rev.step
builtin_range = range
raises(TypeError, lambda: Range(builtin_range(1)))
assert S(builtin_range(10)) == Range(10)
assert S(builtin_range(1000000000000)) == Range(1000000000000)
# test Range.as_relational
assert Range(1, 4).as_relational(x) == (x >= 1) & (x <= 3) & Eq(x, floor(x))
assert Range(oo, 1, -2).as_relational(x) == (x >= 3) & (x < oo) & Eq(x, floor(x))
def test_Range_symbolic():
# symbolic Range
sr = Range(x, y, t)
i = Symbol('i', integer=True)
ip = Symbol('i', integer=True, positive=True)
ir = Range(i, i + 20, 2)
inf = symbols('inf', infinite=True)
# args
assert sr.args == (x, y, t)
assert ir.args == (i, i + 20, 2)
# reversed
raises(ValueError, lambda: sr.reversed)
assert ir.reversed == Range(i + 18, i - 2, -2)
# contains
assert inf not in sr
assert inf not in ir
assert .1 not in sr
assert .1 not in ir
assert i + 1 not in ir
assert i + 2 in ir
raises(TypeError, lambda: 1 in sr) # XXX is this what contains is supposed to do?
# iter
raises(ValueError, lambda: next(iter(sr)))
assert next(iter(ir)) == i
assert sr.intersect(S.Integers) == sr
assert sr.intersect(FiniteSet(x)) == Intersection({x}, sr)
raises(ValueError, lambda: sr[:2])
raises(ValueError, lambda: sr[0])
raises(ValueError, lambda: sr.as_relational(x))
# len
assert len(ir) == ir.size == 10
raises(ValueError, lambda: len(sr))
raises(ValueError, lambda: sr.size)
# bool
assert bool(ir) == bool(sr) == True
# getitem
raises(ValueError, lambda: sr[0])
raises(ValueError, lambda: sr[-1])
raises(ValueError, lambda: sr[:2])
assert ir[:2] == Range(i, i + 4, 2)
assert ir[0] == i
assert ir[-2] == i + 16
assert ir[-1] == i + 18
raises(ValueError, lambda: Range(i)[-1])
assert Range(ip)[-1] == ip - 1
assert ir.inf == i
assert ir.sup == i + 18
assert Range(ip).inf == 0
assert Range(ip).sup == ip - 1
raises(ValueError, lambda: Range(i).inf)
# as_relational
raises(ValueError, lambda: sr.as_relational(x))
assert ir.as_relational(x) == (
x >= i) & Eq(x, floor(x)) & (x <= i + 18)
assert Range(i, i + 1).as_relational(x) == Eq(x, i)
# contains() for symbolic values (issue #18146)
e = Symbol('e', integer=True, even=True)
o = Symbol('o', integer=True, odd=True)
assert Range(5).contains(i) == And(i >= 0, i <= 4)
assert Range(1).contains(i) == Eq(i, 0)
assert Range(-oo, 5, 1).contains(i) == (i <= 4)
assert Range(-oo, oo).contains(i) == True
assert Range(0, 8, 2).contains(i) == Contains(i, Range(0, 8, 2))
assert Range(0, 8, 2).contains(e) == And(e >= 0, e <= 6)
assert Range(0, 8, 2).contains(2*i) == And(2*i >= 0, 2*i <= 6)
assert Range(0, 8, 2).contains(o) == False
assert Range(1, 9, 2).contains(e) == False
assert Range(1, 9, 2).contains(o) == And(o >= 1, o <= 7)
assert Range(8, 0, -2).contains(o) == False
assert Range(9, 1, -2).contains(o) == And(o >= 3, o <= 9)
assert Range(-oo, 8, 2).contains(i) == Contains(i, Range(-oo, 8, 2))
def test_range_range_intersection():
for a, b, r in [
(Range(0), Range(1), S.EmptySet),
(Range(3), Range(4, oo), S.EmptySet),
(Range(3), Range(-3, -1), S.EmptySet),
(Range(1, 3), Range(0, 3), Range(1, 3)),
(Range(1, 3), Range(1, 4), Range(1, 3)),
(Range(1, oo, 2), Range(2, oo, 2), S.EmptySet),
(Range(0, oo, 2), Range(oo), Range(0, oo, 2)),
(Range(0, oo, 2), Range(100), Range(0, 100, 2)),
(Range(2, oo, 2), Range(oo), Range(2, oo, 2)),
(Range(0, oo, 2), Range(5, 6), S.EmptySet),
(Range(2, 80, 1), Range(55, 71, 4), Range(55, 71, 4)),
(Range(0, 6, 3), Range(-oo, 5, 3), S.EmptySet),
(Range(0, oo, 2), Range(5, oo, 3), Range(8, oo, 6)),
(Range(4, 6, 2), Range(2, 16, 7), S.EmptySet),]:
assert a.intersect(b) == r
assert a.intersect(b.reversed) == r
assert a.reversed.intersect(b) == r
assert a.reversed.intersect(b.reversed) == r
a, b = b, a
assert a.intersect(b) == r
assert a.intersect(b.reversed) == r
assert a.reversed.intersect(b) == r
assert a.reversed.intersect(b.reversed) == r
def test_range_interval_intersection():
p = symbols('p', positive=True)
assert isinstance(Range(3).intersect(Interval(p, p + 2)), Intersection)
assert Range(4).intersect(Interval(0, 3)) == Range(4)
assert Range(4).intersect(Interval(-oo, oo)) == Range(4)
assert Range(4).intersect(Interval(1, oo)) == Range(1, 4)
assert Range(4).intersect(Interval(1.1, oo)) == Range(2, 4)
assert Range(4).intersect(Interval(0.1, 3)) == Range(1, 4)
assert Range(4).intersect(Interval(0.1, 3.1)) == Range(1, 4)
assert Range(4).intersect(Interval.open(0, 3)) == Range(1, 3)
assert Range(4).intersect(Interval.open(0.1, 0.5)) is S.EmptySet
# Null Range intersections
assert Range(0).intersect(Interval(0.2, 0.8)) is S.EmptySet
assert Range(0).intersect(Interval(-oo, oo)) is S.EmptySet
def test_Integers_eval_imageset():
ans = ImageSet(Lambda(x, 2*x + Rational(3, 7)), S.Integers)
im = imageset(Lambda(x, -2*x + Rational(3, 7)), S.Integers)
assert im == ans
im = imageset(Lambda(x, -2*x - Rational(11, 7)), S.Integers)
assert im == ans
y = Symbol('y')
L = imageset(x, 2*x + y, S.Integers)
assert y + 4 in L
_x = symbols('x', negative=True)
eq = _x**2 - _x + 1
assert imageset(_x, eq, S.Integers).lamda.expr == _x**2 + _x + 1
eq = 3*_x - 1
assert imageset(_x, eq, S.Integers).lamda.expr == 3*_x + 2
assert imageset(x, (x, 1/x), S.Integers) == \
ImageSet(Lambda(x, (x, 1/x)), S.Integers)
def test_Range_eval_imageset():
a, b, c = symbols('a b c')
assert imageset(x, a*(x + b) + c, Range(3)) == \
imageset(x, a*x + a*b + c, Range(3))
eq = (x + 1)**2
assert imageset(x, eq, Range(3)).lamda.expr == eq
eq = a*(x + b) + c
r = Range(3, -3, -2)
imset = imageset(x, eq, r)
assert imset.lamda.expr != eq
assert list(imset) == [eq.subs(x, i).expand() for i in list(r)]
def test_fun():
assert (FiniteSet(*ImageSet(Lambda(x, sin(pi*x/4)),
Range(-10, 11))) == FiniteSet(-1, -sqrt(2)/2, 0, sqrt(2)/2, 1))
def test_Reals():
assert 5 in S.Reals
assert S.Pi in S.Reals
assert -sqrt(2) in S.Reals
assert (2, 5) not in S.Reals
assert sqrt(-1) not in S.Reals
assert S.Reals == Interval(-oo, oo)
assert S.Reals != Interval(0, oo)
assert S.Reals.is_subset(Interval(-oo, oo))
assert S.Reals.intersect(Range(-oo, oo)) == Range(-oo, oo)
def test_Complex():
assert 5 in S.Complexes
assert 5 + 4*I in S.Complexes
assert S.Pi in S.Complexes
assert -sqrt(2) in S.Complexes
assert -I in S.Complexes
assert sqrt(-1) in S.Complexes
assert S.Complexes.intersect(S.Reals) == S.Reals
assert S.Complexes.union(S.Reals) == S.Complexes
assert S.Complexes == ComplexRegion(S.Reals*S.Reals)
assert (S.Complexes == ComplexRegion(Interval(1, 2)*Interval(3, 4))) == False
assert str(S.Complexes) == "S.Complexes"
assert repr(S.Complexes) == "S.Complexes"
def take(n, iterable):
"Return first n items of the iterable as a list"
return list(itertools.islice(iterable, n))
def test_intersections():
assert S.Integers.intersect(S.Reals) == S.Integers
assert 5 in S.Integers.intersect(S.Reals)
assert 5 in S.Integers.intersect(S.Reals)
assert -5 not in S.Naturals.intersect(S.Reals)
assert 5.5 not in S.Integers.intersect(S.Reals)
assert 5 in S.Integers.intersect(Interval(3, oo))
assert -5 in S.Integers.intersect(Interval(-oo, 3))
assert all(x.is_Integer
for x in take(10, S.Integers.intersect(Interval(3, oo)) ))
def test_infinitely_indexed_set_1():
from sympy.abc import n, m, t
assert imageset(Lambda(n, n), S.Integers) == imageset(Lambda(m, m), S.Integers)
assert imageset(Lambda(n, 2*n), S.Integers).intersect(
imageset(Lambda(m, 2*m + 1), S.Integers)) is S.EmptySet
assert imageset(Lambda(n, 2*n), S.Integers).intersect(
imageset(Lambda(n, 2*n + 1), S.Integers)) is S.EmptySet
assert imageset(Lambda(m, 2*m), S.Integers).intersect(
imageset(Lambda(n, 3*n), S.Integers)) == \
ImageSet(Lambda(t, 6*t), S.Integers)
assert imageset(x, x/2 + Rational(1, 3), S.Integers).intersect(S.Integers) is S.EmptySet
assert imageset(x, x/2 + S.Half, S.Integers).intersect(S.Integers) is S.Integers
# https://github.com/sympy/sympy/issues/17355
S53 = ImageSet(Lambda(n, 5*n + 3), S.Integers)
assert S53.intersect(S.Integers) == S53
def test_infinitely_indexed_set_2():
from sympy.abc import n
a = Symbol('a', integer=True)
assert imageset(Lambda(n, n), S.Integers) == \
imageset(Lambda(n, n + a), S.Integers)
assert imageset(Lambda(n, n + pi), S.Integers) == \
imageset(Lambda(n, n + a + pi), S.Integers)
assert imageset(Lambda(n, n), S.Integers) == \
imageset(Lambda(n, -n + a), S.Integers)
assert imageset(Lambda(n, -6*n), S.Integers) == \
ImageSet(Lambda(n, 6*n), S.Integers)
assert imageset(Lambda(n, 2*n + pi), S.Integers) == \
ImageSet(Lambda(n, 2*n + pi - 2), S.Integers)
def test_imageset_intersect_real():
from sympy import I
from sympy.abc import n
assert imageset(Lambda(n, n + (n - 1)*(n + 1)*I), S.Integers).intersect(S.Reals) == \
FiniteSet(-1, 1)
s = ImageSet(
Lambda(n, -I*(I*(2*pi*n - pi/4) + log(Abs(sqrt(-I))))),
S.Integers)
# s is unevaluated, but after intersection the result
# should be canonical
assert s.intersect(S.Reals) == imageset(
Lambda(n, 2*n*pi - pi/4), S.Integers) == ImageSet(
Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
def test_imageset_intersect_interval():
from sympy.abc import n
f1 = ImageSet(Lambda(n, n*pi), S.Integers)
f2 = ImageSet(Lambda(n, 2*n), Interval(0, pi))
f3 = ImageSet(Lambda(n, 2*n*pi + pi/2), S.Integers)
# complex expressions
f4 = ImageSet(Lambda(n, n*I*pi), S.Integers)
f5 = ImageSet(Lambda(n, 2*I*n*pi + pi/2), S.Integers)
# non-linear expressions
f6 = ImageSet(Lambda(n, log(n)), S.Integers)
f7 = ImageSet(Lambda(n, n**2), S.Integers)
f8 = ImageSet(Lambda(n, Abs(n)), S.Integers)
f9 = ImageSet(Lambda(n, exp(n)), S.Naturals0)
assert f1.intersect(Interval(-1, 1)) == FiniteSet(0)
assert f1.intersect(Interval(0, 2*pi, False, True)) == FiniteSet(0, pi)
assert f2.intersect(Interval(1, 2)) == Interval(1, 2)
assert f3.intersect(Interval(-1, 1)) == S.EmptySet
assert f3.intersect(Interval(-5, 5)) == FiniteSet(pi*Rational(-3, 2), pi/2)
assert f4.intersect(Interval(-1, 1)) == FiniteSet(0)
assert f4.intersect(Interval(1, 2)) == S.EmptySet
assert f5.intersect(Interval(0, 1)) == S.EmptySet
assert f6.intersect(Interval(0, 1)) == FiniteSet(S.Zero, log(2))
assert f7.intersect(Interval(0, 10)) == Intersection(f7, Interval(0, 10))
assert f8.intersect(Interval(0, 2)) == Intersection(f8, Interval(0, 2))
assert f9.intersect(Interval(1, 2)) == Intersection(f9, Interval(1, 2))
def test_imageset_intersect_diophantine():
from sympy.abc import m, n
# Check that same lambda variable for both ImageSets is handled correctly
img1 = ImageSet(Lambda(n, 2*n + 1), S.Integers)
img2 = ImageSet(Lambda(n, 4*n + 1), S.Integers)
assert img1.intersect(img2) == img2
# Empty solution set returned by diophantine:
assert ImageSet(Lambda(n, 2*n), S.Integers).intersect(
ImageSet(Lambda(n, 2*n + 1), S.Integers)) == S.EmptySet
# Check intersection with S.Integers:
assert ImageSet(Lambda(n, 9/n + 20*n/3), S.Integers).intersect(
S.Integers) == FiniteSet(-61, -23, 23, 61)
# Single solution (2, 3) for diophantine solution:
assert ImageSet(Lambda(n, (n - 2)**2), S.Integers).intersect(
ImageSet(Lambda(n, -(n - 3)**2), S.Integers)) == FiniteSet(0)
# Single parametric solution for diophantine solution:
assert ImageSet(Lambda(n, n**2 + 5), S.Integers).intersect(
ImageSet(Lambda(m, 2*m), S.Integers)) == ImageSet(
Lambda(n, 4*n**2 + 4*n + 6), S.Integers)
# 4 non-parametric solution couples for dioph. equation:
assert ImageSet(Lambda(n, n**2 - 9), S.Integers).intersect(
ImageSet(Lambda(m, -m**2), S.Integers)) == FiniteSet(-9, 0)
# Double parametric solution for diophantine solution:
assert ImageSet(Lambda(m, m**2 + 40), S.Integers).intersect(
ImageSet(Lambda(n, 41*n), S.Integers)) == Intersection(
ImageSet(Lambda(m, m**2 + 40), S.Integers),
ImageSet(Lambda(n, 41*n), S.Integers))
# Check that diophantine returns *all* (8) solutions (permute=True)
assert ImageSet(Lambda(n, n**4 - 2**4), S.Integers).intersect(
ImageSet(Lambda(m, -m**4 + 3**4), S.Integers)) == FiniteSet(0, 65)
assert ImageSet(Lambda(n, pi/12 + n*5*pi/12), S.Integers).intersect(
ImageSet(Lambda(n, 7*pi/12 + n*11*pi/12), S.Integers)) == ImageSet(
Lambda(n, 55*pi*n/12 + 17*pi/4), S.Integers)
# TypeError raised by diophantine (#18081)
assert ImageSet(Lambda(n, n*log(2)), S.Integers).intersection(S.Integers) \
== Intersection(ImageSet(Lambda(n, n*log(2)), S.Integers), S.Integers)
# NotImplementedError raised by diophantine (no solver for cubic_thue)
assert ImageSet(Lambda(n, n**3 + 1), S.Integers).intersect(
ImageSet(Lambda(n, n**3), S.Integers)) == Intersection(
ImageSet(Lambda(n, n**3 + 1), S.Integers),
ImageSet(Lambda(n, n**3), S.Integers))
def test_infinitely_indexed_set_3():
from sympy.abc import n, m, t
assert imageset(Lambda(m, 2*pi*m), S.Integers).intersect(
imageset(Lambda(n, 3*pi*n), S.Integers)) == \
ImageSet(Lambda(t, 6*pi*t), S.Integers)
assert imageset(Lambda(n, 2*n + 1), S.Integers) == \
imageset(Lambda(n, 2*n - 1), S.Integers)
assert imageset(Lambda(n, 3*n + 2), S.Integers) == \
imageset(Lambda(n, 3*n - 1), S.Integers)
def test_ImageSet_simplification():
from sympy.abc import n, m
assert imageset(Lambda(n, n), S.Integers) == S.Integers
assert imageset(Lambda(n, sin(n)),
imageset(Lambda(m, tan(m)), S.Integers)) == \
imageset(Lambda(m, sin(tan(m))), S.Integers)
assert imageset(n, 1 + 2*n, S.Naturals) == Range(3, oo, 2)
assert imageset(n, 1 + 2*n, S.Naturals0) == Range(1, oo, 2)
assert imageset(n, 1 - 2*n, S.Naturals) == Range(-1, -oo, -2)
def test_ImageSet_contains():
from sympy.abc import x
assert (2, S.Half) in imageset(x, (x, 1/x), S.Integers)
assert imageset(x, x + I*3, S.Integers).intersection(S.Reals) is S.EmptySet
i = Dummy(integer=True)
q = imageset(x, x + I*y, S.Integers).intersection(S.Reals)
assert q.subs(y, I*i).intersection(S.Integers) is S.Integers
q = imageset(x, x + I*y/x, S.Integers).intersection(S.Reals)
assert q.subs(y, 0) is S.Integers
assert q.subs(y, I*i*x).intersection(S.Integers) is S.Integers
z = cos(1)**2 + sin(1)**2 - 1
q = imageset(x, x + I*z, S.Integers).intersection(S.Reals)
assert q is not S.EmptySet
def test_ComplexRegion_contains():
r = Symbol('r', real=True)
# contains in ComplexRegion
a = Interval(2, 3)
b = Interval(4, 6)
c = Interval(7, 9)
c1 = ComplexRegion(a*b)
c2 = ComplexRegion(Union(a*b, c*a))
assert 2.5 + 4.5*I in c1
assert 2 + 4*I in c1
assert 3 + 4*I in c1
assert 8 + 2.5*I in c2
assert 2.5 + 6.1*I not in c1
assert 4.5 + 3.2*I not in c1
assert c1.contains(x) == Contains(x, c1, evaluate=False)
assert c1.contains(r) == False
assert c2.contains(x) == Contains(x, c2, evaluate=False)
assert c2.contains(r) == False
r1 = Interval(0, 1)
theta1 = Interval(0, 2*S.Pi)
c3 = ComplexRegion(r1*theta1, polar=True)
assert (0.5 + I*Rational(6, 10)) in c3
assert (S.Half + I*Rational(6, 10)) in c3
assert (S.Half + .6*I) in c3
assert (0.5 + .6*I) in c3
assert I in c3
assert 1 in c3
assert 0 in c3
assert 1 + I not in c3
assert 1 - I not in c3
assert c3.contains(x) == Contains(x, c3, evaluate=False)
assert c3.contains(r + 2*I) == Contains(
r + 2*I, c3, evaluate=False) # is in fact False
assert c3.contains(1/(1 + r**2)) == Contains(
1/(1 + r**2), c3, evaluate=False) # is in fact True
r2 = Interval(0, 3)
theta2 = Interval(pi, 2*pi, left_open=True)
c4 = ComplexRegion(r2*theta2, polar=True)
assert c4.contains(0) == True
assert c4.contains(2 + I) == False
assert c4.contains(-2 + I) == False
assert c4.contains(-2 - I) == True
assert c4.contains(2 - I) == True
assert c4.contains(-2) == False
assert c4.contains(2) == True
assert c4.contains(x) == Contains(x, c4, evaluate=False)
assert c4.contains(3/(1 + r**2)) == Contains(
3/(1 + r**2), c4, evaluate=False) # is in fact True
raises(ValueError, lambda: ComplexRegion(r1*theta1, polar=2))
def test_ComplexRegion_intersect():
# Polar form
X_axis = ComplexRegion(Interval(0, oo)*FiniteSet(0, S.Pi), polar=True)
unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
upper_half_unit_disk = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
upper_half_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
lower_half_disk = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
right_half_disk = ComplexRegion(Interval(0, oo)*Interval(-S.Pi/2, S.Pi/2), polar=True)
first_quad_disk = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi/2), polar=True)
assert upper_half_disk.intersect(unit_disk) == upper_half_unit_disk
assert right_half_disk.intersect(first_quad_disk) == first_quad_disk
assert upper_half_disk.intersect(right_half_disk) == first_quad_disk
assert upper_half_disk.intersect(lower_half_disk) == X_axis
c1 = ComplexRegion(Interval(0, 4)*Interval(0, 2*S.Pi), polar=True)
assert c1.intersect(Interval(1, 5)) == Interval(1, 4)
assert c1.intersect(Interval(4, 9)) == FiniteSet(4)
assert c1.intersect(Interval(5, 12)) is S.EmptySet
# Rectangular form
X_axis = ComplexRegion(Interval(-oo, oo)*FiniteSet(0))
unit_square = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
upper_half_unit_square = ComplexRegion(Interval(-1, 1)*Interval(0, 1))
upper_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(0, oo))
lower_half_plane = ComplexRegion(Interval(-oo, oo)*Interval(-oo, 0))
right_half_plane = ComplexRegion(Interval(0, oo)*Interval(-oo, oo))
first_quad_plane = ComplexRegion(Interval(0, oo)*Interval(0, oo))
assert upper_half_plane.intersect(unit_square) == upper_half_unit_square
assert right_half_plane.intersect(first_quad_plane) == first_quad_plane
assert upper_half_plane.intersect(right_half_plane) == first_quad_plane
assert upper_half_plane.intersect(lower_half_plane) == X_axis
c1 = ComplexRegion(Interval(-5, 5)*Interval(-10, 10))
assert c1.intersect(Interval(2, 7)) == Interval(2, 5)
assert c1.intersect(Interval(5, 7)) == FiniteSet(5)
assert c1.intersect(Interval(6, 9)) is S.EmptySet
# unevaluated object
C1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
C2 = ComplexRegion(Interval(-1, 1)*Interval(-1, 1))
assert C1.intersect(C2) == Intersection(C1, C2, evaluate=False)
def test_ComplexRegion_union():
# Polar form
c1 = ComplexRegion(Interval(0, 1)*Interval(0, 2*S.Pi), polar=True)
c2 = ComplexRegion(Interval(0, 1)*Interval(0, S.Pi), polar=True)
c3 = ComplexRegion(Interval(0, oo)*Interval(0, S.Pi), polar=True)
c4 = ComplexRegion(Interval(0, oo)*Interval(S.Pi, 2*S.Pi), polar=True)
p1 = Union(Interval(0, 1)*Interval(0, 2*S.Pi), Interval(0, 1)*Interval(0, S.Pi))
p2 = Union(Interval(0, oo)*Interval(0, S.Pi), Interval(0, oo)*Interval(S.Pi, 2*S.Pi))
assert c1.union(c2) == ComplexRegion(p1, polar=True)
assert c3.union(c4) == ComplexRegion(p2, polar=True)
# Rectangular form
c5 = ComplexRegion(Interval(2, 5)*Interval(6, 9))
c6 = ComplexRegion(Interval(4, 6)*Interval(10, 12))
c7 = ComplexRegion(Interval(0, 10)*Interval(-10, 0))
c8 = ComplexRegion(Interval(12, 16)*Interval(14, 20))
p3 = Union(Interval(2, 5)*Interval(6, 9), Interval(4, 6)*Interval(10, 12))
p4 = Union(Interval(0, 10)*Interval(-10, 0), Interval(12, 16)*Interval(14, 20))
assert c5.union(c6) == ComplexRegion(p3)
assert c7.union(c8) == ComplexRegion(p4)
assert c1.union(Interval(2, 4)) == Union(c1, Interval(2, 4), evaluate=False)
assert c5.union(Interval(2, 4)) == Union(c5, ComplexRegion.from_real(Interval(2, 4)))
def test_ComplexRegion_from_real():
c1 = ComplexRegion(Interval(0, 1) * Interval(0, 2 * S.Pi), polar=True)
raises(ValueError, lambda: c1.from_real(c1))
assert c1.from_real(Interval(-1, 1)) == ComplexRegion(Interval(-1, 1) * FiniteSet(0), False)
def test_ComplexRegion_measure():
a, b = Interval(2, 5), Interval(4, 8)
theta1, theta2 = Interval(0, 2*S.Pi), Interval(0, S.Pi)
c1 = ComplexRegion(a*b)
c2 = ComplexRegion(Union(a*theta1, b*theta2), polar=True)
assert c1.measure == 12
assert c2.measure == 9*pi
def test_normalize_theta_set():
# Interval
assert normalize_theta_set(Interval(pi, 2*pi)) == \
Union(FiniteSet(0), Interval.Ropen(pi, 2*pi))
assert normalize_theta_set(Interval(pi*Rational(9, 2), 5*pi)) == Interval(pi/2, pi)
assert normalize_theta_set(Interval(pi*Rational(-3, 2), pi/2)) == Interval.Ropen(0, 2*pi)
assert normalize_theta_set(Interval.open(pi*Rational(-3, 2), pi/2)) == \
Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
assert normalize_theta_set(Interval.open(pi*Rational(-7, 2), pi*Rational(-3, 2))) == \
Union(Interval.Ropen(0, pi/2), Interval.open(pi/2, 2*pi))
assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval.open(-pi/2, pi/2)) == \
Union(Interval.Ropen(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval(-4*pi, 3*pi)) == Interval.Ropen(0, 2*pi)
assert normalize_theta_set(Interval(pi*Rational(-3, 2), -pi/2)) == Interval(pi/2, pi*Rational(3, 2))
assert normalize_theta_set(Interval.open(0, 2*pi)) == Interval.open(0, 2*pi)
assert normalize_theta_set(Interval.Ropen(-pi/2, pi/2)) == \
Union(Interval.Ropen(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval.Lopen(-pi/2, pi/2)) == \
Union(Interval(0, pi/2), Interval.open(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval(-pi/2, pi/2)) == \
Union(Interval(0, pi/2), Interval.Ropen(pi*Rational(3, 2), 2*pi))
assert normalize_theta_set(Interval.open(4*pi, pi*Rational(9, 2))) == Interval.open(0, pi/2)
assert normalize_theta_set(Interval.Lopen(4*pi, pi*Rational(9, 2))) == Interval.Lopen(0, pi/2)
assert normalize_theta_set(Interval.Ropen(4*pi, pi*Rational(9, 2))) == Interval.Ropen(0, pi/2)
assert normalize_theta_set(Interval.open(3*pi, 5*pi)) == \
Union(Interval.Ropen(0, pi), Interval.open(pi, 2*pi))
# FiniteSet
assert normalize_theta_set(FiniteSet(0, pi, 3*pi)) == FiniteSet(0, pi)
assert normalize_theta_set(FiniteSet(0, pi/2, pi, 2*pi)) == FiniteSet(0, pi/2, pi)
assert normalize_theta_set(FiniteSet(0, -pi/2, -pi, -2*pi)) == FiniteSet(0, pi, pi*Rational(3, 2))
assert normalize_theta_set(FiniteSet(pi*Rational(-3, 2), pi/2)) == \
FiniteSet(pi/2)
assert normalize_theta_set(FiniteSet(2*pi)) == FiniteSet(0)
# Unions
assert normalize_theta_set(Union(Interval(0, pi/3), Interval(pi/2, pi))) == \
Union(Interval(0, pi/3), Interval(pi/2, pi))
assert normalize_theta_set(Union(Interval(0, pi), Interval(2*pi, pi*Rational(7, 3)))) == \
Interval(0, pi)
# ValueError for non-real sets
raises(ValueError, lambda: normalize_theta_set(S.Complexes))
# NotImplementedError for subset of reals
raises(NotImplementedError, lambda: normalize_theta_set(Interval(0, 1)))
# NotImplementedError without pi as coefficient
raises(NotImplementedError, lambda: normalize_theta_set(Interval(1, 2*pi)))
raises(NotImplementedError, lambda: normalize_theta_set(Interval(2*pi, 10)))
raises(NotImplementedError, lambda: normalize_theta_set(FiniteSet(0, 3, 3*pi)))
def test_ComplexRegion_FiniteSet():
x, y, z, a, b, c = symbols('x y z a b c')
# Issue #9669
assert ComplexRegion(FiniteSet(a, b, c)*FiniteSet(x, y, z)) == \
FiniteSet(a + I*x, a + I*y, a + I*z, b + I*x, b + I*y,
b + I*z, c + I*x, c + I*y, c + I*z)
assert ComplexRegion(FiniteSet(2)*FiniteSet(3)) == FiniteSet(2 + 3*I)
def test_union_RealSubSet():
assert (S.Complexes).union(Interval(1, 2)) == S.Complexes
assert (S.Complexes).union(S.Integers) == S.Complexes
def test_issue_9980():
c1 = ComplexRegion(Interval(1, 2)*Interval(2, 3))
c2 = ComplexRegion(Interval(1, 5)*Interval(1, 3))
R = Union(c1, c2)
assert simplify(R) == ComplexRegion(Union(Interval(1, 2)*Interval(2, 3), \
Interval(1, 5)*Interval(1, 3)), False)
assert c1.func(*c1.args) == c1
assert R.func(*R.args) == R
def test_issue_11732():
interval12 = Interval(1, 2)
finiteset1234 = FiniteSet(1, 2, 3, 4)
pointComplex = Tuple(1, 5)
assert (interval12 in S.Naturals) == False
assert (interval12 in S.Naturals0) == False
assert (interval12 in S.Integers) == False
assert (interval12 in S.Complexes) == False
assert (finiteset1234 in S.Naturals) == False
assert (finiteset1234 in S.Naturals0) == False
assert (finiteset1234 in S.Integers) == False
assert (finiteset1234 in S.Complexes) == False
assert (pointComplex in S.Naturals) == False
assert (pointComplex in S.Naturals0) == False
assert (pointComplex in S.Integers) == False
assert (pointComplex in S.Complexes) == True
def test_issue_11730():
unit = Interval(0, 1)
square = ComplexRegion(unit ** 2)
assert Union(S.Complexes, FiniteSet(oo)) != S.Complexes
assert Union(S.Complexes, FiniteSet(eye(4))) != S.Complexes
assert Union(unit, square) == square
assert Intersection(S.Reals, square) == unit
def test_issue_11938():
unit = Interval(0, 1)
ival = Interval(1, 2)
cr1 = ComplexRegion(ival * unit)
assert Intersection(cr1, S.Reals) == ival
assert Intersection(cr1, unit) == FiniteSet(1)
arg1 = Interval(0, S.Pi)
arg2 = FiniteSet(S.Pi)
arg3 = Interval(S.Pi / 4, 3 * S.Pi / 4)
cp1 = ComplexRegion(unit * arg1, polar=True)
cp2 = ComplexRegion(unit * arg2, polar=True)
cp3 = ComplexRegion(unit * arg3, polar=True)
assert Intersection(cp1, S.Reals) == Interval(-1, 1)
assert Intersection(cp2, S.Reals) == Interval(-1, 0)
assert Intersection(cp3, S.Reals) == FiniteSet(0)
def test_issue_11914():
a, b = Interval(0, 1), Interval(0, pi)
c, d = Interval(2, 3), Interval(pi, 3 * pi / 2)
cp1 = ComplexRegion(a * b, polar=True)
cp2 = ComplexRegion(c * d, polar=True)
assert -3 in cp1.union(cp2)
assert -3 in cp2.union(cp1)
assert -5 not in cp1.union(cp2)
def test_issue_9543():
assert ImageSet(Lambda(x, x**2), S.Naturals).is_subset(S.Reals)
def test_issue_16871():
assert ImageSet(Lambda(x, x), FiniteSet(1)) == {1}
assert ImageSet(Lambda(x, x - 3), S.Integers
).intersection(S.Integers) is S.Integers
@XFAIL
def test_issue_16871b():
assert ImageSet(Lambda(x, x - 3), S.Integers).is_subset(S.Integers)
def test_issue_18050():
assert imageset(Lambda(x, I*x + 1), S.Integers
) == ImageSet(Lambda(x, I*x + 1), S.Integers)
assert imageset(Lambda(x, 3*I*x + 4 + 8*I), S.Integers
) == ImageSet(Lambda(x, 3*I*x + 4 + 2*I), S.Integers)
# no 'Mod' for next 2 tests:
assert imageset(Lambda(x, 2*x + 3*I), S.Integers
) == ImageSet(Lambda(x, 2*x + 3*I), S.Integers)
r = Symbol('r', positive=True)
assert imageset(Lambda(x, r*x + 10), S.Integers
) == ImageSet(Lambda(x, r*x + 10), S.Integers)
# reduce real part:
assert imageset(Lambda(x, 3*x + 8 + 5*I), S.Integers
) == ImageSet(Lambda(x, 3*x + 2 + 5*I), S.Integers)
def test_Rationals():
assert S.Integers.is_subset(S.Rationals)
assert S.Naturals.is_subset(S.Rationals)
assert S.Naturals0.is_subset(S.Rationals)
assert S.Rationals.is_subset(S.Reals)
assert S.Rationals.inf is -oo
assert S.Rationals.sup is oo
it = iter(S.Rationals)
assert [next(it) for i in range(12)] == [
0, 1, -1, S.Half, 2, Rational(-1, 2), -2,
Rational(1, 3), 3, Rational(-1, 3), -3, Rational(2, 3)]
assert Basic() not in S.Rationals
assert S.Half in S.Rationals
assert 1.0 not in S.Rationals
assert 2 in S.Rationals
r = symbols('r', rational=True)
assert r in S.Rationals
raises(TypeError, lambda: x in S.Rationals)
# issue #18134:
assert S.Rationals.boundary == S.Reals
assert S.Rationals.closure == S.Reals
assert S.Rationals.is_open == False
assert S.Rationals.is_closed == False
def test_NZQRC_unions():
# check that all trivial number set unions are simplified:
nbrsets = (S.Naturals, S.Naturals0, S.Integers, S.Rationals,
S.Reals, S.Complexes)
unions = (Union(a, b) for a in nbrsets for b in nbrsets)
assert all(u.is_Union is False for u in unions)
def test_imageset_intersection():
n = Dummy()
s = ImageSet(Lambda(n, -I*(I*(2*pi*n - pi/4) +
log(Abs(sqrt(-I))))), S.Integers)
assert s.intersect(S.Reals) == ImageSet(
Lambda(n, 2*pi*n + pi*Rational(7, 4)), S.Integers)
def test_issue_17858():
assert 1 in Range(-oo, oo)
assert 0 in Range(oo, -oo, -1)
assert oo not in Range(-oo, oo)
assert -oo not in Range(-oo, oo)
def test_issue_17859():
r = Range(-oo,oo)
raises(ValueError,lambda: r[::2])
raises(ValueError, lambda: r[::-2])
r = Range(oo,-oo,-1)
raises(ValueError,lambda: r[::2])
raises(ValueError, lambda: r[::-2])
|
575ea9825b54ff2c5b63e6a52f7b2a3308455993fa1e90f6c35395c17c2d8a16 | from sympy import (Symbol, Set, Union, Interval, oo, S, sympify, nan,
Max, Min, Float,
FiniteSet, Intersection, imageset, I, true, false, ProductSet,
sqrt, Complement, EmptySet, sin, cos, Lambda, ImageSet, pi,
Pow, Contains, Sum, rootof, SymmetricDifference, Piecewise,
Matrix, Range, Add, symbols, zoo, Rational)
from mpmath import mpi
from sympy.core.expr import unchanged
from sympy.core.relational import Eq, Ne, Le, Lt, LessThan
from sympy.logic import And, Or, Xor
from sympy.testing.pytest import raises, XFAIL, warns_deprecated_sympy
from sympy.abc import x, y, z, m, n
def test_imageset():
ints = S.Integers
assert imageset(x, x - 1, S.Naturals) is S.Naturals0
assert imageset(x, x + 1, S.Naturals0) is S.Naturals
assert imageset(x, abs(x), S.Naturals0) is S.Naturals0
assert imageset(x, abs(x), S.Naturals) is S.Naturals
assert imageset(x, abs(x), S.Integers) is S.Naturals0
# issue 16878a
r = symbols('r', real=True)
assert imageset(x, (x, x), S.Reals)._contains((1, r)) == None
assert imageset(x, (x, x), S.Reals)._contains((1, 2)) == False
assert (r, r) in imageset(x, (x, x), S.Reals)
assert 1 + I in imageset(x, x + I, S.Reals)
assert {1} not in imageset(x, (x,), S.Reals)
assert (1, 1) not in imageset(x, (x,) , S.Reals)
raises(TypeError, lambda: imageset(x, ints))
raises(ValueError, lambda: imageset(x, y, z, ints))
raises(ValueError, lambda: imageset(Lambda(x, cos(x)), y))
assert (1, 2) in imageset(Lambda((x, y), (x, y)), ints, ints)
raises(ValueError, lambda: imageset(Lambda(x, x), ints, ints))
assert imageset(cos, ints) == ImageSet(Lambda(x, cos(x)), ints)
def f(x):
return cos(x)
assert imageset(f, ints) == imageset(x, cos(x), ints)
f = lambda x: cos(x)
assert imageset(f, ints) == ImageSet(Lambda(x, cos(x)), ints)
assert imageset(x, 1, ints) == FiniteSet(1)
assert imageset(x, y, ints) == {y}
assert imageset((x, y), (1, z), ints, S.Reals) == {(1, z)}
clash = Symbol('x', integer=true)
assert (str(imageset(lambda x: x + clash, Interval(-2, 1)).lamda.expr)
in ('_x + x', 'x + _x'))
x1, x2 = symbols("x1, x2")
assert imageset(lambda x, y: Add(x, y), Interval(1, 2), Interval(2, 3)) == \
ImageSet(Lambda((x1, x2), x1+x2), Interval(1, 2), Interval(2, 3))
def test_is_empty():
for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
S.UniversalSet]:
assert s.is_empty is False
assert S.EmptySet.is_empty is True
def test_is_finiteset():
for s in [S.Naturals, S.Naturals0, S.Integers, S.Rationals, S.Reals,
S.UniversalSet]:
assert s.is_finite_set is False
assert S.EmptySet.is_finite_set is True
assert FiniteSet(1, 2).is_finite_set is True
assert Interval(1, 2).is_finite_set is False
assert Interval(x, y).is_finite_set is None
assert ProductSet(FiniteSet(1), FiniteSet(2)).is_finite_set is True
assert ProductSet(FiniteSet(1), Interval(1, 2)).is_finite_set is False
assert ProductSet(FiniteSet(1), Interval(x, y)).is_finite_set is None
assert Union(Interval(0, 1), Interval(2, 3)).is_finite_set is False
assert Union(FiniteSet(1), Interval(2, 3)).is_finite_set is False
assert Union(FiniteSet(1), FiniteSet(2)).is_finite_set is True
assert Union(FiniteSet(1), Interval(x, y)).is_finite_set is None
assert Intersection(Interval(x, y), FiniteSet(1)).is_finite_set is True
assert Intersection(Interval(x, y), Interval(1, 2)).is_finite_set is None
assert Intersection(FiniteSet(x), FiniteSet(y)).is_finite_set is True
assert Complement(FiniteSet(1), Interval(x, y)).is_finite_set is True
assert Complement(Interval(x, y), FiniteSet(1)).is_finite_set is None
assert Complement(Interval(1, 2), FiniteSet(x)).is_finite_set is False
def test_deprecated_is_EmptySet():
with warns_deprecated_sympy():
S.EmptySet.is_EmptySet
def test_interval_arguments():
assert Interval(0, oo) == Interval(0, oo, False, True)
assert Interval(0, oo).right_open is true
assert Interval(-oo, 0) == Interval(-oo, 0, True, False)
assert Interval(-oo, 0).left_open is true
assert Interval(oo, -oo) == S.EmptySet
assert Interval(oo, oo) == S.EmptySet
assert Interval(-oo, -oo) == S.EmptySet
assert Interval(oo, x) == S.EmptySet
assert Interval(oo, oo) == S.EmptySet
assert Interval(x, -oo) == S.EmptySet
assert Interval(x, x) == {x}
assert isinstance(Interval(1, 1), FiniteSet)
e = Sum(x, (x, 1, 3))
assert isinstance(Interval(e, e), FiniteSet)
assert Interval(1, 0) == S.EmptySet
assert Interval(1, 1).measure == 0
assert Interval(1, 1, False, True) == S.EmptySet
assert Interval(1, 1, True, False) == S.EmptySet
assert Interval(1, 1, True, True) == S.EmptySet
assert isinstance(Interval(0, Symbol('a')), Interval)
assert Interval(Symbol('a', real=True, positive=True), 0) == S.EmptySet
raises(ValueError, lambda: Interval(0, S.ImaginaryUnit))
raises(ValueError, lambda: Interval(0, Symbol('z', extended_real=False)))
raises(ValueError, lambda: Interval(x, x + S.ImaginaryUnit))
raises(NotImplementedError, lambda: Interval(0, 1, And(x, y)))
raises(NotImplementedError, lambda: Interval(0, 1, False, And(x, y)))
raises(NotImplementedError, lambda: Interval(0, 1, z, And(x, y)))
def test_interval_symbolic_end_points():
a = Symbol('a', real=True)
assert Union(Interval(0, a), Interval(0, 3)).sup == Max(a, 3)
assert Union(Interval(a, 0), Interval(-3, 0)).inf == Min(-3, a)
assert Interval(0, a).contains(1) == LessThan(1, a)
def test_interval_is_empty():
x, y = symbols('x, y')
r = Symbol('r', real=True)
p = Symbol('p', positive=True)
n = Symbol('n', negative=True)
nn = Symbol('nn', nonnegative=True)
assert Interval(1, 2).is_empty == False
assert Interval(3, 3).is_empty == False # FiniteSet
assert Interval(r, r).is_empty == False # FiniteSet
assert Interval(r, r + nn).is_empty == False
assert Interval(x, x).is_empty == False
assert Interval(1, oo).is_empty == False
assert Interval(-oo, oo).is_empty == False
assert Interval(-oo, 1).is_empty == False
assert Interval(x, y).is_empty == None
assert Interval(r, oo).is_empty == False # real implies finite
assert Interval(n, 0).is_empty == False
assert Interval(n, 0, left_open=True).is_empty == False
assert Interval(p, 0).is_empty == True # EmptySet
assert Interval(nn, 0).is_empty == None
assert Interval(n, p).is_empty == False
assert Interval(0, p, left_open=True).is_empty == False
assert Interval(0, p, right_open=True).is_empty == False
assert Interval(0, nn, left_open=True).is_empty == None
assert Interval(0, nn, right_open=True).is_empty == None
def test_union():
assert Union(Interval(1, 2), Interval(2, 3)) == Interval(1, 3)
assert Union(Interval(1, 2), Interval(2, 3, True)) == Interval(1, 3)
assert Union(Interval(1, 3), Interval(2, 4)) == Interval(1, 4)
assert Union(Interval(1, 2), Interval(1, 3)) == Interval(1, 3)
assert Union(Interval(1, 3), Interval(1, 2)) == Interval(1, 3)
assert Union(Interval(1, 3, False, True), Interval(1, 2)) == \
Interval(1, 3, False, True)
assert Union(Interval(1, 3), Interval(1, 2, False, True)) == Interval(1, 3)
assert Union(Interval(1, 2, True), Interval(1, 3)) == Interval(1, 3)
assert Union(Interval(1, 2, True), Interval(1, 3, True)) == \
Interval(1, 3, True)
assert Union(Interval(1, 2, True), Interval(1, 3, True, True)) == \
Interval(1, 3, True, True)
assert Union(Interval(1, 2, True, True), Interval(1, 3, True)) == \
Interval(1, 3, True)
assert Union(Interval(1, 3), Interval(2, 3)) == Interval(1, 3)
assert Union(Interval(1, 3, False, True), Interval(2, 3)) == \
Interval(1, 3)
assert Union(Interval(1, 2, False, True), Interval(2, 3, True)) != \
Interval(1, 3)
assert Union(Interval(1, 2), S.EmptySet) == Interval(1, 2)
assert Union(S.EmptySet) == S.EmptySet
assert Union(Interval(0, 1), *[FiniteSet(1.0/n) for n in range(1, 10)]) == \
Interval(0, 1)
# issue #18241:
x = Symbol('x')
assert Union(Interval(0, 1), FiniteSet(1, x)) == Union(
Interval(0, 1), FiniteSet(x))
assert unchanged(Union, Interval(0, 1), FiniteSet(2, x))
assert Interval(1, 2).union(Interval(2, 3)) == \
Interval(1, 2) + Interval(2, 3)
assert Interval(1, 2).union(Interval(2, 3)) == Interval(1, 3)
assert Union(Set()) == Set()
assert FiniteSet(1) + FiniteSet(2) + FiniteSet(3) == FiniteSet(1, 2, 3)
assert FiniteSet('ham') + FiniteSet('eggs') == FiniteSet('ham', 'eggs')
assert FiniteSet(1, 2, 3) + S.EmptySet == FiniteSet(1, 2, 3)
assert FiniteSet(1, 2, 3) & FiniteSet(2, 3, 4) == FiniteSet(2, 3)
assert FiniteSet(1, 2, 3) | FiniteSet(2, 3, 4) == FiniteSet(1, 2, 3, 4)
assert FiniteSet(1, 2, 3) & S.EmptySet == S.EmptySet
assert FiniteSet(1, 2, 3) | S.EmptySet == FiniteSet(1, 2, 3)
x = Symbol("x")
y = Symbol("y")
z = Symbol("z")
assert S.EmptySet | FiniteSet(x, FiniteSet(y, z)) == \
FiniteSet(x, FiniteSet(y, z))
# Test that Intervals and FiniteSets play nicely
assert Interval(1, 3) + FiniteSet(2) == Interval(1, 3)
assert Interval(1, 3, True, True) + FiniteSet(3) == \
Interval(1, 3, True, False)
X = Interval(1, 3) + FiniteSet(5)
Y = Interval(1, 2) + FiniteSet(3)
XandY = X.intersect(Y)
assert 2 in X and 3 in X and 3 in XandY
assert XandY.is_subset(X) and XandY.is_subset(Y)
raises(TypeError, lambda: Union(1, 2, 3))
assert X.is_iterable is False
# issue 7843
assert Union(S.EmptySet, FiniteSet(-sqrt(-I), sqrt(-I))) == \
FiniteSet(-sqrt(-I), sqrt(-I))
assert Union(S.Reals, S.Integers) == S.Reals
def test_union_iter():
# Use Range because it is ordered
u = Union(Range(3), Range(5), Range(4), evaluate=False)
# Round robin
assert list(u) == [0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 4]
def test_union_is_empty():
assert (Interval(x, y) + FiniteSet(1)).is_empty == False
assert (Interval(x, y) + Interval(-x, y)).is_empty == None
def test_difference():
assert Interval(1, 3) - Interval(1, 2) == Interval(2, 3, True)
assert Interval(1, 3) - Interval(2, 3) == Interval(1, 2, False, True)
assert Interval(1, 3, True) - Interval(2, 3) == Interval(1, 2, True, True)
assert Interval(1, 3, True) - Interval(2, 3, True) == \
Interval(1, 2, True, False)
assert Interval(0, 2) - FiniteSet(1) == \
Union(Interval(0, 1, False, True), Interval(1, 2, True, False))
# issue #18119
assert S.Reals - FiniteSet(I) == S.Reals
assert S.Reals - FiniteSet(-I, I) == S.Reals
assert Interval(0, 10) - FiniteSet(-I, I) == Interval(0, 10)
assert Interval(0, 10) - FiniteSet(1, I) == Union(
Interval.Ropen(0, 1), Interval.Lopen(1, 10))
assert S.Reals - FiniteSet(1, 2 + I, x, y**2) == Complement(
Union(Interval.open(-oo, 1), Interval.open(1, oo)), FiniteSet(x, y**2),
evaluate=False)
assert FiniteSet(1, 2, 3) - FiniteSet(2) == FiniteSet(1, 3)
assert FiniteSet('ham', 'eggs') - FiniteSet('eggs') == FiniteSet('ham')
assert FiniteSet(1, 2, 3, 4) - Interval(2, 10, True, False) == \
FiniteSet(1, 2)
assert FiniteSet(1, 2, 3, 4) - S.EmptySet == FiniteSet(1, 2, 3, 4)
assert Union(Interval(0, 2), FiniteSet(2, 3, 4)) - Interval(1, 3) == \
Union(Interval(0, 1, False, True), FiniteSet(4))
assert -1 in S.Reals - S.Naturals
def test_Complement():
A = FiniteSet(1, 3, 4)
B = FiniteSet(3, 4)
C = Interval(1, 3)
D = Interval(1, 2)
assert Complement(A, B, evaluate=False).is_iterable is True
assert Complement(A, C, evaluate=False).is_iterable is True
assert Complement(C, D, evaluate=False).is_iterable is None
assert FiniteSet(*Complement(A, B, evaluate=False)) == FiniteSet(1)
assert FiniteSet(*Complement(A, C, evaluate=False)) == FiniteSet(4)
raises(TypeError, lambda: FiniteSet(*Complement(C, A, evaluate=False)))
assert Complement(Interval(1, 3), Interval(1, 2)) == Interval(2, 3, True)
assert Complement(FiniteSet(1, 3, 4), FiniteSet(3, 4)) == FiniteSet(1)
assert Complement(Union(Interval(0, 2), FiniteSet(2, 3, 4)),
Interval(1, 3)) == \
Union(Interval(0, 1, False, True), FiniteSet(4))
assert not 3 in Complement(Interval(0, 5), Interval(1, 4), evaluate=False)
assert -1 in Complement(S.Reals, S.Naturals, evaluate=False)
assert not 1 in Complement(S.Reals, S.Naturals, evaluate=False)
assert Complement(S.Integers, S.UniversalSet) == EmptySet
assert S.UniversalSet.complement(S.Integers) == EmptySet
assert (not 0 in S.Reals.intersect(S.Integers - FiniteSet(0)))
assert S.EmptySet - S.Integers == S.EmptySet
assert (S.Integers - FiniteSet(0)) - FiniteSet(1) == S.Integers - FiniteSet(0, 1)
assert S.Reals - Union(S.Naturals, FiniteSet(pi)) == \
Intersection(S.Reals - S.Naturals, S.Reals - FiniteSet(pi))
# issue 12712
assert Complement(FiniteSet(x, y, 2), Interval(-10, 10)) == \
Complement(FiniteSet(x, y), Interval(-10, 10))
A = FiniteSet(*symbols('a:c'))
B = FiniteSet(*symbols('d:f'))
assert unchanged(Complement, ProductSet(A, A), B)
A2 = ProductSet(A, A)
B3 = ProductSet(B, B, B)
assert A2 - B3 == A2
assert B3 - A2 == B3
def test_set_operations_nonsets():
'''Tests that e.g. FiniteSet(1) * 2 raises TypeError'''
ops = [
lambda a, b: a + b,
lambda a, b: a - b,
lambda a, b: a * b,
lambda a, b: a / b,
lambda a, b: a // b,
lambda a, b: a | b,
lambda a, b: a & b,
lambda a, b: a ^ b,
# FiniteSet(1) ** 2 gives a ProductSet
#lambda a, b: a ** b,
]
Sx = FiniteSet(x)
Sy = FiniteSet(y)
sets = [
{1},
FiniteSet(1),
Interval(1, 2),
Union(Sx, Interval(1, 2)),
Intersection(Sx, Sy),
Complement(Sx, Sy),
ProductSet(Sx, Sy),
S.EmptySet,
]
nums = [0, 1, 2, S(0), S(1), S(2)]
for si in sets:
for ni in nums:
for op in ops:
raises(TypeError, lambda : op(si, ni))
raises(TypeError, lambda : op(ni, si))
raises(TypeError, lambda: si ** object())
raises(TypeError, lambda: si ** {1})
def test_complement():
assert Interval(0, 1).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, oo, True, True))
assert Interval(0, 1, True, False).complement(S.Reals) == \
Union(Interval(-oo, 0, True, False), Interval(1, oo, True, True))
assert Interval(0, 1, False, True).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, oo, False, True))
assert Interval(0, 1, True, True).complement(S.Reals) == \
Union(Interval(-oo, 0, True, False), Interval(1, oo, False, True))
assert S.UniversalSet.complement(S.EmptySet) == S.EmptySet
assert S.UniversalSet.complement(S.Reals) == S.EmptySet
assert S.UniversalSet.complement(S.UniversalSet) == S.EmptySet
assert S.EmptySet.complement(S.Reals) == S.Reals
assert Union(Interval(0, 1), Interval(2, 3)).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(1, 2, True, True),
Interval(3, oo, True, True))
assert FiniteSet(0).complement(S.Reals) == \
Union(Interval(-oo, 0, True, True), Interval(0, oo, True, True))
assert (FiniteSet(5) + Interval(S.NegativeInfinity,
0)).complement(S.Reals) == \
Interval(0, 5, True, True) + Interval(5, S.Infinity, True, True)
assert FiniteSet(1, 2, 3).complement(S.Reals) == \
Interval(S.NegativeInfinity, 1, True, True) + \
Interval(1, 2, True, True) + Interval(2, 3, True, True) +\
Interval(3, S.Infinity, True, True)
assert FiniteSet(x).complement(S.Reals) == Complement(S.Reals, FiniteSet(x))
assert FiniteSet(0, x).complement(S.Reals) == Complement(Interval(-oo, 0, True, True) +
Interval(0, oo, True, True)
,FiniteSet(x), evaluate=False)
square = Interval(0, 1) * Interval(0, 1)
notsquare = square.complement(S.Reals*S.Reals)
assert all(pt in square for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
assert not any(
pt in notsquare for pt in [(0, 0), (.5, .5), (1, 0), (1, 1)])
assert not any(pt in square for pt in [(-1, 0), (1.5, .5), (10, 10)])
assert all(pt in notsquare for pt in [(-1, 0), (1.5, .5), (10, 10)])
def test_intersect1():
assert all(S.Integers.intersection(i) is i for i in
(S.Naturals, S.Naturals0))
assert all(i.intersection(S.Integers) is i for i in
(S.Naturals, S.Naturals0))
s = S.Naturals0
assert S.Naturals.intersection(s) is S.Naturals
assert s.intersection(S.Naturals) is S.Naturals
x = Symbol('x')
assert Interval(0, 2).intersect(Interval(1, 2)) == Interval(1, 2)
assert Interval(0, 2).intersect(Interval(1, 2, True)) == \
Interval(1, 2, True)
assert Interval(0, 2, True).intersect(Interval(1, 2)) == \
Interval(1, 2, False, False)
assert Interval(0, 2, True, True).intersect(Interval(1, 2)) == \
Interval(1, 2, False, True)
assert Interval(0, 2).intersect(Union(Interval(0, 1), Interval(2, 3))) == \
Union(Interval(0, 1), Interval(2, 2))
assert FiniteSet(1, 2).intersect(FiniteSet(1, 2, 3)) == FiniteSet(1, 2)
assert FiniteSet(1, 2, x).intersect(FiniteSet(x)) == FiniteSet(x)
assert FiniteSet('ham', 'eggs').intersect(FiniteSet('ham')) == \
FiniteSet('ham')
assert FiniteSet(1, 2, 3, 4, 5).intersect(S.EmptySet) == S.EmptySet
assert Interval(0, 5).intersect(FiniteSet(1, 3)) == FiniteSet(1, 3)
assert Interval(0, 1, True, True).intersect(FiniteSet(1)) == S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(0, 2)) == \
Union(Interval(0, 1), Interval(2, 2))
assert Union(Interval(0, 1), Interval(2, 3)).intersect(Interval(1, 2, True, True)) == \
S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersect(S.EmptySet) == \
S.EmptySet
assert Union(Interval(0, 5), FiniteSet('ham')).intersect(FiniteSet(2, 3, 4, 5, 6)) == \
Intersection(FiniteSet(2, 3, 4, 5, 6), Union(FiniteSet('ham'), Interval(0, 5)))
assert Intersection(FiniteSet(1, 2, 3), Interval(2, x), Interval(3, y)) == \
Intersection(FiniteSet(3), Interval(2, x), Interval(3, y), evaluate=False)
assert Intersection(FiniteSet(1, 2), Interval(0, 3), Interval(x, y)) == \
Intersection({1, 2}, Interval(x, y), evaluate=False)
assert Intersection(FiniteSet(1, 2, 4), Interval(0, 3), Interval(x, y)) == \
Intersection({1, 2}, Interval(x, y), evaluate=False)
# XXX: Is the real=True necessary here?
# https://github.com/sympy/sympy/issues/17532
m, n = symbols('m, n', real=True)
assert Intersection(FiniteSet(m), FiniteSet(m, n), Interval(m, m+1)) == \
FiniteSet(m)
# issue 8217
assert Intersection(FiniteSet(x), FiniteSet(y)) == \
Intersection(FiniteSet(x), FiniteSet(y), evaluate=False)
assert FiniteSet(x).intersect(S.Reals) == \
Intersection(S.Reals, FiniteSet(x), evaluate=False)
# tests for the intersection alias
assert Interval(0, 5).intersection(FiniteSet(1, 3)) == FiniteSet(1, 3)
assert Interval(0, 1, True, True).intersection(FiniteSet(1)) == S.EmptySet
assert Union(Interval(0, 1), Interval(2, 3)).intersection(Interval(1, 2)) == \
Union(Interval(1, 1), Interval(2, 2))
def test_intersection():
# iterable
i = Intersection(FiniteSet(1, 2, 3), Interval(2, 5), evaluate=False)
assert i.is_iterable
assert set(i) == {S(2), S(3)}
# challenging intervals
x = Symbol('x', real=True)
i = Intersection(Interval(0, 3), Interval(x, 6))
assert (5 in i) is False
raises(TypeError, lambda: 2 in i)
# Singleton special cases
assert Intersection(Interval(0, 1), S.EmptySet) == S.EmptySet
assert Intersection(Interval(-oo, oo), Interval(-oo, x)) == Interval(-oo, x)
# Products
line = Interval(0, 5)
i = Intersection(line**2, line**3, evaluate=False)
assert (2, 2) not in i
assert (2, 2, 2) not in i
raises(TypeError, lambda: list(i))
a = Intersection(Intersection(S.Integers, S.Naturals, evaluate=False), S.Reals, evaluate=False)
assert a._argset == frozenset([Intersection(S.Naturals, S.Integers, evaluate=False), S.Reals])
assert Intersection(S.Complexes, FiniteSet(S.ComplexInfinity)) == S.EmptySet
# issue 12178
assert Intersection() == S.UniversalSet
# issue 16987
assert Intersection({1}, {1}, {x}) == Intersection({1}, {x})
def test_issue_9623():
n = Symbol('n')
a = S.Reals
b = Interval(0, oo)
c = FiniteSet(n)
assert Intersection(a, b, c) == Intersection(b, c)
assert Intersection(Interval(1, 2), Interval(3, 4), FiniteSet(n)) == EmptySet
def test_is_disjoint():
assert Interval(0, 2).is_disjoint(Interval(1, 2)) == False
assert Interval(0, 2).is_disjoint(Interval(3, 4)) == True
def test_ProductSet__len__():
A = FiniteSet(1, 2)
B = FiniteSet(1, 2, 3)
assert ProductSet(A).__len__() == 2
assert ProductSet(A).__len__() is not S(2)
assert ProductSet(A, B).__len__() == 6
assert ProductSet(A, B).__len__() is not S(6)
def test_ProductSet():
# ProductSet is always a set of Tuples
assert ProductSet(S.Reals) == S.Reals ** 1
assert ProductSet(S.Reals, S.Reals) == S.Reals ** 2
assert ProductSet(S.Reals, S.Reals, S.Reals) == S.Reals ** 3
assert ProductSet(S.Reals) != S.Reals
assert ProductSet(S.Reals, S.Reals) == S.Reals * S.Reals
assert ProductSet(S.Reals, S.Reals, S.Reals) != S.Reals * S.Reals * S.Reals
assert ProductSet(S.Reals, S.Reals, S.Reals) == (S.Reals * S.Reals * S.Reals).flatten()
assert 1 not in ProductSet(S.Reals)
assert (1,) in ProductSet(S.Reals)
assert 1 not in ProductSet(S.Reals, S.Reals)
assert (1, 2) in ProductSet(S.Reals, S.Reals)
assert (1, I) not in ProductSet(S.Reals, S.Reals)
assert (1, 2, 3) in ProductSet(S.Reals, S.Reals, S.Reals)
assert (1, 2, 3) in S.Reals ** 3
assert (1, 2, 3) not in S.Reals * S.Reals * S.Reals
assert ((1, 2), 3) in S.Reals * S.Reals * S.Reals
assert (1, (2, 3)) not in S.Reals * S.Reals * S.Reals
assert (1, (2, 3)) in S.Reals * (S.Reals * S.Reals)
assert ProductSet() == FiniteSet(())
assert ProductSet(S.Reals, S.EmptySet) == S.EmptySet
# See GH-17458
for ni in range(5):
Rn = ProductSet(*(S.Reals,) * ni)
assert (1,) * ni in Rn
assert 1 not in Rn
assert (S.Reals * S.Reals) * S.Reals != S.Reals * (S.Reals * S.Reals)
S1 = S.Reals
S2 = S.Integers
x1 = pi
x2 = 3
assert x1 in S1
assert x2 in S2
assert (x1, x2) in S1 * S2
S3 = S1 * S2
x3 = (x1, x2)
assert x3 in S3
assert (x3, x3) in S3 * S3
assert x3 + x3 not in S3 * S3
raises(ValueError, lambda: S.Reals**-1)
with warns_deprecated_sympy():
ProductSet(FiniteSet(s) for s in range(2))
raises(TypeError, lambda: ProductSet(None))
S1 = FiniteSet(1, 2)
S2 = FiniteSet(3, 4)
S3 = ProductSet(S1, S2)
assert (S3.as_relational(x, y)
== And(S1.as_relational(x), S2.as_relational(y))
== And(Or(Eq(x, 1), Eq(x, 2)), Or(Eq(y, 3), Eq(y, 4))))
raises(ValueError, lambda: S3.as_relational(x))
raises(ValueError, lambda: S3.as_relational(x, 1))
raises(ValueError, lambda: ProductSet(Interval(0, 1)).as_relational(x, y))
Z2 = ProductSet(S.Integers, S.Integers)
assert Z2.contains((1, 2)) is S.true
assert Z2.contains((1,)) is S.false
assert Z2.contains(x) == Contains(x, Z2, evaluate=False)
assert Z2.contains(x).subs(x, 1) is S.false
assert Z2.contains((x, 1)).subs(x, 2) is S.true
assert Z2.contains((x, y)) == Contains((x, y), Z2, evaluate=False)
assert unchanged(Contains, (x, y), Z2)
assert Contains((1, 2), Z2) is S.true
def test_ProductSet_of_single_arg_is_not_arg():
assert unchanged(ProductSet, Interval(0, 1))
assert ProductSet(Interval(0, 1)) != Interval(0, 1)
def test_ProductSet_is_empty():
assert ProductSet(S.Integers, S.Reals).is_empty == False
assert ProductSet(Interval(x, 1), S.Reals).is_empty == None
def test_interval_subs():
a = Symbol('a', real=True)
assert Interval(0, a).subs(a, 2) == Interval(0, 2)
assert Interval(a, 0).subs(a, 2) == S.EmptySet
def test_interval_to_mpi():
assert Interval(0, 1).to_mpi() == mpi(0, 1)
assert Interval(0, 1, True, False).to_mpi() == mpi(0, 1)
assert type(Interval(0, 1).to_mpi()) == type(mpi(0, 1))
def test_set_evalf():
assert Interval(S(11)/64, S.Half).evalf() == Interval(
Float('0.171875'), Float('0.5'))
assert Interval(x, S.Half, right_open=True).evalf() == Interval(
x, Float('0.5'), right_open=True)
assert Interval(-oo, S.Half).evalf() == Interval(-oo, Float('0.5'))
assert FiniteSet(2, x).evalf() == FiniteSet(Float('2.0'), x)
def test_measure():
a = Symbol('a', real=True)
assert Interval(1, 3).measure == 2
assert Interval(0, a).measure == a
assert Interval(1, a).measure == a - 1
assert Union(Interval(1, 2), Interval(3, 4)).measure == 2
assert Union(Interval(1, 2), Interval(3, 4), FiniteSet(5, 6, 7)).measure \
== 2
assert FiniteSet(1, 2, oo, a, -oo, -5).measure == 0
assert S.EmptySet.measure == 0
square = Interval(0, 10) * Interval(0, 10)
offsetsquare = Interval(5, 15) * Interval(5, 15)
band = Interval(-oo, oo) * Interval(2, 4)
assert square.measure == offsetsquare.measure == 100
assert (square + offsetsquare).measure == 175 # there is some overlap
assert (square - offsetsquare).measure == 75
assert (square * FiniteSet(1, 2, 3)).measure == 0
assert (square.intersect(band)).measure == 20
assert (square + band).measure is oo
assert (band * FiniteSet(1, 2, 3)).measure is nan
def test_is_subset():
assert Interval(0, 1).is_subset(Interval(0, 2)) is True
assert Interval(0, 3).is_subset(Interval(0, 2)) is False
assert Interval(0, 1).is_subset(FiniteSet(0, 1)) is False
assert FiniteSet(1, 2).is_subset(FiniteSet(1, 2, 3, 4))
assert FiniteSet(4, 5).is_subset(FiniteSet(1, 2, 3, 4)) is False
assert FiniteSet(1).is_subset(Interval(0, 2))
assert FiniteSet(1, 2).is_subset(Interval(0, 2, True, True)) is False
assert (Interval(1, 2) + FiniteSet(3)).is_subset(
(Interval(0, 2, False, True) + FiniteSet(2, 3)))
assert Interval(3, 4).is_subset(Union(Interval(0, 1), Interval(2, 5))) is True
assert Interval(3, 6).is_subset(Union(Interval(0, 1), Interval(2, 5))) is False
assert FiniteSet(1, 2, 3, 4).is_subset(Interval(0, 5)) is True
assert S.EmptySet.is_subset(FiniteSet(1, 2, 3)) is True
assert Interval(0, 1).is_subset(S.EmptySet) is False
assert S.EmptySet.is_subset(S.EmptySet) is True
raises(ValueError, lambda: S.EmptySet.is_subset(1))
# tests for the issubset alias
assert FiniteSet(1, 2, 3, 4).issubset(Interval(0, 5)) is True
assert S.EmptySet.issubset(FiniteSet(1, 2, 3)) is True
assert S.Naturals.is_subset(S.Integers)
assert S.Naturals0.is_subset(S.Integers)
assert FiniteSet(x).is_subset(FiniteSet(y)) is None
assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x)) is True
assert FiniteSet(x).is_subset(FiniteSet(y).subs(y, x+1)) is False
assert Interval(0, 1).is_subset(Interval(0, 1, left_open=True)) is False
assert Interval(-2, 3).is_subset(Union(Interval(-oo, -2), Interval(3, oo))) is False
n = Symbol('n', integer=True)
assert Range(-3, 4, 1).is_subset(FiniteSet(-10, 10)) is False
assert Range(S(10)**100).is_subset(FiniteSet(0, 1, 2)) is False
assert Range(6, 0, -2).is_subset(FiniteSet(2, 4, 6)) is True
assert Range(1, oo).is_subset(FiniteSet(1, 2)) is False
assert Range(-oo, 1).is_subset(FiniteSet(1)) is False
assert Range(3).is_subset(FiniteSet(0, 1, n)) is None
assert Range(n, n + 2).is_subset(FiniteSet(n, n + 1)) is True
assert Range(5).is_subset(Interval(0, 4, right_open=True)) is False
def test_is_proper_subset():
assert Interval(0, 1).is_proper_subset(Interval(0, 2)) is True
assert Interval(0, 3).is_proper_subset(Interval(0, 2)) is False
assert S.EmptySet.is_proper_subset(FiniteSet(1, 2, 3)) is True
raises(ValueError, lambda: Interval(0, 1).is_proper_subset(0))
def test_is_superset():
assert Interval(0, 1).is_superset(Interval(0, 2)) == False
assert Interval(0, 3).is_superset(Interval(0, 2))
assert FiniteSet(1, 2).is_superset(FiniteSet(1, 2, 3, 4)) == False
assert FiniteSet(4, 5).is_superset(FiniteSet(1, 2, 3, 4)) == False
assert FiniteSet(1).is_superset(Interval(0, 2)) == False
assert FiniteSet(1, 2).is_superset(Interval(0, 2, True, True)) == False
assert (Interval(1, 2) + FiniteSet(3)).is_superset(
(Interval(0, 2, False, True) + FiniteSet(2, 3))) == False
assert Interval(3, 4).is_superset(Union(Interval(0, 1), Interval(2, 5))) == False
assert FiniteSet(1, 2, 3, 4).is_superset(Interval(0, 5)) == False
assert S.EmptySet.is_superset(FiniteSet(1, 2, 3)) == False
assert Interval(0, 1).is_superset(S.EmptySet) == True
assert S.EmptySet.is_superset(S.EmptySet) == True
raises(ValueError, lambda: S.EmptySet.is_superset(1))
# tests for the issuperset alias
assert Interval(0, 1).issuperset(S.EmptySet) == True
assert S.EmptySet.issuperset(S.EmptySet) == True
def test_is_proper_superset():
assert Interval(0, 1).is_proper_superset(Interval(0, 2)) is False
assert Interval(0, 3).is_proper_superset(Interval(0, 2)) is True
assert FiniteSet(1, 2, 3).is_proper_superset(S.EmptySet) is True
raises(ValueError, lambda: Interval(0, 1).is_proper_superset(0))
def test_contains():
assert Interval(0, 2).contains(1) is S.true
assert Interval(0, 2).contains(3) is S.false
assert Interval(0, 2, True, False).contains(0) is S.false
assert Interval(0, 2, True, False).contains(2) is S.true
assert Interval(0, 2, False, True).contains(0) is S.true
assert Interval(0, 2, False, True).contains(2) is S.false
assert Interval(0, 2, True, True).contains(0) is S.false
assert Interval(0, 2, True, True).contains(2) is S.false
assert (Interval(0, 2) in Interval(0, 2)) is False
assert FiniteSet(1, 2, 3).contains(2) is S.true
assert FiniteSet(1, 2, Symbol('x')).contains(Symbol('x')) is S.true
assert FiniteSet(y)._contains(x) is None
raises(TypeError, lambda: x in FiniteSet(y))
assert FiniteSet({x, y})._contains({x}) is None
assert FiniteSet({x, y}).subs(y, x)._contains({x}) is True
assert FiniteSet({x, y}).subs(y, x+1)._contains({x}) is False
# issue 8197
from sympy.abc import a, b
assert isinstance(FiniteSet(b).contains(-a), Contains)
assert isinstance(FiniteSet(b).contains(a), Contains)
assert isinstance(FiniteSet(a).contains(1), Contains)
raises(TypeError, lambda: 1 in FiniteSet(a))
# issue 8209
rad1 = Pow(Pow(2, Rational(1, 3)) - 1, Rational(1, 3))
rad2 = Pow(Rational(1, 9), Rational(1, 3)) - Pow(Rational(2, 9), Rational(1, 3)) + Pow(Rational(4, 9), Rational(1, 3))
s1 = FiniteSet(rad1)
s2 = FiniteSet(rad2)
assert s1 - s2 == S.EmptySet
items = [1, 2, S.Infinity, S('ham'), -1.1]
fset = FiniteSet(*items)
assert all(item in fset for item in items)
assert all(fset.contains(item) is S.true for item in items)
assert Union(Interval(0, 1), Interval(2, 5)).contains(3) is S.true
assert Union(Interval(0, 1), Interval(2, 5)).contains(6) is S.false
assert Union(Interval(0, 1), FiniteSet(2, 5)).contains(3) is S.false
assert S.EmptySet.contains(1) is S.false
assert FiniteSet(rootof(x**3 + x - 1, 0)).contains(S.Infinity) is S.false
assert rootof(x**5 + x**3 + 1, 0) in S.Reals
assert not rootof(x**5 + x**3 + 1, 1) in S.Reals
# non-bool results
assert Union(Interval(1, 2), Interval(3, 4)).contains(x) == \
Or(And(S.One <= x, x <= 2), And(S(3) <= x, x <= 4))
assert Intersection(Interval(1, x), Interval(2, 3)).contains(y) == \
And(y <= 3, y <= x, S.One <= y, S(2) <= y)
assert (S.Complexes).contains(S.ComplexInfinity) == S.false
def test_interval_symbolic():
x = Symbol('x')
e = Interval(0, 1)
assert e.contains(x) == And(S.Zero <= x, x <= 1)
raises(TypeError, lambda: x in e)
e = Interval(0, 1, True, True)
assert e.contains(x) == And(S.Zero < x, x < 1)
c = Symbol('c', real=False)
assert Interval(x, x + 1).contains(c) == False
e = Symbol('e', extended_real=True)
assert Interval(-oo, oo).contains(e) == And(
S.NegativeInfinity < e, e < S.Infinity)
def test_union_contains():
x = Symbol('x')
i1 = Interval(0, 1)
i2 = Interval(2, 3)
i3 = Union(i1, i2)
assert i3.as_relational(x) == Or(And(S.Zero <= x, x <= 1), And(S(2) <= x, x <= 3))
raises(TypeError, lambda: x in i3)
e = i3.contains(x)
assert e == i3.as_relational(x)
assert e.subs(x, -0.5) is false
assert e.subs(x, 0.5) is true
assert e.subs(x, 1.5) is false
assert e.subs(x, 2.5) is true
assert e.subs(x, 3.5) is false
U = Interval(0, 2, True, True) + Interval(10, oo) + FiniteSet(-1, 2, 5, 6)
assert all(el not in U for el in [0, 4, -oo])
assert all(el in U for el in [2, 5, 10])
def test_is_number():
assert Interval(0, 1).is_number is False
assert Set().is_number is False
def test_Interval_is_left_unbounded():
assert Interval(3, 4).is_left_unbounded is False
assert Interval(-oo, 3).is_left_unbounded is True
assert Interval(Float("-inf"), 3).is_left_unbounded is True
def test_Interval_is_right_unbounded():
assert Interval(3, 4).is_right_unbounded is False
assert Interval(3, oo).is_right_unbounded is True
assert Interval(3, Float("+inf")).is_right_unbounded is True
def test_Interval_as_relational():
x = Symbol('x')
assert Interval(-1, 2, False, False).as_relational(x) == \
And(Le(-1, x), Le(x, 2))
assert Interval(-1, 2, True, False).as_relational(x) == \
And(Lt(-1, x), Le(x, 2))
assert Interval(-1, 2, False, True).as_relational(x) == \
And(Le(-1, x), Lt(x, 2))
assert Interval(-1, 2, True, True).as_relational(x) == \
And(Lt(-1, x), Lt(x, 2))
assert Interval(-oo, 2, right_open=False).as_relational(x) == And(Lt(-oo, x), Le(x, 2))
assert Interval(-oo, 2, right_open=True).as_relational(x) == And(Lt(-oo, x), Lt(x, 2))
assert Interval(-2, oo, left_open=False).as_relational(x) == And(Le(-2, x), Lt(x, oo))
assert Interval(-2, oo, left_open=True).as_relational(x) == And(Lt(-2, x), Lt(x, oo))
assert Interval(-oo, oo).as_relational(x) == And(Lt(-oo, x), Lt(x, oo))
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert Interval(x, y).as_relational(x) == (x <= y)
assert Interval(y, x).as_relational(x) == (y <= x)
def test_Finite_as_relational():
x = Symbol('x')
y = Symbol('y')
assert FiniteSet(1, 2).as_relational(x) == Or(Eq(x, 1), Eq(x, 2))
assert FiniteSet(y, -5).as_relational(x) == Or(Eq(x, y), Eq(x, -5))
def test_Union_as_relational():
x = Symbol('x')
assert (Interval(0, 1) + FiniteSet(2)).as_relational(x) == \
Or(And(Le(0, x), Le(x, 1)), Eq(x, 2))
assert (Interval(0, 1, True, True) + FiniteSet(1)).as_relational(x) == \
And(Lt(0, x), Le(x, 1))
def test_Intersection_as_relational():
x = Symbol('x')
assert (Intersection(Interval(0, 1), FiniteSet(2),
evaluate=False).as_relational(x)
== And(And(Le(0, x), Le(x, 1)), Eq(x, 2)))
def test_Complement_as_relational():
x = Symbol('x')
expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
assert expr.as_relational(x) == \
And(Le(0, x), Le(x, 1), Ne(x, 2))
@XFAIL
def test_Complement_as_relational_fail():
x = Symbol('x')
expr = Complement(Interval(0, 1), FiniteSet(2), evaluate=False)
# XXX This example fails because 0 <= x changes to x >= 0
# during the evaluation.
assert expr.as_relational(x) == \
(0 <= x) & (x <= 1) & Ne(x, 2)
def test_SymmetricDifference_as_relational():
x = Symbol('x')
expr = SymmetricDifference(Interval(0, 1), FiniteSet(2), evaluate=False)
assert expr.as_relational(x) == Xor(Eq(x, 2), Le(0, x) & Le(x, 1))
def test_EmptySet():
assert S.EmptySet.as_relational(Symbol('x')) is S.false
assert S.EmptySet.intersect(S.UniversalSet) == S.EmptySet
assert S.EmptySet.boundary == S.EmptySet
def test_finite_basic():
x = Symbol('x')
A = FiniteSet(1, 2, 3)
B = FiniteSet(3, 4, 5)
AorB = Union(A, B)
AandB = A.intersect(B)
assert A.is_subset(AorB) and B.is_subset(AorB)
assert AandB.is_subset(A)
assert AandB == FiniteSet(3)
assert A.inf == 1 and A.sup == 3
assert AorB.inf == 1 and AorB.sup == 5
assert FiniteSet(x, 1, 5).sup == Max(x, 5)
assert FiniteSet(x, 1, 5).inf == Min(x, 1)
# issue 7335
assert FiniteSet(S.EmptySet) != S.EmptySet
assert FiniteSet(FiniteSet(1, 2, 3)) != FiniteSet(1, 2, 3)
assert FiniteSet((1, 2, 3)) != FiniteSet(1, 2, 3)
# Ensure a variety of types can exist in a FiniteSet
assert FiniteSet((1, 2), Float, A, -5, x, 'eggs', x**2, Interval)
assert (A > B) is False
assert (A >= B) is False
assert (A < B) is False
assert (A <= B) is False
assert AorB > A and AorB > B
assert AorB >= A and AorB >= B
assert A >= A and A <= A
assert A >= AandB and B >= AandB
assert A > AandB and B > AandB
assert FiniteSet(1.0) == FiniteSet(1)
def test_product_basic():
H, T = 'H', 'T'
unit_line = Interval(0, 1)
d6 = FiniteSet(1, 2, 3, 4, 5, 6)
d4 = FiniteSet(1, 2, 3, 4)
coin = FiniteSet(H, T)
square = unit_line * unit_line
assert (0, 0) in square
assert 0 not in square
assert (H, T) in coin ** 2
assert (.5, .5, .5) in (square * unit_line).flatten()
assert ((.5, .5), .5) in square * unit_line
assert (H, 3, 3) in (coin * d6 * d6).flatten()
assert ((H, 3), 3) in coin * d6 * d6
HH, TT = sympify(H), sympify(T)
assert set(coin**2) == set(((HH, HH), (HH, TT), (TT, HH), (TT, TT)))
assert (d4*d4).is_subset(d6*d6)
assert square.complement(Interval(-oo, oo)*Interval(-oo, oo)) == Union(
(Interval(-oo, 0, True, True) +
Interval(1, oo, True, True))*Interval(-oo, oo),
Interval(-oo, oo)*(Interval(-oo, 0, True, True) +
Interval(1, oo, True, True)))
assert (Interval(-5, 5)**3).is_subset(Interval(-10, 10)**3)
assert not (Interval(-10, 10)**3).is_subset(Interval(-5, 5)**3)
assert not (Interval(-5, 5)**2).is_subset(Interval(-10, 10)**3)
assert (Interval(.2, .5)*FiniteSet(.5)).is_subset(square) # segment in square
assert len(coin*coin*coin) == 8
assert len(S.EmptySet*S.EmptySet) == 0
assert len(S.EmptySet*coin) == 0
raises(TypeError, lambda: len(coin*Interval(0, 2)))
def test_real():
x = Symbol('x', real=True, finite=True)
I = Interval(0, 5)
J = Interval(10, 20)
A = FiniteSet(1, 2, 30, x, S.Pi)
B = FiniteSet(-4, 0)
C = FiniteSet(100)
D = FiniteSet('Ham', 'Eggs')
assert all(s.is_subset(S.Reals) for s in [I, J, A, B, C])
assert not D.is_subset(S.Reals)
assert all((a + b).is_subset(S.Reals) for a in [I, J, A, B, C] for b in [I, J, A, B, C])
assert not any((a + D).is_subset(S.Reals) for a in [I, J, A, B, C, D])
assert not (I + A + D).is_subset(S.Reals)
def test_supinf():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert (Interval(0, 1) + FiniteSet(2)).sup == 2
assert (Interval(0, 1) + FiniteSet(2)).inf == 0
assert (Interval(0, 1) + FiniteSet(x)).sup == Max(1, x)
assert (Interval(0, 1) + FiniteSet(x)).inf == Min(0, x)
assert FiniteSet(5, 1, x).sup == Max(5, x)
assert FiniteSet(5, 1, x).inf == Min(1, x)
assert FiniteSet(5, 1, x, y).sup == Max(5, x, y)
assert FiniteSet(5, 1, x, y).inf == Min(1, x, y)
assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).sup == \
S.Infinity
assert FiniteSet(5, 1, x, y, S.Infinity, S.NegativeInfinity).inf == \
S.NegativeInfinity
assert FiniteSet('Ham', 'Eggs').sup == Max('Ham', 'Eggs')
def test_universalset():
U = S.UniversalSet
x = Symbol('x')
assert U.as_relational(x) is S.true
assert U.union(Interval(2, 4)) == U
assert U.intersect(Interval(2, 4)) == Interval(2, 4)
assert U.measure is S.Infinity
assert U.boundary == S.EmptySet
assert U.contains(0) is S.true
def test_Union_of_ProductSets_shares():
line = Interval(0, 2)
points = FiniteSet(0, 1, 2)
assert Union(line * line, line * points) == line * line
def test_Interval_free_symbols():
# issue 6211
assert Interval(0, 1).free_symbols == set()
x = Symbol('x', real=True)
assert Interval(0, x).free_symbols == {x}
def test_image_interval():
from sympy.core.numbers import Rational
x = Symbol('x', real=True)
a = Symbol('a', real=True)
assert imageset(x, 2*x, Interval(-2, 1)) == Interval(-4, 2)
assert imageset(x, 2*x, Interval(-2, 1, True, False)) == \
Interval(-4, 2, True, False)
assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
Interval(0, 4, False, True)
assert imageset(x, x**2, Interval(-2, 1)) == Interval(0, 4)
assert imageset(x, x**2, Interval(-2, 1, True, False)) == \
Interval(0, 4, False, True)
assert imageset(x, x**2, Interval(-2, 1, True, True)) == \
Interval(0, 4, False, True)
assert imageset(x, (x - 2)**2, Interval(1, 3)) == Interval(0, 1)
assert imageset(x, 3*x**4 - 26*x**3 + 78*x**2 - 90*x, Interval(0, 4)) == \
Interval(-35, 0) # Multiple Maxima
assert imageset(x, x + 1/x, Interval(-oo, oo)) == Interval(-oo, -2) \
+ Interval(2, oo) # Single Infinite discontinuity
assert imageset(x, 1/x + 1/(x-1)**2, Interval(0, 2, True, False)) == \
Interval(Rational(3, 2), oo, False) # Multiple Infinite discontinuities
# Test for Python lambda
assert imageset(lambda x: 2*x, Interval(-2, 1)) == Interval(-4, 2)
assert imageset(Lambda(x, a*x), Interval(0, 1)) == \
ImageSet(Lambda(x, a*x), Interval(0, 1))
assert imageset(Lambda(x, sin(cos(x))), Interval(0, 1)) == \
ImageSet(Lambda(x, sin(cos(x))), Interval(0, 1))
def test_image_piecewise():
f = Piecewise((x, x <= -1), (1/x**2, x <= 5), (x**3, True))
f1 = Piecewise((0, x <= 1), (1, x <= 2), (2, True))
assert imageset(x, f, Interval(-5, 5)) == Union(Interval(-5, -1), Interval(Rational(1, 25), oo))
assert imageset(x, f1, Interval(1, 2)) == FiniteSet(0, 1)
@XFAIL # See: https://github.com/sympy/sympy/pull/2723#discussion_r8659826
def test_image_Intersection():
x = Symbol('x', real=True)
y = Symbol('y', real=True)
assert imageset(x, x**2, Interval(-2, 0).intersect(Interval(x, y))) == \
Interval(0, 4).intersect(Interval(Min(x**2, y**2), Max(x**2, y**2)))
def test_image_FiniteSet():
x = Symbol('x', real=True)
assert imageset(x, 2*x, FiniteSet(1, 2, 3)) == FiniteSet(2, 4, 6)
def test_image_Union():
x = Symbol('x', real=True)
assert imageset(x, x**2, Interval(-2, 0) + FiniteSet(1, 2, 3)) == \
(Interval(0, 4) + FiniteSet(9))
def test_image_EmptySet():
x = Symbol('x', real=True)
assert imageset(x, 2*x, S.EmptySet) == S.EmptySet
def test_issue_5724_7680():
assert I not in S.Reals # issue 7680
assert Interval(-oo, oo).contains(I) is S.false
def test_boundary():
assert FiniteSet(1).boundary == FiniteSet(1)
assert all(Interval(0, 1, left_open, right_open).boundary == FiniteSet(0, 1)
for left_open in (true, false) for right_open in (true, false))
def test_boundary_Union():
assert (Interval(0, 1) + Interval(2, 3)).boundary == FiniteSet(0, 1, 2, 3)
assert ((Interval(0, 1, False, True)
+ Interval(1, 2, True, False)).boundary == FiniteSet(0, 1, 2))
assert (Interval(0, 1) + FiniteSet(2)).boundary == FiniteSet(0, 1, 2)
assert Union(Interval(0, 10), Interval(5, 15), evaluate=False).boundary \
== FiniteSet(0, 15)
assert Union(Interval(0, 10), Interval(0, 1), evaluate=False).boundary \
== FiniteSet(0, 10)
assert Union(Interval(0, 10, True, True),
Interval(10, 15, True, True), evaluate=False).boundary \
== FiniteSet(0, 10, 15)
@XFAIL
def test_union_boundary_of_joining_sets():
""" Testing the boundary of unions is a hard problem """
assert Union(Interval(0, 10), Interval(10, 15), evaluate=False).boundary \
== FiniteSet(0, 15)
def test_boundary_ProductSet():
open_square = Interval(0, 1, True, True) ** 2
assert open_square.boundary == (FiniteSet(0, 1) * Interval(0, 1)
+ Interval(0, 1) * FiniteSet(0, 1))
second_square = Interval(1, 2, True, True) * Interval(0, 1, True, True)
assert (open_square + second_square).boundary == (
FiniteSet(0, 1) * Interval(0, 1)
+ FiniteSet(1, 2) * Interval(0, 1)
+ Interval(0, 1) * FiniteSet(0, 1)
+ Interval(1, 2) * FiniteSet(0, 1))
def test_boundary_ProductSet_line():
line_in_r2 = Interval(0, 1) * FiniteSet(0)
assert line_in_r2.boundary == line_in_r2
def test_is_open():
assert Interval(0, 1, False, False).is_open is False
assert Interval(0, 1, True, False).is_open is False
assert Interval(0, 1, True, True).is_open is True
assert FiniteSet(1, 2, 3).is_open is False
def test_is_closed():
assert Interval(0, 1, False, False).is_closed is True
assert Interval(0, 1, True, False).is_closed is False
assert FiniteSet(1, 2, 3).is_closed is True
def test_closure():
assert Interval(0, 1, False, True).closure == Interval(0, 1, False, False)
def test_interior():
assert Interval(0, 1, False, True).interior == Interval(0, 1, True, True)
def test_issue_7841():
raises(TypeError, lambda: x in S.Reals)
def test_Eq():
assert Eq(Interval(0, 1), Interval(0, 1))
assert Eq(Interval(0, 1), Interval(0, 2)) == False
s1 = FiniteSet(0, 1)
s2 = FiniteSet(1, 2)
assert Eq(s1, s1)
assert Eq(s1, s2) == False
assert Eq(s1*s2, s1*s2)
assert Eq(s1*s2, s2*s1) == False
assert unchanged(Eq, FiniteSet({x, y}), FiniteSet({x}))
assert Eq(FiniteSet({x, y}).subs(y, x), FiniteSet({x})) is S.true
assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x) is S.true
assert Eq(FiniteSet({x, y}).subs(y, x+1), FiniteSet({x})) is S.false
assert Eq(FiniteSet({x, y}), FiniteSet({x})).subs(y, x+1) is S.false
assert Eq(ProductSet({1}, {2}), Interval(1, 2)) not in (S.true, S.false)
assert Eq(ProductSet({1}), ProductSet({1}, {2})) is S.false
assert Eq(FiniteSet(()), FiniteSet(1)) is S.false
assert Eq(ProductSet(), FiniteSet(1)) is S.false
i1 = Interval(0, 1)
i2 = Interval(x, y)
assert unchanged(Eq, ProductSet(i1, i1), ProductSet(i2, i2))
def test_SymmetricDifference():
A = FiniteSet(0, 1, 2, 3, 4, 5)
B = FiniteSet(2, 4, 6, 8, 10)
C = Interval(8, 10)
assert SymmetricDifference(A, B, evaluate=False).is_iterable is True
assert SymmetricDifference(A, C, evaluate=False).is_iterable is None
assert FiniteSet(*SymmetricDifference(A, B, evaluate=False)) == \
FiniteSet(0, 1, 3, 5, 6, 8, 10)
raises(TypeError,
lambda: FiniteSet(*SymmetricDifference(A, C, evaluate=False)))
assert SymmetricDifference(FiniteSet(0, 1, 2, 3, 4, 5), \
FiniteSet(2, 4, 6, 8, 10)) == FiniteSet(0, 1, 3, 5, 6, 8, 10)
assert SymmetricDifference(FiniteSet(2, 3, 4), FiniteSet(2, 3 ,4 ,5 )) \
== FiniteSet(5)
assert FiniteSet(1, 2, 3, 4, 5) ^ FiniteSet(1, 2, 5, 6) == \
FiniteSet(3, 4, 6)
assert Set(1, 2 ,3) ^ Set(2, 3, 4) == Union(Set(1, 2, 3) - Set(2, 3, 4), \
Set(2, 3, 4) - Set(1, 2, 3))
assert Interval(0, 4) ^ Interval(2, 5) == Union(Interval(0, 4) - \
Interval(2, 5), Interval(2, 5) - Interval(0, 4))
def test_issue_9536():
from sympy.functions.elementary.exponential import log
a = Symbol('a', real=True)
assert FiniteSet(log(a)).intersect(S.Reals) == Intersection(S.Reals, FiniteSet(log(a)))
def test_issue_9637():
n = Symbol('n')
a = FiniteSet(n)
b = FiniteSet(2, n)
assert Complement(S.Reals, a) == Complement(S.Reals, a, evaluate=False)
assert Complement(Interval(1, 3), a) == Complement(Interval(1, 3), a, evaluate=False)
assert Complement(Interval(1, 3), b) == \
Complement(Union(Interval(1, 2, False, True), Interval(2, 3, True, False)), a)
assert Complement(a, S.Reals) == Complement(a, S.Reals, evaluate=False)
assert Complement(a, Interval(1, 3)) == Complement(a, Interval(1, 3), evaluate=False)
def test_issue_9808():
# See https://github.com/sympy/sympy/issues/16342
assert Complement(FiniteSet(y), FiniteSet(1)) == Complement(FiniteSet(y), FiniteSet(1), evaluate=False)
assert Complement(FiniteSet(1, 2, x), FiniteSet(x, y, 2, 3)) == \
Complement(FiniteSet(1), FiniteSet(y), evaluate=False)
def test_issue_9956():
assert Union(Interval(-oo, oo), FiniteSet(1)) == Interval(-oo, oo)
assert Interval(-oo, oo).contains(1) is S.true
def test_issue_Symbol_inter():
i = Interval(0, oo)
r = S.Reals
mat = Matrix([0, 0, 0])
assert Intersection(r, i, FiniteSet(m), FiniteSet(m, n)) == \
Intersection(i, FiniteSet(m))
assert Intersection(FiniteSet(1, m, n), FiniteSet(m, n, 2), i) == \
Intersection(i, FiniteSet(m, n))
assert Intersection(FiniteSet(m, n, x), FiniteSet(m, z), r) == \
Intersection(Intersection({m, z}, {m, n, x}), r)
assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, x), r) == \
Intersection(FiniteSet(3, m, n), FiniteSet(m, n, x), r, evaluate=False)
assert Intersection(FiniteSet(m, n, 3), FiniteSet(m, n, 2, 3), r) == \
Intersection(FiniteSet(3, m, n), r)
assert Intersection(r, FiniteSet(mat, 2, n), FiniteSet(0, mat, n)) == \
Intersection(r, FiniteSet(n))
assert Intersection(FiniteSet(sin(x), cos(x)), FiniteSet(sin(x), cos(x), 1), r) == \
Intersection(r, FiniteSet(sin(x), cos(x)))
assert Intersection(FiniteSet(x**2, 1, sin(x)), FiniteSet(x**2, 2, sin(x)), r) == \
Intersection(r, FiniteSet(x**2, sin(x)))
def test_issue_11827():
assert S.Naturals0**4
def test_issue_10113():
f = x**2/(x**2 - 4)
assert imageset(x, f, S.Reals) == Union(Interval(-oo, 0), Interval(1, oo, True, True))
assert imageset(x, f, Interval(-2, 2)) == Interval(-oo, 0)
assert imageset(x, f, Interval(-2, 3)) == Union(Interval(-oo, 0), Interval(Rational(9, 5), oo))
def test_issue_10248():
raises(
TypeError, lambda: list(Intersection(S.Reals, FiniteSet(x)))
)
A = Symbol('A', real=True)
assert list(Intersection(S.Reals, FiniteSet(A))) == [A]
def test_issue_9447():
a = Interval(0, 1) + Interval(2, 3)
assert Complement(S.UniversalSet, a) == Complement(
S.UniversalSet, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
assert Complement(S.Naturals, a) == Complement(
S.Naturals, Union(Interval(0, 1), Interval(2, 3)), evaluate=False)
def test_issue_10337():
assert (FiniteSet(2) == 3) is False
assert (FiniteSet(2) != 3) is True
raises(TypeError, lambda: FiniteSet(2) < 3)
raises(TypeError, lambda: FiniteSet(2) <= 3)
raises(TypeError, lambda: FiniteSet(2) > 3)
raises(TypeError, lambda: FiniteSet(2) >= 3)
def test_issue_10326():
bad = [
EmptySet,
FiniteSet(1),
Interval(1, 2),
S.ComplexInfinity,
S.ImaginaryUnit,
S.Infinity,
S.NaN,
S.NegativeInfinity,
]
interval = Interval(0, 5)
for i in bad:
assert i not in interval
x = Symbol('x', real=True)
nr = Symbol('nr', extended_real=False)
assert x + 1 in Interval(x, x + 4)
assert nr not in Interval(x, x + 4)
assert Interval(1, 2) in FiniteSet(Interval(0, 5), Interval(1, 2))
assert Interval(-oo, oo).contains(oo) is S.false
assert Interval(-oo, oo).contains(-oo) is S.false
def test_issue_2799():
U = S.UniversalSet
a = Symbol('a', real=True)
inf_interval = Interval(a, oo)
R = S.Reals
assert U + inf_interval == inf_interval + U
assert U + R == R + U
assert R + inf_interval == inf_interval + R
def test_issue_9706():
assert Interval(-oo, 0).closure == Interval(-oo, 0, True, False)
assert Interval(0, oo).closure == Interval(0, oo, False, True)
assert Interval(-oo, oo).closure == Interval(-oo, oo)
def test_issue_8257():
reals_plus_infinity = Union(Interval(-oo, oo), FiniteSet(oo))
reals_plus_negativeinfinity = Union(Interval(-oo, oo), FiniteSet(-oo))
assert Interval(-oo, oo) + FiniteSet(oo) == reals_plus_infinity
assert FiniteSet(oo) + Interval(-oo, oo) == reals_plus_infinity
assert Interval(-oo, oo) + FiniteSet(-oo) == reals_plus_negativeinfinity
assert FiniteSet(-oo) + Interval(-oo, oo) == reals_plus_negativeinfinity
def test_issue_10931():
assert S.Integers - S.Integers == EmptySet
assert S.Integers - S.Reals == EmptySet
def test_issue_11174():
soln = Intersection(Interval(-oo, oo), FiniteSet(-x), evaluate=False)
assert Intersection(FiniteSet(-x), S.Reals) == soln
soln = Intersection(S.Reals, FiniteSet(x), evaluate=False)
assert Intersection(FiniteSet(x), S.Reals) == soln
def test_finite_set_intersection():
# The following should not produce recursion errors
# Note: some of these are not completely correct. See
# https://github.com/sympy/sympy/issues/16342.
assert Intersection(FiniteSet(-oo, x), FiniteSet(x)) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(0, x)]) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(-oo, x), FiniteSet(x)]) == FiniteSet(x)
assert Intersection._handle_finite_sets([FiniteSet(2, 3, x, y), FiniteSet(1, 2, x)]) == \
Intersection._handle_finite_sets([FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)]) == \
Intersection(FiniteSet(1, 2, x), FiniteSet(2, 3, x, y)) == \
Intersection(FiniteSet(1, 2, x), FiniteSet(2, x, y))
assert FiniteSet(1+x-y) & FiniteSet(1) == \
FiniteSet(1) & FiniteSet(1+x-y) == \
Intersection(FiniteSet(1+x-y), FiniteSet(1), evaluate=False)
assert FiniteSet(1) & FiniteSet(x) == FiniteSet(x) & FiniteSet(1) == \
Intersection(FiniteSet(1), FiniteSet(x), evaluate=False)
assert FiniteSet({x}) & FiniteSet({x, y}) == \
Intersection(FiniteSet({x}), FiniteSet({x, y}), evaluate=False)
def test_union_intersection_constructor():
# The actual exception does not matter here, so long as these fail
sets = [FiniteSet(1), FiniteSet(2)]
raises(Exception, lambda: Union(sets))
raises(Exception, lambda: Intersection(sets))
raises(Exception, lambda: Union(tuple(sets)))
raises(Exception, lambda: Intersection(tuple(sets)))
raises(Exception, lambda: Union(i for i in sets))
raises(Exception, lambda: Intersection(i for i in sets))
# Python sets are treated the same as FiniteSet
# The union of a single set (of sets) is the set (of sets) itself
assert Union(set(sets)) == FiniteSet(*sets)
assert Intersection(set(sets)) == FiniteSet(*sets)
assert Union({1}, {2}) == FiniteSet(1, 2)
assert Intersection({1, 2}, {2, 3}) == FiniteSet(2)
def test_Union_contains():
assert zoo not in Union(
Interval.open(-oo, 0), Interval.open(0, oo))
@XFAIL
def test_issue_16878b():
# in intersection_sets for (ImageSet, Set) there is no code
# that handles the base_set of S.Reals like there is
# for Integers
assert imageset(x, (x, x), S.Reals).is_subset(S.Reals**2) is True
|
8fdb17691261c40879f1babdc551df55ad91c492712c0da48443508d2aa1f51c | from sympy import (plot_implicit, cos, Symbol, symbols, Eq, sin, re, And, Or, exp, I,
tan, pi)
from sympy.plotting.plot import unset_show
from tempfile import NamedTemporaryFile, mkdtemp
from sympy.testing.pytest import skip, warns
from sympy.external import import_module
from sympy.testing.tmpfiles import TmpFileManager
import os
#Set plots not to show
unset_show()
def tmp_file(dir=None, name=''):
return NamedTemporaryFile(
suffix='.png', dir=dir, delete=False).name
def plot_and_save(expr, *args, **kwargs):
name = kwargs.pop('name', '')
dir = kwargs.pop('dir', None)
p = plot_implicit(expr, *args, **kwargs)
p.save(tmp_file(dir=dir, name=name))
# Close the plot to avoid a warning from matplotlib
p._backend.close()
def plot_implicit_tests(name):
temp_dir = mkdtemp()
TmpFileManager.tmp_folder(temp_dir)
x = Symbol('x')
y = Symbol('y')
#implicit plot tests
plot_and_save(Eq(y, cos(x)), (x, -5, 5), (y, -2, 2), name=name, dir=temp_dir)
plot_and_save(Eq(y**2, x**3 - x), (x, -5, 5),
(y, -4, 4), name=name, dir=temp_dir)
plot_and_save(y > 1 / x, (x, -5, 5),
(y, -2, 2), name=name, dir=temp_dir)
plot_and_save(y < 1 / tan(x), (x, -5, 5),
(y, -2, 2), name=name, dir=temp_dir)
plot_and_save(y >= 2 * sin(x) * cos(x), (x, -5, 5),
(y, -2, 2), name=name, dir=temp_dir)
plot_and_save(y <= x**2, (x, -3, 3),
(y, -1, 5), name=name, dir=temp_dir)
#Test all input args for plot_implicit
plot_and_save(Eq(y**2, x**3 - x), dir=temp_dir)
plot_and_save(Eq(y**2, x**3 - x), adaptive=False, dir=temp_dir)
plot_and_save(Eq(y**2, x**3 - x), adaptive=False, points=500, dir=temp_dir)
plot_and_save(y > x, (x, -5, 5), dir=temp_dir)
plot_and_save(And(y > exp(x), y > x + 2), dir=temp_dir)
plot_and_save(Or(y > x, y > -x), dir=temp_dir)
plot_and_save(x**2 - 1, (x, -5, 5), dir=temp_dir)
plot_and_save(x**2 - 1, dir=temp_dir)
plot_and_save(y > x, depth=-5, dir=temp_dir)
plot_and_save(y > x, depth=5, dir=temp_dir)
plot_and_save(y > cos(x), adaptive=False, dir=temp_dir)
plot_and_save(y < cos(x), adaptive=False, dir=temp_dir)
plot_and_save(And(y > cos(x), Or(y > x, Eq(y, x))), dir=temp_dir)
plot_and_save(y - cos(pi / x), dir=temp_dir)
#Test plots which cannot be rendered using the adaptive algorithm
with warns(UserWarning, match="Adaptive meshing could not be applied"):
plot_and_save(Eq(y, re(cos(x) + I*sin(x))), name=name, dir=temp_dir)
plot_and_save(x**2 - 1, title='An implicit plot', dir=temp_dir)
def test_line_color():
x, y = symbols('x, y')
p = plot_implicit(x**2 + y**2 - 1, line_color="green", show=False)
assert p._series[0].line_color == "green"
p = plot_implicit(x**2 + y**2 - 1, line_color='r', show=False)
assert p._series[0].line_color == "r"
def test_matplotlib():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_implicit_tests('test')
test_line_color()
finally:
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_region_and():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
from matplotlib.testing.compare import compare_images
test_directory = os.path.dirname(os.path.abspath(__file__))
try:
temp_dir = mkdtemp()
TmpFileManager.tmp_folder(temp_dir)
x, y = symbols('x y')
r1 = (x - 1)**2 + y**2 < 2
r2 = (x + 1)**2 + y**2 < 2
test_filename = tmp_file(dir=temp_dir, name="test_region_and")
cmp_filename = os.path.join(test_directory, "test_region_and.png")
p = plot_implicit(r1 & r2, x, y)
p.save(test_filename)
compare_images(cmp_filename, test_filename, 0.005)
test_filename = tmp_file(dir=temp_dir, name="test_region_or")
cmp_filename = os.path.join(test_directory, "test_region_or.png")
p = plot_implicit(r1 | r2, x, y)
p.save(test_filename)
compare_images(cmp_filename, test_filename, 0.005)
test_filename = tmp_file(dir=temp_dir, name="test_region_not")
cmp_filename = os.path.join(test_directory, "test_region_not.png")
p = plot_implicit(~r1, x, y)
p.save(test_filename)
compare_images(cmp_filename, test_filename, 0.005)
test_filename = tmp_file(dir=temp_dir, name="test_region_xor")
cmp_filename = os.path.join(test_directory, "test_region_xor.png")
p = plot_implicit(r1 ^ r2, x, y)
p.save(test_filename)
compare_images(cmp_filename, test_filename, 0.005)
finally:
TmpFileManager.cleanup()
|
9aeab96d535fc08a7eba31e58bb8533825cba8bdab65ad4885f55995c3496639 | from typing import List
from sympy import (pi, sin, cos, Symbol, Integral, Sum, sqrt, log, exp, Ne,
oo, LambertW, I, meijerg, exp_polar, Max, Piecewise, And,
real_root)
from sympy.plotting import (plot, plot_parametric, plot3d_parametric_line,
plot3d, plot3d_parametric_surface)
from sympy.plotting.plot import (unset_show, plot_contour, PlotGrid,
DefaultBackend, MatplotlibBackend, TextBackend)
from sympy.utilities import lambdify as lambdify_
from sympy.testing.pytest import skip, raises, warns
from sympy.plotting.experimental_lambdify import lambdify
from sympy.external import import_module
from tempfile import NamedTemporaryFile
import os
unset_show()
# XXX: We could implement this as a context manager instead
# That would need rewriting the plot_and_save() function
# entirely
class TmpFileManager:
tmp_files = [] # type: List[str]
@classmethod
def tmp_file(cls, name=''):
cls.tmp_files.append(NamedTemporaryFile(prefix=name, suffix='.png').name)
return cls.tmp_files[-1]
@classmethod
def cleanup(cls):
for file in cls.tmp_files:
try:
os.remove(file)
except OSError:
# If the file doesn't exist, for instance, if the test failed.
pass
def plot_and_save_1(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
y = Symbol('y')
###
# Examples from the 'introduction' notebook
###
p = plot(x)
p = plot(x*sin(x), x*cos(x))
p.extend(p)
p[0].line_color = lambda a: a
p[1].line_color = 'b'
p.title = 'Big title'
p.xlabel = 'the x axis'
p[1].label = 'straight line'
p.legend = True
p.aspect_ratio = (1, 1)
p.xlim = (-15, 20)
p.save(tmp_file('%s_basic_options_and_colors' % name))
p._backend.close()
p.extend(plot(x + 1))
p.append(plot(x + 3, x**2)[1])
p.save(tmp_file('%s_plot_extend_append' % name))
p[2] = plot(x**2, (x, -2, 3))
p.save(tmp_file('%s_plot_setitem' % name))
p._backend.close()
p = plot(sin(x), (x, -2*pi, 4*pi))
p.save(tmp_file('%s_line_explicit' % name))
p._backend.close()
p = plot(sin(x))
p.save(tmp_file('%s_line_default_range' % name))
p._backend.close()
p = plot((x**2, (x, -5, 5)), (x**3, (x, -3, 3)))
p.save(tmp_file('%s_line_multiple_range' % name))
p._backend.close()
raises(ValueError, lambda: plot(x, y))
#Piecewise plots
p = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1))
p.save(tmp_file('%s_plot_piecewise' % name))
p._backend.close()
p = plot(Piecewise((x, x < 1), (x**2, True)), (x, -3, 3))
p.save(tmp_file('%s_plot_piecewise_2' % name))
p._backend.close()
# test issue 7471
p1 = plot(x)
p2 = plot(3)
p1.extend(p2)
p.save(tmp_file('%s_horizontal_line' % name))
p._backend.close()
# test issue 10925
f = Piecewise((-1, x < -1), (x, And(-1 <= x, x < 0)), \
(x**2, And(0 <= x, x < 1)), (x**3, x >= 1))
p = plot(f, (x, -3, 3))
p.save(tmp_file('%s_plot_piecewise_3' % name))
p._backend.close()
def plot_and_save_2(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
#parametric 2d plots.
#Single plot with default range.
plot_parametric(sin(x), cos(x)).save(tmp_file())
#Single plot with range.
p = plot_parametric(sin(x), cos(x), (x, -5, 5))
p.save(tmp_file('%s_parametric_range' % name))
p._backend.close()
#Multiple plots with same range.
p = plot_parametric((sin(x), cos(x)), (x, sin(x)))
p.save(tmp_file('%s_parametric_multiple' % name))
p._backend.close()
#Multiple plots with different ranges.
p = plot_parametric((sin(x), cos(x), (x, -3, 3)), (x, sin(x), (x, -5, 5)))
p.save(tmp_file('%s_parametric_multiple_ranges' % name))
p._backend.close()
#depth of recursion specified.
p = plot_parametric(x, sin(x), depth=13)
p.save(tmp_file('%s_recursion_depth' % name))
p._backend.close()
#No adaptive sampling.
p = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500)
p.save(tmp_file('%s_adaptive' % name))
p._backend.close()
#3d parametric plots
p = plot3d_parametric_line(sin(x), cos(x), x)
p.save(tmp_file('%s_3d_line' % name))
p._backend.close()
p = plot3d_parametric_line(
(sin(x), cos(x), x, (x, -5, 5)), (cos(x), sin(x), x, (x, -3, 3)))
p.save(tmp_file('%s_3d_line_multiple' % name))
p._backend.close()
p = plot3d_parametric_line(sin(x), cos(x), x, nb_of_points=30)
p.save(tmp_file('%s_3d_line_points' % name))
p._backend.close()
# 3d surface single plot.
p = plot3d(x * y)
p.save(tmp_file('%s_surface' % name))
p._backend.close()
# Multiple 3D plots with same range.
p = plot3d(-x * y, x * y, (x, -5, 5))
p.save(tmp_file('%s_surface_multiple' % name))
p._backend.close()
# Multiple 3D plots with different ranges.
p = plot3d(
(x * y, (x, -3, 3), (y, -3, 3)), (-x * y, (x, -3, 3), (y, -3, 3)))
p.save(tmp_file('%s_surface_multiple_ranges' % name))
p._backend.close()
# Single Parametric 3D plot
p = plot3d_parametric_surface(sin(x + y), cos(x - y), x - y)
p.save(tmp_file('%s_parametric_surface' % name))
p._backend.close()
# Multiple Parametric 3D plots.
p = plot3d_parametric_surface(
(x*sin(z), x*cos(z), z, (x, -5, 5), (z, -5, 5)),
(sin(x + y), cos(x - y), x - y, (x, -5, 5), (y, -5, 5)))
p.save(tmp_file('%s_parametric_surface' % name))
p._backend.close()
# Single Contour plot.
p = plot_contour(sin(x)*sin(y), (x, -5, 5), (y, -5, 5))
p.save(tmp_file('%s_contour_plot' % name))
p._backend.close()
# Multiple Contour plots with same range.
p = plot_contour(x**2 + y**2, x**3 + y**3, (x, -5, 5), (y, -5, 5))
p.save(tmp_file('%s_contour_plot' % name))
p._backend.close()
# Multiple Contour plots with different range.
p = plot_contour((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)))
p.save(tmp_file('%s_contour_plot' % name))
p._backend.close()
def plot_and_save_3(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
###
# Examples from the 'colors' notebook
###
p = plot(sin(x))
p[0].line_color = lambda a: a
p.save(tmp_file('%s_colors_line_arity1' % name))
p[0].line_color = lambda a, b: b
p.save(tmp_file('%s_colors_line_arity2' % name))
p._backend.close()
p = plot(x*sin(x), x*cos(x), (x, 0, 10))
p[0].line_color = lambda a: a
p.save(tmp_file('%s_colors_param_line_arity1' % name))
p[0].line_color = lambda a, b: a
p.save(tmp_file('%s_colors_param_line_arity2a' % name))
p[0].line_color = lambda a, b: b
p.save(tmp_file('%s_colors_param_line_arity2b' % name))
p._backend.close()
p = plot3d_parametric_line(sin(x) + 0.1*sin(x)*cos(7*x),
cos(x) + 0.1*cos(x)*cos(7*x),
0.1*sin(7*x),
(x, 0, 2*pi))
p[0].line_color = lambdify_(x, sin(4*x))
p.save(tmp_file('%s_colors_3d_line_arity1' % name))
p[0].line_color = lambda a, b: b
p.save(tmp_file('%s_colors_3d_line_arity2' % name))
p[0].line_color = lambda a, b, c: c
p.save(tmp_file('%s_colors_3d_line_arity3' % name))
p._backend.close()
p = plot3d(sin(x)*y, (x, 0, 6*pi), (y, -5, 5))
p[0].surface_color = lambda a: a
p.save(tmp_file('%s_colors_surface_arity1' % name))
p[0].surface_color = lambda a, b: b
p.save(tmp_file('%s_colors_surface_arity2' % name))
p[0].surface_color = lambda a, b, c: c
p.save(tmp_file('%s_colors_surface_arity3a' % name))
p[0].surface_color = lambdify_((x, y, z), sqrt((x - 3*pi)**2 + y**2))
p.save(tmp_file('%s_colors_surface_arity3b' % name))
p._backend.close()
p = plot3d_parametric_surface(x * cos(4 * y), x * sin(4 * y), y,
(x, -1, 1), (y, -1, 1))
p[0].surface_color = lambda a: a
p.save(tmp_file('%s_colors_param_surf_arity1' % name))
p[0].surface_color = lambda a, b: a*b
p.save(tmp_file('%s_colors_param_surf_arity2' % name))
p[0].surface_color = lambdify_((x, y, z), sqrt(x**2 + y**2 + z**2))
p.save(tmp_file('%s_colors_param_surf_arity3' % name))
p._backend.close()
def plot_and_save_4(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
y = Symbol('y')
###
# Examples from the 'advanced' notebook
###
# XXX: This raises the warning "The evaluation of the expression is
# problematic. We are trying a failback method that may still work. Please
# report this as a bug." It has to use the fallback because using evalf()
# is the only way to evaluate the integral. We should perhaps just remove
# that warning.
with warns(UserWarning, match="The evaluation of the expression is problematic"):
i = Integral(log((sin(x)**2 + 1)*sqrt(x**2 + 1)), (x, 0, y))
p = plot(i, (y, 1, 5))
p.save(tmp_file('%s_advanced_integral' % name))
p._backend.close()
def plot_and_save_5(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
y = Symbol('y')
s = Sum(1/x**y, (x, 1, oo))
p = plot(s, (y, 2, 10))
p.save(tmp_file('%s_advanced_inf_sum' % name))
p._backend.close()
p = plot(Sum(1/x, (x, 1, y)), (y, 2, 10), show=False)
p[0].only_integers = True
p[0].steps = True
p.save(tmp_file('%s_advanced_fin_sum' % name))
p._backend.close()
def plot_and_save_6(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
###
# Test expressions that can not be translated to np and generate complex
# results.
###
plot(sin(x) + I*cos(x)).save(tmp_file())
plot(sqrt(sqrt(-x))).save(tmp_file())
plot(LambertW(x)).save(tmp_file())
plot(sqrt(LambertW(x))).save(tmp_file())
#Characteristic function of a StudentT distribution with nu=10
plot((meijerg(((1 / 2,), ()), ((5, 0, 1 / 2), ()), 5 * x**2 * exp_polar(-I*pi)/2)
+ meijerg(((1/2,), ()), ((5, 0, 1/2), ()),
5*x**2 * exp_polar(I*pi)/2)) / (48 * pi), (x, 1e-6, 1e-2)).save(tmp_file())
def plotgrid_and_save(name):
tmp_file = TmpFileManager.tmp_file
x = Symbol('x')
y = Symbol('y')
p1 = plot(x)
p2 = plot_parametric((sin(x), cos(x)), (x, sin(x)), show=False)
p3 = plot_parametric(cos(x), sin(x), adaptive=False, nb_of_points=500, show=False)
p4 = plot3d_parametric_line(sin(x), cos(x), x, show=False)
# symmetric grid
p = PlotGrid(2, 2, p1, p2, p3, p4)
p.save(tmp_file('%s_grid1' % name))
p._backend.close()
# grid size greater than the number of subplots
p = PlotGrid(3, 4, p1, p2, p3, p4)
p.save(tmp_file('%s_grid2' % name))
p._backend.close()
p5 = plot(cos(x),(x, -pi, pi), show=False)
p5[0].line_color = lambda a: a
p6 = plot(Piecewise((1, x > 0), (0, True)), (x, -1, 1), show=False)
p7 = plot_contour((x**2 + y**2, (x, -5, 5), (y, -5, 5)), (x**3 + y**3, (x, -3, 3), (y, -3, 3)), show=False)
# unsymmetric grid (subplots in one line)
p = PlotGrid(1, 3, p5, p6, p7)
p.save(tmp_file('%s_grid3' % name))
p._backend.close()
def test_matplotlib_1():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_and_save_1('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_matplotlib_2():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_and_save_2('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_matplotlib_3():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_and_save_3('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_matplotlib_4():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_and_save_4('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_matplotlib_5():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_and_save_5('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_matplotlib_6():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plot_and_save_6('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
def test_matplotlib_7():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if matplotlib:
try:
plotgrid_and_save('test')
finally:
# clean up
TmpFileManager.cleanup()
else:
skip("Matplotlib not the default backend")
# Tests for exception handling in experimental_lambdify
def test_experimental_lambify():
x = Symbol('x')
f = lambdify([x], Max(x, 5))
# XXX should f be tested? If f(2) is attempted, an
# error is raised because a complex produced during wrapping of the arg
# is being compared with an int.
assert Max(2, 5) == 5
assert Max(5, 7) == 7
x = Symbol('x-3')
f = lambdify([x], x + 1)
assert f(1) == 2
def test_append_issue_7140():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p1 = plot(x)
p2 = plot(x**2)
plot(x + 2)
# append a series
p2.append(p1[0])
assert len(p2._series) == 2
with raises(TypeError):
p1.append(p2)
with raises(TypeError):
p1.append(p2._series)
def test_issue_15265():
from sympy.core.sympify import sympify
from sympy.core.singleton import S
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
eqn = sin(x)
p = plot(eqn, xlim=(-S.Pi, S.Pi), ylim=(-1, 1))
p._backend.close()
p = plot(eqn, xlim=(-1, 1), ylim=(-S.Pi, S.Pi))
p._backend.close()
p = plot(eqn, xlim=(-1, 1), ylim=(sympify('-3.14'), sympify('3.14')))
p._backend.close()
p = plot(eqn, xlim=(sympify('-3.14'), sympify('3.14')), ylim=(-1, 1))
p._backend.close()
raises(ValueError,
lambda: plot(eqn, xlim=(-S.ImaginaryUnit, 1), ylim=(-1, 1)))
raises(ValueError,
lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.ImaginaryUnit)))
raises(ValueError,
lambda: plot(eqn, xlim=(S.NegativeInfinity, 1), ylim=(-1, 1)))
raises(ValueError,
lambda: plot(eqn, xlim=(-1, 1), ylim=(-1, S.Infinity)))
def test_empty_Plot():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
from sympy.plotting.plot import Plot
p = Plot()
# No exception showing an empty plot
p.show()
def test_empty_plot():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
# No exception showing an empty plot
plot()
def test_issue_17405():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
f = x**0.3 - 10*x**3 + x**2
p = plot(f, (x, -10, 10), show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_segments()) >= 30
def test_logplot_PR_16796():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(x, (x, .001, 100), xscale='log', show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_segments()) >= 30
assert p[0].end == 100.0
assert p[0].start == .001
def test_issue_16572():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(LambertW(x), show=False)
# Random number of segments, probably more than 50, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_segments()) >= 30
def test_issue_11865():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
k = Symbol('k', integer=True)
f = Piecewise((-I*exp(I*pi*k)/k + I*exp(-I*pi*k)/k, Ne(k, 0)), (2*pi, True))
p = plot(f, show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
# and that there are no exceptions.
assert len(p[0].get_segments()) >= 30
def test_issue_11461():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot(real_root((log(x/(x-2))), 3), show=False)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
# and that there are no exceptions.
assert len(p[0].get_segments()) >= 30
def test_issue_11764():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
if not matplotlib:
skip("Matplotlib not the default backend")
x = Symbol('x')
p = plot_parametric(cos(x), sin(x), (x, 0, 2 * pi), aspect_ratio=(1,1), show=False)
p.aspect_ratio == (1, 1)
# Random number of segments, probably more than 100, but we want to see
# that there are segments generated, as opposed to when the bug was present
assert len(p[0].get_segments()) >= 30
def test_issue_13516():
matplotlib = import_module('matplotlib', min_module_version='1.1.0', catch=(RuntimeError,))
np = import_module('numpy')
if not matplotlib:
skip("Matplotlib not the default backend")
if not np:
skip("Numpy not found")
x = Symbol('x')
pm = plot(sin(x), backend="matplotlib", show=False)
assert pm.backend == MatplotlibBackend
assert len(pm[0].get_segments()) >= 30
pt = plot(sin(x), backend="text", show=False)
assert pt.backend == TextBackend
assert len(pt[0].get_segments()) >= 30
pd = plot(sin(x), backend="default", show=False)
assert pd.backend == DefaultBackend
assert len(pd[0].get_segments()) >= 30
p = plot(sin(x), show=False)
assert p.backend == DefaultBackend
assert len(p[0].get_segments()) >= 30
|
11f5ddde56930dd6ed047a36174bed682ff440abe042d89dbcbbd3031212eaa7 | from __future__ import print_function, division
from sympy import Symbol, sympify
from sympy.core.compatibility import is_sequence
from sympy.geometry.entity import GeometryEntity
from .plot_interval import PlotInterval
from .plot_object import PlotObject
from .util import parse_option_string
class PlotMode(PlotObject):
"""
Grandparent class for plotting
modes. Serves as interface for
registration, lookup, and init
of modes.
To create a new plot mode,
inherit from PlotModeBase
or one of its children, such
as PlotSurface or PlotCurve.
"""
## Class-level attributes
## used to register and lookup
## plot modes. See PlotModeBase
## for descriptions and usage.
i_vars, d_vars = '', ''
intervals = []
aliases = []
is_default = False
## Draw is the only method here which
## is meant to be overridden in child
## classes, and PlotModeBase provides
## a base implementation.
def draw(self):
raise NotImplementedError()
## Everything else in this file has to
## do with registration and retrieval
## of plot modes. This is where I've
## hidden much of the ugliness of automatic
## plot mode divination...
## Plot mode registry data structures
_mode_alias_list = []
_mode_map = {
1: {1: {}, 2: {}},
2: {1: {}, 2: {}},
3: {1: {}, 2: {}},
} # [d][i][alias_str]: class
_mode_default_map = {
1: {},
2: {},
3: {},
} # [d][i]: class
_i_var_max, _d_var_max = 2, 3
def __new__(cls, *args, **kwargs):
"""
This is the function which interprets
arguments given to Plot.__init__ and
Plot.__setattr__. Returns an initialized
instance of the appropriate child class.
"""
newargs, newkwargs = PlotMode._extract_options(args, kwargs)
mode_arg = newkwargs.get('mode', '')
# Interpret the arguments
d_vars, intervals = PlotMode._interpret_args(newargs)
i_vars = PlotMode._find_i_vars(d_vars, intervals)
i, d = max([len(i_vars), len(intervals)]), len(d_vars)
# Find the appropriate mode
subcls = PlotMode._get_mode(mode_arg, i, d)
# Create the object
o = object.__new__(subcls)
# Do some setup for the mode instance
o.d_vars = d_vars
o._fill_i_vars(i_vars)
o._fill_intervals(intervals)
o.options = newkwargs
return o
@staticmethod
def _get_mode(mode_arg, i_var_count, d_var_count):
"""
Tries to return an appropriate mode class.
Intended to be called only by __new__.
mode_arg
Can be a string or a class. If it is a
PlotMode subclass, it is simply returned.
If it is a string, it can an alias for
a mode or an empty string. In the latter
case, we try to find a default mode for
the i_var_count and d_var_count.
i_var_count
The number of independent variables
needed to evaluate the d_vars.
d_var_count
The number of dependent variables;
usually the number of functions to
be evaluated in plotting.
For example, a Cartesian function y = f(x) has
one i_var (x) and one d_var (y). A parametric
form x,y,z = f(u,v), f(u,v), f(u,v) has two
two i_vars (u,v) and three d_vars (x,y,z).
"""
# if the mode_arg is simply a PlotMode class,
# check that the mode supports the numbers
# of independent and dependent vars, then
# return it
try:
m = None
if issubclass(mode_arg, PlotMode):
m = mode_arg
except TypeError:
pass
if m:
if not m._was_initialized:
raise ValueError(("To use unregistered plot mode %s "
"you must first call %s._init_mode().")
% (m.__name__, m.__name__))
if d_var_count != m.d_var_count:
raise ValueError(("%s can only plot functions "
"with %i dependent variables.")
% (m.__name__,
m.d_var_count))
if i_var_count > m.i_var_count:
raise ValueError(("%s cannot plot functions "
"with more than %i independent "
"variables.")
% (m.__name__,
m.i_var_count))
return m
# If it is a string, there are two possibilities.
if isinstance(mode_arg, str):
i, d = i_var_count, d_var_count
if i > PlotMode._i_var_max:
raise ValueError(var_count_error(True, True))
if d > PlotMode._d_var_max:
raise ValueError(var_count_error(False, True))
# If the string is '', try to find a suitable
# default mode
if not mode_arg:
return PlotMode._get_default_mode(i, d)
# Otherwise, interpret the string as a mode
# alias (e.g. 'cartesian', 'parametric', etc)
else:
return PlotMode._get_aliased_mode(mode_arg, i, d)
else:
raise ValueError("PlotMode argument must be "
"a class or a string")
@staticmethod
def _get_default_mode(i, d, i_vars=-1):
if i_vars == -1:
i_vars = i
try:
return PlotMode._mode_default_map[d][i]
except KeyError:
# Keep looking for modes in higher i var counts
# which support the given d var count until we
# reach the max i_var count.
if i < PlotMode._i_var_max:
return PlotMode._get_default_mode(i + 1, d, i_vars)
else:
raise ValueError(("Couldn't find a default mode "
"for %i independent and %i "
"dependent variables.") % (i_vars, d))
@staticmethod
def _get_aliased_mode(alias, i, d, i_vars=-1):
if i_vars == -1:
i_vars = i
if alias not in PlotMode._mode_alias_list:
raise ValueError(("Couldn't find a mode called"
" %s. Known modes: %s.")
% (alias, ", ".join(PlotMode._mode_alias_list)))
try:
return PlotMode._mode_map[d][i][alias]
except TypeError:
# Keep looking for modes in higher i var counts
# which support the given d var count and alias
# until we reach the max i_var count.
if i < PlotMode._i_var_max:
return PlotMode._get_aliased_mode(alias, i + 1, d, i_vars)
else:
raise ValueError(("Couldn't find a %s mode "
"for %i independent and %i "
"dependent variables.")
% (alias, i_vars, d))
@classmethod
def _register(cls):
"""
Called once for each user-usable plot mode.
For Cartesian2D, it is invoked after the
class definition: Cartesian2D._register()
"""
name = cls.__name__
cls._init_mode()
try:
i, d = cls.i_var_count, cls.d_var_count
# Add the mode to _mode_map under all
# given aliases
for a in cls.aliases:
if a not in PlotMode._mode_alias_list:
# Also track valid aliases, so
# we can quickly know when given
# an invalid one in _get_mode.
PlotMode._mode_alias_list.append(a)
PlotMode._mode_map[d][i][a] = cls
if cls.is_default:
# If this mode was marked as the
# default for this d,i combination,
# also set that.
PlotMode._mode_default_map[d][i] = cls
except Exception as e:
raise RuntimeError(("Failed to register "
"plot mode %s. Reason: %s")
% (name, (str(e))))
@classmethod
def _init_mode(cls):
"""
Initializes the plot mode based on
the 'mode-specific parameters' above.
Only intended to be called by
PlotMode._register(). To use a mode without
registering it, you can directly call
ModeSubclass._init_mode().
"""
def symbols_list(symbol_str):
return [Symbol(s) for s in symbol_str]
# Convert the vars strs into
# lists of symbols.
cls.i_vars = symbols_list(cls.i_vars)
cls.d_vars = symbols_list(cls.d_vars)
# Var count is used often, calculate
# it once here
cls.i_var_count = len(cls.i_vars)
cls.d_var_count = len(cls.d_vars)
if cls.i_var_count > PlotMode._i_var_max:
raise ValueError(var_count_error(True, False))
if cls.d_var_count > PlotMode._d_var_max:
raise ValueError(var_count_error(False, False))
# Try to use first alias as primary_alias
if len(cls.aliases) > 0:
cls.primary_alias = cls.aliases[0]
else:
cls.primary_alias = cls.__name__
di = cls.intervals
if len(di) != cls.i_var_count:
raise ValueError("Plot mode must provide a "
"default interval for each i_var.")
for i in range(cls.i_var_count):
# default intervals must be given [min,max,steps]
# (no var, but they must be in the same order as i_vars)
if len(di[i]) != 3:
raise ValueError("length should be equal to 3")
# Initialize an incomplete interval,
# to later be filled with a var when
# the mode is instantiated.
di[i] = PlotInterval(None, *di[i])
# To prevent people from using modes
# without these required fields set up.
cls._was_initialized = True
_was_initialized = False
## Initializer Helper Methods
@staticmethod
def _find_i_vars(functions, intervals):
i_vars = []
# First, collect i_vars in the
# order they are given in any
# intervals.
for i in intervals:
if i.v is None:
continue
elif i.v in i_vars:
raise ValueError(("Multiple intervals given "
"for %s.") % (str(i.v)))
i_vars.append(i.v)
# Then, find any remaining
# i_vars in given functions
# (aka d_vars)
for f in functions:
for a in f.free_symbols:
if a not in i_vars:
i_vars.append(a)
return i_vars
def _fill_i_vars(self, i_vars):
# copy default i_vars
self.i_vars = [Symbol(str(i)) for i in self.i_vars]
# replace with given i_vars
for i in range(len(i_vars)):
self.i_vars[i] = i_vars[i]
def _fill_intervals(self, intervals):
# copy default intervals
self.intervals = [PlotInterval(i) for i in self.intervals]
# track i_vars used so far
v_used = []
# fill copy of default
# intervals with given info
for i in range(len(intervals)):
self.intervals[i].fill_from(intervals[i])
if self.intervals[i].v is not None:
v_used.append(self.intervals[i].v)
# Find any orphan intervals and
# assign them i_vars
for i in range(len(self.intervals)):
if self.intervals[i].v is None:
u = [v for v in self.i_vars if v not in v_used]
if len(u) == 0:
raise ValueError("length should not be equal to 0")
self.intervals[i].v = u[0]
v_used.append(u[0])
@staticmethod
def _interpret_args(args):
interval_wrong_order = "PlotInterval %s was given before any function(s)."
interpret_error = "Could not interpret %s as a function or interval."
functions, intervals = [], []
if isinstance(args[0], GeometryEntity):
for coords in list(args[0].arbitrary_point()):
functions.append(coords)
intervals.append(PlotInterval.try_parse(args[0].plot_interval()))
else:
for a in args:
i = PlotInterval.try_parse(a)
if i is not None:
if len(functions) == 0:
raise ValueError(interval_wrong_order % (str(i)))
else:
intervals.append(i)
else:
if is_sequence(a, include=str):
raise ValueError(interpret_error % (str(a)))
try:
f = sympify(a)
functions.append(f)
except TypeError:
raise ValueError(interpret_error % str(a))
return functions, intervals
@staticmethod
def _extract_options(args, kwargs):
newkwargs, newargs = {}, []
for a in args:
if isinstance(a, str):
newkwargs = dict(newkwargs, **parse_option_string(a))
else:
newargs.append(a)
newkwargs = dict(newkwargs, **kwargs)
return newargs, newkwargs
def var_count_error(is_independent, is_plotting):
"""
Used to format an error message which differs
slightly in 4 places.
"""
if is_plotting:
v = "Plotting"
else:
v = "Registering plot modes"
if is_independent:
n, s = PlotMode._i_var_max, "independent"
else:
n, s = PlotMode._d_var_max, "dependent"
return ("%s with more than %i %s variables "
"is not supported.") % (v, n, s)
|
8a08495024a6195607f88ba84992fcf43ecb07a04fd520aac0122b0d1a8b0319 | from __future__ import print_function, division
from sympy import Basic, Symbol, symbols, lambdify
from .util import interpolate, rinterpolate, create_bounds, update_bounds
from sympy.utilities.iterables import sift
class ColorGradient(object):
colors = [0.4, 0.4, 0.4], [0.9, 0.9, 0.9]
intervals = 0.0, 1.0
def __init__(self, *args):
if len(args) == 2:
self.colors = list(args)
self.intervals = [0.0, 1.0]
elif len(args) > 0:
if len(args) % 2 != 0:
raise ValueError("len(args) should be even")
self.colors = [args[i] for i in range(1, len(args), 2)]
self.intervals = [args[i] for i in range(0, len(args), 2)]
assert len(self.colors) == len(self.intervals)
def copy(self):
c = ColorGradient()
c.colors = [e[::] for e in self.colors]
c.intervals = self.intervals[::]
return c
def _find_interval(self, v):
m = len(self.intervals)
i = 0
while i < m - 1 and self.intervals[i] <= v:
i += 1
return i
def _interpolate_axis(self, axis, v):
i = self._find_interval(v)
v = rinterpolate(self.intervals[i - 1], self.intervals[i], v)
return interpolate(self.colors[i - 1][axis], self.colors[i][axis], v)
def __call__(self, r, g, b):
c = self._interpolate_axis
return c(0, r), c(1, g), c(2, b)
default_color_schemes = {} # defined at the bottom of this file
class ColorScheme(object):
def __init__(self, *args, **kwargs):
self.args = args
self.f, self.gradient = None, ColorGradient()
if len(args) == 1 and not isinstance(args[0], Basic) and callable(args[0]):
self.f = args[0]
elif len(args) == 1 and isinstance(args[0], str):
if args[0] in default_color_schemes:
cs = default_color_schemes[args[0]]
self.f, self.gradient = cs.f, cs.gradient.copy()
else:
self.f = lambdify('x,y,z,u,v', args[0])
else:
self.f, self.gradient = self._interpret_args(args)
self._test_color_function()
if not isinstance(self.gradient, ColorGradient):
raise ValueError("Color gradient not properly initialized. "
"(Not a ColorGradient instance.)")
def _interpret_args(self, args):
f, gradient = None, self.gradient
atoms, lists = self._sort_args(args)
s = self._pop_symbol_list(lists)
s = self._fill_in_vars(s)
# prepare the error message for lambdification failure
f_str = ', '.join(str(fa) for fa in atoms)
s_str = (str(sa) for sa in s)
s_str = ', '.join(sa for sa in s_str if sa.find('unbound') < 0)
f_error = ValueError("Could not interpret arguments "
"%s as functions of %s." % (f_str, s_str))
# try to lambdify args
if len(atoms) == 1:
fv = atoms[0]
try:
f = lambdify(s, [fv, fv, fv])
except TypeError:
raise f_error
elif len(atoms) == 3:
fr, fg, fb = atoms
try:
f = lambdify(s, [fr, fg, fb])
except TypeError:
raise f_error
else:
raise ValueError("A ColorScheme must provide 1 or 3 "
"functions in x, y, z, u, and/or v.")
# try to intrepret any given color information
if len(lists) == 0:
gargs = []
elif len(lists) == 1:
gargs = lists[0]
elif len(lists) == 2:
try:
(r1, g1, b1), (r2, g2, b2) = lists
except TypeError:
raise ValueError("If two color arguments are given, "
"they must be given in the format "
"(r1, g1, b1), (r2, g2, b2).")
gargs = lists
elif len(lists) == 3:
try:
(r1, r2), (g1, g2), (b1, b2) = lists
except Exception:
raise ValueError("If three color arguments are given, "
"they must be given in the format "
"(r1, r2), (g1, g2), (b1, b2). To create "
"a multi-step gradient, use the syntax "
"[0, colorStart, step1, color1, ..., 1, "
"colorEnd].")
gargs = [[r1, g1, b1], [r2, g2, b2]]
else:
raise ValueError("Don't know what to do with collection "
"arguments %s." % (', '.join(str(l) for l in lists)))
if gargs:
try:
gradient = ColorGradient(*gargs)
except Exception as ex:
raise ValueError(("Could not initialize a gradient "
"with arguments %s. Inner "
"exception: %s") % (gargs, str(ex)))
return f, gradient
def _pop_symbol_list(self, lists):
symbol_lists = []
for l in lists:
mark = True
for s in l:
if s is not None and not isinstance(s, Symbol):
mark = False
break
if mark:
lists.remove(l)
symbol_lists.append(l)
if len(symbol_lists) == 1:
return symbol_lists[0]
elif len(symbol_lists) == 0:
return []
else:
raise ValueError("Only one list of Symbols "
"can be given for a color scheme.")
def _fill_in_vars(self, args):
defaults = symbols('x,y,z,u,v')
v_error = ValueError("Could not find what to plot.")
if len(args) == 0:
return defaults
if not isinstance(args, (tuple, list)):
raise v_error
if len(args) == 0:
return defaults
for s in args:
if s is not None and not isinstance(s, Symbol):
raise v_error
# when vars are given explicitly, any vars
# not given are marked 'unbound' as to not
# be accidentally used in an expression
vars = [Symbol('unbound%i' % (i)) for i in range(1, 6)]
# interpret as t
if len(args) == 1:
vars[3] = args[0]
# interpret as u,v
elif len(args) == 2:
if args[0] is not None:
vars[3] = args[0]
if args[1] is not None:
vars[4] = args[1]
# interpret as x,y,z
elif len(args) >= 3:
# allow some of x,y,z to be
# left unbound if not given
if args[0] is not None:
vars[0] = args[0]
if args[1] is not None:
vars[1] = args[1]
if args[2] is not None:
vars[2] = args[2]
# interpret the rest as t
if len(args) >= 4:
vars[3] = args[3]
# ...or u,v
if len(args) >= 5:
vars[4] = args[4]
return vars
def _sort_args(self, args):
lists, atoms = sift(args,
lambda a: isinstance(a, (tuple, list)), binary=True)
return atoms, lists
def _test_color_function(self):
if not callable(self.f):
raise ValueError("Color function is not callable.")
try:
result = self.f(0, 0, 0, 0, 0)
if len(result) != 3:
raise ValueError("length should be equal to 3")
except TypeError:
raise ValueError("Color function needs to accept x,y,z,u,v, "
"as arguments even if it doesn't use all of them.")
except AssertionError:
raise ValueError("Color function needs to return 3-tuple r,g,b.")
except Exception:
pass # color function probably not valid at 0,0,0,0,0
def __call__(self, x, y, z, u, v):
try:
return self.f(x, y, z, u, v)
except Exception:
return None
def apply_to_curve(self, verts, u_set, set_len=None, inc_pos=None):
"""
Apply this color scheme to a
set of vertices over a single
independent variable u.
"""
bounds = create_bounds()
cverts = list()
if callable(set_len):
set_len(len(u_set)*2)
# calculate f() = r,g,b for each vert
# and find the min and max for r,g,b
for _u in range(len(u_set)):
if verts[_u] is None:
cverts.append(None)
else:
x, y, z = verts[_u]
u, v = u_set[_u], None
c = self(x, y, z, u, v)
if c is not None:
c = list(c)
update_bounds(bounds, c)
cverts.append(c)
if callable(inc_pos):
inc_pos()
# scale and apply gradient
for _u in range(len(u_set)):
if cverts[_u] is not None:
for _c in range(3):
# scale from [f_min, f_max] to [0,1]
cverts[_u][_c] = rinterpolate(bounds[_c][0], bounds[_c][1],
cverts[_u][_c])
# apply gradient
cverts[_u] = self.gradient(*cverts[_u])
if callable(inc_pos):
inc_pos()
return cverts
def apply_to_surface(self, verts, u_set, v_set, set_len=None, inc_pos=None):
"""
Apply this color scheme to a
set of vertices over two
independent variables u and v.
"""
bounds = create_bounds()
cverts = list()
if callable(set_len):
set_len(len(u_set)*len(v_set)*2)
# calculate f() = r,g,b for each vert
# and find the min and max for r,g,b
for _u in range(len(u_set)):
column = list()
for _v in range(len(v_set)):
if verts[_u][_v] is None:
column.append(None)
else:
x, y, z = verts[_u][_v]
u, v = u_set[_u], v_set[_v]
c = self(x, y, z, u, v)
if c is not None:
c = list(c)
update_bounds(bounds, c)
column.append(c)
if callable(inc_pos):
inc_pos()
cverts.append(column)
# scale and apply gradient
for _u in range(len(u_set)):
for _v in range(len(v_set)):
if cverts[_u][_v] is not None:
# scale from [f_min, f_max] to [0,1]
for _c in range(3):
cverts[_u][_v][_c] = rinterpolate(bounds[_c][0],
bounds[_c][1], cverts[_u][_v][_c])
# apply gradient
cverts[_u][_v] = self.gradient(*cverts[_u][_v])
if callable(inc_pos):
inc_pos()
return cverts
def str_base(self):
return ", ".join(str(a) for a in self.args)
def __repr__(self):
return "%s" % (self.str_base())
x, y, z, t, u, v = symbols('x,y,z,t,u,v')
default_color_schemes['rainbow'] = ColorScheme(z, y, x)
default_color_schemes['zfade'] = ColorScheme(z, (0.4, 0.4, 0.97),
(0.97, 0.4, 0.4), (None, None, z))
default_color_schemes['zfade3'] = ColorScheme(z, (None, None, z),
[0.00, (0.2, 0.2, 1.0),
0.35, (0.2, 0.8, 0.4),
0.50, (0.3, 0.9, 0.3),
0.65, (0.4, 0.8, 0.2),
1.00, (1.0, 0.2, 0.2)])
default_color_schemes['zfade4'] = ColorScheme(z, (None, None, z),
[0.0, (0.3, 0.3, 1.0),
0.30, (0.3, 1.0, 0.3),
0.55, (0.95, 1.0, 0.2),
0.65, (1.0, 0.95, 0.2),
0.85, (1.0, 0.7, 0.2),
1.0, (1.0, 0.3, 0.2)])
|
5bee128a52765f15c5a5ea5003f690a702cde2ea56d450b758908ad57b74b908 | from __future__ import print_function, division
import pyglet.gl as pgl
from sympy.core import S
from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase
class PlotCurve(PlotModeBase):
style_override = 'wireframe'
def _on_calculate_verts(self):
self.t_interval = self.intervals[0]
self.t_set = list(self.t_interval.frange())
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0]]
evaluate = self._get_evaluator()
self._calculating_verts_pos = 0.0
self._calculating_verts_len = float(self.t_interval.v_len)
self.verts = list()
b = self.bounds
for t in self.t_set:
try:
_e = evaluate(t) # calculate vertex
except (NameError, ZeroDivisionError):
_e = None
if _e is not None: # update bounding box
for axis in range(3):
b[axis][0] = min([b[axis][0], _e[axis]])
b[axis][1] = max([b[axis][1], _e[axis]])
self.verts.append(_e)
self._calculating_verts_pos += 1.0
for axis in range(3):
b[axis][2] = b[axis][1] - b[axis][0]
if b[axis][2] == 0.0:
b[axis][2] = 1.0
self.push_wireframe(self.draw_verts(False))
def _on_calculate_cverts(self):
if not self.verts or not self.color:
return
def set_work_len(n):
self._calculating_cverts_len = float(n)
def inc_work_pos():
self._calculating_cverts_pos += 1.0
set_work_len(1)
self._calculating_cverts_pos = 0
self.cverts = self.color.apply_to_curve(self.verts,
self.t_set,
set_len=set_work_len,
inc_pos=inc_work_pos)
self.push_wireframe(self.draw_verts(True))
def calculate_one_cvert(self, t):
vert = self.verts[t]
return self.color(vert[0], vert[1], vert[2],
self.t_set[t], None)
def draw_verts(self, use_cverts):
def f():
pgl.glBegin(pgl.GL_LINE_STRIP)
for t in range(len(self.t_set)):
p = self.verts[t]
if p is None:
pgl.glEnd()
pgl.glBegin(pgl.GL_LINE_STRIP)
continue
if use_cverts:
c = self.cverts[t]
if c is None:
c = (0, 0, 0)
pgl.glColor3f(*c)
else:
pgl.glColor3f(*self.default_wireframe_color)
pgl.glVertex3f(*p)
pgl.glEnd()
return f
|
e9af0261f5a8e04ab650dad6bf9a6c55405ada079afb0a752914ae9ce44f69b9 | from __future__ import print_function, division
import pyglet.gl as pgl
from sympy.core import S
from sympy.plotting.pygletplot.plot_mode_base import PlotModeBase
class PlotSurface(PlotModeBase):
default_rot_preset = 'perspective'
def _on_calculate_verts(self):
self.u_interval = self.intervals[0]
self.u_set = list(self.u_interval.frange())
self.v_interval = self.intervals[1]
self.v_set = list(self.v_interval.frange())
self.bounds = [[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0]]
evaluate = self._get_evaluator()
self._calculating_verts_pos = 0.0
self._calculating_verts_len = float(
self.u_interval.v_len*self.v_interval.v_len)
verts = list()
b = self.bounds
for u in self.u_set:
column = list()
for v in self.v_set:
try:
_e = evaluate(u, v) # calculate vertex
except ZeroDivisionError:
_e = None
if _e is not None: # update bounding box
for axis in range(3):
b[axis][0] = min([b[axis][0], _e[axis]])
b[axis][1] = max([b[axis][1], _e[axis]])
column.append(_e)
self._calculating_verts_pos += 1.0
verts.append(column)
for axis in range(3):
b[axis][2] = b[axis][1] - b[axis][0]
if b[axis][2] == 0.0:
b[axis][2] = 1.0
self.verts = verts
self.push_wireframe(self.draw_verts(False, False))
self.push_solid(self.draw_verts(False, True))
def _on_calculate_cverts(self):
if not self.verts or not self.color:
return
def set_work_len(n):
self._calculating_cverts_len = float(n)
def inc_work_pos():
self._calculating_cverts_pos += 1.0
set_work_len(1)
self._calculating_cverts_pos = 0
self.cverts = self.color.apply_to_surface(self.verts,
self.u_set,
self.v_set,
set_len=set_work_len,
inc_pos=inc_work_pos)
self.push_solid(self.draw_verts(True, True))
def calculate_one_cvert(self, u, v):
vert = self.verts[u][v]
return self.color(vert[0], vert[1], vert[2],
self.u_set[u], self.v_set[v])
def draw_verts(self, use_cverts, use_solid_color):
def f():
for u in range(1, len(self.u_set)):
pgl.glBegin(pgl.GL_QUAD_STRIP)
for v in range(len(self.v_set)):
pa = self.verts[u - 1][v]
pb = self.verts[u][v]
if pa is None or pb is None:
pgl.glEnd()
pgl.glBegin(pgl.GL_QUAD_STRIP)
continue
if use_cverts:
ca = self.cverts[u - 1][v]
cb = self.cverts[u][v]
if ca is None:
ca = (0, 0, 0)
if cb is None:
cb = (0, 0, 0)
else:
if use_solid_color:
ca = cb = self.default_solid_color
else:
ca = cb = self.default_wireframe_color
pgl.glColor3f(*ca)
pgl.glVertex3f(*pa)
pgl.glColor3f(*cb)
pgl.glVertex3f(*pb)
pgl.glEnd()
return f
|
6ae19c4f63b6da65e82ff3a7da9ea3e0cfab4301d1de9d19e474d48a5e9a9f05 | from __future__ import print_function, division
from sympy import Symbol, sympify
from sympy.core.numbers import Integer
class PlotInterval(object):
"""
"""
_v, _v_min, _v_max, _v_steps = None, None, None, None
def require_all_args(f):
def check(self, *args, **kwargs):
for g in [self._v, self._v_min, self._v_max, self._v_steps]:
if g is None:
raise ValueError("PlotInterval is incomplete.")
return f(self, *args, **kwargs)
return check
def __init__(self, *args):
if len(args) == 1:
if isinstance(args[0], PlotInterval):
self.fill_from(args[0])
return
elif isinstance(args[0], str):
try:
args = eval(args[0])
except TypeError:
s_eval_error = "Could not interpret string %s."
raise ValueError(s_eval_error % (args[0]))
elif isinstance(args[0], (tuple, list)):
args = args[0]
else:
raise ValueError("Not an interval.")
if not isinstance(args, (tuple, list)) or len(args) > 4:
f_error = "PlotInterval must be a tuple or list of length 4 or less."
raise ValueError(f_error)
args = list(args)
if len(args) > 0 and (args[0] is None or isinstance(args[0], Symbol)):
self.v = args.pop(0)
if len(args) in [2, 3]:
self.v_min = args.pop(0)
self.v_max = args.pop(0)
if len(args) == 1:
self.v_steps = args.pop(0)
elif len(args) == 1:
self.v_steps = args.pop(0)
def get_v(self):
return self._v
def set_v(self, v):
if v is None:
self._v = None
return
if not isinstance(v, Symbol):
raise ValueError("v must be a sympy Symbol.")
self._v = v
def get_v_min(self):
return self._v_min
def set_v_min(self, v_min):
if v_min is None:
self._v_min = None
return
try:
self._v_min = sympify(v_min)
float(self._v_min.evalf())
except TypeError:
raise ValueError("v_min could not be interpreted as a number.")
def get_v_max(self):
return self._v_max
def set_v_max(self, v_max):
if v_max is None:
self._v_max = None
return
try:
self._v_max = sympify(v_max)
float(self._v_max.evalf())
except TypeError:
raise ValueError("v_max could not be interpreted as a number.")
def get_v_steps(self):
return self._v_steps
def set_v_steps(self, v_steps):
if v_steps is None:
self._v_steps = None
return
if isinstance(v_steps, int):
v_steps = Integer(v_steps)
elif not isinstance(v_steps, Integer):
raise ValueError("v_steps must be an int or sympy Integer.")
if v_steps <= Integer(0):
raise ValueError("v_steps must be positive.")
self._v_steps = v_steps
@require_all_args
def get_v_len(self):
return self.v_steps + 1
v = property(get_v, set_v)
v_min = property(get_v_min, set_v_min)
v_max = property(get_v_max, set_v_max)
v_steps = property(get_v_steps, set_v_steps)
v_len = property(get_v_len)
def fill_from(self, b):
if b.v is not None:
self.v = b.v
if b.v_min is not None:
self.v_min = b.v_min
if b.v_max is not None:
self.v_max = b.v_max
if b.v_steps is not None:
self.v_steps = b.v_steps
@staticmethod
def try_parse(*args):
"""
Returns a PlotInterval if args can be interpreted
as such, otherwise None.
"""
if len(args) == 1 and isinstance(args[0], PlotInterval):
return args[0]
try:
return PlotInterval(*args)
except ValueError:
return None
def _str_base(self):
return ",".join([str(self.v), str(self.v_min),
str(self.v_max), str(self.v_steps)])
def __repr__(self):
"""
A string representing the interval in class constructor form.
"""
return "PlotInterval(%s)" % (self._str_base())
def __str__(self):
"""
A string representing the interval in list form.
"""
return "[%s]" % (self._str_base())
@require_all_args
def assert_complete(self):
pass
@require_all_args
def vrange(self):
"""
Yields v_steps+1 sympy numbers ranging from
v_min to v_max.
"""
d = (self.v_max - self.v_min) / self.v_steps
for i in range(self.v_steps + 1):
a = self.v_min + (d * Integer(i))
yield a
@require_all_args
def vrange2(self):
"""
Yields v_steps pairs of sympy numbers ranging from
(v_min, v_min + step) to (v_max - step, v_max).
"""
d = (self.v_max - self.v_min) / self.v_steps
a = self.v_min + (d * Integer(0))
for i in range(self.v_steps):
b = self.v_min + (d * Integer(i + 1))
yield a, b
a = b
def frange(self):
for i in self.vrange():
yield float(i.evalf())
|
f8678f949a2555e99c53de255629591b840025b630e78d463445590be4b90d41 | from __future__ import print_function, division
try:
from ctypes import c_float, c_int, c_double
except ImportError:
pass
import pyglet.gl as pgl
from sympy.core import S
def get_model_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv):
"""
Returns the current modelview matrix.
"""
m = (array_type*16)()
glGetMethod(pgl.GL_MODELVIEW_MATRIX, m)
return m
def get_projection_matrix(array_type=c_float, glGetMethod=pgl.glGetFloatv):
"""
Returns the current modelview matrix.
"""
m = (array_type*16)()
glGetMethod(pgl.GL_PROJECTION_MATRIX, m)
return m
def get_viewport():
"""
Returns the current viewport.
"""
m = (c_int*4)()
pgl.glGetIntegerv(pgl.GL_VIEWPORT, m)
return m
def get_direction_vectors():
m = get_model_matrix()
return ((m[0], m[4], m[8]),
(m[1], m[5], m[9]),
(m[2], m[6], m[10]))
def get_view_direction_vectors():
m = get_model_matrix()
return ((m[0], m[1], m[2]),
(m[4], m[5], m[6]),
(m[8], m[9], m[10]))
def get_basis_vectors():
return ((1, 0, 0), (0, 1, 0), (0, 0, 1))
def screen_to_model(x, y, z):
m = get_model_matrix(c_double, pgl.glGetDoublev)
p = get_projection_matrix(c_double, pgl.glGetDoublev)
w = get_viewport()
mx, my, mz = c_double(), c_double(), c_double()
pgl.gluUnProject(x, y, z, m, p, w, mx, my, mz)
return float(mx.value), float(my.value), float(mz.value)
def model_to_screen(x, y, z):
m = get_model_matrix(c_double, pgl.glGetDoublev)
p = get_projection_matrix(c_double, pgl.glGetDoublev)
w = get_viewport()
mx, my, mz = c_double(), c_double(), c_double()
pgl.gluProject(x, y, z, m, p, w, mx, my, mz)
return float(mx.value), float(my.value), float(mz.value)
def vec_subs(a, b):
return tuple(a[i] - b[i] for i in range(len(a)))
def billboard_matrix():
"""
Removes rotational components of
current matrix so that primitives
are always drawn facing the viewer.
|1|0|0|x|
|0|1|0|x|
|0|0|1|x| (x means left unchanged)
|x|x|x|x|
"""
m = get_model_matrix()
# XXX: for i in range(11): m[i] = i ?
m[0] = 1
m[1] = 0
m[2] = 0
m[4] = 0
m[5] = 1
m[6] = 0
m[8] = 0
m[9] = 0
m[10] = 1
pgl.glLoadMatrixf(m)
def create_bounds():
return [[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0],
[S.Infinity, S.NegativeInfinity, 0]]
def update_bounds(b, v):
if v is None:
return
for axis in range(3):
b[axis][0] = min([b[axis][0], v[axis]])
b[axis][1] = max([b[axis][1], v[axis]])
def interpolate(a_min, a_max, a_ratio):
return a_min + a_ratio * (a_max - a_min)
def rinterpolate(a_min, a_max, a_value):
a_range = a_max - a_min
if a_max == a_min:
a_range = 1.0
return (a_value - a_min) / float(a_range)
def interpolate_color(color1, color2, ratio):
return tuple(interpolate(color1[i], color2[i], ratio) for i in range(3))
def scale_value(v, v_min, v_len):
return (v - v_min) / v_len
def scale_value_list(flist):
v_min, v_max = min(flist), max(flist)
v_len = v_max - v_min
return list(scale_value(f, v_min, v_len) for f in flist)
def strided_range(r_min, r_max, stride, max_steps=50):
o_min, o_max = r_min, r_max
if abs(r_min - r_max) < 0.001:
return []
try:
range(int(r_min - r_max))
except (TypeError, OverflowError):
return []
if r_min > r_max:
raise ValueError("r_min can not be greater than r_max")
r_min_s = (r_min % stride)
r_max_s = stride - (r_max % stride)
if abs(r_max_s - stride) < 0.001:
r_max_s = 0.0
r_min -= r_min_s
r_max += r_max_s
r_steps = int((r_max - r_min)/stride)
if max_steps and r_steps > max_steps:
return strided_range(o_min, o_max, stride*2)
return [r_min] + list(r_min + e*stride for e in range(1, r_steps + 1)) + [r_max]
def parse_option_string(s):
if not isinstance(s, str):
return None
options = {}
for token in s.split(';'):
pieces = token.split('=')
if len(pieces) == 1:
option, value = pieces[0], ""
elif len(pieces) == 2:
option, value = pieces
else:
raise ValueError("Plot option string '%s' is malformed." % (s))
options[option.strip()] = value.strip()
return options
def dot_product(v1, v2):
return sum(v1[i]*v2[i] for i in range(3))
def vec_sub(v1, v2):
return tuple(v1[i] - v2[i] for i in range(3))
def vec_mag(v):
return sum(v[i]**2 for i in range(3))**(0.5)
|
9dd04c733aeceb160c3794469f208bf72abba4d531ad71d3494d66754b29e6d5 | from sympy.plotting.intervalmath import interval
from sympy.testing.pytest import raises
def test_interval():
assert (interval(1, 1) == interval(1, 1, is_valid=True)) == (True, True)
assert (interval(1, 1) == interval(1, 1, is_valid=False)) == (True, False)
assert (interval(1, 1) == interval(1, 1, is_valid=None)) == (True, None)
assert (interval(1, 1.5) == interval(1, 2)) == (None, True)
assert (interval(0, 1) == interval(2, 3)) == (False, True)
assert (interval(0, 1) == interval(1, 2)) == (None, True)
assert (interval(1, 2) != interval(1, 2)) == (False, True)
assert (interval(1, 3) != interval(2, 3)) == (None, True)
assert (interval(1, 3) != interval(-5, -3)) == (True, True)
assert (
interval(1, 3, is_valid=False) != interval(-5, -3)) == (True, False)
assert (interval(1, 3, is_valid=None) != interval(-5, 3)) == (None, None)
assert (interval(4, 4) != 4) == (False, True)
assert (interval(1, 1) == 1) == (True, True)
assert (interval(1, 3, is_valid=False) == interval(1, 3)) == (True, False)
assert (interval(1, 3, is_valid=None) == interval(1, 3)) == (True, None)
inter = interval(-5, 5)
assert (interval(inter) == interval(-5, 5)) == (True, True)
assert inter.width == 10
assert 0 in inter
assert -5 in inter
assert 5 in inter
assert interval(0, 3) in inter
assert interval(-6, 2) not in inter
assert -5.05 not in inter
assert 5.3 not in inter
interb = interval(-float('inf'), float('inf'))
assert 0 in inter
assert inter in interb
assert interval(0, float('inf')) in interb
assert interval(-float('inf'), 5) in interb
assert interval(-1e50, 1e50) in interb
assert (
-interval(-1, -2, is_valid=False) == interval(1, 2)) == (True, False)
raises(ValueError, lambda: interval(1, 2, 3))
def test_interval_add():
assert (interval(1, 2) + interval(2, 3) == interval(3, 5)) == (True, True)
assert (1 + interval(1, 2) == interval(2, 3)) == (True, True)
assert (interval(1, 2) + 1 == interval(2, 3)) == (True, True)
compare = (1 + interval(0, float('inf')) == interval(1, float('inf')))
assert compare == (True, True)
a = 1 + interval(2, 5, is_valid=False)
assert a.is_valid is False
a = 1 + interval(2, 5, is_valid=None)
assert a.is_valid is None
a = interval(2, 5, is_valid=False) + interval(3, 5, is_valid=None)
assert a.is_valid is False
a = interval(3, 5) + interval(-1, 1, is_valid=None)
assert a.is_valid is None
a = interval(2, 5, is_valid=False) + 1
assert a.is_valid is False
def test_interval_sub():
assert (interval(1, 2) - interval(1, 5) == interval(-4, 1)) == (True, True)
assert (interval(1, 2) - 1 == interval(0, 1)) == (True, True)
assert (1 - interval(1, 2) == interval(-1, 0)) == (True, True)
a = 1 - interval(1, 2, is_valid=False)
assert a.is_valid is False
a = interval(1, 4, is_valid=None) - 1
assert a.is_valid is None
a = interval(1, 3, is_valid=False) - interval(1, 3)
assert a.is_valid is False
a = interval(1, 3, is_valid=None) - interval(1, 3)
assert a.is_valid is None
def test_interval_inequality():
assert (interval(1, 2) < interval(3, 4)) == (True, True)
assert (interval(1, 2) < interval(2, 4)) == (None, True)
assert (interval(1, 2) < interval(-2, 0)) == (False, True)
assert (interval(1, 2) <= interval(2, 4)) == (True, True)
assert (interval(1, 2) <= interval(1.5, 6)) == (None, True)
assert (interval(2, 3) <= interval(1, 2)) == (None, True)
assert (interval(2, 3) <= interval(1, 1.5)) == (False, True)
assert (
interval(1, 2, is_valid=False) <= interval(-2, 0)) == (False, False)
assert (interval(1, 2, is_valid=None) <= interval(-2, 0)) == (False, None)
assert (interval(1, 2) <= 1.5) == (None, True)
assert (interval(1, 2) <= 3) == (True, True)
assert (interval(1, 2) <= 0) == (False, True)
assert (interval(5, 8) > interval(2, 3)) == (True, True)
assert (interval(2, 5) > interval(1, 3)) == (None, True)
assert (interval(2, 3) > interval(3.1, 5)) == (False, True)
assert (interval(-1, 1) == 0) == (None, True)
assert (interval(-1, 1) == 2) == (False, True)
assert (interval(-1, 1) != 0) == (None, True)
assert (interval(-1, 1) != 2) == (True, True)
assert (interval(3, 5) > 2) == (True, True)
assert (interval(3, 5) < 2) == (False, True)
assert (interval(1, 5) < 2) == (None, True)
assert (interval(1, 5) > 2) == (None, True)
assert (interval(0, 1) > 2) == (False, True)
assert (interval(1, 2) >= interval(0, 1)) == (True, True)
assert (interval(1, 2) >= interval(0, 1.5)) == (None, True)
assert (interval(1, 2) >= interval(3, 4)) == (False, True)
assert (interval(1, 2) >= 0) == (True, True)
assert (interval(1, 2) >= 1.2) == (None, True)
assert (interval(1, 2) >= 3) == (False, True)
assert (2 > interval(0, 1)) == (True, True)
a = interval(-1, 1, is_valid=False) < interval(2, 5, is_valid=None)
assert a == (True, False)
a = interval(-1, 1, is_valid=None) < interval(2, 5, is_valid=False)
assert a == (True, False)
a = interval(-1, 1, is_valid=None) < interval(2, 5, is_valid=None)
assert a == (True, None)
a = interval(-1, 1, is_valid=False) > interval(-5, -2, is_valid=None)
assert a == (True, False)
a = interval(-1, 1, is_valid=None) > interval(-5, -2, is_valid=False)
assert a == (True, False)
a = interval(-1, 1, is_valid=None) > interval(-5, -2, is_valid=None)
assert a == (True, None)
def test_interval_mul():
assert (
interval(1, 5) * interval(2, 10) == interval(2, 50)) == (True, True)
a = interval(-1, 1) * interval(2, 10) == interval(-10, 10)
assert a == (True, True)
a = interval(-1, 1) * interval(-5, 3) == interval(-5, 5)
assert a == (True, True)
assert (interval(1, 3) * 2 == interval(2, 6)) == (True, True)
assert (3 * interval(-1, 2) == interval(-3, 6)) == (True, True)
a = 3 * interval(1, 2, is_valid=False)
assert a.is_valid is False
a = 3 * interval(1, 2, is_valid=None)
assert a.is_valid is None
a = interval(1, 5, is_valid=False) * interval(1, 2, is_valid=None)
assert a.is_valid is False
def test_interval_div():
div = interval(1, 2, is_valid=False) / 3
assert div == interval(-float('inf'), float('inf'), is_valid=False)
div = interval(1, 2, is_valid=None) / 3
assert div == interval(-float('inf'), float('inf'), is_valid=None)
div = 3 / interval(1, 2, is_valid=None)
assert div == interval(-float('inf'), float('inf'), is_valid=None)
a = interval(1, 2) / 0
assert a.is_valid is False
a = interval(0.5, 1) / interval(-1, 0)
assert a.is_valid is None
a = interval(0, 1) / interval(0, 1)
assert a.is_valid is None
a = interval(-1, 1) / interval(-1, 1)
assert a.is_valid is None
a = interval(-1, 2) / interval(0.5, 1) == interval(-2.0, 4.0)
assert a == (True, True)
a = interval(0, 1) / interval(0.5, 1) == interval(0.0, 2.0)
assert a == (True, True)
a = interval(-1, 0) / interval(0.5, 1) == interval(-2.0, 0.0)
assert a == (True, True)
a = interval(-0.5, -0.25) / interval(0.5, 1) == interval(-1.0, -0.25)
assert a == (True, True)
a = interval(0.5, 1) / interval(0.5, 1) == interval(0.5, 2.0)
assert a == (True, True)
a = interval(0.5, 4) / interval(0.5, 1) == interval(0.5, 8.0)
assert a == (True, True)
a = interval(-1, -0.5) / interval(0.5, 1) == interval(-2.0, -0.5)
assert a == (True, True)
a = interval(-4, -0.5) / interval(0.5, 1) == interval(-8.0, -0.5)
assert a == (True, True)
a = interval(-1, 2) / interval(-2, -0.5) == interval(-4.0, 2.0)
assert a == (True, True)
a = interval(0, 1) / interval(-2, -0.5) == interval(-2.0, 0.0)
assert a == (True, True)
a = interval(-1, 0) / interval(-2, -0.5) == interval(0.0, 2.0)
assert a == (True, True)
a = interval(-0.5, -0.25) / interval(-2, -0.5) == interval(0.125, 1.0)
assert a == (True, True)
a = interval(0.5, 1) / interval(-2, -0.5) == interval(-2.0, -0.25)
assert a == (True, True)
a = interval(0.5, 4) / interval(-2, -0.5) == interval(-8.0, -0.25)
assert a == (True, True)
a = interval(-1, -0.5) / interval(-2, -0.5) == interval(0.25, 2.0)
assert a == (True, True)
a = interval(-4, -0.5) / interval(-2, -0.5) == interval(0.25, 8.0)
assert a == (True, True)
a = interval(-5, 5, is_valid=False) / 2
assert a.is_valid is False
def test_hashable():
'''
test that interval objects are hashable.
this is required in order to be able to put them into the cache, which
appears to be necessary for plotting in py3k. For details, see:
https://github.com/sympy/sympy/pull/2101
https://github.com/sympy/sympy/issues/6533
'''
hash(interval(1, 1))
hash(interval(1, 1, is_valid=True))
hash(interval(-4, -0.5))
hash(interval(-2, -0.5))
hash(interval(0.25, 8.0))
|
0f52a372b2f10303a60c452a03ef130aa905586b6679ead1f4ac26cd2eedca39 | from sympy.core.symbol import Symbol
from sympy.plotting.intervalmath import interval
from sympy.plotting.intervalmath.interval_membership import intervalMembership
from sympy.plotting.experimental_lambdify import experimental_lambdify
from sympy.testing.pytest import raises
def test_creation():
assert intervalMembership(True, True)
raises(TypeError, lambda: intervalMembership(True))
raises(TypeError, lambda: intervalMembership(True, True, True))
def test_getitem():
a = intervalMembership(True, False)
assert a[0] is True
assert a[1] is False
raises(IndexError, lambda: a[2])
def test_str():
a = intervalMembership(True, False)
assert str(a) == 'intervalMembership(True, False)'
assert repr(a) == 'intervalMembership(True, False)'
def test_equivalence():
a = intervalMembership(True, True)
b = intervalMembership(True, False)
assert (a == b) is False
assert (a != b) is True
a = intervalMembership(True, False)
b = intervalMembership(True, False)
assert (a == b) is True
assert (a != b) is False
def test_not():
x = Symbol('x')
r1 = x > -1
r2 = x <= -1
i = interval
f1 = experimental_lambdify((x,), r1)
f2 = experimental_lambdify((x,), r2)
tt = i(-0.1, 0.1, is_valid=True)
tn = i(-0.1, 0.1, is_valid=None)
tf = i(-0.1, 0.1, is_valid=False)
assert f1(tt) == ~f2(tt)
assert f1(tn) == ~f2(tn)
assert f1(tf) == ~f2(tf)
nt = i(0.9, 1.1, is_valid=True)
nn = i(0.9, 1.1, is_valid=None)
nf = i(0.9, 1.1, is_valid=False)
assert f1(nt) == ~f2(nt)
assert f1(nn) == ~f2(nn)
assert f1(nf) == ~f2(nf)
ft = i(1.9, 2.1, is_valid=True)
fn = i(1.9, 2.1, is_valid=None)
ff = i(1.9, 2.1, is_valid=False)
assert f1(ft) == ~f2(ft)
assert f1(fn) == ~f2(fn)
assert f1(ff) == ~f2(ff)
def test_boolean():
# There can be 9*9 test cases in full mapping of the cartesian product.
# But we only consider 3*3 cases for simplicity.
s = [
intervalMembership(False, False),
intervalMembership(None, None),
intervalMembership(True, True)
]
# Reduced tests for 'And'
a1 = [
intervalMembership(False, False),
intervalMembership(False, False),
intervalMembership(False, False),
intervalMembership(False, False),
intervalMembership(None, None),
intervalMembership(None, None),
intervalMembership(False, False),
intervalMembership(None, None),
intervalMembership(True, True)
]
a1_iter = iter(a1)
for i in range(len(s)):
for j in range(len(s)):
assert s[i] & s[j] == next(a1_iter)
# Reduced tests for 'Or'
a1 = [
intervalMembership(False, False),
intervalMembership(None, False),
intervalMembership(True, False),
intervalMembership(None, False),
intervalMembership(None, None),
intervalMembership(True, None),
intervalMembership(True, False),
intervalMembership(True, None),
intervalMembership(True, True)
]
a1_iter = iter(a1)
for i in range(len(s)):
for j in range(len(s)):
assert s[i] | s[j] == next(a1_iter)
# Reduced tests for 'Xor'
a1 = [
intervalMembership(False, False),
intervalMembership(None, False),
intervalMembership(True, False),
intervalMembership(None, False),
intervalMembership(None, None),
intervalMembership(None, None),
intervalMembership(True, False),
intervalMembership(None, None),
intervalMembership(False, True)
]
a1_iter = iter(a1)
for i in range(len(s)):
for j in range(len(s)):
assert s[i] ^ s[j] == next(a1_iter)
# Reduced tests for 'Not'
a1 = [
intervalMembership(True, False),
intervalMembership(None, None),
intervalMembership(False, True)
]
a1_iter = iter(a1)
for i in range(len(s)):
assert ~s[i] == next(a1_iter)
def test_boolean_errors():
a = intervalMembership(True, True)
raises(ValueError, lambda: a & 1)
raises(ValueError, lambda: a | 1)
raises(ValueError, lambda: a ^ 1)
|
b12ba7e422c92e348d06d3405b020497ecd5184b67b18497a8818572925e0540 | """
SymPy is a Python library for symbolic mathematics. It aims to become a
full-featured computer algebra system (CAS) while keeping the code as simple
as possible in order to be comprehensible and easily extensible. SymPy is
written entirely in Python. It depends on mpmath, and other external libraries
may be optionally for things like plotting support.
See the webpage for more information and documentation:
https://sympy.org
"""
from __future__ import absolute_import, print_function
del absolute_import, print_function
try:
import mpmath
except ImportError:
raise ImportError("SymPy now depends on mpmath as an external library. "
"See https://docs.sympy.org/latest/install.html#mpmath for more information.")
del mpmath
from sympy.release import __version__
if 'dev' in __version__:
def enable_warnings():
import warnings
warnings.filterwarnings('default', '.*', DeprecationWarning, module='sympy.*')
del warnings
enable_warnings()
del enable_warnings
import sys
if ((sys.version_info[0] == 2 and sys.version_info[1] < 7) or
(sys.version_info[0] == 3 and sys.version_info[1] < 5)):
raise ImportError("Python version 2.7 or 3.5 or above "
"is required for SymPy.")
del sys
def __sympy_debug():
# helper function so we don't import os globally
import os
debug_str = os.getenv('SYMPY_DEBUG', 'False')
if debug_str in ('True', 'False'):
return eval(debug_str)
else:
raise RuntimeError("unrecognized value for SYMPY_DEBUG: %s" %
debug_str)
SYMPY_DEBUG = __sympy_debug()
from .core import *
from .logic import *
from .assumptions import *
from .polys import *
from .series import *
from .functions import *
from .ntheory import *
from .concrete import *
from .discrete import *
from .simplify import *
from .sets import *
from .solvers import *
from .matrices import *
from .geometry import *
from .utilities import *
from .integrals import *
from .tensor import *
from .parsing import *
from .calculus import *
from .algebras import *
# This module causes conflicts with other modules:
# from .stats import *
# Adds about .04-.05 seconds of import time
# from combinatorics import *
# This module is slow to import:
#from physics import units
from .plotting import plot, textplot, plot_backends, plot_implicit, plot_parametric
from .printing import *
from .interactive import init_session, init_printing
evalf._create_evalf_table()
# This is slow to import:
#import abc
from .deprecated import *
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.