Skip to content

Instantly share code, notes, and snippets.

@debugger22
Last active August 29, 2015 14:05
Show Gist options
  • Save debugger22/9a3ba468f8679b7ba3d1 to your computer and use it in GitHub Desktop.
Save debugger22/9a3ba468f8679b7ba3d1 to your computer and use it in GitHub Desktop.
My patch of work done in SymPy from 19 May 2014 to 17 Auhust 2014
commit 9bff894c5adff98632c6982d262910f1de49c45d
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Aug 12 09:49:56 2014 +0530
Do not escape raw string literals
diff --git a/sympy/concrete/summations.py b/sympy/concrete/summations.py
index 570ba23..e90b88c 100644
--- a/sympy/concrete/summations.py
+++ b/sympy/concrete/summations.py
@@ -18,7 +18,7 @@
class Sum(AddWithLimits,ExprWithIntLimits):
- """Represents unevaluated summation.
+ r"""Represents unevaluated summation.
``Sum`` represents a finite or infinite series, with the first argument
being the general form of terms in the series, and the second argument
commit b8f7145003c611584e7e48c9f9f76bf913609591
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Aug 10 17:57:13 2014 +0530
Make a statement gender neutral in documentation of unit systems
diff --git a/doc/src/modules/physics/unitsystems/index.rst b/doc/src/modules/physics/unitsystems/index.rst
index 45f3d1e..502a4d7 100644
--- a/doc/src/modules/physics/unitsystems/index.rst
+++ b/doc/src/modules/physics/unitsystems/index.rst
@@ -3,7 +3,7 @@ Unit systems
============
This module integrates unit systems into SymPy, allowing a user choose which
-system to use when doing his computations and providing utilities to display
+system to use when doing their computations and providing utilities to display
and convert units.
Unit systems are composed of units and constants, which are themselves
commit f0b0b4cc2026d3beb9956a278270e3d00f1dae33
Merge: 6e8f97d 80ed0e2
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Aug 6 13:08:37 2014 +0530
Merge pull request #7829 from pbrady/boolalg_fix
Fix boolalg test failure
commit f6fa0b34bfa5846e1d930f4ebf4c6811c8b44602
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Aug 4 13:43:26 2014 +0530
Fix limiting condition issue and add tests
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index e4d89c0..4f46eeb 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -17,10 +17,10 @@
from . import gaussopt
-from .gaussopt import RayTransferMatrix, FreeSpace, FlatRefraction,\
- CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay,\
- BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,\
- geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams
+from .gaussopt import (RayTransferMatrix, FreeSpace, FlatRefraction,
+ CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay,
+ BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,
+ geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams)
__all__.extend(gaussopt.__all__)
@@ -30,6 +30,6 @@
from . import utils
-from .utils import refraction_angle, deviation, lens_makers_formula,\
- mirror_formula
+from .utils import (refraction_angle, deviation, lens_makers_formula,
+ mirror_formula, lens_formula)
__all__.extend(utils.__all__)
diff --git a/sympy/physics/optics/tests/test_utils.py b/sympy/physics/optics/tests/test_utils.py
index 5c4c1d9..024363e 100644
--- a/sympy/physics/optics/tests/test_utils.py
+++ b/sympy/physics/optics/tests/test_utils.py
@@ -1,9 +1,11 @@
from __future__ import division
-from sympy.physics.optics.utils import refraction_angle, deviation
+from sympy.physics.optics.utils import (refraction_angle, deviation,
+ lens_makers_formula, mirror_formula, lens_formula)
from sympy.physics.optics.medium import Medium
+from sympy.physics.units import e0
-from sympy import symbols, sqrt, Matrix
+from sympy import symbols, sqrt, Matrix, oo
from sympy.geometry.point3d import Point3D
from sympy.geometry.line3d import Ray3D
from sympy.geometry.plane import Plane
@@ -76,3 +78,30 @@ def test_deviation():
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
+
+
+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 round(lens_makers_formula(m1, m2, 10, -10), 2) == -20.15
+ assert round(lens_makers_formula(1.33, 1, 10, -10), 2) == 15.15
+
+
+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) == oo
+
+
+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) == oo
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index b63a678..6e81d43 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -17,7 +17,7 @@
'lens_formula'
]
-from sympy import Symbol, sympify, sqrt, Matrix, acos
+from sympy import Symbol, sympify, sqrt, Matrix, acos, oo, Limit
from sympy.geometry.line3d import Ray3D
from sympy.geometry.util import intersection
from sympy.geometry.plane import Plane
@@ -321,11 +321,102 @@ def mirror_formula(focal_length=None, u=None, v=None):
focal_length = sympify(focal_length)
u = sympify(u)
v = sympify(v)
-
+ if u == oo:
+ _u = Symbol('u')
+ if v == oo:
+ _v = Symbol('v')
+ if focal_length == oo:
+ _f = Symbol('f')
if focal_length is None:
+ if u == oo and v == oo:
+ return Limit(Limit(_v*_u/(_v + _u), _u, oo), _v, oo).doit()
+ if u == oo:
+ return Limit(v*_u/(v + _u), _u, oo).doit()
+ if v == oo:
+ return Limit(_v*u/(_v + u), _v, oo).doit()
return v*u/(v + u)
if u is None:
+ if v == oo and focal_length == oo:
+ return Limit(Limit(_v*_f/(_v - _f), _v, oo), _f, oo).doit()
+ if v == oo:
+ return Limit(_v*focal_length/(_v - focal_length), _v, oo).doit()
+ if focal_length == oo:
+ return Limit(v*_f/(v - _f), _f, oo).doit()
return v*focal_length/(v - focal_length)
if v is None:
+ if u == oo and focal_length == oo:
+ return Limit(Limit(_u*_f/(_u - _f), _u, oo), _f, oo).doit()
+ if u == oo:
+ return Limit(_u*focal_length/(_u - focal_length), _u, oo).doit()
+ if focal_length == oo:
+ return Limit(u*_f/(u - _f), _f, oo).doit()
return u*focal_length/(u - focal_length)
+
+def lens_formula(focal_length=None, u=None, v=None):
+ """
+ This function provides one of the three parameters
+ when two of them are supplied.
+ This is valid only for paraxial rays.
+
+ Parameters
+ ==========
+
+ focal_length : sympifiable
+ Focal length of the mirror.
+ u : sympifiable
+ Distance of object from the optical center on
+ the principal axis.
+ v : sympifiable
+ Distance of the image from the optical center
+ on the principal axis.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import lens_formula
+ >>> from sympy.abc import f, u, v
+ >>> lens_formula(focal_length=f, u=u)
+ f*u/(f + u)
+ >>> lens_formula(focal_length=f, v=v)
+ f*v/(f - v)
+ >>> lens_formula(u=u, v=v)
+ u*v/(u - v)
+
+ """
+ if focal_length and u and v:
+ raise ValueError("Please provide only two parameters")
+
+ focal_length = sympify(focal_length)
+ u = sympify(u)
+ v = sympify(v)
+ if u == oo:
+ _u = Symbol('u')
+ if v == oo:
+ _v = Symbol('v')
+ if focal_length == oo:
+ _f = Symbol('f')
+ if focal_length is None:
+ if u == oo and v == oo:
+ return Limit(Limit(_v*_u/(_u - _v), _u, oo), _v, oo).doit()
+ if u == oo:
+ return Limit(v*_u/(_u - v), _u, oo).doit()
+ if v == oo:
+ return Limit(_v*u/(u - _v), _v, oo).doit()
+ return v*u/(u - v)
+ if u is None:
+ if v == oo and focal_length == oo:
+ return Limit(Limit(_v*_f/(_f - _v), _v, oo), _f, oo).doit()
+ if v == oo:
+ return Limit(_v*focal_length/(focal_length - _v), _v, oo).doit()
+ if focal_length == oo:
+ return Limit(v*_f/(_f - v), _f, oo).doit()
+ return v*focal_length/(focal_length - v)
+ if v is None:
+ if u == oo and focal_length == oo:
+ return Limit(Limit(_u*_f/(_u + _f), _u, oo), _f, oo).doit()
+ if u == oo:
+ return Limit(_u*focal_length/(_u + focal_length), _u, oo).doit()
+ if focal_length == oo:
+ return Limit(u*_f/(u + _f), _f, oo).doit()
+ return u*focal_length/(u + focal_length)
commit c5d5a558778d6661c716953862bc141917f54ccc
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jul 28 13:34:18 2014 +0530
Add Marcus Näslund to AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index 1d0efed..7c2a473 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -351,3 +351,4 @@ John V. Siratt <jvsiratt@gmail.com>
Sarwar Chahal <chahal.sarwar98@gmail.com>
Nathan Woods <charlesnwoods@gmail.com>
Colin B. Macdonald <macdonald@maths.ox.ac.uk>
+Marcus Näslund <naslundx@gmail.com>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index a3dbb37..d277d36 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -356,6 +356,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Sarwar Chahal: Fix to documentation
#. Nathan Woods: Fix to C code printer
#. Colin B. Macdonald: Fix to documentation
+#. Marcus Näslund: Fix to documentation
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit d9faad6946437330ed66ed6d91be2a0b9958ec8b
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 26 11:40:39 2014 +0530
Add a util function 'mirror_formula'
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 17526d6..e4d89c0 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -30,5 +30,6 @@
from . import utils
-from .utils import refraction_angle, deviation, lens_makers_formula
+from .utils import refraction_angle, deviation, lens_makers_formula,\
+ mirror_formula
__all__.extend(utils.__all__)
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index 64a25f7..b63a678 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -4,11 +4,18 @@
* refraction_angle
* deviation
* lens_makers_formula
+* mirror_formula
+* lens_formula
"""
from __future__ import division
-__all__ = ['refraction_angle', 'deviation', 'lens_makers_formula']
+__all__ = ['refraction_angle',
+ 'deviation',
+ 'lens_makers_formula',
+ 'mirror_formula',
+ 'lens_formula'
+ ]
from sympy import Symbol, sympify, sqrt, Matrix, acos
from sympy.geometry.line3d import Ray3D
@@ -275,3 +282,50 @@ def lens_makers_formula(n_lens, n_surr, r1, r2):
r2 = sympify(r2)
return 1/((n_lens - n_surr)/n_surr*(1/r1 - 1/r2))
+
+
+def mirror_formula(focal_length=None, u=None, v=None):
+ """
+ This function provides one of the three parameters
+ when two of them are supplied.
+ This is valid only for paraxial rays.
+
+ Parameters
+ ==========
+
+ focal_length : sympifiable
+ Focal length of the mirror.
+ u : sympifiable
+ Distance of object from the pole on
+ the principal axis.
+ v : sympifiable
+ Distance of the image from the pole
+ on the principal axis.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import mirror_formula
+ >>> from sympy.abc import f, u, v
+ >>> mirror_formula(focal_length=f, u=u)
+ f*u/(-f + u)
+ >>> mirror_formula(focal_length=f, v=v)
+ f*v/(-f + v)
+ >>> mirror_formula(u=u, v=v)
+ u*v/(u + v)
+
+ """
+ if focal_length and u and v:
+ raise ValueError("Please provide only two parameters")
+
+ focal_length = sympify(focal_length)
+ u = sympify(u)
+ v = sympify(v)
+
+ if focal_length is None:
+ return v*u/(v + u)
+ if u is None:
+ return v*focal_length/(v - focal_length)
+ if v is None:
+ return u*focal_length/(u - focal_length)
+
commit aafb655180450148a4489eb5ced63f70bfc625b5
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Thu Jul 24 22:18:07 2014 +0530
Add lens_makers_formula
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 0eadd01..17526d6 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -30,5 +30,5 @@
from . import utils
-from .utils import refraction_angle, deviation
+from .utils import refraction_angle, deviation, lens_makers_formula
__all__.extend(utils.__all__)
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index 47dd04a..64a25f7 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -3,11 +3,12 @@
* refraction_angle
* deviation
+* lens_makers_formula
"""
from __future__ import division
-__all__ = ['refraction_angle', 'deviation']
+__all__ = ['refraction_angle', 'deviation', 'lens_makers_formula']
from sympy import Symbol, sympify, sqrt, Matrix, acos
from sympy.geometry.line3d import Ray3D
@@ -234,3 +235,43 @@ def deviation(incident, medium1, medium2, normal=None, plane=None):
i = acos(_incident.dot(_normal))
r = acos(refracted.dot(_normal))
return i - r
+
+
+def lens_makers_formula(n_lens, n_surr, r1, r2):
+ """
+ This function calculates focal length of a thin lens.
+ It follows cartesian sign convention.
+
+ Parameters
+ ==========
+
+ n_lens : Medium or sympifiable
+ Index of refraction of lens.
+ n_surr : Medium or sympifiable
+ Index of reflection of surrounding.
+ r1 : sympifiable
+ Radius of curvature of first surface.
+ r2 : sympifiable
+ Radius of curvature of second surface.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import lens_makers_formula
+ >>> lens_makers_formula(1.33, 1, 10, -10)
+ 15.1515151515151
+
+ """
+ if isinstance(n_lens, Medium):
+ n_lens = n_lens.refractive_index
+ else:
+ n_lens = sympify(n_lens)
+ if isinstance(n_surr, Medium):
+ n_surr = n_surr.refractive_index
+ else:
+ n_surr = sympify(n_surr)
+
+ r1 = sympify(r1)
+ r2 = sympify(r2)
+
+ return 1/((n_lens - n_surr)/n_surr*(1/r1 - 1/r2))
commit 07299f9276f6ce1f22d42f2e1b1cadad259238ae
Merge: 5dbca60 b480968
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 26 01:02:06 2014 +0530
Merge pull request #7782 from debugger22/dioptre-unit
Add dioptre in physics.units
commit 7785c4e0a3835789295faac74770d6fa71f5c5fa
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri Jul 25 23:48:29 2014 +0530
Compare only with the integral part after the period
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index c20b32c..8ad181a 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -24,7 +24,9 @@
# Exit on error
set -e
-if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_JOB_NUMBER" == "1" ]; then
+ACTUAL_TRAVIS_JOB_NUMBER = `echo $TRAVIS_JOB_NUMBER| cut -d'.' -f 2`
+
+if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$ACTUAL_TRAVIS_JOB_NUMBER" == "1" ]; then
echo "Installing dependencies"
sudo apt-get install --no-install-recommends graphviz inkscape texlive texlive-xetex texlive-fonts-recommended texlive-latex-extra lmodern librsvg2-bin imagemagick docbook2x
commit db5de3593484a48e74aff50ff988e91142c5c2a1
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri Jul 25 23:39:34 2014 +0530
Make build_doc run only for the first job
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index 0307708..c20b32c 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -24,7 +24,7 @@
# Exit on error
set -e
-if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
+if [ "$TRAVIS_PULL_REQUEST" == "false" ] && [ "$TRAVIS_JOB_NUMBER" == "1" ]; then
echo "Installing dependencies"
sudo apt-get install --no-install-recommends graphviz inkscape texlive texlive-xetex texlive-fonts-recommended texlive-latex-extra lmodern librsvg2-bin imagemagick docbook2x
commit 02c089fecfad6af44400ffa54c37800efa5f91e9
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri Jul 25 21:21:06 2014 +0530
Redirect stdout and stderr to void when git push fails [skip ci]
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index d4444fc..0307708 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -53,5 +53,5 @@ if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
git commit -am "Update dev doc after building $TRAVIS_BUILD_NUMBER"
echo -e "Pushing commit"
- git push -fq origin gh-pages > /dev/null
+ git push -fq origin gh-pages > /dev/null 2>&1
fi
commit b480968e32a5efb8c6972a5fd30c947ad82d1f27
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Thu Jul 24 22:45:16 2014 +0530
Add dioptre in physics.units
diff --git a/sympy/physics/units.py b/sympy/physics/units.py
index a24bf9f..3588157 100644
--- a/sympy/physics/units.py
+++ b/sympy/physics/units.py
@@ -185,6 +185,7 @@ def free_symbols(self):
speed = m/s
acceleration = m/s**2
density = kg/m**3
+optical_power = dioptre = D = 1/m
# Common length units
commit f7b5d1d1149c1b8285e79d315d5b92391404651f
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jul 23 10:44:31 2014 +0530
Add Colin B. Macdonald to AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index 5edc44a..1d0efed 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -350,3 +350,4 @@ David P. Sanders <dpsanders@gmail.com>
John V. Siratt <jvsiratt@gmail.com>
Sarwar Chahal <chahal.sarwar98@gmail.com>
Nathan Woods <charlesnwoods@gmail.com>
+Colin B. Macdonald <macdonald@maths.ox.ac.uk>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 7ae7a8e..a3dbb37 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -355,6 +355,7 @@ want to be mentioned here, so see our repository history for a full list).
#. John V. Siratt: Fix to documentation
#. Sarwar Chahal: Fix to documentation
#. Nathan Woods: Fix to C code printer
+#. Colin B. Macdonald: Fix to documentation
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit eabb083a109550b2687c05dda3d7000adc31d181
Merge: 7b238de 1dbe8a9
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jul 23 10:41:13 2014 +0530
Merge pull request #7768 from cbm755/typofix
Minor typo fixes in docs
commit f28d2f5888d9f8d945f9ceaf51cb00eeb3eb2716
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jul 23 00:23:17 2014 +0530
UnXFAIL a failing test
diff --git a/sympy/physics/optics/tests/test_utils.py b/sympy/physics/optics/tests/test_utils.py
index cd5ffea..5c4c1d9 100644
--- a/sympy/physics/optics/tests/test_utils.py
+++ b/sympy/physics/optics/tests/test_utils.py
@@ -56,11 +56,6 @@ def test_refraction_angle():
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
-
-
-@XFAIL
-def test_refraction_angle_failing():
- # Failing due to issue https://github.com/sympy/sympy/issues/7757
assert refraction_angle(r1, 1, 1, normal_ray) == \
Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index b6fc4f2..47dd04a 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -100,7 +100,7 @@ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
# an instance of Ray3D.
if isinstance(incident, Ray3D):
return_ray = True
- intersection_pt = plane.intersection(incident)
+ intersection_pt = plane.intersection(incident)[0]
_normal = plane.normal_vector
if isinstance(_normal, list):
_normal = Matrix(_normal)
commit dd737102e4c4ab73f4cd2b0c49708390f98c6a57
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jul 20 15:19:40 2014 +0530
Remove unused imports
diff --git a/sympy/physics/optics/tests/test_utils.py b/sympy/physics/optics/tests/test_utils.py
index 80f879e..cd5ffea 100644
--- a/sympy/physics/optics/tests/test_utils.py
+++ b/sympy/physics/optics/tests/test_utils.py
@@ -1,8 +1,7 @@
-from __future__ import division, print_function
+from __future__ import division
from sympy.physics.optics.utils import refraction_angle, deviation
from sympy.physics.optics.medium import Medium
-from sympy.physics.optics.waves import TWave
from sympy import symbols, sqrt, Matrix
from sympy.geometry.point3d import Point3D
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index b5616e9..b6fc4f2 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -2,6 +2,7 @@
**Contains**
* refraction_angle
+* deviation
"""
from __future__ import division
@@ -13,7 +14,6 @@
from sympy.geometry.util import intersection
from sympy.geometry.plane import Plane
from .medium import Medium
-from .waves import TWave
def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
commit 0ca7332496a86affb9875508c9aa9a0037be0535
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jul 20 01:19:32 2014 +0530
Add tests for refraction_angle and deviation
diff --git a/sympy/physics/optics/tests/test_utils.py b/sympy/physics/optics/tests/test_utils.py
index 280fbc4..80f879e 100644
--- a/sympy/physics/optics/tests/test_utils.py
+++ b/sympy/physics/optics/tests/test_utils.py
@@ -1,4 +1,6 @@
-from sympy.physics.optics.utils import refraction_angle
+from __future__ import division, print_function
+
+from sympy.physics.optics.utils import refraction_angle, deviation
from sympy.physics.optics.medium import Medium
from sympy.physics.optics.waves import TWave
@@ -6,19 +8,77 @@
from sympy.geometry.point3d import Point3D
from sympy.geometry.line3d import Ray3D
from sympy.geometry.plane import Plane
+from sympy.utilities.pytest import XFAIL
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(r1, 1, 1, plane=P) ==\
+ 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(100/133, 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
+
+
+@XFAIL
+def test_refraction_angle_failing():
+ # Failing due to issue https://github.com/sympy/sympy/issues/7757
+ assert refraction_angle(r1, 1, 1, normal_ray) == \
+ Ray3D(Point3D(0, 0, 0), direction_ratio=[1, 1, -1])
+
+
+def test_deviation():
+ n1, n2 = symbols('n1, n2')
+ m1 = Medium('m1')
+ m2 = Medium('m2')
+ 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
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index e9c3272..b5616e9 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -98,7 +98,8 @@ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
# If we have the plane, we can get the intersection
# point of incident ray and the plane and thus return
# an instance of Ray3D.
- return_ray = True
+ if isinstance(incident, Ray3D):
+ return_ray = True
intersection_pt = plane.intersection(incident)
_normal = plane.normal_vector
if isinstance(_normal, list):
@@ -180,6 +181,7 @@ def deviation(incident, medium1, medium2, normal=None, plane=None):
>>> from sympy.geometry import Point3D, Ray3D, Plane
>>> from sympy.matrices import Matrix
>>> from sympy import symbols
+ >>> n1, n2 = symbols('n1, n2')
>>> n = Matrix([0, 0, 1])
>>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
commit 1c3df936e52dbc9366602b59ca1e5d0432f3b10b
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 19 22:54:35 2014 +0530
Fix a bug in deviation while using plane. [skip ci]
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index 9a0cc12..e9c3272 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -18,8 +18,8 @@
def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
"""
- This function calculates transmitted vector after refraction.
- `medium1` and `medium2` can be `Medium` or any sympifiable object.
+ This function calculates transmitted vector after refraction at planar
+ surface. `medium1` and `medium2` can be `Medium` or any sympifiable object.
If `incident` is an object of `Ray3D`, `normal` also has to be an instance
of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
@@ -157,7 +157,7 @@ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
def deviation(incident, medium1, medium2, normal=None, plane=None):
"""
This function calculates the angle of deviation of a ray
- due to refraction.
+ due to refraction at planar surface.
Parameters
==========
@@ -185,6 +185,8 @@ def deviation(incident, medium1, medium2, normal=None, plane=None):
>>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
>>> deviation(r1, 1, 1, n)
0
+ >>> deviation(r1, n1, n2, plane=P)
+ -acos(-sqrt(-2*n1**2/(3*n2**2) + 1)) + acos(-sqrt(3)/3)
"""
refracted = refraction_angle(incident,
@@ -206,15 +208,20 @@ def deviation(incident, medium1, medium2, normal=None, plane=None):
else:
_incident = incident
- if not isinstance(normal, Matrix):
- if type(normal) == type(()) or type(normal) == type([]):
- _normal = Matrix(normal)
- elif isinstance(normal, Ray3D):
- _normal = Matrix(normal.direction_ratio)
+ if plane is None:
+ if not isinstance(normal, Matrix):
+ if type(normal) == type(()) or type(normal) == type([]):
+ _normal = Matrix(normal)
+ elif isinstance(normal, Ray3D):
+ _normal = Matrix(normal.direction_ratio)
+ else:
+ raise TypeError("normal should be a Matrix, Ray3D, tuple or list")
else:
- raise TypeError("normal should be a Matrix, Ray3D, tuple or list")
+ _normal = normal
else:
- _normal = normal
+ _normal = plane.normal_vector
+ if isinstance(_normal, list):
+ _normal = Matrix(_normal)
mag_incident = sqrt(sum([i**2 for i in _incident]))
mag_normal = sqrt(sum([i**2 for i in _normal]))
commit 42c6be0c9a813a5b701e5d867ae0d21b64ac3966
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 19 19:43:00 2014 +0530
Add deviation [skip ci]
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 9869543..0eadd01 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -30,5 +30,5 @@
from . import utils
-from .utils import refraction_angle
+from .utils import refraction_angle, deviation
__all__.extend(utils.__all__)
diff --git a/sympy/physics/optics/tests/test_utils.py b/sympy/physics/optics/tests/test_utils.py
index 3e41ed2..280fbc4 100644
--- a/sympy/physics/optics/tests/test_utils.py
+++ b/sympy/physics/optics/tests/test_utils.py
@@ -15,7 +15,10 @@ def test_refraction_angle():
r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
n = Matrix([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]])
+ [ 1],
+ [ 1],
+ [-1]])
+ assert refraction_angle(r1, 1, 1, plane=P) ==\
+ Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index c839a2e..9a0cc12 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -6,9 +6,9 @@
from __future__ import division
-__all__ = ['refraction_angle']
+__all__ = ['refraction_angle', 'deviation']
-from sympy import Symbol, sympify, sqrt, Matrix
+from sympy import Symbol, sympify, sqrt, Matrix, acos
from sympy.geometry.line3d import Ray3D
from sympy.geometry.util import intersection
from sympy.geometry.plane import Plane
@@ -121,21 +121,14 @@ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
else:
_normal = normal
- m1, m2 = None, None
n1, n2 = None, None
- # If m1 and m2 are instances of Medium, assign them to m1 and m2
- # respectively otherwise m1 and m2 will be treated as refractive
- # indices of the mediums and will be assigned to n1 and n2 respectively.
-
if isinstance(medium1, Medium):
- m1 = medium1
n1 = medium1.refractive_index
else:
n1 = sympify(medium1)
if isinstance(medium2, Medium):
- m2 = medium2
n2 = medium2.refractive_index
else:
n2 = sympify(medium2)
@@ -159,3 +152,76 @@ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
return drs
else:
return Ray3D(intersection_pt, direction_ratio=drs)
+
+
+def deviation(incident, medium1, medium2, normal=None, plane=None):
+ """
+ This function calculates the angle of deviation of a ray
+ due to refraction.
+
+ Parameters
+ ==========
+
+ incident : Matrix, Ray3D, tuple or list
+ Incident vector
+ medium1 : sympy.physics.optics.medium.Medium or sympifiable
+ Medium 1 or its refractive index
+ medium2 : sympy.physics.optics.medium.Medium or sympifiable
+ Medium 2 or its refractive index
+ normal : Matrix, Ray3D, tuple or list
+ Normal vector
+ plane : Plane
+ Plane of separation of the two media.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import deviation
+ >>> from sympy.geometry import Point3D, Ray3D, Plane
+ >>> from sympy.matrices import Matrix
+ >>> from sympy import symbols
+ >>> n = Matrix([0, 0, 1])
+ >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
+ >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
+ >>> deviation(r1, 1, 1, n)
+ 0
+
+ """
+ refracted = refraction_angle(incident,
+ medium1,
+ medium2,
+ normal=normal,
+ plane=plane)
+ if refracted != 0:
+ if isinstance(refracted, Ray3D):
+ refracted = Matrix(refracted.direction_ratio)
+
+ if not isinstance(incident, Matrix):
+ if type(incident) == type(()) or type(incident) == type([]):
+ _incident = Matrix(incident)
+ elif isinstance(incident, Ray3D):
+ _incident = Matrix(incident.direction_ratio)
+ else:
+ raise TypeError("incident should be a Matrix, Ray3D, tuple or list")
+ else:
+ _incident = incident
+
+ if not isinstance(normal, Matrix):
+ if type(normal) == type(()) or type(normal) == type([]):
+ _normal = Matrix(normal)
+ elif isinstance(normal, Ray3D):
+ _normal = Matrix(normal.direction_ratio)
+ else:
+ raise TypeError("normal should be a Matrix, Ray3D, tuple or list")
+ else:
+ _normal = normal
+
+ mag_incident = sqrt(sum([i**2 for i in _incident]))
+ mag_normal = sqrt(sum([i**2 for i in _normal]))
+ mag_refracted = sqrt(sum([i**2 for i in refracted]))
+ _incident /= mag_incident
+ _normal /= mag_normal
+ refracted /= mag_refracted
+ i = acos(_incident.dot(_normal))
+ r = acos(refracted.dot(_normal))
+ return i - r
commit a0450b89c67d00d901c1c163adac24797ddab9e1
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 19 18:18:52 2014 +0530
Add test_util
diff --git a/sympy/physics/optics/tests/test_utils.py b/sympy/physics/optics/tests/test_utils.py
new file mode 100644
index 0000000..3e41ed2
--- /dev/null
+++ b/sympy/physics/optics/tests/test_utils.py
@@ -0,0 +1,21 @@
+from sympy.physics.optics.utils import refraction_angle
+from sympy.physics.optics.medium import Medium
+from sympy.physics.optics.waves import TWave
+
+from sympy import symbols, sqrt, Matrix
+from sympy.geometry.point3d import Point3D
+from sympy.geometry.line3d import Ray3D
+from sympy.geometry.plane import Plane
+
+
+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))
+ n = Matrix([0, 0, 1])
+ assert refraction_angle(r1, 1, 1, n) == Matrix([
+ [ 1],
+ [ 1],
+ [-1]])
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
index f162d19..c839a2e 100644
--- a/sympy/physics/optics/utils.py
+++ b/sympy/physics/optics/utils.py
@@ -83,7 +83,7 @@ def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
if not isinstance(incident, Matrix):
if type(incident) == type(()) or type(incident) == type([]):
_incident = Matrix(incident)
- elif isinstance(incident, Ray3D):`
+ elif isinstance(incident, Ray3D):
_incident = Matrix(incident.direction_ratio)
else:
raise TypeError("incident should be a Matrix, Ray3D, tuple or list")
commit 7f657823f6502a987e1bfc05d3d8ab6edfc00e45
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jul 8 18:38:42 2014 +0530
Make refraction_angle compatible with Ray3D and plane. [skip ci]
diff --git a/doc/src/modules/physics/optics/index.rst b/doc/src/modules/physics/optics/index.rst
index b119b21..385b8c9 100644
--- a/doc/src/modules/physics/optics/index.rst
+++ b/doc/src/modules/physics/optics/index.rst
@@ -12,4 +12,5 @@ Optics Module
gaussopt.rst
medium.rst
+ utils.rst
waves.rst
diff --git a/doc/src/modules/physics/optics/utils.rst b/doc/src/modules/physics/optics/utils.rst
new file mode 100644
index 0000000..83e0ebf
--- /dev/null
+++ b/doc/src/modules/physics/optics/utils.rst
@@ -0,0 +1,5 @@
+Utilities
+---------
+
+.. automodule:: sympy.physics.optics.utils
+ :members:
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index c99b203..9869543 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -29,6 +29,6 @@
__all__.extend(medium.__all__)
-from . import snell
-from .snell import snellslaw
-__all__.extend(medium.__all__)
+from . import utils
+from .utils import refraction_angle
+__all__.extend(utils.__all__)
diff --git a/sympy/physics/optics/snell.py b/sympy/physics/optics/snell.py
deleted file mode 100644
index 6c0d967..0000000
--- a/sympy/physics/optics/snell.py
+++ /dev/null
@@ -1,79 +0,0 @@
-"""
-**Contains**
-
-* refraction_angle
-"""
-
-from __future__ import division
-
-__all__ = ['refraction_angle']
-
-from sympy import Symbol, sympify, sqrt, Matrix
-from sympy.physics.units import c, u0, e0
-from .medium import Medium
-from .waves import TWave
-
-
-def refraction_angle(incident, normal, medium1, medium2):
- """
- This function calculates transmitted vector after refraction.
- `medium1` and `medium2` can be `Medium` or any sympifiable object.
-
- Parameters
- ==========
-
- incident : Matrix, tuple or list
- Incident vector
- normal : Matrix, tuple or list
- Normal vector
- medium1 : sympy.physics.optics.medium.Medium or sympifiable
- Medium 1 or its refractive index
- medium2 : sympy.physics.optics.medium.Medium or sympifiable
- Medium 2 or its refractive index
-
- Examples
- ========
-
-
- """
- if not isinstance(incident, Matrix):
- if type(incident) == type(()) or type(incident) == type([]):
- incident = Matrix(incident)
- else:
- raise TypeError("Incident vector should be a matrix, tuple or list")
- else:
- incident = incident
-
- if not isinstance(normal, Matrix):
- if type(normal) == type(()) or type(normal) == type([]):
- normal = Matrix(normal)
- else:
- raise TypeError("Normal vector should be a matrix, tuple or list")
- else:
- normal = normal
-
- m1, m2 = None, None
- n1, n2 = None, None
-
- # If m1 and m2 are instances of Medium, assign them to m1 and m2
- # respectively otherwise m1 and m2 will be treated as refrative
- # indices of the mediums and will be assigned to n1 and n2 respectively.
-
- if isinstance(medium1, Medium):
- m1 = medium1
- n1 = medium1.refractive_index
- else:
- n1 = sympify(medium1)
-
- if isinstance(medium2, Medium):
- m2 = medium2
- n2 = medium2.refractive_index
- else:
- n2 = sympify(medium2)
-
- eta = n1/n2 # Relative index of refraction
- c1 = -incident.dot(normal) # cos(angle_of_incidence)
- cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
- if cs2 < 0: # This is the case of total internal reflection(TIR).
- return 0
- return eta*incident + (eta*c1 - sqrt(cs2))*normal
diff --git a/sympy/physics/optics/utils.py b/sympy/physics/optics/utils.py
new file mode 100644
index 0000000..f162d19
--- /dev/null
+++ b/sympy/physics/optics/utils.py
@@ -0,0 +1,161 @@
+"""
+**Contains**
+
+* refraction_angle
+"""
+
+from __future__ import division
+
+__all__ = ['refraction_angle']
+
+from sympy import Symbol, sympify, sqrt, Matrix
+from sympy.geometry.line3d import Ray3D
+from sympy.geometry.util import intersection
+from sympy.geometry.plane import Plane
+from .medium import Medium
+from .waves import TWave
+
+
+def refraction_angle(incident, medium1, medium2, normal=None, plane=None):
+ """
+ This function calculates transmitted vector after refraction.
+ `medium1` and `medium2` can be `Medium` or any sympifiable object.
+
+ If `incident` is an object of `Ray3D`, `normal` also has to be an instance
+ of `Ray3D` in order to get the output as a `Ray3D`. Please note that if
+ plane of separation is not provided and normal is an instance of `Ray3D`,
+ normal will be assumed to be intersecting incident ray at the plane of
+ separation. This will not be the case when `normal` is a `Matrix` or
+ any other sequence.
+ If `incident` is an instance of `Ray3D` and `plane` has not been provided
+ and `normal` is not `Ray3D`, output will be a `Matrix`.
+
+ Parameters
+ ==========
+
+ incident : Matrix, Ray3D, tuple or list
+ Incident vector
+ medium1 : sympy.physics.optics.medium.Medium or sympifiable
+ Medium 1 or its refractive index
+ medium2 : sympy.physics.optics.medium.Medium or sympifiable
+ Medium 2 or its refractive index
+ normal : Matrix, Ray3D, tuple or list
+ Normal vector
+ plane : Plane
+ Plane of separation of the two media.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import refraction_angle
+ >>> from sympy.geometry import Point3D, Ray3D, Plane
+ >>> from sympy.matrices import Matrix
+ >>> from sympy import symbols
+ >>> n = Matrix([0, 0, 1])
+ >>> P = Plane(Point3D(0, 0, 0), normal_vector=[0, 0, 1])
+ >>> r1 = Ray3D(Point3D(-1, -1, 1), Point3D(0, 0, 0))
+ >>> refraction_angle(r1, 1, 1, n)
+ Matrix([
+ [ 1],
+ [ 1],
+ [-1]])
+ >>> refraction_angle(r1, 1, 1, plane=P)
+ Ray3D(Point3D(0, 0, 0), Point3D(1, 1, -1))
+
+ With different index of refraction of the two media
+
+ >>> n1, n2 = symbols('n1, n2')
+ >>> refraction_angle(r1, n1, n2, n)
+ Matrix([
+ [ n1/n2],
+ [ n1/n2],
+ [-sqrt(3)*sqrt(-2*n1**2/(3*n2**2) + 1)]])
+ >>> 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)))
+
+ """
+ # A flag to check whether to return Ray3D or not
+ return_ray = False
+
+ if plane is not None and normal is not None:
+ raise ValueError("Either plane or normal is acceptable.")
+
+ if not isinstance(incident, Matrix):
+ if type(incident) == type(()) or type(incident) == type([]):
+ _incident = Matrix(incident)
+ elif isinstance(incident, Ray3D):`
+ _incident = Matrix(incident.direction_ratio)
+ else:
+ raise TypeError("incident should be a Matrix, Ray3D, tuple or list")
+ else:
+ _incident = incident
+
+ # If plane is provided, get direction ratios of the normal
+ # to the plane from the plane else go with `normal` param.
+ if plane is not None:
+ if not isinstance(plane, Plane):
+ raise TypeError("plane should be an instance of geometry.plane.Plane")
+ # If we have the plane, we can get the intersection
+ # point of incident ray and the plane and thus return
+ # an instance of Ray3D.
+ return_ray = True
+ intersection_pt = plane.intersection(incident)
+ _normal = plane.normal_vector
+ if isinstance(_normal, list):
+ _normal = Matrix(_normal)
+ else:
+ if not isinstance(normal, Matrix):
+ if type(normal) == type(()) or type(normal) == type([]):
+ _normal = Matrix(normal)
+ elif isinstance(normal, Ray3D):
+ _normal = Matrix(normal.direction_ratio)
+ if isinstance(incident, Ray3D):
+ intersection_pt = intersection(incident, normal)
+ if len(intersection_pt) == 0:
+ raise ValueError("Normal isn't concurrent with the incident ray.")
+ else:
+ return_ray = True
+ intersection_pt = intersection_pt[0]
+ else:
+ raise TypeError("Normal should be a Matrix, Ray3D, tuple or list")
+ else:
+ _normal = normal
+
+ m1, m2 = None, None
+ n1, n2 = None, None
+
+ # If m1 and m2 are instances of Medium, assign them to m1 and m2
+ # respectively otherwise m1 and m2 will be treated as refractive
+ # indices of the mediums and will be assigned to n1 and n2 respectively.
+
+ if isinstance(medium1, Medium):
+ m1 = medium1
+ n1 = medium1.refractive_index
+ else:
+ n1 = sympify(medium1)
+
+ if isinstance(medium2, Medium):
+ m2 = medium2
+ n2 = medium2.refractive_index
+ else:
+ n2 = sympify(medium2)
+
+ eta = n1/n2 # Relative index of refraction
+ # Calculating magnitude of the vectors
+ mag_incident = sqrt(sum([i**2 for i in _incident]))
+ mag_normal = sqrt(sum([i**2 for i in _normal]))
+ # Converting vectors to unit vectors by dividing
+ # them with their magnitudes
+ _incident /= mag_incident
+ _normal /= mag_normal
+ c1 = -_incident.dot(_normal) # cos(angle_of_incidence)
+ cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
+ if cs2.is_negative: # This is the case of total internal reflection(TIR).
+ return 0
+ drs = eta*_incident + (eta*c1 - sqrt(cs2))*_normal
+ # Multiplying unit vector by its magnitude
+ drs = drs*mag_incident
+ if not return_ray:
+ return drs
+ else:
+ return Ray3D(intersection_pt, direction_ratio=drs)
commit fcbc49055f2a56f7835846cf980ea784c8a649f4
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 23 11:31:33 2014 +0530
Change the name of function to refraction_angle and fix a typo [skip ci]
diff --git a/sympy/physics/optics/snell.py b/sympy/physics/optics/snell.py
index 6ecadbe..6c0d967 100644
--- a/sympy/physics/optics/snell.py
+++ b/sympy/physics/optics/snell.py
@@ -1,19 +1,20 @@
"""
**Contains**
-* snellslaw
+* refraction_angle
"""
from __future__ import division
-__all__ = ['snellslaw']
+__all__ = ['refraction_angle']
from sympy import Symbol, sympify, sqrt, Matrix
from sympy.physics.units import c, u0, e0
-from sympy.physics.optics import Medium
+from .medium import Medium
+from .waves import TWave
-def snellslaw(incident, normal, medium1, medium2):
+def refraction_angle(incident, normal, medium1, medium2):
"""
This function calculates transmitted vector after refraction.
`medium1` and `medium2` can be `Medium` or any sympifiable object.
@@ -73,6 +74,6 @@ def snellslaw(incident, normal, medium1, medium2):
eta = n1/n2 # Relative index of refraction
c1 = -incident.dot(normal) # cos(angle_of_incidence)
cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
- if cs2 < 0: # This is the case of total internal refraction(TIR).
+ if cs2 < 0: # This is the case of total internal reflection(TIR).
return 0
return eta*incident + (eta*c1 - sqrt(cs2))*normal
commit 9e60cb4edb2c15be9c4848b795f05825d2aa7672
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 22 21:23:33 2014 +0530
Add function to calculate transmitted vector after refraction [skip ci]
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 7797530..c99b203 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -27,3 +27,8 @@
from . import medium
from .medium import Medium
__all__.extend(medium.__all__)
+
+
+from . import snell
+from .snell import snellslaw
+__all__.extend(medium.__all__)
diff --git a/sympy/physics/optics/snell.py b/sympy/physics/optics/snell.py
new file mode 100644
index 0000000..6ecadbe
--- /dev/null
+++ b/sympy/physics/optics/snell.py
@@ -0,0 +1,78 @@
+"""
+**Contains**
+
+* snellslaw
+"""
+
+from __future__ import division
+
+__all__ = ['snellslaw']
+
+from sympy import Symbol, sympify, sqrt, Matrix
+from sympy.physics.units import c, u0, e0
+from sympy.physics.optics import Medium
+
+
+def snellslaw(incident, normal, medium1, medium2):
+ """
+ This function calculates transmitted vector after refraction.
+ `medium1` and `medium2` can be `Medium` or any sympifiable object.
+
+ Parameters
+ ==========
+
+ incident : Matrix, tuple or list
+ Incident vector
+ normal : Matrix, tuple or list
+ Normal vector
+ medium1 : sympy.physics.optics.medium.Medium or sympifiable
+ Medium 1 or its refractive index
+ medium2 : sympy.physics.optics.medium.Medium or sympifiable
+ Medium 2 or its refractive index
+
+ Examples
+ ========
+
+
+ """
+ if not isinstance(incident, Matrix):
+ if type(incident) == type(()) or type(incident) == type([]):
+ incident = Matrix(incident)
+ else:
+ raise TypeError("Incident vector should be a matrix, tuple or list")
+ else:
+ incident = incident
+
+ if not isinstance(normal, Matrix):
+ if type(normal) == type(()) or type(normal) == type([]):
+ normal = Matrix(normal)
+ else:
+ raise TypeError("Normal vector should be a matrix, tuple or list")
+ else:
+ normal = normal
+
+ m1, m2 = None, None
+ n1, n2 = None, None
+
+ # If m1 and m2 are instances of Medium, assign them to m1 and m2
+ # respectively otherwise m1 and m2 will be treated as refrative
+ # indices of the mediums and will be assigned to n1 and n2 respectively.
+
+ if isinstance(medium1, Medium):
+ m1 = medium1
+ n1 = medium1.refractive_index
+ else:
+ n1 = sympify(medium1)
+
+ if isinstance(medium2, Medium):
+ m2 = medium2
+ n2 = medium2.refractive_index
+ else:
+ n2 = sympify(medium2)
+
+ eta = n1/n2 # Relative index of refraction
+ c1 = -incident.dot(normal) # cos(angle_of_incidence)
+ cs2 = 1 - eta**2*(1 - c1**2) # cos(angle_of_refraction)**2
+ if cs2 < 0: # This is the case of total internal refraction(TIR).
+ return 0
+ return eta*incident + (eta*c1 - sqrt(cs2))*normal
commit 4d068842642642ae8cc5914db4bdbf08c534de4b
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 19 23:34:26 2014 +0530
Put a space. Change 'anormal' to 'a normal'.
diff --git a/sympy/geometry/plane.py b/sympy/geometry/plane.py
index 396a7f1..788f1a1 100644
--- a/sympy/geometry/plane.py
+++ b/sympy/geometry/plane.py
@@ -62,7 +62,7 @@ def __new__(cls, p1, pt1=None, pt2=None, normal_vector=(), **kwargs):
normal_vector = tuple(Matrix(a).cross(Matrix(b)))
else:
raise ValueError('Either provide 3 3D points or a point with a'
- 'normal vector')
+ ' normal vector')
return GeometryEntity.__new__(cls, p1, normal_vector, **kwargs)
@property
commit 6767080c10e5020d1aa917ee47a858fb31772904
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 19 22:15:57 2014 +0530
Add Nathan Woods to AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index 6836ace..5edc44a 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -349,3 +349,4 @@ Mark Shoulson <mark@kli.org>
David P. Sanders <dpsanders@gmail.com>
John V. Siratt <jvsiratt@gmail.com>
Sarwar Chahal <chahal.sarwar98@gmail.com>
+Nathan Woods <charlesnwoods@gmail.com>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 63ee181..7ae7a8e 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -354,6 +354,7 @@ want to be mentioned here, so see our repository history for a full list).
#. David P. Sanders: Fix to latex printer
#. John V. Siratt: Fix to documentation
#. Sarwar Chahal: Fix to documentation
+#. Nathan Woods: Fix to C code printer
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit 5c1ed1d17e04f8acebba52a6cc829c565c7ad958
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jul 16 22:57:52 2014 +0530
Fix infinite recursion for NegativeInfinity when doing mod with a number
diff --git a/sympy/core/numbers.py b/sympy/core/numbers.py
index b22f7b5..f181ba9 100644
--- a/sympy/core/numbers.py
+++ b/sympy/core/numbers.py
@@ -2465,6 +2465,11 @@ def __ge__(self, other):
raise TypeError("Invalid comparison of %s and %s" % (self, other))
return _sympify(other is S.NegativeInfinity)
+ def __mod__(self, other):
+ return S.NaN
+
+ __rmod__ = __mod__
+
class NaN(with_metaclass(Singleton, Number)):
"""
diff --git a/sympy/core/tests/test_numbers.py b/sympy/core/tests/test_numbers.py
index 9ce30da..00b1311 100644
--- a/sympy/core/tests/test_numbers.py
+++ b/sympy/core/tests/test_numbers.py
@@ -1423,3 +1423,7 @@ def test_latex():
assert latex(zoo) == r"\tilde{\infty}"
assert latex(nan) == r"\mathrm{NaN}"
assert latex(I) == r"i"
+
+
+def test_issue_7742():
+ assert -oo % 1 == nan
commit ccff3d0fc1dd9e1d371cb3ceeaab5954b93923e8
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jul 15 23:14:44 2014 +0530
Split geometry.rst into module specific files and also add rsts for new geometry modules
diff --git a/doc/src/modules/geometry.rst b/doc/src/modules/geometry.rst
deleted file mode 100644
index 830dc21..0000000
--- a/doc/src/modules/geometry.rst
+++ /dev/null
@@ -1,282 +0,0 @@
-Geometry Module
-===============
-
-.. module:: sympy.geometry
-
-Introduction
-------------
-
-The geometry module for SymPy allows one to create two-dimensional geometrical
-entities, such as lines and circles, and query for information about these
-entities. This could include asking the area of an ellipse, checking for
-collinearity of a set of points, or finding the intersection between two lines.
-The primary use case of the module involves entities with numerical values, but
-it is possible to also use symbolic representations.
-
-Available Entities
-------------------
-
-The following entities are currently available in the geometry module:
-
-* ``Point``
-* ``Line``, ``Ray``, ``Segment``
-* ``Ellipse``, ``Circle``
-* ``Polygon``, ``RegularPolygon``, ``Triangle``
-
-Most of the work one will do will be through the properties and methods of
-these entities, but several global methods exist:
-
-* ``intersection(entity1, entity2)``
-* ``are_similar(entity1, entity2)``
-* ``convex_hull(points)``
-
-For a full API listing and an explanation of the methods and their return
-values please see the list of classes at the end of this document.
-
-Example Usage
--------------
-
-The following Python session gives one an idea of how to work with some of the
-geometry module.
-
- >>> from sympy import *
- >>> from sympy.geometry import *
- >>> x = Point(0, 0)
- >>> y = Point(1, 1)
- >>> z = Point(2, 2)
- >>> zp = Point(1, 0)
- >>> Point.is_collinear(x, y, z)
- True
- >>> Point.is_collinear(x, y, zp)
- False
- >>> t = Triangle(zp, y, x)
- >>> t.area
- 1/2
- >>> t.medians[x]
- Segment(Point(0, 0), Point(1, 1/2))
- >>> Segment(Point(1, S(1)/2), Point(0, 0))
- Segment(Point(0, 0), Point(1, 1/2))
- >>> m = t.medians
- >>> intersection(m[x], m[y], m[zp])
- [Point(2/3, 1/3)]
- >>> c = Circle(x, 5)
- >>> l = Line(Point(5, -5), Point(5, 5))
- >>> c.is_tangent(l) # is l tangent to c?
- True
- >>> l = Line(x, y)
- >>> c.is_tangent(l) # is l tangent to c?
- False
- >>> intersection(c, l)
- [Point(-5*sqrt(2)/2, -5*sqrt(2)/2), Point(5*sqrt(2)/2, 5*sqrt(2)/2)]
-
-Intersection of medians
------------------------
-::
-
- >>> from sympy import symbols
- >>> from sympy.geometry import Point, Triangle, intersection
-
- >>> a, b = symbols("a,b", positive=True)
-
- >>> x = Point(0, 0)
- >>> y = Point(a, 0)
- >>> z = Point(2*a, b)
- >>> t = Triangle(x, y, z)
-
- >>> t.area
- a*b/2
-
- >>> t.medians[x]
- Segment(Point(0, 0), Point(3*a/2, b/2))
-
- >>> intersection(t.medians[x], t.medians[y], t.medians[z])
- [Point(a, b/3)]
-
-An in-depth example: Pappus' Hexagon Theorem
---------------------------------------------
-
-From Wikipedia ([WikiPappus]_):
-
- Given one set of collinear points `A`, `B`, `C`, and another set of collinear
- points `a`, `b`, `c`, then the intersection points `X`, `Y`, `Z` of line pairs `Ab` and
- `aB`, `Ac` and `aC`, `Bc` and `bC` are collinear.
-
-::
-
- >>> from sympy import *
- >>> from sympy.geometry import *
- >>>
- >>> l1 = Line(Point(0, 0), Point(5, 6))
- >>> l2 = Line(Point(0, 0), Point(2, -2))
- >>>
- >>> def subs_point(l, val):
- ... """Take an arbitrary point and make it a fixed point."""
- ... t = Symbol('t', real=True)
- ... ap = l.arbitrary_point()
- ... return Point(ap.x.subs(t, val), ap.y.subs(t, val))
- ...
- >>> p11 = subs_point(l1, 5)
- >>> p12 = subs_point(l1, 6)
- >>> p13 = subs_point(l1, 11)
- >>>
- >>> p21 = subs_point(l2, -1)
- >>> p22 = subs_point(l2, 2)
- >>> p23 = subs_point(l2, 13)
- >>>
- >>> ll1 = Line(p11, p22)
- >>> ll2 = Line(p11, p23)
- >>> ll3 = Line(p12, p21)
- >>> ll4 = Line(p12, p23)
- >>> ll5 = Line(p13, p21)
- >>> ll6 = Line(p13, p22)
- >>>
- >>> pp1 = intersection(ll1, ll3)[0]
- >>> pp2 = intersection(ll2, ll5)[0]
- >>> pp3 = intersection(ll4, ll6)[0]
- >>>
- >>> Point.is_collinear(pp1, pp2, pp3)
- True
-
-References
-~~~~~~~~~~
-
-.. [WikiPappus] "Pappus's Hexagon Theorem" Wikipedia, the Free Encyclopedia.
- Web. 26 Apr. 2013.
- <http://en.wikipedia.org/wiki/Pappus's_hexagon_theorem>
-
-Miscellaneous Notes
--------------------
-
-* The area property of ``Polygon`` and ``Triangle`` may return a positive or
- negative value, depending on whether or not the points are oriented
- counter-clockwise or clockwise, respectively. If you always want a
- positive value be sure to use the ``abs`` function.
-* Although ``Polygon`` can refer to any type of polygon, the code has been
- written for simple polygons. Hence, expect potential problems if dealing
- with complex polygons (overlapping sides).
-* Since SymPy is still in its infancy some things may not simplify
- properly and hence some things that should return ``True`` (e.g.,
- ``Point.is_collinear``) may not actually do so. Similarly, attempting to find
- the intersection of entities that do intersect may result in an empty
- result.
-
-Future Work
------------
-
-Truth Setting Expressions
-~~~~~~~~~~~~~~~~~~~~~~~~~
-
-When one deals with symbolic entities, it often happens that an assertion
-cannot be guaranteed. For example, consider the following code:
-
- >>> from sympy import *
- >>> from sympy.geometry import *
- >>> x,y,z = map(Symbol, 'xyz')
- >>> p1,p2,p3 = Point(x, y), Point(y, z), Point(2*x*y, y)
- >>> Point.is_collinear(p1, p2, p3)
- False
-
-Even though the result is currently ``False``, this is not *always* true. If the
-quantity `z - y - 2*y*z + 2*y**2 == 0` then the points will be collinear. It
-would be really nice to inform the user of this because such a quantity may be
-useful to a user for further calculation and, at the very least, being nice to
-know. This could be potentially done by returning an object (e.g.,
-GeometryResult) that the user could use. This actually would not involve an
-extensive amount of work.
-
-Three Dimensions and Beyond
-~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
-Currently there are no plans for extending the module to three dimensions, but
-it certainly would be a good addition. This would probably involve a fair
-amount of work since many of the algorithms used are specific to two
-dimensions.
-
-Geometry Visualization
-~~~~~~~~~~~~~~~~~~~~~~
-
-The plotting module is capable of plotting geometric entities. See
-:ref:`Plotting Geometric Entities <plot_geom>` in
-the plotting module entry.
-
-API Reference
--------------
-
-Entities
-~~~~~~~~
-
-.. module:: sympy.geometry.entity
-
-.. autoclass:: sympy.geometry.entity.GeometryEntity
- :members:
-
-Utils
-~~~~~
-
-.. module:: sympy.geometry.util
-
-.. autofunction:: intersection
-
-.. autofunction:: convex_hull
-
-.. autofunction:: are_similar
-
-.. autofunction:: centroid
-
-Points
-~~~~~~
-
-.. module:: sympy.geometry.point
-
-.. autoclass:: Point
- :members:
-
-Lines
-~~~~~
-
-.. module:: sympy.geometry.line
-
-.. autoclass:: LinearEntity
- :members:
-
-.. autoclass:: Line
- :members:
-
-.. autoclass:: Ray
- :members:
-
-.. autoclass:: Segment
- :members:
-
-Curves
-~~~~~~
-
-.. module:: sympy.geometry.curve
-
-.. autoclass:: Curve
- :members:
-
-Ellipses
-~~~~~~~~
-
-.. module:: sympy.geometry.ellipse
-
-.. autoclass:: Ellipse
- :members:
-
-.. autoclass:: Circle
- :members:
-
-Polygons
-~~~~~~~~
-
-.. module:: sympy.geometry.polygon
-
-.. autoclass:: Polygon
- :members:
-
-.. autoclass:: RegularPolygon
- :members:
-
-.. autoclass:: Triangle
- :members:
diff --git a/doc/src/modules/geometry/curves.rst b/doc/src/modules/geometry/curves.rst
new file mode 100644
index 0000000..6920e5d
--- /dev/null
+++ b/doc/src/modules/geometry/curves.rst
@@ -0,0 +1,7 @@
+Curves
+------
+
+.. module:: sympy.geometry.curve
+
+.. autoclass:: Curve
+ :members:
diff --git a/doc/src/modules/geometry/ellipses.rst b/doc/src/modules/geometry/ellipses.rst
new file mode 100644
index 0000000..cc422b9
--- /dev/null
+++ b/doc/src/modules/geometry/ellipses.rst
@@ -0,0 +1,10 @@
+Ellipses
+--------
+
+.. module:: sympy.geometry.ellipse
+
+.. autoclass:: Ellipse
+ :members:
+
+.. autoclass:: Circle
+ :members:
diff --git a/doc/src/modules/geometry/entities.rst b/doc/src/modules/geometry/entities.rst
new file mode 100644
index 0000000..8565647
--- /dev/null
+++ b/doc/src/modules/geometry/entities.rst
@@ -0,0 +1,7 @@
+Entities
+--------
+
+.. module:: sympy.geometry.entity
+
+.. autoclass:: sympy.geometry.entity.GeometryEntity
+ :members:
diff --git a/doc/src/modules/geometry/index.rst b/doc/src/modules/geometry/index.rst
new file mode 100644
index 0000000..0a1ea4c
--- /dev/null
+++ b/doc/src/modules/geometry/index.rst
@@ -0,0 +1,217 @@
+===============
+Geometry Module
+===============
+
+
+Introduction
+------------
+
+The geometry module for SymPy allows one to create two-dimensional geometrical
+entities, such as lines and circles, and query for information about these
+entities. This could include asking the area of an ellipse, checking for
+collinearity of a set of points, or finding the intersection between two lines.
+The primary use case of the module involves entities with numerical values, but
+it is possible to also use symbolic representations.
+
+Available Entities
+------------------
+
+The following entities are currently available in the geometry module:
+
+* ``Point``
+* ``Line``, ``Ray``, ``Segment``
+* ``Ellipse``, ``Circle``
+* ``Polygon``, ``RegularPolygon``, ``Triangle``
+
+Most of the work one will do will be through the properties and methods of
+these entities, but several global methods exist:
+
+* ``intersection(entity1, entity2)``
+* ``are_similar(entity1, entity2)``
+* ``convex_hull(points)``
+
+For a full API listing and an explanation of the methods and their return
+values please see the list of classes at the end of this document.
+
+Example Usage
+-------------
+
+The following Python session gives one an idea of how to work with some of the
+geometry module.
+
+ >>> from sympy import *
+ >>> from sympy.geometry import *
+ >>> x = Point(0, 0)
+ >>> y = Point(1, 1)
+ >>> z = Point(2, 2)
+ >>> zp = Point(1, 0)
+ >>> Point.is_collinear(x, y, z)
+ True
+ >>> Point.is_collinear(x, y, zp)
+ False
+ >>> t = Triangle(zp, y, x)
+ >>> t.area
+ 1/2
+ >>> t.medians[x]
+ Segment(Point(0, 0), Point(1, 1/2))
+ >>> Segment(Point(1, S(1)/2), Point(0, 0))
+ Segment(Point(0, 0), Point(1, 1/2))
+ >>> m = t.medians
+ >>> intersection(m[x], m[y], m[zp])
+ [Point(2/3, 1/3)]
+ >>> c = Circle(x, 5)
+ >>> l = Line(Point(5, -5), Point(5, 5))
+ >>> c.is_tangent(l) # is l tangent to c?
+ True
+ >>> l = Line(x, y)
+ >>> c.is_tangent(l) # is l tangent to c?
+ False
+ >>> intersection(c, l)
+ [Point(-5*sqrt(2)/2, -5*sqrt(2)/2), Point(5*sqrt(2)/2, 5*sqrt(2)/2)]
+
+Intersection of medians
+-----------------------
+::
+
+ >>> from sympy import symbols
+ >>> from sympy.geometry import Point, Triangle, intersection
+
+ >>> a, b = symbols("a,b", positive=True)
+
+ >>> x = Point(0, 0)
+ >>> y = Point(a, 0)
+ >>> z = Point(2*a, b)
+ >>> t = Triangle(x, y, z)
+
+ >>> t.area
+ a*b/2
+
+ >>> t.medians[x]
+ Segment(Point(0, 0), Point(3*a/2, b/2))
+
+ >>> intersection(t.medians[x], t.medians[y], t.medians[z])
+ [Point(a, b/3)]
+
+An in-depth example: Pappus' Hexagon Theorem
+--------------------------------------------
+
+From Wikipedia ([WikiPappus]_):
+
+ Given one set of collinear points `A`, `B`, `C`, and another set of collinear
+ points `a`, `b`, `c`, then the intersection points `X`, `Y`, `Z` of line pairs `Ab` and
+ `aB`, `Ac` and `aC`, `Bc` and `bC` are collinear.
+
+::
+
+ >>> from sympy import *
+ >>> from sympy.geometry import *
+ >>>
+ >>> l1 = Line(Point(0, 0), Point(5, 6))
+ >>> l2 = Line(Point(0, 0), Point(2, -2))
+ >>>
+ >>> def subs_point(l, val):
+ ... """Take an arbitrary point and make it a fixed point."""
+ ... t = Symbol('t', real=True)
+ ... ap = l.arbitrary_point()
+ ... return Point(ap.x.subs(t, val), ap.y.subs(t, val))
+ ...
+ >>> p11 = subs_point(l1, 5)
+ >>> p12 = subs_point(l1, 6)
+ >>> p13 = subs_point(l1, 11)
+ >>>
+ >>> p21 = subs_point(l2, -1)
+ >>> p22 = subs_point(l2, 2)
+ >>> p23 = subs_point(l2, 13)
+ >>>
+ >>> ll1 = Line(p11, p22)
+ >>> ll2 = Line(p11, p23)
+ >>> ll3 = Line(p12, p21)
+ >>> ll4 = Line(p12, p23)
+ >>> ll5 = Line(p13, p21)
+ >>> ll6 = Line(p13, p22)
+ >>>
+ >>> pp1 = intersection(ll1, ll3)[0]
+ >>> pp2 = intersection(ll2, ll5)[0]
+ >>> pp3 = intersection(ll4, ll6)[0]
+ >>>
+ >>> Point.is_collinear(pp1, pp2, pp3)
+ True
+
+References
+~~~~~~~~~~
+
+.. [WikiPappus] "Pappus's Hexagon Theorem" Wikipedia, the Free Encyclopedia.
+ Web. 26 Apr. 2013.
+ <http://en.wikipedia.org/wiki/Pappus's_hexagon_theorem>
+
+Miscellaneous Notes
+-------------------
+
+* The area property of ``Polygon`` and ``Triangle`` may return a positive or
+ negative value, depending on whether or not the points are oriented
+ counter-clockwise or clockwise, respectively. If you always want a
+ positive value be sure to use the ``abs`` function.
+* Although ``Polygon`` can refer to any type of polygon, the code has been
+ written for simple polygons. Hence, expect potential problems if dealing
+ with complex polygons (overlapping sides).
+* Since SymPy is still in its infancy some things may not simplify
+ properly and hence some things that should return ``True`` (e.g.,
+ ``Point.is_collinear``) may not actually do so. Similarly, attempting to find
+ the intersection of entities that do intersect may result in an empty
+ result.
+
+Future Work
+-----------
+
+Truth Setting Expressions
+~~~~~~~~~~~~~~~~~~~~~~~~~
+
+When one deals with symbolic entities, it often happens that an assertion
+cannot be guaranteed. For example, consider the following code:
+
+ >>> from sympy import *
+ >>> from sympy.geometry import *
+ >>> x,y,z = map(Symbol, 'xyz')
+ >>> p1,p2,p3 = Point(x, y), Point(y, z), Point(2*x*y, y)
+ >>> Point.is_collinear(p1, p2, p3)
+ False
+
+Even though the result is currently ``False``, this is not *always* true. If the
+quantity `z - y - 2*y*z + 2*y**2 == 0` then the points will be collinear. It
+would be really nice to inform the user of this because such a quantity may be
+useful to a user for further calculation and, at the very least, being nice to
+know. This could be potentially done by returning an object (e.g.,
+GeometryResult) that the user could use. This actually would not involve an
+extensive amount of work.
+
+Three Dimensions and Beyond
+~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+Currently there are no plans for extending the module to three dimensions, but
+it certainly would be a good addition. This would probably involve a fair
+amount of work since many of the algorithms used are specific to two
+dimensions.
+
+Geometry Visualization
+~~~~~~~~~~~~~~~~~~~~~~
+
+The plotting module is capable of plotting geometric entities. See
+:ref:`Plotting Geometric Entities <plot_geom>` in
+the plotting module entry.
+
+Submodules
+~~~~~~~~~~
+
+.. toctree::
+ :maxdepth: 3
+
+ entities.rst
+ utils.rst
+ points.rst
+ point3d.rst
+ lines.rst
+ line3d.rst
+ curves.rst
+ ellipses.rst
+ polygons.rst
+ plane.rst
diff --git a/doc/src/modules/geometry/line3d.rst b/doc/src/modules/geometry/line3d.rst
new file mode 100644
index 0000000..ede1685
--- /dev/null
+++ b/doc/src/modules/geometry/line3d.rst
@@ -0,0 +1,5 @@
+3D Line
+-------
+
+.. automodule:: sympy.geometry.line3d
+ :members:
diff --git a/doc/src/modules/geometry/lines.rst b/doc/src/modules/geometry/lines.rst
new file mode 100644
index 0000000..2799748
--- /dev/null
+++ b/doc/src/modules/geometry/lines.rst
@@ -0,0 +1,16 @@
+Lines
+-----
+
+.. module:: sympy.geometry.line
+
+.. autoclass:: LinearEntity
+ :members:
+
+.. autoclass:: Line
+ :members:
+
+.. autoclass:: Ray
+ :members:
+
+.. autoclass:: Segment
+ :members:
diff --git a/doc/src/modules/geometry/plane.rst b/doc/src/modules/geometry/plane.rst
new file mode 100644
index 0000000..d44a49b
--- /dev/null
+++ b/doc/src/modules/geometry/plane.rst
@@ -0,0 +1,5 @@
+Plane
+-----
+
+.. automodule:: sympy.geometry.plane
+ :members:
diff --git a/doc/src/modules/geometry/point3d.rst b/doc/src/modules/geometry/point3d.rst
new file mode 100644
index 0000000..9066eea
--- /dev/null
+++ b/doc/src/modules/geometry/point3d.rst
@@ -0,0 +1,5 @@
+3D Point
+--------
+
+.. automodule:: sympy.geometry.point3d
+ :members:
diff --git a/doc/src/modules/geometry/points.rst b/doc/src/modules/geometry/points.rst
new file mode 100644
index 0000000..0e68abf
--- /dev/null
+++ b/doc/src/modules/geometry/points.rst
@@ -0,0 +1,7 @@
+Points
+------
+
+.. module:: sympy.geometry.point
+
+.. autoclass:: Point
+ :members:
diff --git a/doc/src/modules/geometry/polygons.rst b/doc/src/modules/geometry/polygons.rst
new file mode 100644
index 0000000..2a87eac
--- /dev/null
+++ b/doc/src/modules/geometry/polygons.rst
@@ -0,0 +1,13 @@
+Polygons
+--------
+
+.. module:: sympy.geometry.polygon
+
+.. autoclass:: Polygon
+ :members:
+
+.. autoclass:: RegularPolygon
+ :members:
+
+.. autoclass:: Triangle
+ :members:
diff --git a/doc/src/modules/geometry/utils.rst b/doc/src/modules/geometry/utils.rst
new file mode 100644
index 0000000..5aef8f1
--- /dev/null
+++ b/doc/src/modules/geometry/utils.rst
@@ -0,0 +1,12 @@
+Utils
+-----
+
+.. module:: sympy.geometry.util
+
+.. autofunction:: intersection
+
+.. autofunction:: convex_hull
+
+.. autofunction:: are_similar
+
+.. autofunction:: centroid
diff --git a/doc/src/modules/index.rst b/doc/src/modules/index.rst
index 441f212..e4fef3b 100644
--- a/doc/src/modules/index.rst
+++ b/doc/src/modules/index.rst
@@ -25,7 +25,7 @@ access any SymPy module, or use this contens:
numeric-computation.rst
functions/index.rst
galgebra/index.rst
- geometry.rst
+ geometry/index.rst
integrals/integrals.rst
logic.rst
matrices/index.rst
commit 44b724d8086d49c0dfeaf62e70307976a31f3cc2
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 12 01:11:13 2014 +0530
Redirect both stdout and stderr to void
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index dade887..d4444fc 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -41,11 +41,11 @@ if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
git config --global user.name "SymPy (Travis CI)"
echo -e "Cloning repository"
- git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/sympy/sympy_doc.git gh-pages 2>/dev/null
+ git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/sympy/sympy_doc.git gh-pages > /dev/null 2>&1
cd gh-pages
git remote rm origin
- git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git 2>/dev/null
+ git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git > /dev/null 2>&1
rm -rf dev/
cp -R ../sympy/doc/_build/html dev/
git add -A dev/
commit 2f47f38ea9bf63ab7e6d1e063c1b2d269fa90832
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 12 00:52:35 2014 +0530
Redirect standard error to void
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index a823909..dade887 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -41,11 +41,11 @@ if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
git config --global user.name "SymPy (Travis CI)"
echo -e "Cloning repository"
- git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/sympy/sympy_doc.git gh-pages > /dev/null
+ git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/sympy/sympy_doc.git gh-pages 2>/dev/null
cd gh-pages
git remote rm origin
- git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git > /dev/null
+ git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git 2>/dev/null
rm -rf dev/
cp -R ../sympy/doc/_build/html dev/
git add -A dev/
commit f5d21222df18cfd5e750337a086dc7feecb165e4
Merge: c2bf0b1 735a5d5
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jul 9 10:55:34 2014 +0530
Merge pull request #7670 from sarwarc/remote_branch
Added functionality of point to be accepted as tuple. Fixes #7669
commit 219bbb74a185975426cbd01d78c84fbcf6997238
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jul 9 10:53:56 2014 +0530
Skip physics/gaussopt.py for doctest
diff --git a/sympy/utilities/runtests.py b/sympy/utilities/runtests.py
index 45ab7b4..3538c3b 100644
--- a/sympy/utilities/runtests.py
+++ b/sympy/utilities/runtests.py
@@ -554,7 +554,8 @@ def _doctest(*paths, **kwargs):
"doc/src/modules/mpmath", # needs to be fixed upstream
"sympy/mpmath", # needs to be fixed upstream
"doc/src/modules/plotting.rst", # generates live plots
- "sympy/utilities/compilef.py" # needs tcc
+ "sympy/utilities/compilef.py", # needs tcc
+ "sympy/physics/gaussopt.py", # raises deprecation warning
])
if import_module('numpy') is None:
@@ -1123,10 +1124,7 @@ def test(self):
self._reporter.start()
for f in self._testfiles:
try:
- # Remove this condition once this file is removed.
- # See https://github.com/sympy/sympy/issues/7659
- if f.find('/sympy/physics/gaussopt.py') == -1:
- self.test_file(f)
+ self.test_file(f)
except KeyboardInterrupt:
print(" interrupted by user")
self._reporter.finish()
commit 65609ff0df424c4f09cdbd82f1c2b735ecc416b2
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jul 5 15:04:00 2014 +0530
Add test for issue 7181. Fixes #7181.
diff --git a/sympy/integrals/tests/test_transforms.py b/sympy/integrals/tests/test_transforms.py
index a562019..9acb1ee 100644
--- a/sympy/integrals/tests/test_transforms.py
+++ b/sympy/integrals/tests/test_transforms.py
@@ -714,3 +714,7 @@ def test_hankel_transform():
assert inverse_hankel_transform(
2**(nu + 1)*a*k**(-nu - 3)*(a**2/k**2 + 1)**(-nu - S(3)/2)*gamma(
nu + S(3)/2)/sqrt(pi), k, r, nu) == r**nu*exp(-a*r)
+
+
+def test_issue_7181():
+ assert mellin_transform(1/(1 - x), x, s) != None
commit f4f6502e237874d2c7803e98dae8bb063b81d810
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jul 7 11:37:34 2014 +0530
Do not test duplicate gaussopt.py file
diff --git a/sympy/utilities/runtests.py b/sympy/utilities/runtests.py
index 0875405..45ab7b4 100644
--- a/sympy/utilities/runtests.py
+++ b/sympy/utilities/runtests.py
@@ -1123,7 +1123,10 @@ def test(self):
self._reporter.start()
for f in self._testfiles:
try:
- self.test_file(f)
+ # Remove this condition once this file is removed.
+ # See https://github.com/sympy/sympy/issues/7659
+ if f.find('/sympy/physics/gaussopt.py') == -1:
+ self.test_file(f)
except KeyboardInterrupt:
print(" interrupted by user")
self._reporter.finish()
commit 26a53d220cb99d4886f24a7578a2fdc648c98b03
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jul 6 09:26:38 2014 +0530
Add Sawar Chahal to AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index 0d4afe5..6836ace 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -348,3 +348,4 @@ Ambar Mehrotra <mehrotraambar@gmail.com>
Mark Shoulson <mark@kli.org>
David P. Sanders <dpsanders@gmail.com>
John V. Siratt <jvsiratt@gmail.com>
+Sarwar Chahal <chahal.sarwar98@gmail.com>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 21e0cc8..63ee181 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -353,6 +353,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Mark Shoulson: Enhanced Egyptian fractions
#. David P. Sanders: Fix to latex printer
#. John V. Siratt: Fix to documentation
+#. Sarwar Chahal: Fix to documentation
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit 1bc3a17b05842d27acc3a2eb36a4e8ea28da4ff4
Merge: 8ea8c54 79a79bf
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jul 6 09:23:51 2014 +0530
Merge pull request #7697 from sarwarc/issue7696
Replaced f_ with g_ in polytools/reduced and solves issue #7696
commit 062f1b8a46543281efd9df309cb9b2a88186a644
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 30 03:54:40 2014 +0530
Add John V. Siratt to AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index ce930b7..0d4afe5 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -347,3 +347,4 @@ Fawaz Alazemi <Mba7eth@gmail.com>
Ambar Mehrotra <mehrotraambar@gmail.com>
Mark Shoulson <mark@kli.org>
David P. Sanders <dpsanders@gmail.com>
+John V. Siratt <jvsiratt@gmail.com>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index ca08b03..21e0cc8 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -352,6 +352,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Ambar Mehrotra: Fix to documentation
#. Mark Shoulson: Enhanced Egyptian fractions
#. David P. Sanders: Fix to latex printer
+#. John V. Siratt: Fix to documentation
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit eb170e45365578b73da1021c277cd7d458225ccd
Merge: 7324a1e a7e026b
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 30 03:05:29 2014 +0530
Merge pull request #7666 from jvsiratt/correction_symbols_doc
Corrections to core.symbol.symbols docstring
commit d8289f47de23cfcfa795ec88abd13f5146ea2247
Merge: facf9df 2035007
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 16:55:20 2014 +0530
Merge pull request #7668 from debugger22/auto-deploy-dev-doc
Add command to exit on error(build_doc.sh)
commit 2035007b043c6b304537175aacc72f5ddfc860dd
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 16:53:25 2014 +0530
Add command to exit on error(build_doc.sh)
It is important to exit on error and not delete all the doc files and push an empty dev folder
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index 99d0eff..a823909 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -21,6 +21,8 @@
#
# Add this secure code to .travis.yml as described here http://docs.travis-ci.com/user/encryption-keys/
+# Exit on error
+set -e
if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
commit bcf66f2425d75c564a9bcb6513851c8db10ce280
Merge: d672a4c 5c6456a
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 07:08:49 2014 +0530
Merge pull request #7643 from debugger22/auto-deploy-dev-doc
Create auto update mechanism for development docs
commit 81210e645a7fbef1d8c01c2ac415154d29b8fe54
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 05:51:41 2014 +0530
Test with Mul's instance instead of expr
diff --git a/sympy/parsing/tests/test_sympy_parser.py b/sympy/parsing/tests/test_sympy_parser.py
index b1cc54e..5482b33 100644
--- a/sympy/parsing/tests/test_sympy_parser.py
+++ b/sympy/parsing/tests/test_sympy_parser.py
@@ -84,4 +84,4 @@ def test_issue_2515():
def test_issue_7663():
x = Symbol('x')
- parse_expr('2*(x+1)', evaluate=0) == 2*(x + 1)
+ parse_expr('2*(x+1)', evaluate=0) == Mul(2, x + 1, evaluate=False)
commit d672a4cd096c28cb614c671493f7ffbfb6554771
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 05:49:07 2014 +0530
Added David P. Sanders to AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index ae6afcf..ce930b7 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -346,3 +346,4 @@ Kaushik Varanasi <kaushik.varanasi1@gmail.com>
Fawaz Alazemi <Mba7eth@gmail.com>
Ambar Mehrotra <mehrotraambar@gmail.com>
Mark Shoulson <mark@kli.org>
+David P. Sanders <dpsanders@gmail.com>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 2cdd6f1..ca08b03 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -351,6 +351,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Fawaz Alazemi: combinatorics cheat sheet
#. Ambar Mehrotra: Fix to documentation
#. Mark Shoulson: Enhanced Egyptian fractions
+#. David P. Sanders: Fix to latex printer
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit af7ee1fed8e8409ede9e829326abdb2fc7fd7bd7
Merge: 388a906 988ffe1
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 05:41:18 2014 +0530
Merge pull request #7660 from debugger22/dpsanders-latex_Lambda
Change latex output of Lambda to use \mapsto
commit 1bea8327cd3f174c635171eba9015cf7fe67bd6a
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 04:51:41 2014 +0530
Make sympy_parser work with evaluate=0. Fixes #7663
diff --git a/sympy/parsing/sympy_parser.py b/sympy/parsing/sympy_parser.py
index eb928a7..3d353ba 100644
--- a/sympy/parsing/sympy_parser.py
+++ b/sympy/parsing/sympy_parser.py
@@ -786,7 +786,7 @@ def parse_expr(s, local_dict=None, transformations=standard_transformations,
code = stringify_expr(s, local_dict, global_dict, transformations)
- if evaluate is False:
+ if not evaluate:
code = compile(evaluateFalse(code), '<string>', 'eval')
return eval_expr(code, local_dict, global_dict)
diff --git a/sympy/parsing/tests/test_sympy_parser.py b/sympy/parsing/tests/test_sympy_parser.py
index 616f03d..b1cc54e 100644
--- a/sympy/parsing/tests/test_sympy_parser.py
+++ b/sympy/parsing/tests/test_sympy_parser.py
@@ -54,6 +54,7 @@ def test_factorial_fail():
except TokenError:
assert True
+
def test_local_dict():
local_dict = {
'my_function': lambda x: x + 2
@@ -64,6 +65,7 @@ def test_local_dict():
for text, result in inputs.items():
assert parse_expr(text, local_dict=local_dict) == result
+
def test_global_dict():
global_dict = {
'Symbol': Symbol
@@ -74,6 +76,12 @@ def test_global_dict():
for text, result in inputs.items():
assert parse_expr(text, global_dict=global_dict) == result
+
def test_issue_2515():
raises(TokenError, lambda: parse_expr('(()'))
raises(TokenError, lambda: parse_expr('"""'))
+
+
+def test_issue_7663():
+ x = Symbol('x')
+ parse_expr('2*(x+1)', evaluate=0) == 2*(x + 1)
commit 5c6456aaa0c789beca333c970baeb276d6111cbc
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 29 02:41:32 2014 +0530
Add instructions to reproduce access token
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index 6e5d6e1..99d0eff 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -1,5 +1,27 @@
#! /usr/bin/env bash
+# This file automatically deploys changes to http://docs.sympy.org/dev/index.html.
+# This will happen only when a PR gets merged which is basically when a new commit
+# is added to master.
+# It requires an access token which should be present in .travis.yml file.
+#
+# Following is the procedure to get the access token:
+#
+# $ curl -X POST -u <github_username> -H "Content-Type: application/json" -d\
+# "{\"scopes\":[\"public_repo\"],\"note\":\"token for pushing from travis\"}"\
+# https://api.github.com/authorizations
+#
+# It'll give you a JSON response having a key called "token".
+#
+# $ gem install travis
+# $ travis encrypt -r sympy/sympy GH_TOKEN=<token> env.global
+#
+# This will give you an access token("secure"). This helps in creating an
+# environment variable named GH_TOKEN while building.
+#
+# Add this secure code to .travis.yml as described here http://docs.travis-ci.com/user/encryption-keys/
+
+
if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
echo "Installing dependencies"
commit a3a6966781dc7d6c6838bb2986e05dfc68f766cd
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Thu Jun 26 06:47:03 2014 +0530
Add access token
Finalize things
diff --git a/.travis.yml b/.travis.yml
index ca63486..400f92c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -5,7 +5,7 @@ env:
- SPLIT="1/2"
- SPLIT="2/2"
global:
- secure: <access_token>
+ secure: uJycOcgT3Rg9TsU6ID2UMHc56Fh6Q70p1/mFiod8r97g8zER9kWTZ2GVDSRiw1Nfh0Wojcy04PAG3t5m9bwM08YF8qZy1PJkCb/pu7PN8Hzt+6FSBb84gGEXMiv1xuZWSQ0pUuBa1Lfcxuq6m2/eA8aNfgoqnpLgR8zeg/2xhFw=
python:
- 2.6
- 2.7
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
index 8422693..6e5d6e1 100755
--- a/bin/build_doc.sh
+++ b/bin/build_doc.sh
@@ -2,25 +2,32 @@
if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
+ echo "Installing dependencies"
+ sudo apt-get install --no-install-recommends graphviz inkscape texlive texlive-xetex texlive-fonts-recommended texlive-latex-extra lmodern librsvg2-bin imagemagick docbook2x
+ pip install "sphinx==1.1.3"
+
+ echo -e "Building docs"
cd doc
make clean
make html
cd ../../
-
+ echo -e "Setting git attributes"
git config --global user.email "sympy@googlegroups.com"
git config --global user.name "SymPy (Travis CI)"
+ echo -e "Cloning repository"
git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/sympy/sympy_doc.git gh-pages > /dev/null
cd gh-pages
git remote rm origin
- git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git
+ git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git > /dev/null
rm -rf dev/
cp -R ../sympy/doc/_build/html dev/
- git add -A dev
+ git add -A dev/
./generate_indexes.py
git commit -am "Update dev doc after building $TRAVIS_BUILD_NUMBER"
+ echo -e "Pushing commit"
git push -fq origin gh-pages > /dev/null
fi
commit 988ffe1a486bdd4d7f4009e0253006d9ceaff3ff
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 17:58:14 2014 +0530
Correct failing test
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 3b41ba7..46ccabc 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -807,7 +807,7 @@ def test_latex_RootOf():
def test_latex_RootSum():
assert latex(RootSum(x**5 + x + 3, sin)) == \
- r"\operatorname{RootSum} {\left(x^{5} + x + 3, x \mapsto \sin{\left (x \right )}\right)}"
+ r"\operatorname{RootSum} {\left(x^{5} + x + 3, \left( x \mapsto \sin{\left (x \right )} \right)\right)}"
def test_settings():
commit f2f3563886db5e7f96c7c412cb98991a443301b9
Merge: 5f27cd8 c42bf83
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 17:51:08 2014 +0530
Merge branch 'latex_Lambda' of https://github.com/dpsanders/sympy into dpsanders-latex_Lambda
commit 3d02640633f3e1f579ec55dd5e3185a7ae877aee
Merge: 5f27cd8 540e0a8
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 16:14:36 2014 +0530
Merge pull request #7657 from KDMOE/typo_deutils_desolve
Incomplete doc in deutils [skip ci]
commit 5f27cd8f3388305a0bba1b27ae499e287b5908f5
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 11:20:22 2014 +0530
Add Mark Shoulson to the AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index f506882..0215862 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -336,3 +336,4 @@ Zamrath Nizam <zamiguy_ni@yahoo.com>
Benjamin Gudehus <hastebrot@gmail.com>
Faisal Anees <faisal.iiit@gmail.com>
Ambar Mehrotra <mehrotraambar@gmail.com>
+Mark Shoulson <mark@kli.org>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 3307f49..480a75e 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -341,6 +341,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Benjamin Gudehus: add sampling_density to stats
#. Faisal Anees: Egyptian Fractions
#. Ambar Mehrotra: Fix to documentation
+#. Mark Shoulson: Enhanced Egyptian fractions
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit ad4c1014184f8a7c4b72a4620262bf5fda3264d2
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 08:03:51 2014 +0530
Add issue number(7659) in the deprecation warning
diff --git a/sympy/physics/gaussopt.py b/sympy/physics/gaussopt.py
index ec2d472..84dd45d 100644
--- a/sympy/physics/gaussopt.py
+++ b/sympy/physics/gaussopt.py
@@ -8,5 +8,4 @@
SymPyDeprecationWarning(feature="Module sympy.physics.gaussopt",
useinstead="sympy.physics.optics.gaussopt",
- deprecated_since_version="0.7.6").warn()
-
+ deprecated_since_version="0.7.6", issue=7659).warn()
commit 5ab1b0e55bc8fdc1ed2a3aaceab24475e5ea0cc7
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 07:43:19 2014 +0530
Change Google code to GitHub in SymPyDecprecationWarning docstring
diff --git a/sympy/utilities/exceptions.py b/sympy/utilities/exceptions.py
index 77c1f90..aecbabd 100644
--- a/sympy/utilities/exceptions.py
+++ b/sympy/utilities/exceptions.py
@@ -84,8 +84,8 @@ class in this way:
Old feature has been deprecated. Use new feature instead. See
https://github.com/sympy/sympy/issues/5241 for more info.
- Every formal deprecation should have an associated issue in the Google
- Code issue tracker. All such issues should have the DeprecationRemoval
+ Every formal deprecation should have an associated issue in the GitHub
+ issue tracker. All such issues should have the DeprecationRemoval
tag.
Additionally, each formal deprecation should mark the first release for
commit 585deabeb178143c193dbf0a625ec86bc0f5894a
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 07:38:45 2014 +0530
Add deprecation warning for sympy.physics.gaussopt
diff --git a/sympy/physics/gaussopt.py b/sympy/physics/gaussopt.py
new file mode 100644
index 0000000..ec2d472
--- /dev/null
+++ b/sympy/physics/gaussopt.py
@@ -0,0 +1,12 @@
+from sympy.physics.optics.gaussopt import RayTransferMatrix, FreeSpace,\
+ FlatRefraction, CurvedRefraction, FlatMirror, CurvedMirror, ThinLens,\
+ GeometricRay, BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,\
+ geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams
+
+from sympy.utilities.exceptions import SymPyDeprecationWarning
+
+
+SymPyDeprecationWarning(feature="Module sympy.physics.gaussopt",
+ useinstead="sympy.physics.optics.gaussopt",
+ deprecated_since_version="0.7.6").warn()
+
commit 2adf5947a152768b24b9cd5251e337010c6063fe
Merge: d1a603e 9e4ba43
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat Jun 28 06:09:00 2014 +0530
Merge pull request #7613 from clsn/str_unicode
Handle unicode literals properly in matrices
commit 617760e7567d1afae5978245a4a5b8c13b79d46b
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri Jun 27 23:04:06 2014 +0530
Added Ambar Mehrotra to the AUTHORS/aboutus. Welcome to SymPy
diff --git a/AUTHORS b/AUTHORS
index 2484050..f506882 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -335,3 +335,4 @@ Maciej Baranski <getrox.sc@gmail.com>
Zamrath Nizam <zamiguy_ni@yahoo.com>
Benjamin Gudehus <hastebrot@gmail.com>
Faisal Anees <faisal.iiit@gmail.com>
+Ambar Mehrotra <mehrotraambar@gmail.com>
diff --git a/doc/src/aboutus.rst b/doc/src/aboutus.rst
index 19855bd..3307f49 100644
--- a/doc/src/aboutus.rst
+++ b/doc/src/aboutus.rst
@@ -340,6 +340,7 @@ want to be mentioned here, so see our repository history for a full list).
#. Zamrath Nizam: replace atoms(Symbol) with free_symbols where appropriate
#. Benjamin Gudehus: add sampling_density to stats
#. Faisal Anees: Egyptian Fractions
+#. Ambar Mehrotra: Fix to documentation
Up-to-date list in the order of the first contribution is given in the `AUTHORS
<https://github.com/sympy/sympy/blob/master/AUTHORS>`_ file.
commit 0594e8727d8bf45c2b444b01751ccac26e40a16f
Merge: 012a919 4e67b58
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri Jun 27 13:09:04 2014 +0530
Merge pull request #7647 from coder006/typo
Correct a typo in piecewise.py
commit d25d46e52a43460bfe761c8460126372740aaf2d
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Thu Jun 26 08:46:45 2014 +0530
Change absolute import to relative import
diff --git a/sympy/polys/heuristicgcd.py b/sympy/polys/heuristicgcd.py
index 66b9ddb..65e02be 100644
--- a/sympy/polys/heuristicgcd.py
+++ b/sympy/polys/heuristicgcd.py
@@ -2,7 +2,7 @@
from __future__ import print_function, division
from sympy.core.compatibility import xrange
-from sympy.polys.polyerrors import HeuristicGCDFailed
+from .polyerrors import HeuristicGCDFailed
HEU_GCD_MAX = 6
commit 8d09c7ecae438ff693aeeb8ae053a94dd62a3b8c
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jun 25 14:22:26 2014 +0530
Create auto update mechanism for development docs [skip ci]
diff --git a/.travis.yml b/.travis.yml
index 1ba711e..ca63486 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -1,8 +1,11 @@
language: python
env:
+ matrix:
- TEST_DOCTESTS="true"
- SPLIT="1/2"
- SPLIT="2/2"
+ global:
+ secure: <access_token>
python:
- 2.6
- 2.7
@@ -149,3 +152,5 @@ script:
- bin/test_travis.sh
notifications:
email: false
+after_success:
+ - bin/build_doc.sh
diff --git a/bin/build_doc.sh b/bin/build_doc.sh
new file mode 100755
index 0000000..8422693
--- /dev/null
+++ b/bin/build_doc.sh
@@ -0,0 +1,26 @@
+#! /usr/bin/env bash
+
+if [ "$TRAVIS_PULL_REQUEST" == "false" ]; then
+
+ cd doc
+ make clean
+ make html
+
+ cd ../../
+
+ git config --global user.email "sympy@googlegroups.com"
+ git config --global user.name "SymPy (Travis CI)"
+
+ git clone --quiet --branch=gh-pages https://${GH_TOKEN}@github.com/sympy/sympy_doc.git gh-pages > /dev/null
+
+ cd gh-pages
+ git remote rm origin
+ git remote add origin https://${GH_TOKEN}@github.com/sympy/sympy_doc.git
+ rm -rf dev/
+ cp -R ../sympy/doc/_build/html dev/
+ git add -A dev
+ ./generate_indexes.py
+
+ git commit -am "Update dev doc after building $TRAVIS_BUILD_NUMBER"
+ git push -fq origin gh-pages > /dev/null
+fi
commit ed0be80664d800d1d54d0c3eb0842001e82fca4b
Merge: abe2a6e f46a8a2
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 24 09:11:21 2014 +0530
Remove merge conflicts
commit 87577b1aab4478a3593ccf2dfa78a400e380a639
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 23 13:10:28 2014 -0500
remove redundant import
[ci skip]
diff --git a/sympy/simplify/fu.py b/sympy/simplify/fu.py
index 8930904..9793603 100644
--- a/sympy/simplify/fu.py
+++ b/sympy/simplify/fu.py
@@ -1072,7 +1072,7 @@ def TR12i(rv):
>>> TR12i(eq.expand())
-3*tan(a + b)*tan(a + c)/(2*(tan(a) + tan(b) - 1))
"""
- from sympy import factor, fraction, factor_terms
+ from sympy import factor, fraction
def f(rv):
if not (rv.is_Add or rv.is_Mul or rv.is_Pow):
commit abe2a6ed3dc4453a4fd91c596d6377ea66f7f4d7
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 23 11:22:23 2014 +0530
Change location of docs
diff --git a/doc/src/modules/physics/gaussopt.rst b/doc/src/modules/physics/gaussopt.rst
deleted file mode 100644
index 36743fa..0000000
--- a/doc/src/modules/physics/gaussopt.rst
+++ /dev/null
@@ -1,6 +0,0 @@
-===============
-Gaussian Optics
-===============
-
-.. automodule:: sympy.physics.gaussopt
- :members:
diff --git a/doc/src/modules/physics/index.rst b/doc/src/modules/physics/index.rst
index 23c26ec..eeb6407 100644
--- a/doc/src/modules/physics/index.rst
+++ b/doc/src/modules/physics/index.rst
@@ -12,7 +12,6 @@ Contents
.. toctree::
:maxdepth: 3
- gaussopt.rst
hydrogen.rst
matrices.rst
paulialgebra.rst
diff --git a/doc/src/modules/physics/optics/gaussopt.rst b/doc/src/modules/physics/optics/gaussopt.rst
new file mode 100644
index 0000000..2963e66
--- /dev/null
+++ b/doc/src/modules/physics/optics/gaussopt.rst
@@ -0,0 +1,6 @@
+===============
+Gaussian Optics
+===============
+
+.. automodule:: sympy.physics.optics.gaussopt
+ :members:
diff --git a/doc/src/modules/physics/optics/index.rst b/doc/src/modules/physics/optics/index.rst
index e3f2ec9..9b39e11 100644
--- a/doc/src/modules/physics/optics/index.rst
+++ b/doc/src/modules/physics/optics/index.rst
@@ -10,4 +10,5 @@ Optics Module
.. toctree::
:maxdepth: 3
+ gaussopt.rst
waves.rst
commit 46e8cb9c8a0e358f94d354fa122c3f0d77418310
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 23 00:41:02 2014 +0530
Import not imported exception HeuristicGCDFailed
HeuristicGCDFailed was being raised without importing it in polys/heuristicgcd.py.
diff --git a/sympy/polys/heuristicgcd.py b/sympy/polys/heuristicgcd.py
index 5408dee..66b9ddb 100644
--- a/sympy/polys/heuristicgcd.py
+++ b/sympy/polys/heuristicgcd.py
@@ -2,6 +2,7 @@
from __future__ import print_function, division
from sympy.core.compatibility import xrange
+from sympy.polys.polyerrors import HeuristicGCDFailed
HEU_GCD_MAX = 6
commit ea76749dd4650ad435b128be8ee05b9d5164ee30
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 22 23:48:41 2014 +0530
Fix implicit import in plotting/textplot.py
diff --git a/sympy/plotting/textplot.py b/sympy/plotting/textplot.py
index bfd6e2f..d5f3966 100644
--- a/sympy/plotting/textplot.py
+++ b/sympy/plotting/textplot.py
@@ -1,6 +1,7 @@
from __future__ import print_function, division
-from sympy import *
+from sympy.core.symbol import Dummy
+from sympy.utilities.lambdify import lambdify
def textplot(expr, a, b, W=55, H=18):
diff --git a/sympy/utilities/tests/test_code_quality.py b/sympy/utilities/tests/test_code_quality.py
index 90d4cd3..e5673f5 100644
--- a/sympy/utilities/tests/test_code_quality.py
+++ b/sympy/utilities/tests/test_code_quality.py
@@ -175,9 +175,8 @@ def test_this_file(fname, test_file):
"%(sep)sbin%(sep)ssympy_time_cache.py" % sepd,
# Taken from Python stdlib:
"%(sep)sparsing%(sep)ssympy_tokenize.py" % sepd,
- # these two should be fixed:
+ # this one should be fixed:
"%(sep)splotting%(sep)spygletplot%(sep)s" % sepd,
- "%(sep)splotting%(sep)stextplot.py" % sepd,
])
check_files(top_level_files, test)
check_directory_tree(BIN_PATH, test, set(["~", ".pyc", ".sh"]), "*")
commit d2fce08604b960e110feaa4cb2869cc6439fdd24
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 22 23:05:11 2014 +0530
Correct implicit import
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 5db147f..fcb8641 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -16,5 +16,8 @@
__all__.extend(waves.__all__)
from . import gaussopt
-from .gaussopt import *
+from .gaussopt import RayTransferMatrix, FreeSpace, FlatRefraction,\
+ CurvedRefraction, FlatMirror, CurvedMirror, ThinLens, GeometricRay,\
+ BeamParameter, waist2rayleigh, rayleigh2waist, geometric_conj_ab,\
+ geometric_conj_af, geometric_conj_bf, gaussian_conj, conjugate_gauss_beams
__all__.extend(gaussopt.__all__)
commit 91435dac5c829143987148d0832bdad584faa79e
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jun 18 20:14:09 2014 +0530
Move guassopt to optics/guassopt
Correct import in test_gaussopt
Correct imports in docstrings
diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index 2dfb68d..5d4d534 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -2037,10 +2037,6 @@ def test_sympy__physics__vector__frame__CoordinateSym():
from sympy.physics.vector import ReferenceFrame
assert _test_args(CoordinateSym('R_x', ReferenceFrame('R'), 0))
-def test_sympy__physics__gaussopt__BeamParameter():
- from sympy.physics.gaussopt import BeamParameter
- assert _test_args(BeamParameter(530e-9, 1, w=1e-3))
-
def test_sympy__physics__paulialgebra__Pauli():
from sympy.physics.paulialgebra import Pauli
@@ -3160,6 +3156,7 @@ def test_sympy__categories__baseclasses__Category():
K = Category("K", commutative_diagrams=[d1, d2])
assert _test_args(K)
+
def test_sympy__ntheory__factor___totient():
from sympy.ntheory.factor_ import totient
k = symbols('k', integer=True)
@@ -3171,7 +3168,13 @@ def test_sympy__ntheory__residue_ntheory__mobius():
from sympy.ntheory import mobius
assert _test_args(mobius(2))
+
def test_sympy__physics__optics__waves__TWave():
from sympy.physics.optics import TWave
A, f, phi = symbols('A, f, phi')
assert _test_args(TWave(A, f, phi))
+
+
+def test_sympy__physics__optics__gaussopt__BeamParameter():
+ from sympy.physics.optics import BeamParameter
+ assert _test_args(BeamParameter(530e-9, 1, w=1e-3))
diff --git a/sympy/physics/gaussopt.py b/sympy/physics/gaussopt.py
deleted file mode 100644
index cc49785..0000000
--- a/sympy/physics/gaussopt.py
+++ /dev/null
@@ -1,855 +0,0 @@
-# -*- encoding: utf-8 -*-
-"""
-Gaussian optics.
-
-The module implements:
-
-- Ray transfer matrices for geometrical and gaussian optics.
-
- See RayTransferMatrix, GeometricRay and BeamParameter
-
-- Conjugation relations for geometrical and gaussian optics.
-
- See geometric_conj*, gauss_conj and conjugate_gauss_beams
-
-The conventions for the distances are as follows:
-
-focal distance
- positive for convergent lenses
-object distance
- positive for real objects
-image distance
- positive for real images
-"""
-
-from __future__ import print_function, division
-
-from sympy import (atan2, Expr, I, im, Matrix, oo, pi, re, sqrt, sympify,
- together)
-from sympy.utilities.misc import filldedent
-
-###
-# A, B, C, D matrices
-###
-
-
-class RayTransferMatrix(Matrix):
- """
- Base class for a Ray Transfer Matrix.
-
- It should be used if there isn't already a more specific subclass mentioned
- in See Also.
-
- Parameters
- ==========
-
- parameters : A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import RayTransferMatrix, ThinLens
- >>> from sympy import Symbol, Matrix
-
- >>> mat = RayTransferMatrix(1, 2, 3, 4)
- >>> mat
- Matrix([
- [1, 2],
- [3, 4]])
-
- >>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
- Matrix([
- [1, 2],
- [3, 4]])
-
- >>> mat.A
- 1
-
- >>> f = Symbol('f')
- >>> lens = ThinLens(f)
- >>> lens
- Matrix([
- [ 1, 0],
- [-1/f, 1]])
-
- >>> lens.C
- -1/f
-
- See Also
- ========
-
- GeometricRay, BeamParameter,
- FreeSpace, FlatRefraction, CurvedRefraction,
- FlatMirror, CurvedMirror, ThinLens
-
- References
- ==========
-
- .. [1] http://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
- """
-
- def __new__(cls, *args):
-
- if len(args) == 4:
- temp = ((args[0], args[1]), (args[2], args[3]))
- elif len(args) == 1 \
- and isinstance(args[0], Matrix) \
- and args[0].shape == (2, 2):
- temp = args[0]
- else:
- raise ValueError(filldedent('''
- Expecting 2x2 Matrix or the 4 elements of
- the Matrix but got %s''' % str(args)))
- return Matrix.__new__(cls, temp)
-
- def __mul__(self, other):
- if isinstance(other, RayTransferMatrix):
- return RayTransferMatrix(Matrix.__mul__(self, other))
- elif isinstance(other, GeometricRay):
- return GeometricRay(Matrix.__mul__(self, other))
- elif isinstance(other, BeamParameter):
- temp = self*Matrix(((other.q,), (1,)))
- q = (temp[0]/temp[1]).expand(complex=True)
- return BeamParameter(other.wavelen,
- together(re(q)),
- z_r=together(im(q)))
- else:
- return Matrix.__mul__(self, other)
-
- @property
- def A(self):
- """
- The A parameter of the Matrix.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import RayTransferMatrix
- >>> mat = RayTransferMatrix(1, 2, 3, 4)
- >>> mat.A
- 1
- """
- return self[0, 0]
-
- @property
- def B(self):
- """
- The B parameter of the Matrix.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import RayTransferMatrix
- >>> mat = RayTransferMatrix(1, 2, 3, 4)
- >>> mat.B
- 2
- """
- return self[0, 1]
-
- @property
- def C(self):
- """
- The C parameter of the Matrix.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import RayTransferMatrix
- >>> mat = RayTransferMatrix(1, 2, 3, 4)
- >>> mat.C
- 3
- """
- return self[1, 0]
-
- @property
- def D(self):
- """
- The D parameter of the Matrix.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import RayTransferMatrix
- >>> mat = RayTransferMatrix(1, 2, 3, 4)
- >>> mat.D
- 4
- """
- return self[1, 1]
-
-
-class FreeSpace(RayTransferMatrix):
- """
- Ray Transfer Matrix for free space.
-
- Parameters
- ==========
-
- distance
-
- See Also
- ========
-
- RayTransferMatrix
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import FreeSpace
- >>> from sympy import symbols
- >>> d = symbols('d')
- >>> FreeSpace(d)
- Matrix([
- [1, d],
- [0, 1]])
- """
- def __new__(cls, d):
- return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
-
-
-class FlatRefraction(RayTransferMatrix):
- """
- Ray Transfer Matrix for refraction.
-
- Parameters
- ==========
-
- n1 : refractive index of one medium
- n2 : refractive index of other medium
-
- See Also
- ========
-
- RayTransferMatrix
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import FlatRefraction
- >>> from sympy import symbols
- >>> n1, n2 = symbols('n1 n2')
- >>> FlatRefraction(n1, n2)
- Matrix([
- [1, 0],
- [0, n1/n2]])
- """
- def __new__(cls, n1, n2):
- n1, n2 = map(sympify, (n1, n2))
- return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
-
-
-class CurvedRefraction(RayTransferMatrix):
- """
- Ray Transfer Matrix for refraction on curved interface.
-
- Parameters
- ==========
-
- R : radius of curvature (positive for concave)
- n1 : refractive index of one medium
- n2 : refractive index of other medium
-
- See Also
- ========
-
- RayTransferMatrix
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import CurvedRefraction
- >>> from sympy import symbols
- >>> R, n1, n2 = symbols('R n1 n2')
- >>> CurvedRefraction(R, n1, n2)
- Matrix([
- [ 1, 0],
- [(n1 - n2)/(R*n2), n1/n2]])
- """
- def __new__(cls, R, n1, n2):
- R, n1, n2 = map(sympify, (R, n1, n2))
- return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
-
-
-class FlatMirror(RayTransferMatrix):
- """
- Ray Transfer Matrix for reflection.
-
- See Also
- ========
-
- RayTransferMatrix
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import FlatMirror
- >>> FlatMirror()
- Matrix([
- [1, 0],
- [0, 1]])
- """
- def __new__(cls):
- return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
-
-
-class CurvedMirror(RayTransferMatrix):
- """
- Ray Transfer Matrix for reflection from curved surface.
-
- Parameters
- ==========
-
- R : radius of curvature (positive for concave)
-
- See Also
- ========
-
- RayTransferMatrix
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import CurvedMirror
- >>> from sympy import symbols
- >>> R = symbols('R')
- >>> CurvedMirror(R)
- Matrix([
- [ 1, 0],
- [-2/R, 1]])
- """
- def __new__(cls, R):
- R = sympify(R)
- return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
-
-
-class ThinLens(RayTransferMatrix):
- """
- Ray Transfer Matrix for a thin lens.
-
- Parameters
- ==========
-
- f : the focal distance
-
- See Also
- ========
-
- RayTransferMatrix
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import ThinLens
- >>> from sympy import symbols
- >>> f = symbols('f')
- >>> ThinLens(f)
- Matrix([
- [ 1, 0],
- [-1/f, 1]])
- """
- def __new__(cls, f):
- f = sympify(f)
- return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
-
-
-###
-# Representation for geometric ray
-###
-
-class GeometricRay(Matrix):
- """
- Representation for a geometric ray in the Ray Transfer Matrix formalism.
-
- Parameters
- ==========
-
- h : height, and
- angle : angle, or
- matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
-
- Examples
- =======
-
- >>> from sympy.physics.gaussopt import GeometricRay, FreeSpace
- >>> from sympy import symbols, Matrix
- >>> d, h, angle = symbols('d, h, angle')
-
- >>> GeometricRay(h, angle)
- Matrix([
- [ h],
- [angle]])
-
- >>> FreeSpace(d)*GeometricRay(h, angle)
- Matrix([
- [angle*d + h],
- [ angle]])
-
- >>> GeometricRay( Matrix( ((h,), (angle,)) ) )
- Matrix([
- [ h],
- [angle]])
-
- See Also
- ========
-
- RayTransferMatrix
-
- """
-
- def __new__(cls, *args):
- if len(args) == 1 and isinstance(args[0], Matrix) \
- and args[0].shape == (2, 1):
- temp = args[0]
- elif len(args) == 2:
- temp = ((args[0],), (args[1],))
- else:
- raise ValueError(filldedent('''
- Expecting 2x1 Matrix or the 2 elements of
- the Matrix but got %s''' % str(args)))
- return Matrix.__new__(cls, temp)
-
- @property
- def height(self):
- """
- The distance from the optical axis.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import GeometricRay
- >>> from sympy import symbols
- >>> h, angle = symbols('h, angle')
- >>> gRay = GeometricRay(h, angle)
- >>> gRay.height
- h
- """
- return self[0]
-
- @property
- def angle(self):
- """
- The angle with the optical axis.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import GeometricRay
- >>> from sympy import symbols
- >>> h, angle = symbols('h, angle')
- >>> gRay = GeometricRay(h, angle)
- >>> gRay.angle
- angle
- """
- return self[1]
-
-
-###
-# Representation for gauss beam
-###
-
-class BeamParameter(Expr):
- """
- Representation for a gaussian ray in the Ray Transfer Matrix formalism.
-
- Parameters
- ==========
-
- wavelen : the wavelength,
- z : the distance to waist, and
- w : the waist, or
- z_r : the rayleigh range
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.q
- 1 + 1.88679245283019*I*pi
-
- >>> p.q.n()
- 1.0 + 5.92753330865999*I
- >>> p.w_0.n()
- 0.00100000000000000
- >>> p.z_r.n()
- 5.92753330865999
-
- >>> from sympy.physics.gaussopt import FreeSpace
- >>> fs = FreeSpace(10)
- >>> p1 = fs*p
- >>> p.w.n()
- 0.00101413072159615
- >>> p1.w.n()
- 0.00210803120913829
-
- See Also
- ========
-
- RayTransferMatrix
-
- References
- ==========
-
- .. [1] http://en.wikipedia.org/wiki/Complex_beam_parameter
- """
- #TODO A class Complex may be implemented. The BeamParameter may
- # subclass it. See:
- # https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
-
- __slots__ = ['z', 'z_r', 'wavelen']
-
- def __new__(cls, wavelen, z, **kwargs):
- wavelen, z = map(sympify, (wavelen, z))
- inst = Expr.__new__(cls, wavelen, z)
- inst.wavelen = wavelen
- inst.z = z
- if len(kwargs) != 1:
- raise ValueError('Constructor expects exactly one named argument.')
- elif 'z_r' in kwargs:
- inst.z_r = sympify(kwargs['z_r'])
- elif 'w' in kwargs:
- inst.z_r = waist2rayleigh(sympify(kwargs['w']), wavelen)
- else:
- raise ValueError('The constructor needs named argument w or z_r')
- return inst
-
- @property
- def q(self):
- """
- The complex parameter representing the beam.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.q
- 1 + 1.88679245283019*I*pi
- """
- return self.z + I*self.z_r
-
- @property
- def radius(self):
- """
- The radius of curvature of the phase front.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.radius
- 0.2809/pi**2 + 1
- """
- return self.z*(1 + (self.z/self.z_r)**2)
-
- @property
- def w(self):
- """
- The beam radius at `1/e^2` intensity.
-
- See Also
- ========
-
- w_0 : the minimal radius of beam
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.w
- 0.001*sqrt(0.2809/pi**2 + 1)
- """
- return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
-
- @property
- def w_0(self):
- """
- The beam waist (minimal radius).
-
- See Also
- ========
-
- w : the beam radius at `1/e^2` intensity
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.w_0
- 0.00100000000000000
- """
- return sqrt(self.z_r/pi*self.wavelen)
-
- @property
- def divergence(self):
- """
- Half of the total angular spread.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.divergence
- 0.00053/pi
- """
- return self.wavelen/pi/self.w_0
-
- @property
- def gouy(self):
- """
- The Gouy phase.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.gouy
- atan(0.53/pi)
- """
- return atan2(self.z, self.z_r)
-
- @property
- def waist_approximation_limit(self):
- """
- The minimal waist for which the gauss beam approximation is valid.
-
- The gauss beam is a solution to the paraxial equation. For curvatures
- that are too great it is not a valid approximation.
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import BeamParameter
- >>> p = BeamParameter(530e-9, 1, w=1e-3)
- >>> p.waist_approximation_limit
- 1.06e-6/pi
- """
- return 2*self.wavelen/pi
-
-
-###
-# Utilities
-###
-
-def waist2rayleigh(w, wavelen):
- """
- Calculate the rayleigh range from the waist of a gaussian beam.
-
- See Also
- ========
-
- rayleigh2waist, BeamParameter
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import waist2rayleigh
- >>> from sympy import symbols
- >>> w, wavelen = symbols('w wavelen')
- >>> waist2rayleigh(w, wavelen)
- pi*w**2/wavelen
- """
- w, wavelen = map(sympify, (w, wavelen))
- return w**2*pi/wavelen
-
-
-def rayleigh2waist(z_r, wavelen):
- """Calculate the waist from the rayleigh range of a gaussian beam.
-
- See Also
- ========
-
- waist2rayleigh, BeamParameter
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import rayleigh2waist
- >>> from sympy import symbols
- >>> z_r, wavelen = symbols('z_r wavelen')
- >>> rayleigh2waist(z_r, wavelen)
- sqrt(wavelen*z_r)/sqrt(pi)
- """
- z_r, wavelen = map(sympify, (z_r, wavelen))
- return sqrt(z_r/pi*wavelen)
-
-
-def geometric_conj_ab(a, b):
- """
- Conjugation relation for geometrical beams under paraxial conditions.
-
- Takes the distances to the optical element and returns the needed
- focal distance.
-
- See Also
- ========
-
- geometric_conj_af, geometric_conj_bf
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import geometric_conj_ab
- >>> from sympy import symbols
- >>> a, b = symbols('a b')
- >>> geometric_conj_ab(a, b)
- a*b/(a + b)
- """
- a, b = map(sympify, (a, b))
- if abs(a) == oo or abs(b) == oo:
- return a if abs(b) == oo else b
- else:
- return a*b/(a + b)
-
-
-def geometric_conj_af(a, f):
- """
- Conjugation relation for geometrical beams under paraxial conditions.
-
- Takes the object distance (for geometric_conj_af) or the image distance
- (for geometric_conj_bf) to the optical element and the focal distance.
- Then it returns the other distance needed for conjugation.
-
- See Also
- ========
-
- geometric_conj_ab
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import geometric_conj_af, geometric_conj_bf
- >>> from sympy import symbols
- >>> a, b, f = symbols('a b f')
- >>> geometric_conj_af(a, f)
- a*f/(a - f)
- >>> geometric_conj_bf(b, f)
- b*f/(b - f)
- """
- a, f = map(sympify, (a, f))
- return -geometric_conj_ab(a, -f)
-
-geometric_conj_bf = geometric_conj_af
-
-
-def gaussian_conj(s_in, z_r_in, f):
- """
- Conjugation relation for gaussian beams.
-
- Parameters
- ==========
-
- s_in : the distance to optical element from the waist
- z_r_in : the rayleigh range of the incident beam
- f : the focal length of the optical element
-
- Returns
- =======
-
- a tuple containing (s_out, z_r_out, m)
- s_out : the distance between the new waist and the optical element
- z_r_out : the rayleigh range of the emergent beam
- m : the ration between the new and the old waists
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import gaussian_conj
- >>> from sympy import symbols
- >>> s_in, z_r_in, f = symbols('s_in z_r_in f')
-
- >>> gaussian_conj(s_in, z_r_in, f)[0]
- 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
-
- >>> gaussian_conj(s_in, z_r_in, f)[1]
- z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
-
- >>> gaussian_conj(s_in, z_r_in, f)[2]
- 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
- """
- s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
- s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
- m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
- z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
- return (s_out, z_r_out, m)
-
-
-def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
- """
- Find the optical setup conjugating the object/image waists.
-
- Parameters
- ==========
-
- wavelen : the wavelength of the beam
- waist_in and waist_out : the waists to be conjugated
- f : the focal distance of the element used in the conjugation
-
- Returns
- =======
-
- a tuple containing (s_in, s_out, f)
- s_in : the distance before the optical element
- s_out : the distance after the optical element
- f : the focal distance of the optical element
-
- Examples
- ========
-
- >>> from sympy.physics.gaussopt import conjugate_gauss_beams
- >>> from sympy import symbols, factor
- >>> l, w_i, w_o, f = symbols('l w_i w_o f')
-
- >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
- f*(-sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
-
- >>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
- f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
- pi**2*w_i**4/(f**2*l**2)))/w_i**2
-
- >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
- f
- """
- #TODO add the other possible arguments
- wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
- m = waist_out / waist_in
- z = waist2rayleigh(waist_in, wavelen)
- if len(kwargs) != 1:
- raise ValueError("The function expects only one named argument")
- elif 'dist' in kwargs:
- raise NotImplementedError(filldedent('''
- Currently only focal length is supported as a parameter'''))
- elif 'f' in kwargs:
- f = sympify(kwargs['f'])
- s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
- s_out = gaussian_conj(s_in, z, f)[0]
- elif 's_in' in kwargs:
- raise NotImplementedError(filldedent('''
- Currently only focal length is supported as a parameter'''))
- else:
- raise ValueError(filldedent('''
- The functions expects the focal length as a named argument'''))
- return (s_in, s_out, f)
-
-#TODO
-#def plot_beam():
-# """Plot the beam radius as it propagates in space."""
-# pass
-
-#TODO
-#def plot_beam_conjugation():
-# """
-# Plot the intersection of two beams.
-#
-# Represents the conjugation relation.
-#
-# See Also
-# ========
-#
-# conjugate_gauss_beams
-# """
-# pass
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 8cd92de..5db147f 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -14,3 +14,7 @@
from . import waves
from .waves import TWave
__all__.extend(waves.__all__)
+
+from . import gaussopt
+from .gaussopt import *
+__all__.extend(gaussopt.__all__)
diff --git a/sympy/physics/optics/gaussopt.py b/sympy/physics/optics/gaussopt.py
new file mode 100644
index 0000000..4b6b062
--- /dev/null
+++ b/sympy/physics/optics/gaussopt.py
@@ -0,0 +1,875 @@
+# -*- encoding: utf-8 -*-
+"""
+Gaussian optics.
+
+The module implements:
+
+- Ray transfer matrices for geometrical and gaussian optics.
+
+ See RayTransferMatrix, GeometricRay and BeamParameter
+
+- Conjugation relations for geometrical and gaussian optics.
+
+ See geometric_conj*, gauss_conj and conjugate_gauss_beams
+
+The conventions for the distances are as follows:
+
+focal distance
+ positive for convergent lenses
+object distance
+ positive for real objects
+image distance
+ positive for real images
+"""
+
+from __future__ import print_function, division
+
+__all__ = [
+ 'RayTransferMatrix',
+ 'FreeSpace',
+ 'FlatRefraction',
+ 'CurvedRefraction',
+ 'FlatMirror',
+ 'CurvedMirror',
+ 'ThinLens',
+ 'GeometricRay',
+ 'BeamParameter',
+ 'waist2rayleigh',
+ 'rayleigh2waist',
+ 'geometric_conj_ab',
+ 'geometric_conj_af',
+ 'geometric_conj_bf',
+ 'gaussian_conj',
+ 'conjugate_gauss_beams',
+]
+
+
+from sympy import (atan2, Expr, I, im, Matrix, oo, pi, re, sqrt, sympify,
+ together)
+from sympy.utilities.misc import filldedent
+
+###
+# A, B, C, D matrices
+###
+
+
+class RayTransferMatrix(Matrix):
+ """
+ Base class for a Ray Transfer Matrix.
+
+ It should be used if there isn't already a more specific subclass mentioned
+ in See Also.
+
+ Parameters
+ ==========
+
+ parameters : A, B, C and D or 2x2 matrix (Matrix(2, 2, [A, B, C, D]))
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import RayTransferMatrix, ThinLens
+ >>> from sympy import Symbol, Matrix
+
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
+ >>> mat
+ Matrix([
+ [1, 2],
+ [3, 4]])
+
+ >>> RayTransferMatrix(Matrix([[1, 2], [3, 4]]))
+ Matrix([
+ [1, 2],
+ [3, 4]])
+
+ >>> mat.A
+ 1
+
+ >>> f = Symbol('f')
+ >>> lens = ThinLens(f)
+ >>> lens
+ Matrix([
+ [ 1, 0],
+ [-1/f, 1]])
+
+ >>> lens.C
+ -1/f
+
+ See Also
+ ========
+
+ GeometricRay, BeamParameter,
+ FreeSpace, FlatRefraction, CurvedRefraction,
+ FlatMirror, CurvedMirror, ThinLens
+
+ References
+ ==========
+
+ .. [1] http://en.wikipedia.org/wiki/Ray_transfer_matrix_analysis
+ """
+
+ def __new__(cls, *args):
+
+ if len(args) == 4:
+ temp = ((args[0], args[1]), (args[2], args[3]))
+ elif len(args) == 1 \
+ and isinstance(args[0], Matrix) \
+ and args[0].shape == (2, 2):
+ temp = args[0]
+ else:
+ raise ValueError(filldedent('''
+ Expecting 2x2 Matrix or the 4 elements of
+ the Matrix but got %s''' % str(args)))
+ return Matrix.__new__(cls, temp)
+
+ def __mul__(self, other):
+ if isinstance(other, RayTransferMatrix):
+ return RayTransferMatrix(Matrix.__mul__(self, other))
+ elif isinstance(other, GeometricRay):
+ return GeometricRay(Matrix.__mul__(self, other))
+ elif isinstance(other, BeamParameter):
+ temp = self*Matrix(((other.q,), (1,)))
+ q = (temp[0]/temp[1]).expand(complex=True)
+ return BeamParameter(other.wavelen,
+ together(re(q)),
+ z_r=together(im(q)))
+ else:
+ return Matrix.__mul__(self, other)
+
+ @property
+ def A(self):
+ """
+ The A parameter of the Matrix.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import RayTransferMatrix
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
+ >>> mat.A
+ 1
+ """
+ return self[0, 0]
+
+ @property
+ def B(self):
+ """
+ The B parameter of the Matrix.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import RayTransferMatrix
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
+ >>> mat.B
+ 2
+ """
+ return self[0, 1]
+
+ @property
+ def C(self):
+ """
+ The C parameter of the Matrix.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import RayTransferMatrix
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
+ >>> mat.C
+ 3
+ """
+ return self[1, 0]
+
+ @property
+ def D(self):
+ """
+ The D parameter of the Matrix.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import RayTransferMatrix
+ >>> mat = RayTransferMatrix(1, 2, 3, 4)
+ >>> mat.D
+ 4
+ """
+ return self[1, 1]
+
+
+class FreeSpace(RayTransferMatrix):
+ """
+ Ray Transfer Matrix for free space.
+
+ Parameters
+ ==========
+
+ distance
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import FreeSpace
+ >>> from sympy import symbols
+ >>> d = symbols('d')
+ >>> FreeSpace(d)
+ Matrix([
+ [1, d],
+ [0, 1]])
+ """
+ def __new__(cls, d):
+ return RayTransferMatrix.__new__(cls, 1, d, 0, 1)
+
+
+class FlatRefraction(RayTransferMatrix):
+ """
+ Ray Transfer Matrix for refraction.
+
+ Parameters
+ ==========
+
+ n1 : refractive index of one medium
+ n2 : refractive index of other medium
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import FlatRefraction
+ >>> from sympy import symbols
+ >>> n1, n2 = symbols('n1 n2')
+ >>> FlatRefraction(n1, n2)
+ Matrix([
+ [1, 0],
+ [0, n1/n2]])
+ """
+ def __new__(cls, n1, n2):
+ n1, n2 = map(sympify, (n1, n2))
+ return RayTransferMatrix.__new__(cls, 1, 0, 0, n1/n2)
+
+
+class CurvedRefraction(RayTransferMatrix):
+ """
+ Ray Transfer Matrix for refraction on curved interface.
+
+ Parameters
+ ==========
+
+ R : radius of curvature (positive for concave)
+ n1 : refractive index of one medium
+ n2 : refractive index of other medium
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import CurvedRefraction
+ >>> from sympy import symbols
+ >>> R, n1, n2 = symbols('R n1 n2')
+ >>> CurvedRefraction(R, n1, n2)
+ Matrix([
+ [ 1, 0],
+ [(n1 - n2)/(R*n2), n1/n2]])
+ """
+ def __new__(cls, R, n1, n2):
+ R, n1, n2 = map(sympify, (R, n1, n2))
+ return RayTransferMatrix.__new__(cls, 1, 0, (n1 - n2)/R/n2, n1/n2)
+
+
+class FlatMirror(RayTransferMatrix):
+ """
+ Ray Transfer Matrix for reflection.
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import FlatMirror
+ >>> FlatMirror()
+ Matrix([
+ [1, 0],
+ [0, 1]])
+ """
+ def __new__(cls):
+ return RayTransferMatrix.__new__(cls, 1, 0, 0, 1)
+
+
+class CurvedMirror(RayTransferMatrix):
+ """
+ Ray Transfer Matrix for reflection from curved surface.
+
+ Parameters
+ ==========
+
+ R : radius of curvature (positive for concave)
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import CurvedMirror
+ >>> from sympy import symbols
+ >>> R = symbols('R')
+ >>> CurvedMirror(R)
+ Matrix([
+ [ 1, 0],
+ [-2/R, 1]])
+ """
+ def __new__(cls, R):
+ R = sympify(R)
+ return RayTransferMatrix.__new__(cls, 1, 0, -2/R, 1)
+
+
+class ThinLens(RayTransferMatrix):
+ """
+ Ray Transfer Matrix for a thin lens.
+
+ Parameters
+ ==========
+
+ f : the focal distance
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import ThinLens
+ >>> from sympy import symbols
+ >>> f = symbols('f')
+ >>> ThinLens(f)
+ Matrix([
+ [ 1, 0],
+ [-1/f, 1]])
+ """
+ def __new__(cls, f):
+ f = sympify(f)
+ return RayTransferMatrix.__new__(cls, 1, 0, -1/f, 1)
+
+
+###
+# Representation for geometric ray
+###
+
+class GeometricRay(Matrix):
+ """
+ Representation for a geometric ray in the Ray Transfer Matrix formalism.
+
+ Parameters
+ ==========
+
+ h : height, and
+ angle : angle, or
+ matrix : a 2x1 matrix (Matrix(2, 1, [height, angle]))
+
+ Examples
+ =======
+
+ >>> from sympy.physics.optics import GeometricRay, FreeSpace
+ >>> from sympy import symbols, Matrix
+ >>> d, h, angle = symbols('d, h, angle')
+
+ >>> GeometricRay(h, angle)
+ Matrix([
+ [ h],
+ [angle]])
+
+ >>> FreeSpace(d)*GeometricRay(h, angle)
+ Matrix([
+ [angle*d + h],
+ [ angle]])
+
+ >>> GeometricRay( Matrix( ((h,), (angle,)) ) )
+ Matrix([
+ [ h],
+ [angle]])
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ """
+
+ def __new__(cls, *args):
+ if len(args) == 1 and isinstance(args[0], Matrix) \
+ and args[0].shape == (2, 1):
+ temp = args[0]
+ elif len(args) == 2:
+ temp = ((args[0],), (args[1],))
+ else:
+ raise ValueError(filldedent('''
+ Expecting 2x1 Matrix or the 2 elements of
+ the Matrix but got %s''' % str(args)))
+ return Matrix.__new__(cls, temp)
+
+ @property
+ def height(self):
+ """
+ The distance from the optical axis.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import GeometricRay
+ >>> from sympy import symbols
+ >>> h, angle = symbols('h, angle')
+ >>> gRay = GeometricRay(h, angle)
+ >>> gRay.height
+ h
+ """
+ return self[0]
+
+ @property
+ def angle(self):
+ """
+ The angle with the optical axis.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import GeometricRay
+ >>> from sympy import symbols
+ >>> h, angle = symbols('h, angle')
+ >>> gRay = GeometricRay(h, angle)
+ >>> gRay.angle
+ angle
+ """
+ return self[1]
+
+
+###
+# Representation for gauss beam
+###
+
+class BeamParameter(Expr):
+ """
+ Representation for a gaussian ray in the Ray Transfer Matrix formalism.
+
+ Parameters
+ ==========
+
+ wavelen : the wavelength,
+ z : the distance to waist, and
+ w : the waist, or
+ z_r : the rayleigh range
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.q
+ 1 + 1.88679245283019*I*pi
+
+ >>> p.q.n()
+ 1.0 + 5.92753330865999*I
+ >>> p.w_0.n()
+ 0.00100000000000000
+ >>> p.z_r.n()
+ 5.92753330865999
+
+ >>> from sympy.physics.optics import FreeSpace
+ >>> fs = FreeSpace(10)
+ >>> p1 = fs*p
+ >>> p.w.n()
+ 0.00101413072159615
+ >>> p1.w.n()
+ 0.00210803120913829
+
+ See Also
+ ========
+
+ RayTransferMatrix
+
+ References
+ ==========
+
+ .. [1] http://en.wikipedia.org/wiki/Complex_beam_parameter
+ """
+ #TODO A class Complex may be implemented. The BeamParameter may
+ # subclass it. See:
+ # https://groups.google.com/d/topic/sympy/7XkU07NRBEs/discussion
+
+ __slots__ = ['z', 'z_r', 'wavelen']
+
+ def __new__(cls, wavelen, z, **kwargs):
+ wavelen, z = map(sympify, (wavelen, z))
+ inst = Expr.__new__(cls, wavelen, z)
+ inst.wavelen = wavelen
+ inst.z = z
+ if len(kwargs) != 1:
+ raise ValueError('Constructor expects exactly one named argument.')
+ elif 'z_r' in kwargs:
+ inst.z_r = sympify(kwargs['z_r'])
+ elif 'w' in kwargs:
+ inst.z_r = waist2rayleigh(sympify(kwargs['w']), wavelen)
+ else:
+ raise ValueError('The constructor needs named argument w or z_r')
+ return inst
+
+ @property
+ def q(self):
+ """
+ The complex parameter representing the beam.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.q
+ 1 + 1.88679245283019*I*pi
+ """
+ return self.z + I*self.z_r
+
+ @property
+ def radius(self):
+ """
+ The radius of curvature of the phase front.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.radius
+ 0.2809/pi**2 + 1
+ """
+ return self.z*(1 + (self.z/self.z_r)**2)
+
+ @property
+ def w(self):
+ """
+ The beam radius at `1/e^2` intensity.
+
+ See Also
+ ========
+
+ w_0 : the minimal radius of beam
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.w
+ 0.001*sqrt(0.2809/pi**2 + 1)
+ """
+ return self.w_0*sqrt(1 + (self.z/self.z_r)**2)
+
+ @property
+ def w_0(self):
+ """
+ The beam waist (minimal radius).
+
+ See Also
+ ========
+
+ w : the beam radius at `1/e^2` intensity
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.w_0
+ 0.00100000000000000
+ """
+ return sqrt(self.z_r/pi*self.wavelen)
+
+ @property
+ def divergence(self):
+ """
+ Half of the total angular spread.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.divergence
+ 0.00053/pi
+ """
+ return self.wavelen/pi/self.w_0
+
+ @property
+ def gouy(self):
+ """
+ The Gouy phase.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.gouy
+ atan(0.53/pi)
+ """
+ return atan2(self.z, self.z_r)
+
+ @property
+ def waist_approximation_limit(self):
+ """
+ The minimal waist for which the gauss beam approximation is valid.
+
+ The gauss beam is a solution to the paraxial equation. For curvatures
+ that are too great it is not a valid approximation.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import BeamParameter
+ >>> p = BeamParameter(530e-9, 1, w=1e-3)
+ >>> p.waist_approximation_limit
+ 1.06e-6/pi
+ """
+ return 2*self.wavelen/pi
+
+
+###
+# Utilities
+###
+
+def waist2rayleigh(w, wavelen):
+ """
+ Calculate the rayleigh range from the waist of a gaussian beam.
+
+ See Also
+ ========
+
+ rayleigh2waist, BeamParameter
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import waist2rayleigh
+ >>> from sympy import symbols
+ >>> w, wavelen = symbols('w wavelen')
+ >>> waist2rayleigh(w, wavelen)
+ pi*w**2/wavelen
+ """
+ w, wavelen = map(sympify, (w, wavelen))
+ return w**2*pi/wavelen
+
+
+def rayleigh2waist(z_r, wavelen):
+ """Calculate the waist from the rayleigh range of a gaussian beam.
+
+ See Also
+ ========
+
+ waist2rayleigh, BeamParameter
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import rayleigh2waist
+ >>> from sympy import symbols
+ >>> z_r, wavelen = symbols('z_r wavelen')
+ >>> rayleigh2waist(z_r, wavelen)
+ sqrt(wavelen*z_r)/sqrt(pi)
+ """
+ z_r, wavelen = map(sympify, (z_r, wavelen))
+ return sqrt(z_r/pi*wavelen)
+
+
+def geometric_conj_ab(a, b):
+ """
+ Conjugation relation for geometrical beams under paraxial conditions.
+
+ Takes the distances to the optical element and returns the needed
+ focal distance.
+
+ See Also
+ ========
+
+ geometric_conj_af, geometric_conj_bf
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import geometric_conj_ab
+ >>> from sympy import symbols
+ >>> a, b = symbols('a b')
+ >>> geometric_conj_ab(a, b)
+ a*b/(a + b)
+ """
+ a, b = map(sympify, (a, b))
+ if abs(a) == oo or abs(b) == oo:
+ return a if abs(b) == oo else b
+ else:
+ return a*b/(a + b)
+
+
+def geometric_conj_af(a, f):
+ """
+ Conjugation relation for geometrical beams under paraxial conditions.
+
+ Takes the object distance (for geometric_conj_af) or the image distance
+ (for geometric_conj_bf) to the optical element and the focal distance.
+ Then it returns the other distance needed for conjugation.
+
+ See Also
+ ========
+
+ geometric_conj_ab
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics.gaussopt import geometric_conj_af, geometric_conj_bf
+ >>> from sympy import symbols
+ >>> a, b, f = symbols('a b f')
+ >>> geometric_conj_af(a, f)
+ a*f/(a - f)
+ >>> geometric_conj_bf(b, f)
+ b*f/(b - f)
+ """
+ a, f = map(sympify, (a, f))
+ return -geometric_conj_ab(a, -f)
+
+geometric_conj_bf = geometric_conj_af
+
+
+def gaussian_conj(s_in, z_r_in, f):
+ """
+ Conjugation relation for gaussian beams.
+
+ Parameters
+ ==========
+
+ s_in : the distance to optical element from the waist
+ z_r_in : the rayleigh range of the incident beam
+ f : the focal length of the optical element
+
+ Returns
+ =======
+
+ a tuple containing (s_out, z_r_out, m)
+ s_out : the distance between the new waist and the optical element
+ z_r_out : the rayleigh range of the emergent beam
+ m : the ration between the new and the old waists
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import gaussian_conj
+ >>> from sympy import symbols
+ >>> s_in, z_r_in, f = symbols('s_in z_r_in f')
+
+ >>> gaussian_conj(s_in, z_r_in, f)[0]
+ 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
+
+ >>> gaussian_conj(s_in, z_r_in, f)[1]
+ z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
+
+ >>> gaussian_conj(s_in, z_r_in, f)[2]
+ 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
+ """
+ s_in, z_r_in, f = map(sympify, (s_in, z_r_in, f))
+ s_out = 1 / ( -1/(s_in + z_r_in**2/(s_in - f)) + 1/f )
+ m = 1/sqrt((1 - (s_in/f)**2) + (z_r_in/f)**2)
+ z_r_out = z_r_in / ((1 - (s_in/f)**2) + (z_r_in/f)**2)
+ return (s_out, z_r_out, m)
+
+
+def conjugate_gauss_beams(wavelen, waist_in, waist_out, **kwargs):
+ """
+ Find the optical setup conjugating the object/image waists.
+
+ Parameters
+ ==========
+
+ wavelen : the wavelength of the beam
+ waist_in and waist_out : the waists to be conjugated
+ f : the focal distance of the element used in the conjugation
+
+ Returns
+ =======
+
+ a tuple containing (s_in, s_out, f)
+ s_in : the distance before the optical element
+ s_out : the distance after the optical element
+ f : the focal distance of the optical element
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import conjugate_gauss_beams
+ >>> from sympy import symbols, factor
+ >>> l, w_i, w_o, f = symbols('l w_i w_o f')
+
+ >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[0]
+ f*(-sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
+
+ >>> factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1])
+ f*w_o**2*(w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 -
+ pi**2*w_i**4/(f**2*l**2)))/w_i**2
+
+ >>> conjugate_gauss_beams(l, w_i, w_o, f=f)[2]
+ f
+ """
+ #TODO add the other possible arguments
+ wavelen, waist_in, waist_out = map(sympify, (wavelen, waist_in, waist_out))
+ m = waist_out / waist_in
+ z = waist2rayleigh(waist_in, wavelen)
+ if len(kwargs) != 1:
+ raise ValueError("The function expects only one named argument")
+ elif 'dist' in kwargs:
+ raise NotImplementedError(filldedent('''
+ Currently only focal length is supported as a parameter'''))
+ elif 'f' in kwargs:
+ f = sympify(kwargs['f'])
+ s_in = f * (1 - sqrt(1/m**2 - z**2/f**2))
+ s_out = gaussian_conj(s_in, z, f)[0]
+ elif 's_in' in kwargs:
+ raise NotImplementedError(filldedent('''
+ Currently only focal length is supported as a parameter'''))
+ else:
+ raise ValueError(filldedent('''
+ The functions expects the focal length as a named argument'''))
+ return (s_in, s_out, f)
+
+#TODO
+#def plot_beam():
+# """Plot the beam radius as it propagates in space."""
+# pass
+
+#TODO
+#def plot_beam_conjugation():
+# """
+# Plot the intersection of two beams.
+#
+# Represents the conjugation relation.
+#
+# See Also
+# ========
+#
+# conjugate_gauss_beams
+# """
+# pass
diff --git a/sympy/physics/optics/tests/test_gaussopt.py b/sympy/physics/optics/tests/test_gaussopt.py
new file mode 100644
index 0000000..ce7a92e
--- /dev/null
+++ b/sympy/physics/optics/tests/test_gaussopt.py
@@ -0,0 +1,91 @@
+from sympy import atan2, factor, Float, I, Matrix, N, oo, pi, sqrt, symbols
+
+from sympy.physics.optics import (BeamParameter, CurvedMirror,
+ CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
+ RayTransferMatrix, ThinLens, conjugate_gauss_beams,
+ gaussian_conj, geometric_conj_ab, geometric_conj_af, geometric_conj_bf,
+ rayleigh2waist, waist2rayleigh)
+
+
+def streq(a, b):
+ return str(a) == str(b)
+
+
+def test_gauss_opt():
+ mat = RayTransferMatrix(1, 2, 3, 4)
+ assert mat == Matrix([[1, 2], [3, 4]])
+ assert mat == RayTransferMatrix( Matrix([[1, 2], [3, 4]]) )
+ assert [mat.A, mat.B, mat.C, mat.D] == [1, 2, 3, 4]
+
+ d, f, h, n1, n2, R = symbols('d f h n1 n2 R')
+ lens = ThinLens(f)
+ assert lens == Matrix([[ 1, 0], [-1/f, 1]])
+ assert lens.C == -1/f
+ assert FreeSpace(d) == Matrix([[ 1, d], [0, 1]])
+ assert FlatRefraction(n1, n2) == Matrix([[1, 0], [0, n1/n2]])
+ assert CurvedRefraction(
+ R, n1, n2) == Matrix([[1, 0], [(n1 - n2)/(R*n2), n1/n2]])
+ assert FlatMirror() == Matrix([[1, 0], [0, 1]])
+ assert CurvedMirror(R) == Matrix([[ 1, 0], [-2/R, 1]])
+ assert ThinLens(f) == Matrix([[ 1, 0], [-1/f, 1]])
+
+ mul = CurvedMirror(R)*FreeSpace(d)
+ mul_mat = Matrix([[ 1, 0], [-2/R, 1]])*Matrix([[ 1, d], [0, 1]])
+ assert mul.A == mul_mat[0, 0]
+ assert mul.B == mul_mat[0, 1]
+ assert mul.C == mul_mat[1, 0]
+ assert mul.D == mul_mat[1, 1]
+
+ angle = symbols('angle')
+ assert GeometricRay(h, angle) == Matrix([[ h], [angle]])
+ assert FreeSpace(
+ d)*GeometricRay(h, angle) == Matrix([[angle*d + h], [angle]])
+ assert GeometricRay( Matrix( ((h,), (angle,)) ) ) == Matrix([[h], [angle]])
+ assert (FreeSpace(d)*GeometricRay(h, angle)).height == angle*d + h
+ assert (FreeSpace(d)*GeometricRay(h, angle)).angle == angle
+
+ p = BeamParameter(530e-9, 1, w=1e-3)
+ assert streq(p.q, 1 + 1.88679245283019*I*pi)
+ assert streq(N(p.q), 1.0 + 5.92753330865999*I)
+ assert streq(N(p.w_0), Float(0.00100000000000000))
+ assert streq(N(p.z_r), Float(5.92753330865999))
+ fs = FreeSpace(10)
+ p1 = fs*p
+ assert streq(N(p.w), Float(0.00101413072159615))
+ assert streq(N(p1.w), Float(0.00210803120913829))
+
+ w, wavelen = symbols('w wavelen')
+ assert waist2rayleigh(w, wavelen) == pi*w**2/wavelen
+ z_r, wavelen = symbols('z_r wavelen')
+ assert rayleigh2waist(z_r, wavelen) == sqrt(wavelen*z_r)/sqrt(pi)
+
+ a, b, f = symbols('a b f')
+ assert geometric_conj_ab(a, b) == a*b/(a + b)
+ assert geometric_conj_af(a, f) == a*f/(a - f)
+ assert geometric_conj_bf(b, f) == b*f/(b - f)
+ assert geometric_conj_ab(oo, b) == b
+ assert geometric_conj_ab(a, oo) == a
+
+ s_in, z_r_in, f = symbols('s_in z_r_in f')
+ assert gaussian_conj(
+ s_in, z_r_in, f)[0] == 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
+ assert gaussian_conj(
+ s_in, z_r_in, f)[1] == z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
+ assert gaussian_conj(
+ s_in, z_r_in, f)[2] == 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
+
+ l, w_i, w_o, f = symbols('l w_i w_o f')
+ assert conjugate_gauss_beams(l, w_i, w_o, f=f)[0] == f*(
+ -sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
+ assert factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) == f*w_o**2*(
+ w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2
+ assert conjugate_gauss_beams(l, w_i, w_o, f=f)[2] == f
+
+ z, l, w = symbols('z l r', positive=True)
+ p = BeamParameter(l, z, w=w)
+ assert p.radius == z*(l**2*z**2/(pi**2*w**4) + 1)
+ assert p.w == w*sqrt(l**2*z**2/(pi**2*w**4) + 1)
+ assert p.w_0 == w
+ assert p.divergence == l/(pi*w)
+ assert p.gouy == atan2(z, pi*w**2/l)
+ assert p.waist_approximation_limit == 2*l/pi
diff --git a/sympy/physics/tests/test_gaussopt.py b/sympy/physics/tests/test_gaussopt.py
deleted file mode 100644
index b6ee754..0000000
--- a/sympy/physics/tests/test_gaussopt.py
+++ /dev/null
@@ -1,91 +0,0 @@
-from sympy import atan2, factor, Float, I, Matrix, N, oo, pi, sqrt, symbols
-
-from sympy.physics.gaussopt import (BeamParameter, CurvedMirror,
- CurvedRefraction, FlatMirror, FlatRefraction, FreeSpace, GeometricRay,
- RayTransferMatrix, ThinLens, conjugate_gauss_beams,
- gaussian_conj, geometric_conj_ab, geometric_conj_af, geometric_conj_bf,
- rayleigh2waist, waist2rayleigh)
-
-
-def streq(a, b):
- return str(a) == str(b)
-
-
-def test_gauss_opt():
- mat = RayTransferMatrix(1, 2, 3, 4)
- assert mat == Matrix([[1, 2], [3, 4]])
- assert mat == RayTransferMatrix( Matrix([[1, 2], [3, 4]]) )
- assert [mat.A, mat.B, mat.C, mat.D] == [1, 2, 3, 4]
-
- d, f, h, n1, n2, R = symbols('d f h n1 n2 R')
- lens = ThinLens(f)
- assert lens == Matrix([[ 1, 0], [-1/f, 1]])
- assert lens.C == -1/f
- assert FreeSpace(d) == Matrix([[ 1, d], [0, 1]])
- assert FlatRefraction(n1, n2) == Matrix([[1, 0], [0, n1/n2]])
- assert CurvedRefraction(
- R, n1, n2) == Matrix([[1, 0], [(n1 - n2)/(R*n2), n1/n2]])
- assert FlatMirror() == Matrix([[1, 0], [0, 1]])
- assert CurvedMirror(R) == Matrix([[ 1, 0], [-2/R, 1]])
- assert ThinLens(f) == Matrix([[ 1, 0], [-1/f, 1]])
-
- mul = CurvedMirror(R)*FreeSpace(d)
- mul_mat = Matrix([[ 1, 0], [-2/R, 1]])*Matrix([[ 1, d], [0, 1]])
- assert mul.A == mul_mat[0, 0]
- assert mul.B == mul_mat[0, 1]
- assert mul.C == mul_mat[1, 0]
- assert mul.D == mul_mat[1, 1]
-
- angle = symbols('angle')
- assert GeometricRay(h, angle) == Matrix([[ h], [angle]])
- assert FreeSpace(
- d)*GeometricRay(h, angle) == Matrix([[angle*d + h], [angle]])
- assert GeometricRay( Matrix( ((h,), (angle,)) ) ) == Matrix([[h], [angle]])
- assert (FreeSpace(d)*GeometricRay(h, angle)).height == angle*d + h
- assert (FreeSpace(d)*GeometricRay(h, angle)).angle == angle
-
- p = BeamParameter(530e-9, 1, w=1e-3)
- assert streq(p.q, 1 + 1.88679245283019*I*pi)
- assert streq(N(p.q), 1.0 + 5.92753330865999*I)
- assert streq(N(p.w_0), Float(0.00100000000000000))
- assert streq(N(p.z_r), Float(5.92753330865999))
- fs = FreeSpace(10)
- p1 = fs*p
- assert streq(N(p.w), Float(0.00101413072159615))
- assert streq(N(p1.w), Float(0.00210803120913829))
-
- w, wavelen = symbols('w wavelen')
- assert waist2rayleigh(w, wavelen) == pi*w**2/wavelen
- z_r, wavelen = symbols('z_r wavelen')
- assert rayleigh2waist(z_r, wavelen) == sqrt(wavelen*z_r)/sqrt(pi)
-
- a, b, f = symbols('a b f')
- assert geometric_conj_ab(a, b) == a*b/(a + b)
- assert geometric_conj_af(a, f) == a*f/(a - f)
- assert geometric_conj_bf(b, f) == b*f/(b - f)
- assert geometric_conj_ab(oo, b) == b
- assert geometric_conj_ab(a, oo) == a
-
- s_in, z_r_in, f = symbols('s_in z_r_in f')
- assert gaussian_conj(
- s_in, z_r_in, f)[0] == 1/(-1/(s_in + z_r_in**2/(-f + s_in)) + 1/f)
- assert gaussian_conj(
- s_in, z_r_in, f)[1] == z_r_in/(1 - s_in**2/f**2 + z_r_in**2/f**2)
- assert gaussian_conj(
- s_in, z_r_in, f)[2] == 1/sqrt(1 - s_in**2/f**2 + z_r_in**2/f**2)
-
- l, w_i, w_o, f = symbols('l w_i w_o f')
- assert conjugate_gauss_beams(l, w_i, w_o, f=f)[0] == f*(
- -sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)) + 1)
- assert factor(conjugate_gauss_beams(l, w_i, w_o, f=f)[1]) == f*w_o**2*(
- w_i**2/w_o**2 - sqrt(w_i**2/w_o**2 - pi**2*w_i**4/(f**2*l**2)))/w_i**2
- assert conjugate_gauss_beams(l, w_i, w_o, f=f)[2] == f
-
- z, l, w = symbols('z l r', positive=True)
- p = BeamParameter(l, z, w=w)
- assert p.radius == z*(l**2*z**2/(pi**2*w**4) + 1)
- assert p.w == w*sqrt(l**2*z**2/(pi**2*w**4) + 1)
- assert p.w_0 == w
- assert p.divergence == l/(pi*w)
- assert p.gouy == atan2(z, pi*w**2/l)
- assert p.waist_approximation_limit == 2*l/pi
commit 9682009f1af0b3145b61bb78de222c7df41f01a5
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Thu Jun 19 08:44:46 2014 +0530
Correct center shift part
diff --git a/sympy/geometry/ellipse.py b/sympy/geometry/ellipse.py
index d4071f8..518ee3f 100644
--- a/sympy/geometry/ellipse.py
+++ b/sympy/geometry/ellipse.py
@@ -1209,13 +1209,13 @@ def evolute(self, x='x', y='y'):
>>> from sympy import Point, Ellipse
>>> e1 = Ellipse(Point(1, 0), 3, 2)
>>> e1.evolute()
- 3**(2/3)*x**(2/3) + 2**(2/3)*y**(2/3) - 5**(2/3)
+ 2**(2/3)*y**(2/3) + (3*x - 3)**(2/3) - 5**(2/3)
"""
x = _symbol(x)
y = _symbol(y)
- return (self.hradius*x)**Rational(2, 3) + \
- (self.vradius*y)**Rational(2, 3) -\
- (self.hradius**2 - self.vradius**2)**Rational(2, 3)
+ t1 = (self.hradius*(x - self.center.x))**Rational(2, 3)
+ t2 = (self.vradius*(y - self.center.y))**Rational(2, 3)
+ return t1 + t2 - (self.hradius**2 - self.vradius**2)**Rational(2, 3)
def __eq__(self, o):
"""Is the other GeometryEntity the same as this ellipse?"""
commit 5a8a05eabf011af1bfb7fc55d9e64a3a4e4c159d
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Thu Jun 19 05:11:05 2014 +0530
Add evolute method to calculate evolute of an ellipse
diff --git a/sympy/geometry/ellipse.py b/sympy/geometry/ellipse.py
index 60ec9db..d4071f8 100644
--- a/sympy/geometry/ellipse.py
+++ b/sympy/geometry/ellipse.py
@@ -10,7 +10,7 @@
from sympy.core import S, C, sympify, pi, Dummy
from sympy.core.logic import fuzzy_bool
-from sympy.core.numbers import oo, zoo
+from sympy.core.numbers import oo, zoo, Rational
from sympy.simplify import simplify, trigsimp
from sympy.functions.elementary.miscellaneous import sqrt, Max, Min
from sympy.functions.elementary.complexes import im
@@ -1187,6 +1187,36 @@ def intersection(self, o):
return o.intersection(self)
+ def evolute(self, x='x', y='y'):
+ """The equation of evolute of the ellipse.
+
+ Parameters
+ ==========
+
+ x : str, optional
+ Label for the x-axis. Default value is 'x'.
+ y : str, optional
+ Label for the y-axis. Default value is 'y'.
+
+ Returns
+ =======
+
+ equation : sympy expression
+
+ Examples
+ ========
+
+ >>> from sympy import Point, Ellipse
+ >>> e1 = Ellipse(Point(1, 0), 3, 2)
+ >>> e1.evolute()
+ 3**(2/3)*x**(2/3) + 2**(2/3)*y**(2/3) - 5**(2/3)
+ """
+ x = _symbol(x)
+ y = _symbol(y)
+ return (self.hradius*x)**Rational(2, 3) + \
+ (self.vradius*y)**Rational(2, 3) -\
+ (self.hradius**2 - self.vradius**2)**Rational(2, 3)
+
def __eq__(self, o):
"""Is the other GeometryEntity the same as this ellipse?"""
return isinstance(o, GeometryEntity) and (self.center == o.center and
commit 20c414707a56c3fa9a625453fa7e8a5278a8ddef
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jun 18 22:29:56 2014 +0530
Remove unnecessary flag and change default params
diff --git a/sympy/physics/optics/medium.py b/sympy/physics/optics/medium.py
index ebff2d4..34014e4 100644
--- a/sympy/physics/optics/medium.py
+++ b/sympy/physics/optics/medium.py
@@ -22,8 +22,8 @@ class Medium(Symbol):
waves propagate in it.
- Prameters
- =========
+ Parameters
+ ==========
name: string
The display name of the Medium.
@@ -58,27 +58,24 @@ class Medium(Symbol):
"""
- def __new__(cls, name, permittivity=e0, permeability=u0, n=None):
+ def __new__(cls, name, permittivity=None, permeability=None, n=None):
obj = super(Medium, cls).__new__(cls, name)
obj._permittivity = sympify(permittivity)
obj._permeability = sympify(permeability)
obj._n = sympify(n)
if n is not None:
- if permittivity != e0 and permeability == u0:
+ if permittivity != None and permeability == None:
obj._permeability = n**2/(c**2*obj._permittivity)
- if permeability != u0 and permittivity == e0:
+ if permeability != None and permittivity == None:
obj._permittivity = n**2/(c**2*obj._permeability)
- # XXX: There's issue with precision. Values may be
- # different slightly.
- #if permittivity != u0 and permittivity != e0:
- # if n != c*sqrt(permittivity*permeability):
- # raise ValueError("Values are not consistent.")
- else:
+ if permittivity != None and permittivity != None:
+ if abs(n - c*sqrt(obj._permittivity*obj._permeability)) > 1e-6:
+ raise ValueError("Values are not consistent.")
+ elif permittivity is not None and permeability is not None:
obj._n = c*sqrt(permittivity*permeability)
- if n is None and permittivity == e0 and permeability == u0:
- obj._flag = False
- else:
- obj._flag = True
+ elif permittivity is None and permeability is None:
+ obj._permittivity = e0
+ obj._permeability = u0
return obj
@property
diff --git a/sympy/physics/optics/tests/test_medium.py b/sympy/physics/optics/tests/test_medium.py
index 09b9467..83084c0 100644
--- a/sympy/physics/optics/tests/test_medium.py
+++ b/sympy/physics/optics/tests/test_medium.py
@@ -30,9 +30,7 @@ def test_medium():
assert m4 < m1
m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
assert simplify(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) == 0
- # XXX: This is supposed to be zero but it turns out to be
- # very close to zero and not zero.
- # assert simplify(m5.speed - 225407863.157895*m/s) == 0
+ assert abs(m5.speed - 225407863.157895*m/s) < 1e-6*m/s
assert simplify(m5.refractive_index - 1.33000000000000) == 0
assert simplify(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) == 0
assert simplify(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) == 0
commit eb1a46d10962c747592845e500326bbaa647e628
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 10 17:23:46 2014 +0530
Add spatial component in representation
Add rewrite as exp function
Add more tests
diff --git a/sympy/physics/optics/tests/test_waves.py b/sympy/physics/optics/tests/test_waves.py
index 7f9ec6a..3782718 100644
--- a/sympy/physics/optics/tests/test_waves.py
+++ b/sympy/physics/optics/tests/test_waves.py
@@ -1,14 +1,18 @@
from sympy import (symbols, Symbol, pi, sqrt, cos, sin, Derivative,
- Function, simplify)
+ Function, simplify, C, I)
from sympy.abc import x, epsilon, mu
+from sympy.physics.units import c, m, s
from sympy.physics.optics import TWave
def test_twave():
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
- c = Symbol('c') # Speed of light in vacuum
n = Symbol('n') # Refractive index
t = Symbol('t') # Time
+ x = Symbol('x') # Spatial varaible
+ k = Symbol('k') # Wave number
+ E = Function('E')
+ exp = C.exp
w1 = TWave(A1, f, phi1)
w2 = TWave(A2, f, phi2)
assert w1.amplitude == A1
@@ -24,7 +28,9 @@ def test_twave():
assert w3.angular_velocity == 2*pi*f
assert w3.wavenumber == 2*pi*f*n/c
assert simplify(w3.rewrite('sin') - sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
- + A2**2)*sin(2*pi*f*t + phi1 + phi2 + pi/2)) == 0
- E = Function('E')
+ + A2**2)*sin(pi*f*n*x*s/(149896229*m) - 2*pi*f*t + phi1 + 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(2*pi*f*t + phi1 + phi2)
+ 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 + phi1 + 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 + phi1 + phi2))
diff --git a/sympy/physics/optics/waves.py b/sympy/physics/optics/waves.py
index 89f49fc..7f5ab90 100644
--- a/sympy/physics/optics/waves.py
+++ b/sympy/physics/optics/waves.py
@@ -13,18 +13,20 @@
from sympy import (sympify, pi, sin, cos, sqrt, simplify, Symbol, S, C, I,
symbols, Derivative)
from sympy.core.expr import Expr
+from sympy.physics.units import c
class TWave(Expr):
r"""
- This is a simple transverse wave travelling in a two dimensional space.
+ This is a simple transverse sine wave travelling in a one dimensional space.
Basic properties are required at the time of creation of the object but
they can be changed later with respective methods provided.
- It has been represented as :math:`A \times cos(\omega \times t + \phi )`
- where :math:`A` is amplitude, :math:`\omega` is angular velocity and
- :math:`\phi` is phase angle of the wave.
+ It has been represented as :math:`A \times cos(k*x - \omega \times t + \phi )`
+ where :math:`A` is amplitude, :math:`\omega` is angular velocity, :math:`k`is
+ wavenumber, :math:`x` is a spatial variable to represent the position on the
+ dimension on which the wave propagates and :math:`\phi` is phase angle of the wave.
Arguments
@@ -65,7 +67,7 @@ class TWave(Expr):
>>> w3.phase
phi1 + phi2
>>> w3.speed
- c/n
+ 299792458*m/(n*s)
>>> w3.angular_velocity
2*pi*f
@@ -88,7 +90,6 @@ def __init__(
self._phase = phase
self._time_period = time_period
self._n = n
- self.c = Symbol('c') # Speed of light in vacuum
if time_period is not None:
self._frequency = 1/self._time_period
if frequency is not None:
@@ -147,9 +148,9 @@ def wavelength(self):
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavelength
- c/(f*n)
+ 299792458*m/(f*n*s)
"""
- return self.c/(self._frequency*self._n)
+ return c/(self._frequency*self._n)
@property
def amplitude(self):
@@ -199,7 +200,7 @@ def speed(self):
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.speed
- c/n
+ 299792458*m/(n*s)
"""
return self.wavelength*self._frequency
@@ -233,7 +234,7 @@ def wavenumber(self):
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavenumber
- 2*pi*f*n/c
+ pi*f*n*s/(149896229*m)
"""
return 2*pi/self.wavelength
@@ -261,13 +262,21 @@ def __add__(self, other):
raise TypeError(type(other).__name__ + " and TWave objects can't be added.")
def _eval_rewrite_as_sin(self, *args):
- return self._amplitude*sin(self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False)
+ return self._amplitude*sin(self.wavenumber*Symbol('x')
+ - self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False)
def _eval_rewrite_as_cos(self, *args):
- return self._amplitude*cos(self.angular_velocity*Symbol('t') + self._phase)
+ return self._amplitude*cos(self.wavenumber*Symbol('x')
+ - self.angular_velocity*Symbol('t') + self._phase)
def _eval_rewrite_as_pde(self, *args):
from sympy import Function
mu, epsilon, x, t = symbols('mu, epsilon, x, t')
E = Function('E')
return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
+
+ def _eval_rewrite_as_exp(self, *args):
+ from sympy import C, I
+ exp = C.exp
+ return self._amplitude*exp(I*(self.wavenumber*Symbol('x')
+ - self.angular_velocity*Symbol('t') + self._phase))
commit 9a55d392cd4049f33067a556326507f6712a6040
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 10 16:51:25 2014 +0530
Add note for the commented failing test
diff --git a/sympy/physics/optics/medium.py b/sympy/physics/optics/medium.py
index 3158d45..ebff2d4 100644
--- a/sympy/physics/optics/medium.py
+++ b/sympy/physics/optics/medium.py
@@ -34,6 +34,9 @@ class Medium(Symbol):
permeability: Sympifyable
Magnetic permeability of the space.
+ n: Sympifyable
+ Index of refraction of the medium.
+
Examples
========
@@ -67,7 +70,6 @@ def __new__(cls, name, permittivity=e0, permeability=u0, n=None):
obj._permittivity = n**2/(c**2*obj._permeability)
# XXX: There's issue with precision. Values may be
# different slightly.
- #
#if permittivity != u0 and permittivity != e0:
# if n != c*sqrt(permittivity*permeability):
# raise ValueError("Values are not consistent.")
diff --git a/sympy/physics/optics/tests/test_medium.py b/sympy/physics/optics/tests/test_medium.py
index 25ff915..09b9467 100644
--- a/sympy/physics/optics/tests/test_medium.py
+++ b/sympy/physics/optics/tests/test_medium.py
@@ -30,6 +30,8 @@ def test_medium():
assert m4 < m1
m5 = Medium('m5', permittivity=710*10**(-12)*s**4*A**2/(m**3*kg), n=1.33)
assert simplify(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) == 0
+ # XXX: This is supposed to be zero but it turns out to be
+ # very close to zero and not zero.
# assert simplify(m5.speed - 225407863.157895*m/s) == 0
assert simplify(m5.refractive_index - 1.33000000000000) == 0
assert simplify(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) == 0
commit bcf53c8d34eda777d25bb011049958fc588aab98
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 10 12:11:48 2014 +0530
Add args test for Medium
diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index 2dfb68d..d4b2abe 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -3175,3 +3175,7 @@ def test_sympy__physics__optics__waves__TWave():
from sympy.physics.optics import TWave
A, f, phi = symbols('A, f, phi')
assert _test_args(TWave(A, f, phi))
+
+def test_sympy__physics__optics__medium__Medium():
+ from sympy.physics.optics import Medium
+ assert _test_args(Medium('m'))
commit ae13e53970e7f700c6d8a529a6eea70ba65ee26e
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 10 03:28:25 2014 +0530
Add tests for medium
diff --git a/sympy/physics/optics/tests/test_medium.py b/sympy/physics/optics/tests/test_medium.py
new file mode 100644
index 0000000..25ff915
--- /dev/null
+++ b/sympy/physics/optics/tests/test_medium.py
@@ -0,0 +1,36 @@
+from __future__ import division
+
+from sympy import symbols, Symbol, sqrt, simplify
+from sympy.physics.optics import Medium
+from sympy.abc import epsilon, mu
+from sympy.physics.units import c, u0, e0, m, kg, s, A
+
+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
+ # 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 simplify(m5.intrinsic_impedance - 6.24845417765552*kg*m**2/(A**2*s**3)) == 0
+ # assert simplify(m5.speed - 225407863.157895*m/s) == 0
+ assert simplify(m5.refractive_index - 1.33000000000000) == 0
+ assert simplify(m5.permittivity - 7.1e-10*A**2*s**4/(kg*m**3)) == 0
+ assert simplify(m5.permeability - 2.77206575232851e-8*kg*m/(A**2*s**2)) == 0
commit 07f276ddae574a4f6919c519ec6d1fec639a690b
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Tue Jun 10 00:39:58 2014 +0530
Add feature to initialize medium with refractive index. [skip ci]
Import constants like permittivity of free space, speed of light in vacuum and magnetic permeability from sympy.physics.units rather than using Symbols for them.
diff --git a/sympy/physics/optics/medium.py b/sympy/physics/optics/medium.py
index dbf14ef..3158d45 100644
--- a/sympy/physics/optics/medium.py
+++ b/sympy/physics/optics/medium.py
@@ -9,7 +9,7 @@
__all__ = ['Medium']
from sympy import Symbol, sympify, sqrt
-from sympy.physics.units import c
+from sympy.physics.units import c, u0, e0
class Medium(Symbol):
@@ -43,7 +43,7 @@ class Medium(Symbol):
>>> m1 = Medium('m1')
>>> m2 = Medium('m2', epsilon, mu)
>>> m1.intrinsic_impedance
- sqrt(mu_0/epsilon_0)
+ 149896229*pi*kg*m**2/(1250000*A**2*s**3)
>>> m2.refractive_index
299792458*m*sqrt(epsilon*mu)/s
@@ -55,10 +55,28 @@ class Medium(Symbol):
"""
- def __new__(cls, name, permittivity=Symbol('epsilon_0'), permeability=Symbol('mu_0')):
+ def __new__(cls, name, permittivity=e0, permeability=u0, n=None):
obj = super(Medium, cls).__new__(cls, name)
obj._permittivity = sympify(permittivity)
obj._permeability = sympify(permeability)
+ obj._n = sympify(n)
+ if n is not None:
+ if permittivity != e0 and permeability == u0:
+ obj._permeability = n**2/(c**2*obj._permittivity)
+ if permeability != u0 and permittivity == e0:
+ obj._permittivity = n**2/(c**2*obj._permeability)
+ # XXX: There's issue with precision. Values may be
+ # different slightly.
+ #
+ #if permittivity != u0 and permittivity != e0:
+ # if n != c*sqrt(permittivity*permeability):
+ # raise ValueError("Values are not consistent.")
+ else:
+ obj._n = c*sqrt(permittivity*permeability)
+ if n is None and permittivity == e0 and permeability == u0:
+ obj._flag = False
+ else:
+ obj._flag = True
return obj
@property
@@ -79,7 +97,7 @@ def intrinsic_impedance(self):
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.intrinsic_impedance
- sqrt(mu_0/epsilon_0)
+ 149896229*pi*kg*m**2/(1250000*A**2*s**3)
"""
return sqrt(self._permeability/self._permittivity)
@@ -95,7 +113,7 @@ def speed(self):
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.speed
- 1/sqrt(epsilon_0*mu_0)
+ 299792458*m/s
"""
return 1/sqrt(self._permittivity*self._permeability)
@@ -111,7 +129,8 @@ def refractive_index(self):
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.refractive_index
- 299792458*m*sqrt(epsilon_0*mu_0)/s
+ 1
+
"""
return c/self.speed
@@ -126,7 +145,7 @@ def permittivity(self):
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.permittivity
- epsilon_0
+ 625000*A**2*s**4/(22468879468420441*pi*kg*m**3)
"""
return self._permittivity
@@ -142,7 +161,7 @@ def permeability(self):
>>> from sympy.physics.optics import Medium
>>> m = Medium('m')
>>> m.permeability
- mu_0
+ pi*kg*m/(2500000*A**2*s**2)
"""
return self._permeability
@@ -151,14 +170,14 @@ def __str__(self):
from sympy.printing import sstr
return type(self).__name__ + sstr(self.args)
- def __le__(self, other):
+ def __lt__(self, other):
"""
Compares based on refractive index of the medium.
"""
return self.refractive_index < other.refractive_index
- def __ge__(self, other):
- return not self.__le__(other)
+ def __gt__(self, other):
+ return not self.__lt__(other)
def __eq__(self, other):
return self.refractive_index == other.refractive_index
commit 8b4b186fe6d34b9925c993604f23c82b3265707f
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 9 19:41:56 2014 +0530
Add medium [skip ci]
diff --git a/doc/src/modules/physics/optics/index.rst b/doc/src/modules/physics/optics/index.rst
index e3f2ec9..6b1f3a2 100644
--- a/doc/src/modules/physics/optics/index.rst
+++ b/doc/src/modules/physics/optics/index.rst
@@ -10,4 +10,5 @@ Optics Module
.. toctree::
:maxdepth: 3
+ medium.rst
waves.rst
diff --git a/doc/src/modules/physics/optics/medium.rst b/doc/src/modules/physics/optics/medium.rst
new file mode 100644
index 0000000..a480b91
--- /dev/null
+++ b/doc/src/modules/physics/optics/medium.rst
@@ -0,0 +1,6 @@
+======
+Medium
+======
+
+.. automodule:: sympy.physics.optics.medium
+ :members:
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index 8cd92de..2f0181b 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -14,3 +14,8 @@
from . import waves
from .waves import TWave
__all__.extend(waves.__all__)
+
+
+from . import medium
+from .medium import Medium
+__all__.extend(medium.__all__)
diff --git a/sympy/physics/optics/medium.py b/sympy/physics/optics/medium.py
new file mode 100644
index 0000000..dbf14ef
--- /dev/null
+++ b/sympy/physics/optics/medium.py
@@ -0,0 +1,167 @@
+"""
+**Contains**
+
+* Medium
+"""
+
+from __future__ import division
+
+__all__ = ['Medium']
+
+from sympy import Symbol, sympify, sqrt
+from sympy.physics.units import c
+
+class Medium(Symbol):
+
+ """
+ This class represents an optical medium. The prime reason to implement this is
+ to facilitate refraction, Fermat's priciple, etc.
+
+ An optical medium is a material through which electromagnetic waves propagate.
+ The permittivity and permeability of the medium define how electromagnetic
+ waves propagate in it.
+
+
+ Prameters
+ =========
+
+ name: string
+ The display name of the Medium.
+
+ permittivity: Sympifyable
+ Electric permittivity of the space.
+
+ permeability: Sympifyable
+ Magnetic permeability of the space.
+
+
+ Examples
+ ========
+
+ >>> from sympy.abc import epsilon, mu
+ >>> from sympy.physics.optics import Medium
+ >>> m1 = Medium('m1')
+ >>> m2 = Medium('m2', epsilon, mu)
+ >>> m1.intrinsic_impedance
+ sqrt(mu_0/epsilon_0)
+ >>> m2.refractive_index
+ 299792458*m*sqrt(epsilon*mu)/s
+
+
+ References
+ ==========
+
+ .. [1] http://en.wikipedia.org/wiki/Optical_medium
+
+ """
+
+ def __new__(cls, name, permittivity=Symbol('epsilon_0'), permeability=Symbol('mu_0')):
+ obj = super(Medium, cls).__new__(cls, name)
+ obj._permittivity = sympify(permittivity)
+ obj._permeability = sympify(permeability)
+ return obj
+
+ @property
+ def intrinsic_impedance(self):
+ """
+ Returns intrinsic impedance of the medium.
+
+ The intrinsic impedance of a medium is the ratio of the
+ transverse components of the electric and magnetic fields
+ of the electromagnetic wave travelling in the medium.
+ In a region with no electrical conductivity it simplifies
+ to the square root of ratio of magnetic permeability to
+ electric permittivity.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import Medium
+ >>> m = Medium('m')
+ >>> m.intrinsic_impedance
+ sqrt(mu_0/epsilon_0)
+
+ """
+ return sqrt(self._permeability/self._permittivity)
+
+ @property
+ def speed(self):
+ """
+ Returns speed of the electromagnetic wave travelling in the medium.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import Medium
+ >>> m = Medium('m')
+ >>> m.speed
+ 1/sqrt(epsilon_0*mu_0)
+
+ """
+ return 1/sqrt(self._permittivity*self._permeability)
+
+ @property
+ def refractive_index(self):
+ """
+ Returns refractive index of the medium.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import Medium
+ >>> m = Medium('m')
+ >>> m.refractive_index
+ 299792458*m*sqrt(epsilon_0*mu_0)/s
+ """
+ return c/self.speed
+
+ @property
+ def permittivity(self):
+ """
+ Returns electric permittivity of the medium.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import Medium
+ >>> m = Medium('m')
+ >>> m.permittivity
+ epsilon_0
+
+ """
+ return self._permittivity
+
+ @property
+ def permeability(self):
+ """
+ Returns magnetic permeability of the medium.
+
+ Examples
+ ========
+
+ >>> from sympy.physics.optics import Medium
+ >>> m = Medium('m')
+ >>> m.permeability
+ mu_0
+
+ """
+ return self._permeability
+
+ def __str__(self):
+ from sympy.printing import sstr
+ return type(self).__name__ + sstr(self.args)
+
+ def __le__(self, other):
+ """
+ Compares based on refractive index of the medium.
+ """
+ return self.refractive_index < other.refractive_index
+
+ def __ge__(self, other):
+ return not self.__le__(other)
+
+ def __eq__(self, other):
+ return self.refractive_index == other.refractive_index
+
+ def __ne__(self, other):
+ return not self.__eq__(other)
commit b1711b5e7d0fe6515f498f737233af787424205c
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon Jun 9 12:37:53 2014 +0530
Add test for rewrite expr using cos
diff --git a/sympy/physics/optics/tests/test_waves.py b/sympy/physics/optics/tests/test_waves.py
index 922bdc4..7f9ec6a 100644
--- a/sympy/physics/optics/tests/test_waves.py
+++ b/sympy/physics/optics/tests/test_waves.py
@@ -27,3 +27,4 @@ def test_twave():
+ A2**2)*sin(2*pi*f*t + phi1 + phi2 + pi/2)) == 0
E = Function('E')
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(2*pi*f*t + phi1 + phi2)
commit c8b0a4f90e5046b1341a5faba77d992ca179c411
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jun 4 21:21:37 2014 +0530
Add equation rewrite methods
diff --git a/sympy/physics/optics/tests/test_waves.py b/sympy/physics/optics/tests/test_waves.py
index 489c3dc..922bdc4 100644
--- a/sympy/physics/optics/tests/test_waves.py
+++ b/sympy/physics/optics/tests/test_waves.py
@@ -1,4 +1,6 @@
-from sympy import symbols, Symbol, pi, sqrt, cos
+from sympy import (symbols, Symbol, pi, sqrt, cos, sin, Derivative,
+ Function, simplify)
+from sympy.abc import x, epsilon, mu
from sympy.physics.optics import TWave
@@ -21,3 +23,7 @@ def test_twave():
assert w3.time_period == 1/f
assert w3.angular_velocity == 2*pi*f
assert w3.wavenumber == 2*pi*f*n/c
+ assert simplify(w3.rewrite('sin') - sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2)
+ + A2**2)*sin(2*pi*f*t + phi1 + phi2 + pi/2)) == 0
+ E = Function('E')
+ assert w3.rewrite('pde') == epsilon*mu*Derivative(E(x, t), t, t) + Derivative(E(x, t), x, x)
diff --git a/sympy/physics/optics/waves.py b/sympy/physics/optics/waves.py
index ec7b99a..89f49fc 100644
--- a/sympy/physics/optics/waves.py
+++ b/sympy/physics/optics/waves.py
@@ -10,7 +10,8 @@
__all__ = ['TWave']
-from sympy import sympify, pi, cos, sqrt, simplify, Symbol, S
+from sympy import (sympify, pi, sin, cos, sqrt, simplify, Symbol, S, C, I,
+ symbols, Derivative)
from sympy.core.expr import Expr
@@ -43,7 +44,7 @@ class TWave(Expr):
Raises
=======
- ValueError : When niether frequency nor time period is provided
+ ValueError : When neither frequency nor time period is provided
or they are not consistent.
TypeError : When anyting other than TWave objects is added.
@@ -258,3 +259,15 @@ def __add__(self, other):
)
else:
raise TypeError(type(other).__name__ + " and TWave objects can't be added.")
+
+ def _eval_rewrite_as_sin(self, *args):
+ return self._amplitude*sin(self.angular_velocity*Symbol('t') + self._phase + pi/2, evaluate=False)
+
+ def _eval_rewrite_as_cos(self, *args):
+ return self._amplitude*cos(self.angular_velocity*Symbol('t') + self._phase)
+
+ def _eval_rewrite_as_pde(self, *args):
+ from sympy import Function
+ mu, epsilon, x, t = symbols('mu, epsilon, x, t')
+ E = Function('E')
+ return Derivative(E(x, t), x, 2) + mu*epsilon*Derivative(E(x, t), t, 2)
commit e35434b956c3833db3f67d4c8870c281298807ca
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Wed Jun 4 21:20:55 2014 +0530
Add wavenumber property
diff --git a/sympy/physics/optics/tests/test_waves.py b/sympy/physics/optics/tests/test_waves.py
index 0b691d6..489c3dc 100644
--- a/sympy/physics/optics/tests/test_waves.py
+++ b/sympy/physics/optics/tests/test_waves.py
@@ -20,4 +20,4 @@ def test_twave():
assert w3.wavelength == c/(f*n)
assert w3.time_period == 1/f
assert w3.angular_velocity == 2*pi*f
- assert w3.equation() == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)*cos(2*pi*f*t + phi1 + phi2)
+ assert w3.wavenumber == 2*pi*f*n/c
diff --git a/sympy/physics/optics/waves.py b/sympy/physics/optics/waves.py
index b215ac7..ec7b99a 100644
--- a/sympy/physics/optics/waves.py
+++ b/sympy/physics/optics/waves.py
@@ -43,7 +43,8 @@ class TWave(Expr):
Raises
=======
- ValueError : When niether frequency nor time period is provided.
+ ValueError : When niether frequency nor time period is provided
+ or they are not consistent.
TypeError : When anyting other than TWave objects is added.
@@ -218,9 +219,10 @@ def angular_velocity(self):
"""
return 2*pi*self._frequency
- def equation(self, type='cosine'):
+ @property
+ def wavenumber(self):
"""
- Returns equation of the wave.
+ Returns wavenumber of the wave.
Examples
========
@@ -229,13 +231,10 @@ def equation(self, type='cosine'):
>>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
- >>> w.equation('cosine')
- A*cos(2*pi*f*t + phi)
+ >>> w.wavenumber
+ 2*pi*f*n/c
"""
- if not isinstance(type, str):
- raise TypeError("type can only be a string.")
- if type == 'cosine':
- return self._amplitude*cos(self.angular_velocity*Symbol('t') + self._phase)
+ return 2*pi/self.wavelength
def __str__(self):
"""String representation of a TWave."""
commit 9963af0e927ba37b7ad258c0767e1bb55d6a63b6
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 1 05:48:42 2014 +0530
Add tests for pretty printer
diff --git a/sympy/printing/pretty/tests/test_pretty.py b/sympy/printing/pretty/tests/test_pretty.py
index 02c3ed0..63b80fc 100644
--- a/sympy/printing/pretty/tests/test_pretty.py
+++ b/sympy/printing/pretty/tests/test_pretty.py
@@ -4717,3 +4717,12 @@ def test_Tr():
def test_pretty_Add():
eq = Mul(-2, x - 2, evaluate=False) + 5
assert pretty(eq) == '-2*(x - 2) + 5'
+
+
+def test_issue_7179():
+ assert upretty(Not(Equivalent(x, y))) == u('x ≢ y')
+ assert upretty(Not(Implies(x, y))) == u('x ↛ y')
+
+
+def test_issue_7180():
+ assert upretty(Equivalent(x, y)) == u('x ≡ y')
commit afd6444c0bc6d6ef325028e18771609106dd990d
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat May 31 22:38:55 2014 +0530
Remove unnecessary if block
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 37f3e67..5a4369b 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -754,14 +754,10 @@ def _print_Or(self, e):
return tex
def _print_Implies(self, e, altchar=None):
- if altchar:
- return r"%s %s %s" % (self._print(e.args[0]), altchar, self._print(e.args[1]))
- return r"%s \Rightarrow %s" % (self._print(e.args[0]), self._print(e.args[1]))
+ return r"%s %s %s" % (self._print(e.args[0]), altchar or r"\Rightarrow", self._print(e.args[1]))
def _print_Equivalent(self, e, altchar=None):
- if altchar:
- return r"%s %s %s" % (self._print(e.args[0]), altchar, self._print(e.args[1]))
- return r"%s \equiv %s" % (self._print(e.args[0]), self._print(e.args[1]))
+ return r"%s %s %s" % (self._print(e.args[0]), altchar or r"\equiv", self._print(e.args[1]))
def _print_conjugate(self, expr, exp=None):
tex = r"\overline{%s}" % self._print(expr.args[0])
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index 5a13e26..e95cd4d 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -210,17 +210,13 @@ def _print_Nor(self, e):
def _print_Implies(self, e, altchar=None):
if self._use_unicode:
- if altchar:
- return self.__print_Boolean(e, altchar, sort=False)
- return self.__print_Boolean(e, u("\u2192"), sort=False)
+ return self.__print_Boolean(e, altchar or u("\u2192"), sort=False)
else:
return self._print_Function(e)
def _print_Equivalent(self, e, altchar=None):
if self._use_unicode:
- if altchar:
- return self.__print_Boolean(e, altchar)
- return self.__print_Boolean(e, u("\u2261"))
+ return self.__print_Boolean(e, altchar or u("\u2261"))
else:
return self._print_Function(e, sort=True)
commit 8b90e357b5e9f1d72196dde988c0aab0017327a9
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun Jun 1 01:45:07 2014 +0530
Add IPython Notebook Checkpoints to .gitignore
diff --git a/.gitignore b/.gitignore
index 829f148..c8cf3a3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -64,3 +64,6 @@ doc/src/modules/physics/mechanics/*.pdf
# Temp output of sympy/printing/preview.py:
sample.tex
+
+# IPython Notebook Checkpoints
+.ipynb_checkpoints/
commit 9debb51c762ba89cba1e6acd247b8cd3a7ff86e4
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat May 31 20:28:06 2014 +0530
Remove double wrapping with u
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index c3fb751..5a13e26 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -211,7 +211,7 @@ def _print_Nor(self, e):
def _print_Implies(self, e, altchar=None):
if self._use_unicode:
if altchar:
- return self.__print_Boolean(e, u(altchar), sort=False)
+ return self.__print_Boolean(e, altchar, sort=False)
return self.__print_Boolean(e, u("\u2192"), sort=False)
else:
return self._print_Function(e)
@@ -219,7 +219,7 @@ def _print_Implies(self, e, altchar=None):
def _print_Equivalent(self, e, altchar=None):
if self._use_unicode:
if altchar:
- return self.__print_Boolean(e, u(altchar))
+ return self.__print_Boolean(e, altchar)
return self.__print_Boolean(e, u("\u2261"))
else:
return self._print_Function(e, sort=True)
commit d1956a1cf93c8882dc8db2308cad03bbc7056d78
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat May 31 17:55:03 2014 +0530
Add tests for printing Equivalent. fixes #7180
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index 044cc1b..8405304 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -13,7 +13,7 @@
hyper, im, im, jacobi, laguerre, legendre, lerchphi, log, lowergamma,
meijerg, oo, polar_lift, polylog, re, re, root, sin, sqrt, symbols,
uppergamma, zeta, subfactorial, totient, elliptic_k, elliptic_f,
- elliptic_e, elliptic_pi, cos, tan, Wild, true, false)
+ elliptic_e, elliptic_pi, cos, tan, Wild, true, false, Equivalent, Not)
from sympy.abc import mu, tau
from sympy.printing.latex import latex, translate
@@ -1254,3 +1254,8 @@ def test_Mul():
def test_Pow():
e = Pow(2, 2, evaluate=False)
assert latex(e) == r'2^{2}'
+
+
+def test_issue_7180():
+ assert latex(Equivalent(x, y)) == r"x \equiv y"
+ assert latex(Not(Equivalent(x, y))) == r"x \not\equiv y"
commit 33e79c218383a7ac57d2118e88877d522c845f35
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat May 31 17:45:10 2014 +0530
Wrap unicode chars with u and fix a bug in latex printer
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 638b924..37f3e67 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -713,9 +713,9 @@ def _print_im(self, expr, exp=None):
def _print_Not(self, e):
from sympy import Equivalent, Implies
if isinstance(e.args[0], Equivalent):
- return self._print_Equivalent(e.args, "\not\equiv")
+ return self._print_Equivalent(e.args[0], r"\not\equiv")
if isinstance(e.args[0], Implies):
- return self._print_Implies(e.args, "\not\Rightarrow")
+ return self._print_Implies(e.args[0], r"\not\Rightarrow")
if (e.args[0].is_Boolean):
return r"\neg (%s)" % self._print(e.args[0])
else:
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index e39cbde..c3fb751 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -146,9 +146,9 @@ def _print_Not(self, e):
arg = e.args[0]
pform = self._print(arg)
if isinstance(arg, Equivalent):
- return self._print_Equivalent(arg, altchar="\u2262")
+ return self._print_Equivalent(arg, altchar=u("\u2262"))
if isinstance(arg, Implies):
- return self._print_Implies(arg, altchar="\u219b")
+ return self._print_Implies(arg, altchar=u("\u219b"))
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
diff --git a/sympy/printing/tests/test_latex.py b/sympy/printing/tests/test_latex.py
index da488e3..044cc1b 100644
--- a/sympy/printing/tests/test_latex.py
+++ b/sympy/printing/tests/test_latex.py
@@ -96,7 +96,7 @@ def test_latex_basic():
assert latex(x | y | z) == r"x \vee y \vee z"
assert latex((x & y) | z) == r"z \vee \left(x \wedge y\right)"
assert latex(Implies(x, y)) == r"x \Rightarrow y"
- assert latex(~(x >> ~y)) == r"\neg (x \Rightarrow \neg y)"
+ assert latex(~(x >> ~y)) == r"x \not\Rightarrow \neg y"
assert latex(~x, symbol_names={x: "x_i"}) == r"\neg x_i"
assert latex(x & y, symbol_names={x: "x_i", y: "y_i"}) == \
commit 477f9a07721b17d85e99270a3bb85d7e8d3baa86
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat May 31 01:55:37 2014 +0530
Fix a typo in manipulation.rst [skip ci]
diff --git a/doc/src/tutorial/manipulation.rst b/doc/src/tutorial/manipulation.rst
index 6d58ff9..704d09e 100644
--- a/doc/src/tutorial/manipulation.rst
+++ b/doc/src/tutorial/manipulation.rst
@@ -119,7 +119,7 @@ Thus, we could have created the same object by writing ``Mul(x, y)``.
Now we get to our final expression, ``x**2 + x*y``. This is the addition of
our last two objects, ``Pow(x, 2)``, and ``Mul(x, y)``. The SymPy class for
addition is ``Add``, so, as you might expect, to create this object, we use
-``Add(Pow(x, 2), Mul(x, y)``.
+``Add(Pow(x, 2), Mul(x, y))``.
>>> Add(Pow(x, 2), Mul(x, y))
x**2 + x*y
commit fa3019436d261912a2e886f9bf13d774d397c69c
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri May 30 22:21:50 2014 +0530
Make equivalence symbol same for pretty printer and latex printer
and change not equivalent symbol to u+2262 [skip ci]
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index e38df02..638b924 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -713,7 +713,7 @@ def _print_im(self, expr, exp=None):
def _print_Not(self, e):
from sympy import Equivalent, Implies
if isinstance(e.args[0], Equivalent):
- return self._print_Equivalent(e.args, "\not\Leftrightarrow")
+ return self._print_Equivalent(e.args, "\not\equiv")
if isinstance(e.args[0], Implies):
return self._print_Implies(e.args, "\not\Rightarrow")
if (e.args[0].is_Boolean):
@@ -761,7 +761,7 @@ def _print_Implies(self, e, altchar=None):
def _print_Equivalent(self, e, altchar=None):
if altchar:
return r"%s %s %s" % (self._print(e.args[0]), altchar, self._print(e.args[1]))
- return r"%s \Leftrightarrow %s" % (self._print(e.args[0]), self._print(e.args[1]))
+ return r"%s \equiv %s" % (self._print(e.args[0]), self._print(e.args[1]))
def _print_conjugate(self, expr, exp=None):
tex = r"\overline{%s}" % self._print(expr.args[0])
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index 0583fe5..e39cbde 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -146,7 +146,7 @@ def _print_Not(self, e):
arg = e.args[0]
pform = self._print(arg)
if isinstance(arg, Equivalent):
- return self._print_Equivalent(arg, altchar="\u226d")
+ return self._print_Equivalent(arg, altchar="\u2262")
if isinstance(arg, Implies):
return self._print_Implies(arg, altchar="\u219b")
commit df72c00112971c17f3177c5af1ff0765db694963
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri May 30 19:02:02 2014 +0530
Fix latex printing for Not(Equivalent) and Not(Implies).
diff --git a/sympy/printing/latex.py b/sympy/printing/latex.py
index 98cd3c6..e38df02 100644
--- a/sympy/printing/latex.py
+++ b/sympy/printing/latex.py
@@ -711,6 +711,11 @@ def _print_im(self, expr, exp=None):
return self._do_exponent(tex, exp)
def _print_Not(self, e):
+ from sympy import Equivalent, Implies
+ if isinstance(e.args[0], Equivalent):
+ return self._print_Equivalent(e.args, "\not\Leftrightarrow")
+ if isinstance(e.args[0], Implies):
+ return self._print_Implies(e.args, "\not\Rightarrow")
if (e.args[0].is_Boolean):
return r"\neg (%s)" % self._print(e.args[0])
else:
@@ -748,10 +753,14 @@ def _print_Or(self, e):
return tex
- def _print_Implies(self, e):
+ def _print_Implies(self, e, altchar=None):
+ if altchar:
+ return r"%s %s %s" % (self._print(e.args[0]), altchar, self._print(e.args[1]))
return r"%s \Rightarrow %s" % (self._print(e.args[0]), self._print(e.args[1]))
- def _print_Equivalent(self, e):
+ def _print_Equivalent(self, e, altchar=None):
+ if altchar:
+ return r"%s %s %s" % (self._print(e.args[0]), altchar, self._print(e.args[1]))
return r"%s \Leftrightarrow %s" % (self._print(e.args[0]), self._print(e.args[1]))
def _print_conjugate(self, expr, exp=None):
commit fd1cdacd014f5490066d1da79997e542ffa14478
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Fri May 30 18:34:39 2014 +0530
Fix pretty printing for Not(Equivalent) and Not(Implies). fixes #7179
diff --git a/sympy/printing/pretty/pretty.py b/sympy/printing/pretty/pretty.py
index a6397e1..0583fe5 100644
--- a/sympy/printing/pretty/pretty.py
+++ b/sympy/printing/pretty/pretty.py
@@ -141,9 +141,14 @@ def _print_Relational(self, e):
return pform
def _print_Not(self, e):
+ from sympy import Equivalent, Implies
if self._use_unicode:
arg = e.args[0]
pform = self._print(arg)
+ if isinstance(arg, Equivalent):
+ return self._print_Equivalent(arg, altchar="\u226d")
+ if isinstance(arg, Implies):
+ return self._print_Implies(arg, altchar="\u219b")
if arg.is_Boolean and not arg.is_Not:
pform = prettyForm(*pform.parens())
@@ -203,14 +208,18 @@ def _print_Nor(self, e):
else:
return self._print_Function(e, sort=True)
- def _print_Implies(self, e):
+ def _print_Implies(self, e, altchar=None):
if self._use_unicode:
+ if altchar:
+ return self.__print_Boolean(e, u(altchar), sort=False)
return self.__print_Boolean(e, u("\u2192"), sort=False)
else:
return self._print_Function(e)
- def _print_Equivalent(self, e):
+ def _print_Equivalent(self, e, altchar=None):
if self._use_unicode:
+ if altchar:
+ return self.__print_Boolean(e, u(altchar))
return self.__print_Boolean(e, u("\u2261"))
else:
return self._print_Function(e, sort=True)
commit b33b45aa3727ceeb3d333e9612c452e868ed1589
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun May 25 20:11:39 2014 +0530
Add equation method and a better printing way
Fix code quality failures
Add check for consistency of frequency and time_period
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
index bf4dfea..8cd92de 100644
--- a/sympy/physics/optics/__init__.py
+++ b/sympy/physics/optics/__init__.py
@@ -12,5 +12,5 @@
# "from sympy.physics.optics import *" is done.
from . import waves
-from .waves import *
+from .waves import TWave
__all__.extend(waves.__all__)
diff --git a/sympy/physics/optics/tests/test_waves.py b/sympy/physics/optics/tests/test_waves.py
index a2ec25e..0b691d6 100644
--- a/sympy/physics/optics/tests/test_waves.py
+++ b/sympy/physics/optics/tests/test_waves.py
@@ -6,6 +6,7 @@ def test_twave():
A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
c = Symbol('c') # Speed of light in vacuum
n = Symbol('n') # Refractive index
+ t = Symbol('t') # Time
w1 = TWave(A1, f, phi1)
w2 = TWave(A2, f, phi2)
assert w1.amplitude == A1
@@ -19,3 +20,4 @@ def test_twave():
assert w3.wavelength == c/(f*n)
assert w3.time_period == 1/f
assert w3.angular_velocity == 2*pi*f
+ assert w3.equation() == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)*cos(2*pi*f*t + phi1 + phi2)
diff --git a/sympy/physics/optics/waves.py b/sympy/physics/optics/waves.py
index afb378d..b215ac7 100644
--- a/sympy/physics/optics/waves.py
+++ b/sympy/physics/optics/waves.py
@@ -40,16 +40,24 @@ class TWave(Expr):
n : Sympifyable
Refractive index of the medium.
+ Raises
+ =======
+
+ ValueError : When niether frequency nor time period is provided.
+ TypeError : When anyting other than TWave objects is added.
+
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
>>> w1 = TWave(A1, f, phi1)
>>> w2 = TWave(A2, f, phi2)
>>> w3 = w1 + w2 # Superposition of two waves
+ >>> w3
+ TWave(sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2), f, phi1 + phi2)
>>> w3.amplitude
sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
>>> w3.phase
@@ -83,8 +91,11 @@ def __init__(
self._frequency = 1/self._time_period
if frequency is not None:
self._time_period = 1/self._frequency
+ if time_period is not None:
+ if frequency != 1/time_period:
+ raise ValueError("frequency and time_period should be consistent.")
if frequency is None and time_period is None:
- raise Exception("Either frequency or time period is needed.")
+ raise ValueError("Either frequency or time period is needed.")
@property
def frequency(self):
@@ -94,8 +105,8 @@ def frequency(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.frequency
@@ -111,8 +122,8 @@ def time_period(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.time_period
@@ -129,8 +140,8 @@ def wavelength(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.wavelength
@@ -146,8 +157,8 @@ def amplitude(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.amplitude
@@ -163,8 +174,8 @@ def phase(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.phase
@@ -181,8 +192,8 @@ def speed(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.speed
@@ -198,8 +209,8 @@ def angular_velocity(self):
Examples
========
- >>> from sympy import *
- >>> from sympy.physics.optics import *
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
>>> A, phi, f = symbols('A, phi, f')
>>> w = TWave(A, f, phi)
>>> w.angular_velocity
@@ -207,10 +218,31 @@ def angular_velocity(self):
"""
return 2*pi*self._frequency
- def __repr__(self):
- return repr(self._amplitude*cos(2*pi*self._frequency*Symbol('t') + self._phase))
+ def equation(self, type='cosine'):
+ """
+ Returns equation of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import symbols
+ >>> from sympy.physics.optics import TWave
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.equation('cosine')
+ A*cos(2*pi*f*t + phi)
+ """
+ if not isinstance(type, str):
+ raise TypeError("type can only be a string.")
+ if type == 'cosine':
+ return self._amplitude*cos(self.angular_velocity*Symbol('t') + self._phase)
+
+ def __str__(self):
+ """String representation of a TWave."""
+ from sympy.printing import sstr
+ return type(self).__name__ + sstr(self.args)
- __str__ = __repr__
+ __repr__ = __str__
def __add__(self, other):
"""
@@ -226,4 +258,4 @@ def __add__(self, other):
self._phase + other._phase
)
else:
- raise TypeError(repr(type(other)) + " and TWave objects can't be added.")
+ raise TypeError(type(other).__name__ + " and TWave objects can't be added.")
commit 6779cb06c6a9a804bcf5c651587efdc68d4fcde8
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sun May 25 15:55:20 2014 +0530
Add sphinx docs for optics module
diff --git a/doc/src/modules/physics/index.rst b/doc/src/modules/physics/index.rst
index c77af27..23c26ec 100644
--- a/doc/src/modules/physics/index.rst
+++ b/doc/src/modules/physics/index.rst
@@ -25,3 +25,4 @@ Contents
vector/index.rst
mechanics/index.rst
quantum/index.rst
+ optics/index.rst
diff --git a/doc/src/modules/physics/optics/index.rst b/doc/src/modules/physics/optics/index.rst
new file mode 100644
index 0000000..e3f2ec9
--- /dev/null
+++ b/doc/src/modules/physics/optics/index.rst
@@ -0,0 +1,13 @@
+==============
+Optics Module
+==============
+
+.. topic:: Abstract
+
+ Contains docstrings of Physics-Optics module
+
+
+.. toctree::
+ :maxdepth: 3
+
+ waves.rst
diff --git a/doc/src/modules/physics/optics/waves.rst b/doc/src/modules/physics/optics/waves.rst
new file mode 100644
index 0000000..d5c91c9
--- /dev/null
+++ b/doc/src/modules/physics/optics/waves.rst
@@ -0,0 +1,6 @@
+======
+Waves
+======
+
+.. automodule:: sympy.physics.optics.waves
+ :members:
diff --git a/sympy/physics/optics/waves.py b/sympy/physics/optics/waves.py
index 7d2a2b8..afb378d 100644
--- a/sympy/physics/optics/waves.py
+++ b/sympy/physics/optics/waves.py
@@ -1,8 +1,7 @@
"""
This module has all the classes and functions related to waves in optics.
-Contains
-========
+**Contains**
* TWave
"""
@@ -23,8 +22,8 @@ class TWave(Expr):
they can be changed later with respective methods provided.
It has been represented as :math:`A \times cos(\omega \times t + \phi )`
- where :math:`A` is amplitude, :math:` \omega ` is angular velocity and
- :math:` \phi ` is phase angle of the wave.
+ where :math:`A` is amplitude, :math:`\omega` is angular velocity and
+ :math:`\phi` is phase angle of the wave.
Arguments
commit 975f87dc6f26105902f0292e0f2f88ab3b32e277
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Sat May 24 13:17:52 2014 +0530
Add Waves module
Add directory structure for optics
Created optics folder in sympy.physics and mentioned it in setup.py
Added TWave class
diff --git a/setup.py b/setup.py
index dc5439f..ff67c07 100755
--- a/setup.py
+++ b/setup.py
@@ -80,6 +80,7 @@
'sympy.physics',
'sympy.physics.hep',
'sympy.physics.mechanics',
+ 'sympy.physics.optics',
'sympy.physics.quantum',
'sympy.physics.vector',
'sympy.plotting',
@@ -245,6 +246,7 @@ def run(self):
'sympy.parsing.tests',
'sympy.physics.hep.tests',
'sympy.physics.mechanics.tests',
+ 'sympy.physics.optics.tests',
'sympy.physics.quantum.tests',
'sympy.physics.tests',
'sympy.physics.vector.tests',
diff --git a/sympy/core/tests/test_args.py b/sympy/core/tests/test_args.py
index 8152ad2..e8d0315 100644
--- a/sympy/core/tests/test_args.py
+++ b/sympy/core/tests/test_args.py
@@ -3120,3 +3120,8 @@ def test_sympy__ntheory__factor___totient():
def test_sympy__ntheory__residue_ntheory__mobius():
from sympy.ntheory import mobius
assert _test_args(mobius(2))
+
+def test_sympy__physics__optics__waves__TWave():
+ from sympy.physics.optics import TWave
+ A, f, phi = symbols('A, f, phi')
+ assert _test_args(TWave(A, f, phi))
diff --git a/sympy/physics/optics/__init__.py b/sympy/physics/optics/__init__.py
new file mode 100644
index 0000000..bf4dfea
--- /dev/null
+++ b/sympy/physics/optics/__init__.py
@@ -0,0 +1,16 @@
+__all__ = []
+
+# The following pattern is used below for importing sub-modules:
+#
+# 1. "from foo import *". This imports all the names from foo.__all__ into
+# this module. But, this does not put those names into the __all__ of
+# this module. This enables "from sympy.physics.optics import TWave" to
+# work.
+# 2. "import foo; __all__.extend(foo.__all__)". This adds all the names in
+# foo.__all__ to the __all__ of this module. The names in __all__
+# determine which names are imported when
+# "from sympy.physics.optics import *" is done.
+
+from . import waves
+from .waves import *
+__all__.extend(waves.__all__)
diff --git a/sympy/physics/optics/tests/__init__.py b/sympy/physics/optics/tests/__init__.py
new file mode 100644
index 0000000..e69de29
diff --git a/sympy/physics/optics/tests/test_waves.py b/sympy/physics/optics/tests/test_waves.py
new file mode 100644
index 0000000..a2ec25e
--- /dev/null
+++ b/sympy/physics/optics/tests/test_waves.py
@@ -0,0 +1,21 @@
+from sympy import symbols, Symbol, pi, sqrt, cos
+from sympy.physics.optics import TWave
+
+
+def test_twave():
+ A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
+ c = Symbol('c') # Speed of light in vacuum
+ n = Symbol('n') # Refractive index
+ 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
+ w3 = w1 + w2
+ assert w3.amplitude == sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
+ assert w3.frequency == f
+ assert w3.wavelength == c/(f*n)
+ assert w3.time_period == 1/f
+ assert w3.angular_velocity == 2*pi*f
diff --git a/sympy/physics/optics/waves.py b/sympy/physics/optics/waves.py
new file mode 100644
index 0000000..7d2a2b8
--- /dev/null
+++ b/sympy/physics/optics/waves.py
@@ -0,0 +1,230 @@
+"""
+This module has all the classes and functions related to waves in optics.
+
+Contains
+========
+
+* TWave
+"""
+
+from __future__ import print_function, division
+
+__all__ = ['TWave']
+
+from sympy import sympify, pi, cos, sqrt, simplify, Symbol, S
+from sympy.core.expr import Expr
+
+
+class TWave(Expr):
+
+ r"""
+ This is a simple transverse wave travelling in a two dimensional space.
+ Basic properties are required at the time of creation of the object but
+ they can be changed later with respective methods provided.
+
+ It has been represented as :math:`A \times cos(\omega \times t + \phi )`
+ where :math:`A` is amplitude, :math:` \omega ` is angular velocity and
+ :math:` \phi ` is phase angle of the wave.
+
+
+ Arguments
+ =========
+
+ amplitude : Sympifyable
+ Amplitude of the wave.
+ frequency : Sympifyable
+ Frequency of the wave.
+ phase : Sympifyable
+ Phase angle of the wave.
+ time_period : Sympifyable
+ Time period of the wave.
+ n : Sympifyable
+ Refractive index of the medium.
+
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A1, phi1, A2, phi2, f = symbols('A1, phi1, A2, phi2, f')
+ >>> w1 = TWave(A1, f, phi1)
+ >>> w2 = TWave(A2, f, phi2)
+ >>> w3 = w1 + w2 # Superposition of two waves
+ >>> w3.amplitude
+ sqrt(A1**2 + 2*A1*A2*cos(phi1 - phi2) + A2**2)
+ >>> w3.phase
+ phi1 + phi2
+ >>> w3.speed
+ c/n
+ >>> w3.angular_velocity
+ 2*pi*f
+
+ """
+
+ def __init__(
+ self,
+ amplitude,
+ frequency=None,
+ phase=S.Zero,
+ time_period=None,
+ n=Symbol('n')):
+ frequency = sympify(frequency)
+ amplitude = sympify(amplitude)
+ phase = sympify(phase)
+ time_period = sympify(time_period)
+ n = sympify(n)
+ self._frequency = frequency
+ self._amplitude = amplitude
+ self._phase = phase
+ self._time_period = time_period
+ self._n = n
+ self.c = Symbol('c') # Speed of light in vacuum
+ if time_period is not None:
+ self._frequency = 1/self._time_period
+ if frequency is not None:
+ self._time_period = 1/self._frequency
+ if frequency is None and time_period is None:
+ raise Exception("Either frequency or time period is needed.")
+
+ @property
+ def frequency(self):
+ """
+ Returns the frequency of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.frequency
+ f
+ """
+ return self._frequency
+
+ @property
+ def time_period(self):
+ """
+ Returns the time period of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.time_period
+ 1/f
+ """
+ return self._time_period
+
+ @property
+ def wavelength(self):
+ """
+ Returns wavelength of the wave.
+ It depends on the medium of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.wavelength
+ c/(f*n)
+ """
+ return self.c/(self._frequency*self._n)
+
+ @property
+ def amplitude(self):
+ """
+ Returns the amplitude of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.amplitude
+ A
+ """
+ return self._amplitude
+
+ @property
+ def phase(self):
+ """
+ Returns the phase angle of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.phase
+ phi
+ """
+ return self._phase
+
+ @property
+ def speed(self):
+ """
+ Returns the speed of travelling wave.
+ It is medium dependent.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.speed
+ c/n
+ """
+ return self.wavelength*self._frequency
+
+ @property
+ def angular_velocity(self):
+ """
+ Returns angular velocity of the wave.
+
+ Examples
+ ========
+
+ >>> from sympy import *
+ >>> from sympy.physics.optics import *
+ >>> A, phi, f = symbols('A, phi, f')
+ >>> w = TWave(A, f, phi)
+ >>> w.angular_velocity
+ 2*pi*f
+ """
+ return 2*pi*self._frequency
+
+ def __repr__(self):
+ return repr(self._amplitude*cos(2*pi*self._frequency*Symbol('t') + self._phase))
+
+ __str__ = __repr__
+
+ def __add__(self, other):
+ """
+ Addition of two waves will result in their superposition.
+ The type of interference will depend on their phase angles.
+ """
+ if isinstance(other, TWave):
+ if self._frequency == other._frequency and self.wavelength == other.wavelength:
+ return TWave(sqrt(self._amplitude**2 + other._amplitude**2 + 2 *
+ self.amplitude*other.amplitude*cos(
+ self._phase - other.phase)),
+ self.frequency,
+ self._phase + other._phase
+ )
+ else:
+ raise TypeError(repr(type(other)) + " and TWave objects can't be added.")
commit 0b2281a9d6ee29f4c9e530e4c8627a3bfe62ceec
Author: Sudhanshu Mishra <mrsud94@gmail.com>
Date: Mon May 19 21:28:28 2014 +0530
Fix examples
diff --git a/examples/advanced/curvilinear_coordinates.py b/examples/advanced/curvilinear_coordinates.py
index 694bfb8..cd65e9c 100755
--- a/examples/advanced/curvilinear_coordinates.py
+++ b/examples/advanced/curvilinear_coordinates.py
@@ -10,7 +10,7 @@
"""
from sympy import var, sin, cos, pprint, Matrix, eye, trigsimp, Eq, \
- Function, simplify, sinh, cosh, expand
+ Function, simplify, sinh, cosh, expand, symbols
def laplace(f, g_inv, g_det, X):
@@ -56,7 +56,7 @@ def transform(name, X, Y, g_correct=None, recursive=False):
g = J.T*eye(J.shape[0])*J
g = g.applyfunc(expand)
- #g = g.applyfunc(trigsimp)
+ # g = g.applyfunc(trigsimp)
print("metric tensor g_{ij}:")
pprint(g)
if g_correct is not None:
@@ -76,39 +76,43 @@ def transform(name, X, Y, g_correct=None, recursive=False):
def main():
- var("mu nu rho theta phi sigma tau a t x y z w")
+ mu, nu, rho, theta, phi, sigma, tau, a, t, x, y, z, w = symbols(
+ "mu, nu, rho, theta, phi, sigma, tau, a, t, x, y, z, w")
transform("polar", Matrix([rho*cos(phi), rho*sin(phi)]), [rho, phi])
transform("cylindrical", Matrix([rho*cos(phi), rho*sin(phi), z]),
- [rho, phi, z])
+ [rho, phi, z])
transform("spherical",
- Matrix([rho*sin(theta)*cos(phi), rho*sin(theta)*sin(phi),
- rho*cos(theta)]),
- [rho, theta, phi],
- recursive=True
- )
+ Matrix([rho*sin(theta)*cos(phi), rho*sin(theta)*sin(phi),
+ rho*cos(theta)]),
+ [rho, theta, phi],
+ recursive=True
+ )
transform("rotating disk",
- Matrix([t, x*cos(w*t) - y*sin(w*t), x*sin(w*t) + y*cos(w*t), z]),
- [t, x, y, z])
+ Matrix([t,
+ x*cos(w*t) - y*sin(w*t),
+ x*sin(w*t) + y*cos(w*t),
+ z]),
+ [t, x, y, z])
transform("parabolic",
- Matrix([sigma*tau, (tau**2 - sigma**2)/2]),
- [sigma, tau])
+ Matrix([sigma*tau, (tau**2 - sigma**2) / 2]),
+ [sigma, tau])
# too complex:
- #transform("bipolar",
+ # transform("bipolar",
# Matrix([a*sinh(tau)/(cosh(tau)-cos(sigma)),
# a*sin(sigma)/(cosh(tau)-cos(sigma))]),
# [sigma, tau]
# )
transform("elliptic",
- Matrix([a*cosh(mu)*cos(nu), a*sinh(mu)*sin(nu)]),
- [mu, nu]
- )
+ Matrix([a*cosh(mu)*cos(nu), a*sinh(mu)*sin(nu)]),
+ [mu, nu]
+ )
if __name__ == "__main__":
main()
diff --git a/examples/advanced/fem.py b/examples/advanced/fem.py
index 5606b4a..a66b482 100755
--- a/examples/advanced/fem.py
+++ b/examples/advanced/fem.py
@@ -83,7 +83,7 @@ def bernstein_space(order, nsd):
for o4 in range(0, order + 1):
if o1 + o2 + o3 + o4 == order:
aij = Symbol("a_%d_%d_%d_%d" % (o1, o2, o3, o4))
- fac = factorial(order)/ (factorial(o1)*factorial(o2)*factorial(o3)*factorial(o4))
+ fac = factorial(order)/(factorial(o1)*factorial(o2)*factorial(o3)*factorial(o4))
sum += aij*fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)*pow(b4, o4)
basis.append(fac*pow(b1, o1)*pow(b2, o2)*pow(b3, o3)*pow(b4, o4))
coeff.append(aij)
@@ -158,7 +158,7 @@ def compute_basis(self):
ex = ex.subs(y, p[1])
if nsd > 2:
ex = ex.subs(z, p[2])
- equations.append(ex )
+ equations.append(ex)
A = create_matrix(equations, coeffs)
Ainv = A.inv()
@@ -181,7 +181,7 @@ def main():
fe = Lagrange(2, 2)
u = 0
- #compute u = sum_i u_i N_i
+ # compute u = sum_i u_i N_i
us = []
for i in range(0, fe.nbf()):
ui = Symbol("u_%d" % i)
diff --git a/examples/advanced/gibbs_phenomenon.py b/examples/advanced/gibbs_phenomenon.py
index de85cab..3bbb59e 100755
--- a/examples/advanced/gibbs_phenomenon.py
+++ b/examples/advanced/gibbs_phenomenon.py
@@ -16,7 +16,7 @@
from sympy import var, sqrt, integrate, conjugate, seterr, Abs, pprint, I, pi,\
sin, cos, sign, Plot, lambdify, Integral, S
-#seterr(True)
+# seterr(True)
x = var("x", real=True)
@@ -127,8 +127,8 @@ def msolve(f, x):
def main():
- #L = l2_gram_schmidt([1, cos(x), sin(x), cos(2*x), sin(2*x)], (x, -pi, pi))
- #L = l2_gram_schmidt([1, cos(x), sin(x)], (x, -pi, pi))
+ # L = l2_gram_schmidt([1, cos(x), sin(x), cos(2*x), sin(2*x)], (x, -pi, pi))
+ # L = l2_gram_schmidt([1, cos(x), sin(x)], (x, -pi, pi))
# the code below is equivalen to l2_gram_schmidt(), but faster:
L = [1/sqrt(2)]
for i in range(1, 100):
@@ -139,7 +139,7 @@ def main():
f = series(L)
print("Fourier series of the step function")
pprint(f)
- #Plot(f.diff(x), [x, -5, 5, 3000])
+ # Plot(f.diff(x), [x, -5, 5, 3000])
x0 = msolve(f.diff(x), x)
print("x-value of the maximum:", x0)
diff --git a/examples/advanced/pyglet_plotting.py b/examples/advanced/pyglet_plotting.py
index 920e4e2..4156f89 100755
--- a/examples/advanced/pyglet_plotting.py
+++ b/examples/advanced/pyglet_plotting.py
@@ -19,9 +19,15 @@ def main():
# toggle axes visibility with F5, colors with F6
axes_options = 'visible=false; colored=true; label_ticks=true; label_axes=true; overlay=true; stride=0.5'
- #axes_options = 'colored=false; overlay=false; stride=(1.0, 0.5, 0.5)'
+ # axes_options = 'colored=false; overlay=false; stride=(1.0, 0.5, 0.5)'
- p = PygletPlot(width=600, height=500, ortho=False, invert_mouse_zoom=False, axes=axes_options, antialiasing=True)
+ p = PygletPlot(
+ width=600,
+ height=500,
+ ortho=False,
+ invert_mouse_zoom=False,
+ axes=axes_options,
+ antialiasing=True)
examples = []
@@ -59,7 +65,9 @@ def saddle_colored_by_derivative():
@example_wrapper
def ding_dong_surface():
f = sqrt(1.0 - y)*y
- p[1] = f, [x, 0, 2*pi, 40], [y, -1, 4, 100], 'mode=cylindrical; style=solid; color=zfade4'
+ p[1] = f, [x, 0, 2*pi,
+ 40], [y, -
+ 1, 4, 100], 'mode=cylindrical; style=solid; color=zfade4'
@example_wrapper
def polar_circle():
@@ -68,7 +76,8 @@ def polar_circle():
@example_wrapper
def polar_flower():
p[8] = 1.5*sin(4*x), [160], 'mode=polar'
- p[8].color = z, x, y, (0.5, 0.5, 0.5), (0.8, 0.8, 0.8), (x, y, None, z) # z is used for t
+ p[8].color = z, x, y, (0.5, 0.5, 0.5), (
+ 0.8, 0.8, 0.8), (x, y, None, z) # z is used for t
@example_wrapper
def simple_cylinder():
@@ -76,7 +85,7 @@ def simple_cylinder():
@example_wrapper
def cylindrical_hyperbola():
- ## (note that polar is an alias for cylindrical)
+ # (note that polar is an alias for cylindrical)
p[10] = 1/y, 'mode=polar', [x], [y, -2, 2, 20]
@example_wrapper
@@ -87,32 +96,34 @@ def extruded_hyperbolas():
@example_wrapper
def torus():
a, b = 1, 0.5 # radius, thickness
- p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x))*sin(y), b*sin(x), [x, 0, pi*2, 40], [y, 0, pi*2, 40]
+ p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x)) *\
+ sin(y), b*sin(x), [x, 0, pi*2, 40], [y, 0, pi*2, 40]
@example_wrapper
def warped_torus():
a, b = 2, 1 # radius, thickness
- p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x))*sin(y), b*sin(x) + 0.5*sin(4*y), [x, 0, pi*2, 40], [y, 0, pi*2, 40]
+ p[13] = (a + b*cos(x))*cos(y), (a + b*cos(x))*sin(y), b *\
+ sin(x) + 0.5*sin(4*y), [x, 0, pi*2, 40], [y, 0, pi*2, 40]
@example_wrapper
def parametric_spiral():
- p[14] = cos(y), sin(y), y/10.0, [y, -4*pi, 4*pi, 100]
+ p[14] = cos(y), sin(y), y / 10.0, [y, -4*pi, 4*pi, 100]
p[14].color = x, (0.1, 0.9), y, (0.1, 0.9), z, (0.1, 0.9)
@example_wrapper
def multistep_gradient():
p[1] = 1, 'mode=spherical', 'style=both'
- #p[1] = exp(-x**2-y**2+(x*y)/4), [-1.7,1.7,100], [-1.7,1.7,100], 'style=solid'
- #p[1] = 5*x*y*exp(-x**2-y**2), [-2,2,100], [-2,2,100]
- gradient = [ 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) ]
+ # p[1] = exp(-x**2-y**2+(x*y)/4), [-1.7,1.7,100], [-1.7,1.7,100], 'style=solid'
+ # p[1] = 5*x*y*exp(-x**2-y**2), [-2,2,100], [-2,2,100]
+ gradient = [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)]
p[1].color = z, [None, None, z], gradient
- #p[1].color = 'zfade'
- #p[1].color = 'zfade3'
+ # p[1].color = 'zfade'
+ # p[1].color = 'zfade3'
@example_wrapper
def lambda_vs_sympy_evaluation():
@@ -124,7 +135,9 @@ def lambda_vs_sympy_evaluation():
start = clock()
p[4] = x**2 + y**2, [100], [100], 'style=solid; use_sympy_eval'
p.wait_for_calculations()
- print("sympy substitution-based calculation took %s seconds." % (clock() - start))
+ print(
+ "sympy substitution-based calculation took %s seconds." %
+ (clock() - start))
@example_wrapper
def gradient_vectors():
@@ -140,13 +153,13 @@ def draw_gradient_vectors(f, iu, iv):
representing the gradient of f.
"""
dx, dy, dz = f.diff(x), f.diff(y), 0
- FF = lambdify( [x, y], [x, y, f] )
- FG = lambdify( [x, y], [dx, dy, dz] )
+ FF = lambdify([x, y], [x, y, f])
+ FG = lambdify([x, y], [dx, dy, dz])
iu.v_steps /= 5
iv.v_steps /= 5
Gvl = list(list([FF(u, v), FG(u, v)]
- for v in iv.frange())
- for u in iu.frange())
+ for v in iv.frange())
+ for u in iu.frange())
def draw_arrow(p1, p2):
"""
@@ -166,8 +179,8 @@ def draw():
glBegin(GL_LINES)
for u in Gvl:
for v in u:
- point = [ [v[0][0], v[0][1], v[0][2]],
- [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]] ]
+ point = [[v[0][0], v[0][1], v[0][2]],
+ [v[0][0] + v[1][0], v[0][1] + v[1][1], v[0][2] + v[1][2]]]
draw_arrow(point[0], point[1])
glEnd()
@@ -177,7 +190,7 @@ def draw():
iv = PlotInterval(p[i].intervals[1])
p[i].postdraw.append(draw_gradient_vectors(f, iu, iv))
- gradient_vectors_inner( x**2 + y**2, 1)
+ gradient_vectors_inner(x**2 + y**2, 1)
gradient_vectors_inner(-x**2 - y**2, 2)
def help_str():
diff --git a/examples/advanced/qft.py b/examples/advanced/qft.py
index df0d5ac..1bf0ef8 100755
--- a/examples/advanced/qft.py
+++ b/examples/advanced/qft.py
@@ -20,14 +20,14 @@
from sympy.physics import msigma, mgamma
-#gamma^mu
+# gamma^mu
gamma0 = mgamma(0)
gamma1 = mgamma(1)
gamma2 = mgamma(2)
gamma3 = mgamma(3)
gamma5 = mgamma(5)
-#sigma_i
+# sigma_i
sigma1 = msigma(1)
sigma2 = msigma(2)
sigma3 = msigma(3)
@@ -45,10 +45,11 @@ def u(p, r):
ksi = Matrix([[1], [0]])
else:
ksi = Matrix([[0], [1]])
- a = (sigma1*p1 + sigma2*p2 + sigma3*p3) / (E + m) * ksi
+ a = (sigma1*p1 + sigma2*p2 + sigma3*p3) / (E + m)*ksi
if a == 0:
a = zeros(2, 1)
- return sqrt(E + m) * Matrix([[ksi[0, 0]], [ksi[1, 0]], [a[0, 0]], [a[1, 0]]])
+ return sqrt(E + m) *\
+ Matrix([[ksi[0, 0]], [ksi[1, 0]], [a[0, 0]], [a[1, 0]]])
def v(p, r):
@@ -60,10 +61,11 @@ def v(p, r):
ksi = Matrix([[1], [0]])
else:
ksi = -Matrix([[0], [1]])
- a = (sigma1*p1 + sigma2*p2 + sigma3*p3) / (E + m) * ksi
+ a = (sigma1*p1 + sigma2*p2 + sigma3*p3) / (E + m)*ksi
if a == 0:
a = zeros(2, 1)
- return sqrt(E + m) * Matrix([[a[0, 0]], [a[1, 0]], [ksi[0, 0]], [ksi[1, 0]]])
+ return sqrt(E + m) *\
+ Matrix([[a[0, 0]], [a[1, 0]], [ksi[0, 0]], [ksi[1, 0]]])
def pslash(p):
@@ -77,7 +79,7 @@ def Tr(M):
def xprint(lhs, rhs):
- pprint( Eq(sympify(lhs), rhs ) )
+ pprint(Eq(sympify(lhs), rhs))
def main():
@@ -87,8 +89,8 @@ def main():
p = (a, b, c)
- assert u(p, 1).D * u(p, 2) == Matrix(1, 1, [0])
- assert u(p, 2).D * u(p, 1) == Matrix(1, 1, [0])
+ assert u(p, 1).D*u(p, 2) == Matrix(1, 1, [0])
+ assert u(p, 2).D*u(p, 1) == Matrix(1, 1, [0])
p1, p2, p3 = [Symbol(x, real=True) for x in ["p1", "p2", "p3"]]
pp1, pp2, pp3 = [Symbol(x, real=True) for x in ["pp1", "pp2", "pp3"]]
@@ -107,25 +109,25 @@ def main():
f = pslash(p) + m*ones(4)
g = pslash(p) - m*ones(4)
- #pprint(e)
- xprint( 'Tr(f*g)', Tr(f*g) )
- #print Tr(pslash(p) * pslash(k)).expand()
+ # pprint(e)
+ xprint('Tr(f*g)', Tr(f*g))
+ # print Tr(pslash(p)*pslash(k)).expand()
- M0 = [ ( v(pp, 1).D * mgamma(mu) * u(p, 1) ) * ( u(k, 1).D * mgamma(mu, True) *
- v(kp, 1) ) for mu in range(4)]
+ M0 = [(v(pp, 1).D*mgamma(mu)*u(p, 1))*(u(k, 1).D*mgamma(mu, True) *
+ v(kp, 1)) for mu in range(4)]
M = M0[0] + M0[1] + M0[2] + M0[3]
M = M[0]
if not isinstance(M, Basic):
raise TypeError("Invalid type of variable")
- #print M
- #print simplify(M)
+ # print M
+ # print simplify(M)
d = Symbol("d", real=True) # d=E+m
xprint('M', M)
print("-"*40)
- M = ((M.subs(E, d - m)).expand() * d**2 ).expand()
- xprint('M2', 1/(E + m)**2 * M)
+ M = ((M.subs(E, d - m)).expand()*d**2).expand()
+ xprint('M2', 1 / (E + m)**2*M)
print("-"*40)
x, y = M.as_real_imag()
xprint('Re(M)', x)
@@ -135,9 +137,9 @@ def main():
print("-"*40)
xprint('Expand(abs(M)**2)', e.expand())
- #print Pauli(1)*Pauli(1)
- #print Pauli(1)**2
- #print Pauli(1)*2*Pauli(1)
+ # print Pauli(1)*Pauli(1)
+ # print Pauli(1)**2
+ # print Pauli(1)*2*Pauli(1)
if __name__ == "__main__":
main()
diff --git a/examples/advanced/relativity.py b/examples/advanced/relativity.py
index 9243ca6..584d78c 100755
--- a/examples/advanced/relativity.py
+++ b/examples/advanced/relativity.py
@@ -97,12 +97,12 @@ def ud(self, mu, nu):
def curvature(Rmn):
return Rmn.ud(0, 0) + Rmn.ud(1, 1) + Rmn.ud(2, 2) + Rmn.ud(3, 3)
-#class nu(Function):
+# class nu(Function):
# def getname(self):
# return r"\nu"
# return r"nu"
-#class lam(Function):
+# class lam(Function):
# def getname(self):
# return r"\lambda"
# return r"lambda"
@@ -114,29 +114,29 @@ def curvature(Rmn):
theta = Symbol(r"theta")
phi = Symbol(r"phi")
-#general, spherically symmetric metric
+# general, spherically symmetric metric
gdd = Matrix((
(-exp(nu(r)), 0, 0, 0),
(0, exp(lam(r)), 0, 0),
(0, 0, r**2, 0),
(0, 0, 0, r**2*sin(theta)**2)
))
-#spherical - flat
-#gdd=Matrix((
+# spherical - flat
+# gdd=Matrix((
# (-1, 0, 0, 0),
# (0, 1, 0, 0),
# (0, 0, r**2, 0),
# (0, 0, 0, r**2*sin(theta)**2)
# ))
-#polar - flat
-#gdd=Matrix((
+# polar - flat
+# gdd=Matrix((
# (-1, 0, 0, 0),
# (0, 1, 0, 0),
# (0, 0, 1, 0),
# (0, 0, 0, r**2)
# ))
-#polar - on the sphere, on the north pole
-#gdd=Matrix((
+# polar - on the sphere, on the north pole
+# gdd=Matrix((
# (-1, 0, 0, 0),
# (0, 1, 0, 0),
# (0, 0, r**2*sin(theta)**2, 0),
@@ -216,9 +216,9 @@ def main():
pprint_Rmn_dd(1, 1)
pprint_Rmn_dd(2, 2)
pprint_Rmn_dd(3, 3)
- #print()
- #print "scalar curvature:"
- #print curvature(Rmn)
+ # print()
+ # print "scalar curvature:"
+ # print curvature(Rmn)
print("-"*40)
print("Solve Einstein's equations:")
e = e.subs(nu(r), -lam(r)).doit()
diff --git a/examples/galgebra/latex_check.py b/examples/galgebra/latex_check.py
index a22b6c8..ce2f038 100755
--- a/examples/galgebra/latex_check.py
+++ b/examples/galgebra/latex_check.py
@@ -6,11 +6,13 @@
from sympy.galgebra import xdvi, Get_Program, Print_Function
from sympy.galgebra import MV, Format, Com, Nga
+
def F(x):
global n, nbar
Fx = Rational(1, 2)*((x*x)*n + 2*x - nbar)
return(Fx)
+
def make_vector(a, n=3):
if isinstance(a, str):
sym_str = ''
@@ -22,6 +24,7 @@ def make_vector(a, n=3):
a = MV(sym_lst, 'vector')
return(F(a))
+
def basic_multivector_operations_3D():
Print_Function()
@@ -49,6 +52,7 @@ def basic_multivector_operations_3D():
(X | Y).Fmt(2, 'X|Y')
return
+
def basic_multivector_operations_2D():
Print_Function()
(ex, ey) = MV.setup('e*x|y')
@@ -66,6 +70,7 @@ def basic_multivector_operations_2D():
(A > X).Fmt(2, 'A>X')
return
+
def basic_multivector_operations_2D_orthogonal():
Print_Function()
(ex, ey) = MV.setup('e*x|y', metric='[1,1]')
@@ -89,6 +94,7 @@ def basic_multivector_operations_2D_orthogonal():
(A > X).Fmt(2, 'A>X')
return
+
def check_generalized_BAC_CAB_formulas():
Print_Function()
(a, b, c, d) = MV.setup('a b c d')
@@ -106,6 +112,7 @@ def check_generalized_BAC_CAB_formulas():
print('\\bm{(a^b)\\times (c^d)} =', Com(a ^ b, c ^ d))
return
+
def derivatives_in_rectangular_coordinates():
Print_Function()
X = (x, y, z) = symbols('x y z')
@@ -130,6 +137,7 @@ def derivatives_in_rectangular_coordinates():
print('grad|B =', grad | B)
return
+
def derivatives_in_spherical_coordinates():
Print_Function()
X = (r, th, phi) = symbols('r theta phi')
@@ -149,6 +157,7 @@ def derivatives_in_spherical_coordinates():
print('-I*(grad^A) =', (-MV.I*(grad ^ A)).simplify())
print('grad^B =', grad ^ B)
+
def rounding_numerical_components():
Print_Function()
(ex, ey, ez) = MV.setup('e_x e_y e_z', metric='[1,1,1]')
@@ -162,6 +171,7 @@ def rounding_numerical_components():
print('Nga(X*Y,2) =', Nga(X*Y, 2))
return
+
def noneuclidian_distance_calculation():
Print_Function()
from sympy import solve, sqrt
@@ -174,7 +184,7 @@ def noneuclidian_distance_calculation():
print('%(X\\W Y)^{2} =', (X ^ Y)*(X ^ Y))
L = X ^ Y ^ e
- B = L*e # D&L 10.152
+ B = L*e # D&L 10.152
Bsq = (B*B).scalar()
print('#%L = X\\W Y\\W e \\text{ is a non-euclidian line}')
print('B = L*e =', B)
@@ -185,18 +195,18 @@ def noneuclidian_distance_calculation():
print('%L^{2} =', L*L) # D&L 10.153
(s, c, Binv, M, BigS, BigC, alpha, XdotY, Xdote, Ydote) = symbols('s c (1/B) M S C alpha (X.Y) (X.e) (Y.e)')
- Bhat = Binv*B # D&L 10.154
- R = c + s*Bhat # Rotor R = exp(alpha*Bhat/2)
+ Bhat = Binv*B # D&L 10.154
+ R = c + s*Bhat # Rotor R = exp(alpha*Bhat/2)
print('#%s = \\f{\\sinh}{\\alpha/2} \\text{ and } c = \\f{\\cosh}{\\alpha/2}')
print('%e^{\\alpha B/{2\\abs{B}}} =', R)
- Z = R*X*R.rev() # D&L 10.155
+ Z = R*X*R.rev() # D&L 10.155
Z.obj = expand(Z.obj)
Z.obj = Z.obj.collect([Binv, s, c, XdotY])
Z.Fmt(3, '%RXR^{\\dagger}')
- W = Z | Y # Extract scalar part of multivector
+ W = Z | Y # Extract scalar part of multivector
# From this point forward all calculations are with sympy scalars
- #print '#Objective is to determine value of C = cosh(alpha) such that W = 0'
+ # print '#Objective is to determine value of C = cosh(alpha) such that W = 0'
W = W.scalar()
print('%W = Z\\cdot Y =', W)
W = expand(W)
@@ -209,7 +219,7 @@ def noneuclidian_distance_calculation():
Bmag = sqrt(XdotY**2 - 2*XdotY*Xdote*Ydote)
W = W.collect([Binv*c*s, XdotY])
- #Double angle substitutions
+ # Double angle substitutions
W = W.subs(2*XdotY**2 - 4*XdotY*Xdote*Ydote, 2/(Binv**2))
W = W.subs(2*c*s, BigS)
@@ -263,6 +273,7 @@ def noneuclidian_distance_calculation():
print('%\\f{\\cosh}{\\alpha} = C = -b/(2a) =', expand(simplify(expand(C))))
return
+
def conformal_representations_of_circles_lines_spheres_and_planes():
Print_Function()
global n, nbar
@@ -273,7 +284,7 @@ def conformal_representations_of_circles_lines_spheres_and_planes():
print('g_{ij} =', MV.metric)
e = n + nbar
- #conformal representation of points
+ # conformal representation of points
A = make_vector(e1) # point a = (1,0,0) A = F(a)
B = make_vector(e2) # point b = (0,1,0) B = F(b)
@@ -303,6 +314,7 @@ def conformal_representations_of_circles_lines_spheres_and_planes():
L.Fmt(3, 'Hyperbolic\\;\\; Circle: (A^B^e)^X = 0')
return
+
def properties_of_geometric_objects():
Print_Function()
metric = '# # # 0 0,' + \
@@ -333,6 +345,7 @@ def properties_of_geometric_objects():
print('(p2-p1)^(p3-p1)=', (p2 - p1) ^ (p3 - p1))
return
+
def extracting_vectors_from_conformal_2_blade():
Print_Function()
print(r'B = P1\W P2')
@@ -364,6 +377,7 @@ def extracting_vectors_from_conformal_2_blade():
print('a|B =', aB)
return
+
def reciprocal_frame_test():
Print_Function()
metric = '1 # #,' + \
@@ -426,9 +440,11 @@ def reciprocal_frame_test():
print('%(E3\\cdot e3)/E^{2} =', simplify(w/Esq))
return
+
def dummy():
return
+
def main():
Get_Program()
diff --git a/examples/galgebra/manifold_check.py b/examples/galgebra/manifold_check.py
index 344cfbd..0a5dd04 100755
--- a/examples/galgebra/manifold_check.py
+++ b/examples/galgebra/manifold_check.py
@@ -8,6 +8,7 @@
from sympy.galgebra.printing import GA_Printer, enhance_print, Get_Program, Print_Function
from sympy.galgebra.manifold import Manifold
+
def Test_Reciprocal_Frame():
Print_Function()
coords = symbols('x y z')
@@ -40,6 +41,7 @@ def Test_Reciprocal_Frame():
print('ev.ev_r =', ev | ev_r)
return
+
def Plot_Mobius_Strip_Manifold():
Print_Function()
coords = symbols('x y z')
@@ -50,6 +52,7 @@ def Plot_Mobius_Strip_Manifold():
MF.Plot2DSurface([0.0, 6.28, 48], [-0.3, 0.3, 12], surf=False, skip=[4, 4], tan=0.15)
return
+
def Distorted_manifold_with_scalar_function():
Print_Function()
coords = symbols('x y z')
@@ -78,6 +81,7 @@ def Distorted_manifold_with_scalar_function():
print('P(dPS) =', MF.Proj(MF.Grad(PS)))
return
+
def Simple_manifold_with_scalar_function_derivative():
Print_Function()
coords = (x, y, z) = symbols('x y z')
@@ -100,9 +104,11 @@ def Simple_manifold_with_scalar_function_derivative():
print('Vector derivative =', dg.subs({u: 1, v: 0}))
return
+
def dummy():
return
+
def main():
Get_Program(True)
with GA_Printer():
@@ -110,7 +116,7 @@ def main():
Test_Reciprocal_Frame()
Distorted_manifold_with_scalar_function()
Simple_manifold_with_scalar_function_derivative()
- #Plot_Mobius_Strip_Manifold()
+ # Plot_Mobius_Strip_Manifold()
return
if __name__ == "__main__":
diff --git a/examples/galgebra/manifold_check_latex.py b/examples/galgebra/manifold_check_latex.py
index e5c3757..7c216e6 100755
--- a/examples/galgebra/manifold_check_latex.py
+++ b/examples/galgebra/manifold_check_latex.py
@@ -8,6 +8,7 @@
from sympy.galgebra import xdvi, Get_Program, Print_Function
from sympy.galgebra import Manifold
+
def Test_Reciprocal_Frame():
Print_Function()
Format()
@@ -41,6 +42,7 @@ def Test_Reciprocal_Frame():
print(r'%\bm{e}_{v}\cdot\bm{e}^{v} =', ev | ev_r)
return
+
def Plot_Mobius_Strip_Manifold():
Print_Function()
coords = symbols('x y z')
@@ -51,6 +53,7 @@ def Plot_Mobius_Strip_Manifold():
MF.Plot2DSurface([0.0, 6.28, 48], [-0.3, 0.3, 12], surf=False, skip=[4, 4], tan=0.15)
return
+
def Distorted_manifold_with_scalar_function():
Print_Function()
coords = symbols('x y z')
@@ -78,6 +81,7 @@ def Distorted_manifold_with_scalar_function():
print('P(dP(S)) =', MF.Proj(MF.Grad(PS)))
return
+
def Simple_manifold_with_scalar_function_derivative():
Print_Function()
coords = (x, y, z) = symbols('x y z')
@@ -104,6 +108,7 @@ def Simple_manifold_with_scalar_function_derivative():
print('\\eval{\\nabla g}{u=1,v=0} =', dg.subs({u: 1, v: 0}))
return
+
def Simple_manifold_with_vector_function_derivative():
Print_Function()
coords = (x, y, z) = symbols('x y z')
@@ -134,9 +139,11 @@ def Simple_manifold_with_vector_function_derivative():
return
+
def dummy():
return
+
def main():
Get_Program()
@@ -144,7 +151,7 @@ def main():
Distorted_manifold_with_scalar_function()
Simple_manifold_with_scalar_function_derivative()
Simple_manifold_with_vector_function_derivative()
- #Plot_Mobius_Strip_Manifold()
+ # Plot_Mobius_Strip_Manifold()
xdvi()
return
diff --git a/examples/galgebra/matrix_latex.py b/examples/galgebra/matrix_latex.py
index 1fc2f22..c66ea4b 100755
--- a/examples/galgebra/matrix_latex.py
+++ b/examples/galgebra/matrix_latex.py
@@ -6,18 +6,19 @@
from sympy.galgebra import xdvi
from sympy.galgebra import Format
+
def main():
Format()
- a = Matrix( 2, 2, ( 1, 2, 3, 4 ) )
- b = Matrix( 2, 1, ( 5, 6 ) )
- c = a * b
+ a = Matrix(2, 2, (1, 2, 3, 4))
+ b = Matrix(2, 1, (5, 6))
+ c = a*b
print(a, b, '=', c)
- x, y = symbols( 'x, y' )
+ x, y = symbols('x, y')
- d = Matrix( 1, 2, ( x ** 3, y ** 3 ))
- e = Matrix( 2, 2, ( x ** 2, 2 * x * y, 2 * x * y, y ** 2 ) )
- f = d * e
+ d = Matrix(1, 2, (x**3, y**3))
+ e = Matrix(2, 2, (x**2, 2*x*y, 2*x*y, y**2))
+ f = d*e
print('%', d, e, '=', f)
diff --git a/examples/galgebra/physics_check_latex.py b/examples/galgebra/physics_check_latex.py
index 6b55a62..e7dda69 100755
--- a/examples/galgebra/physics_check_latex.py
+++ b/examples/galgebra/physics_check_latex.py
@@ -6,6 +6,7 @@
from sympy.galgebra import xdvi, Get_Program, Print_Function
from sympy.galgebra import MV, Format
+
def Maxwells_Equations_in_Geometric_Calculus():
Print_Function()
X = symbols('t x y z')
@@ -38,6 +39,7 @@ def Maxwells_Equations_in_Geometric_Calculus():
(gradF.grade(3)).Fmt(3, '%\\grade{\\nabla F}_{3} = 0')
return
+
def Dirac_Equation_in_Geometric_Calculus():
Print_Function()
vars = symbols('t x y z')
@@ -60,6 +62,7 @@ def Dirac_Equation_in_Geometric_Calculus():
return
+
def Lorentz_Tranformation_in_Geometric_Algebra():
Print_Function()
(alpha, beta, gamma) = symbols('alpha beta gamma')
@@ -87,9 +90,11 @@ def Lorentz_Tranformation_in_Geometric_Algebra():
print(r"%t\bm{\gamma_{t}}+x\bm{\gamma_{x}} =", Xpp.collect(gamma))
return
+
def dummy():
return
+
def main():
Get_Program()
Format()
diff --git a/examples/galgebra/simple_check_latex.py b/examples/galgebra/simple_check_latex.py
index 6db46b3..4c1d14d 100755
--- a/examples/galgebra/simple_check_latex.py
+++ b/examples/galgebra/simple_check_latex.py
@@ -5,6 +5,7 @@
from sympy.galgebra import xdvi, Get_Program, Print_Function
from sympy.galgebra import MV, Format
+
def basic_multivector_operations_3D():
Print_Function()
@@ -32,6 +33,7 @@ def basic_multivector_operations_3D():
(X | Y).Fmt(2, 'X|Y')
return
+
def basic_multivector_operations_2D():
Print_Function()
@@ -50,9 +52,11 @@ def basic_multivector_operations_2D():
(A > X).Fmt(2, 'A>X')
return
+
def dummy():
return
+
def main():
Get_Program(True)
Format()
diff --git a/examples/galgebra/spherical_latex.py b/examples/galgebra/spherical_latex.py
index 44a9626..baac997 100644
--- a/examples/galgebra/spherical_latex.py
+++ b/examples/galgebra/spherical_latex.py
@@ -6,6 +6,7 @@
from sympy.galgebra import MV, Format
from sympy.galgebra import xdvi, Get_Program, Print_Function
+
def derivatives_in_spherical_coordinates():
Print_Function()
X = (r, th, phi) = symbols('r theta phi')
@@ -25,9 +26,12 @@ def derivatives_in_spherical_coordinates():
print('-I*(grad^A) =', -MV.I*(grad ^ A))
print('grad^B =', grad ^ B)
return
+
+
def dummy():
return
+
def main():
Get_Program()
Format()
diff --git a/examples/galgebra/terminal_check.py b/examples/galgebra/terminal_check.py
index a48bca8..fb2c7d0 100755
--- a/examples/galgebra/terminal_check.py
+++ b/examples/galgebra/terminal_check.py
@@ -7,6 +7,7 @@
from sympy.galgebra import MV, Format, Com, Nga
from sympy.galgebra.printing import GA_Printer
+
def basic_multivector_operations():
Print_Function()
(ex, ey, ez) = MV.setup('e*x|y|z')
@@ -64,6 +65,7 @@ def basic_multivector_operations():
(A > X).Fmt(2, 'A>X')
return
+
def check_generalized_BAC_CAB_formulas():
Print_Function()
@@ -74,9 +76,18 @@ def check_generalized_BAC_CAB_formulas():
print('a|(b*c) =', a | (b*c))
print('a|(b^c) =', a | (b ^ c))
print('a|(b^c^d) =', a | (b ^ c ^ d))
- print('a|(b^c)+c|(a^b)+b|(c^a) =', (a | (b ^ c)) + (c | (a ^ b)) + (b | (c ^ a)))
+ print('a|(b^c)+c|(a^b)+b|(c^a) =', (a | (b ^ c)) +
+ (c | (a ^ b)) +
+ (b | (c ^ a)))
print('a*(b^c)-b*(a^c)+c*(a^b) =', a*(b ^ c) - b*(a ^ c) + c*(a ^ b))
- print('a*(b^c^d)-b*(a^c^d)+c*(a^b^d)-d*(a^b^c) =', a*(b ^ c ^ d) - b*(a ^ c ^ d) + c*(a ^ b ^ d) - d*(a ^ b ^ c))
+ print('a*(b^c^d)-b*(a^c^d)+c*(a^b^d)-d*(a^b^c) =', a *
+ (b ^ c ^ d) -
+ b *
+ (a ^ c ^ d) +
+ c *
+ (a ^ b ^ d) -
+ d *
+ (a ^ b ^ c))
print('(a^b)|(c^d) =', (a ^ b) | (c ^ d))
print('((a^b)|c)|d =', ((a ^ b) | c) | d)
print('(a^b)x(c^d) =', Com(a ^ b, c ^ d))
@@ -84,6 +95,7 @@ def check_generalized_BAC_CAB_formulas():
return
+
def derivatives_in_rectangular_coordinates():
Print_Function()
@@ -117,12 +129,25 @@ def derivatives_in_rectangular_coordinates():
return
+
def derivatives_in_spherical_coordinates():
Print_Function()
X = (r, th, phi) = symbols('r theta phi')
- curv = [[r*cos(phi)*sin(th), r*sin(phi)*sin(th), r*cos(th)], [1, r, r*sin(th)]]
- (er, eth, ephi, grad) = MV.setup('e_r e_theta e_phi', metric='[1,1,1]', coords=X, curv=curv)
+ curv = [[r *
+ cos(phi) *
+ sin(th), r *
+ sin(phi) *
+ sin(th), r *
+ cos(th)], [1, r, r *
+ sin(th)]]
+ (er,
+ eth,
+ ephi,
+ grad) = MV.setup('e_r e_theta e_phi',
+ metric='[1,1,1]',
+ coords=X,
+ curv=curv)
f = MV('f', 'scalar', fct=True)
A = MV('A', 'vector', fct=True)
@@ -138,6 +163,7 @@ def derivatives_in_spherical_coordinates():
print('grad^B =', grad ^ B)
return
+
def rounding_numerical_components():
Print_Function()
@@ -152,6 +178,7 @@ def rounding_numerical_components():
print('Nga(X*Y,2) =', Nga(X*Y, 2))
return
+
def noneuclidian_distance_calculation():
from sympy import solve, sqrt
Print_Function()
@@ -164,7 +191,7 @@ def noneuclidian_distance_calculation():
print('(X^Y)**2 =', (X ^ Y)*(X ^ Y))
L = X ^ Y ^ e
- B = L*e # D&L 10.152
+ B = L*e # D&L 10.152
print('B =', B)
Bsq = B*B
print('B**2 =', Bsq)
@@ -176,18 +203,19 @@ def noneuclidian_distance_calculation():
print('B*e*B.rev() =', BeBr)
print('B**2 =', B*B)
print('L**2 =', L*L) # D&L 10.153
- (s, c, Binv, M, BigS, BigC, alpha, XdotY, Xdote, Ydote) = symbols('s c (1/B) M S C alpha (X.Y) (X.e) (Y.e)')
+ (s, c, Binv, M, BigS, BigC, alpha, XdotY, Xdote, Ydote) = symbols(
+ 's c (1/B) M S C alpha (X.Y) (X.e) (Y.e)')
- Bhat = Binv*B # D&L 10.154
- R = c + s*Bhat # Rotor R = exp(alpha*Bhat/2)
+ Bhat = Binv*B # D&L 10.154
+ R = c + s*Bhat # Rotor R = exp(alpha*Bhat/2)
print('s = sinh(alpha/2) and c = cosh(alpha/2)')
print('exp(alpha*B/(2*|B|)) =', R)
- Z = R*X*R.rev() # D&L 10.155
+ Z = R*X*R.rev() # D&L 10.155
Z.obj = expand(Z.obj)
Z.obj = Z.obj.collect([Binv, s, c, XdotY])
Z.Fmt(3, 'R*X*R.rev()')
- W = Z | Y # Extract scalar part of multivector
+ W = Z | Y # Extract scalar part of multivector
# From this point forward all calculations are with sympy scalars
print('Objective is to determine value of C = cosh(alpha) such that W = 0')
W = W.scalar()
@@ -202,7 +230,7 @@ def noneuclidian_distance_calculation():
Bmag = sqrt(XdotY**2 - 2*XdotY*Xdote*Ydote)
W = W.collect([Binv*c*s, XdotY])
- #Double angle substitutions
+ # Double angle substitutions
W = W.subs(2*XdotY**2 - 4*XdotY*Xdote*Ydote, 2/(Binv**2))
W = W.subs(2*c*s, BigS)
@@ -255,11 +283,13 @@ def noneuclidian_distance_calculation():
print('cosh(alpha) = C = -b/(2*a) =', expand(simplify(expand(C))))
return
+
def F(x):
global n, nbar
Fx = Rational(1, 2)*((x*x)*n + 2*x - nbar)
return(Fx)
+
def make_vector(a, n=3):
if isinstance(a, str):
sym_str = ''
@@ -271,6 +301,7 @@ def make_vector(a, n=3):
a = MV(sym_lst, 'vector')
return(F(a))
+
def conformal_representations_of_circles_lines_spheres_and_planes():
global n, nbar
Print_Function()
@@ -282,7 +313,7 @@ def conformal_representations_of_circles_lines_spheres_and_planes():
print('g_{ij} =\n', MV.metric)
e = n + nbar
- #conformal representation of points
+ # conformal representation of points
A = make_vector(e1) # point a = (1,0,0) A = F(a)
B = make_vector(e2) # point b = (0,1,0) B = F(b)
@@ -312,6 +343,7 @@ def conformal_representations_of_circles_lines_spheres_and_planes():
L.Fmt(3, 'Hyperbolic Circle: (A^B^e)^X = 0 =')
return
+
def properties_of_geometric_objects():
Print_Function()
@@ -342,6 +374,7 @@ def properties_of_geometric_objects():
print('((C^n)|n)|nbar =', delta)
print('(p2-p1)^(p3-p1) =', (p2 - p1) ^ (p3 - p1))
+
def extracting_vectors_from_conformal_2_blade():
Print_Function()
@@ -372,6 +405,7 @@ def extracting_vectors_from_conformal_2_blade():
print('a|B =', aB)
return
+
def reciprocal_frame_test():
Print_Function()
@@ -435,9 +469,11 @@ def reciprocal_frame_test():
print('(E3|e3)/E**2 =', simplify(w/Esq))
return
+
def dummy():
return
+
def main():
Get_Program(True)
with GA_Printer():
diff --git a/examples/intermediate/mplot2d.py b/examples/intermediate/mplot2d.py
index 2c55db6..8f6353e 100755
--- a/examples/intermediate/mplot2d.py
+++ b/examples/intermediate/mplot2d.py
@@ -41,8 +41,8 @@ def mplot2d(f, var, show=True):
def main():
x = Symbol('x')
- #mplot2d(log(x), (x, 0, 2, 100))
- #mplot2d([sin(x), -sin(x)], (x, float(-2*pi), float(2*pi), 50))
+ # mplot2d(log(x), (x, 0, 2, 100))
+ # mplot2d([sin(x), -sin(x)], (x, float(-2*pi), float(2*pi), 50))
mplot2d([sqrt(x), -sqrt(x), sqrt(-x), -sqrt(-x)], (x, -40.0, 40.0, 80))
if __name__ == "__main__":
diff --git a/examples/intermediate/mplot3d.py b/examples/intermediate/mplot3d.py
index 53571b1..e13fdd7 100755
--- a/examples/intermediate/mplot3d.py
+++ b/examples/intermediate/mplot3d.py
@@ -33,7 +33,7 @@ def mplot3d(f, var1, var2, show=True):
fig = p.figure()
ax = p3.Axes3D(fig)
- #ax.plot_surface(x,y,z) #seems to be a bug in matplotlib
+ # ax.plot_surface(x,y,z) #seems to be a bug in matplotlib
ax.plot_wireframe(x, y, z)
ax.set_xlabel('X')
@@ -49,8 +49,8 @@ def main():
y = Symbol('y')
mplot3d(x**2 - y**2, (x, -10.0, 10.0, 20), (y, -10.0, 10.0, 20))
- #mplot3d(x**2+y**2, (x, -10.0, 10.0, 20), (y, -10.0, 10.0, 20))
- #mplot3d(sin(x)+sin(y), (x, -3.14, 3.14, 10), (y, -3.14, 3.14, 10))
+ # mplot3d(x**2+y**2, (x, -10.0, 10.0, 20), (y, -10.0, 10.0, 20))
+ # mplot3d(sin(x)+sin(y), (x, -3.14, 3.14, 10), (y, -3.14, 3.14, 10))
if __name__ == "__main__":
main()
diff --git a/examples/intermediate/sample.py b/examples/intermediate/sample.py
index 4e87db3..08d2f08 100644
--- a/examples/intermediate/sample.py
+++ b/examples/intermediate/sample.py
@@ -89,7 +89,7 @@ def meshgrid(x, y):
for j in range(len(X)):
for k in range(len(X[0])):
try:
- Z[j][k] = float( f.subs(x, X[j][k]).subs(y, Y[j][k]) )
+ Z[j][k] = float(f.subs(x, X[j][k]).subs(y, Y[j][k]))
except (TypeError, NotImplementedError):
Z[j][k] = 0
return X, Y, Z
diff --git a/examples/intermediate/trees.py b/examples/intermediate/trees.py
index 63264fc..de6adc7 100755
--- a/examples/intermediate/trees.py
+++ b/examples/intermediate/trees.py
@@ -17,7 +17,7 @@
def T(x):
return x + x**2 + 2*x**3 + 4*x**4 + 9*x**5 + 20*x**6 + 48 * x**7 + \
- 115* x**8 + 286*x**9 + 719*x**10
+ 115*x**8 + 286*x**9 + 719*x**10
def A(x):
diff --git a/examples/intermediate/vandermonde.py b/examples/intermediate/vandermonde.py
index eb3f6af..5511484 100755
--- a/examples/intermediate/vandermonde.py
+++ b/examples/intermediate/vandermonde.py
@@ -129,7 +129,7 @@ def main():
det(V) = %(det)s
\sum = %(sum)s
= %(sum_expand)s
- """ % { "det": V.det(),
+ """ % {"det": V.det(),
"sum": det_sum,
"sum_expand": det_sum.expand(),
})
@@ -143,7 +143,7 @@ def main():
Quadratic function, represented by 3 points:
points = %(pts)s
f = %(f)s
- """ % { "pts" : points,
+ """ % {"pts": points,
"f": gen_poly(points, 2, [x]),
})
@@ -153,7 +153,7 @@ def main():
2D Quadratic function, represented by 6 points:
points = %(pts)s
f = %(f)s
- """ % { "pts" : points,
+ """ % {"pts": points,
"f": gen_poly(points, 2, [x, y]),
})
@@ -162,7 +162,7 @@ def main():
3D linear function, represented by 4 points:
points = %(pts)s
f = %(f)s
- """ % { "pts" : points,
+ """ % {"pts": points,
"f": gen_poly(points, 1, [x, y, z]),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment