Showing posts with label Python (programming language). Show all posts
Showing posts with label Python (programming language). Show all posts

Sunday, December 4, 2016

Python: Returning Polynomial Function

Command:

$ cat makePoly.py 


Result:

# ax + b
def makePoly(arr):
    def fn(x):
        return sum(c*x**p for p,c in enumerate(arr))
    return fn

my_func = makePoly([6, 2])
print my_func(3) #return 12


Command:

$ python makePoly.py 


Result:

12

Python: Pi and Natural Logarithm

Command:

$ cat pi_and_natural_logarithm.py


Result:

import math

print 'Pi: %.30f' % math.pi
print 'e: %.30f' % math.e


Command:

$ python pi_and_natural_logarithm.py


Result:

Pi: 3.141592653589793115997963468544
e: 2.718281828459045090795598298428


Saturday, December 3, 2016

Python: Farey Sequence: The Farey sequences of orders 8

Command:

$ cat farey.py


Result:

def farey( n, asc=True ):
    if asc:
        a, b, c, d = 0, 1, 1 , n
    else:
        a, b, c, d = 1, 1, n-1, n
    print "%d/%d" % (a,b)
    while (asc and c <= n) or (not asc and a > 0):
        k = int((n + b)/d)
        a, b, c, d = c, d, k*c - a, k*d - b
        print "%d/%d" % (a,b)
farey(8)


Command:

$ python farey.py


Result:

0/1
1/8
1/7
1/6
1/5
1/4
2/7
1/3
3/8
2/5
3/7
1/2
4/7
3/5
5/8
2/3
5/7
3/4
4/5
5/6
6/7
7/8
1/1

Saturday, November 26, 2016

macOS Sierra: Installing 3Blue1Brown Animation Engine for Explanatory Math Videos

Command:

$ git clone https://github.com/3b1b/manim.git


Result:

Cloning into 'manim'...
remote: Counting objects: 2652, done.
remote: Compressing objects: 100% (71/71), done.
remote: Total 2652 (delta 33), reused 0 (delta 0), pack-reused 2581
Receiving objects: 100% (2652/2652), 1.46 MiB | 736.00 KiB/s, done.
Resolving deltas: 100% (1976/1976), done.


Command:

$ cd manim
$ sudo pip install -r requirements.txt
Password:


Result:

The directory '/Users/USERNAME/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/USERNAME/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Requirement already satisfied (use --upgrade to upgrade): colour==0.1.2 in /usr/local/lib/python2.7/site-packages (from -r requirements.txt (line 1))
Requirement already satisfied (use --upgrade to upgrade): numpy==1.11.0 in /usr/local/lib/python2.7/site-packages (from -r requirements.txt (line 2))
Collecting Pillow==3.4.2 (from -r requirements.txt (line 3))
  Downloading Pillow-3.4.2-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (3.4MB)
    100% |████████████████████████████████| 3.5MB 408kB/s
Collecting progressbar==2.3 (from -r requirements.txt (line 4))
Collecting scipy==0.17.1 (from -r requirements.txt (line 5))
  Downloading scipy-0.17.1-cp27-cp27m-macosx_10_6_intel.macosx_10_9_intel.macosx_10_9_x86_64.macosx_10_10_intel.macosx_10_10_x86_64.whl (21.1MB)
    100% |████████████████████████████████| 21.1MB 69kB/s
Collecting tqdm==4.7.1 (from -r requirements.txt (line 6))
  Downloading tqdm-4.7.1-py2.py3-none-any.whl
Installing collected packages: Pillow, progressbar, scipy, tqdm
Successfully installed Pillow-3.4.2 progressbar-2.3 scipy-0.17.1 tqdm-4.7.1
You are using pip version 8.1.2, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.


Command (After installing aggdraw):

$ python extract_scene.py -p example_scenes.py SquareToCircle


Result:

Animation 1: ShowCreationSquare: 100%|█████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:00<00:00, 240.61it/s]
Animation 2: TransformSquareToCircle: 100%|████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████████| 20/20 [00:00<00:00, 233.58it/s]


Graphical result:

3Blue1Brown Animation engine running in Python


macOS Sierra: Installing aggdraw

Command:

$ git clone https://github.com/scottopell/aggdraw-64bits


Result:

Cloning into 'aggdraw-64bits'...
remote: Counting objects: 219, done.
remote: Total 219 (delta 0), reused 0 (delta 0), pack-reused 219
Receiving objects: 100% (219/219), 309.41 KiB | 387.00 KiB/s, done.
Resolving deltas: 100% (107/107), done.


Command:

$ cd aggdraw-64bits/
$ python setup.py build_ext -i


Result:

=== freetype support disabled
running build_ext
building 'aggdraw' extension
creating build
creating build/temp.macosx-10.12-x86_64-2.7
creating build/temp.macosx-10.12-x86_64-2.7/agg2
creating build/temp.macosx-10.12-x86_64-2.7/agg2/src
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c aggdraw.cxx -o build/temp.macosx-10.12-x86_64-2.7/aggdraw.o
aggdraw.cxx:1122:5: warning: delete called on 'draw_adaptor_base' that is abstract but has non-virtual destructor [-Wdelete-non-virtual-dtor]
    delete self->draw;
    ^
aggdraw.cxx:169:21: warning: unused variable 'FontType' [-Wunused-variable]
static PyTypeObject FontType = {
                    ^
2 warnings generated.
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_arc.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_arc.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_bezier_arc.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_bezier_arc.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_curves.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_curves.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_path_storage.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_path_storage.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_rasterizer_scanline_aa.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_rasterizer_scanline_aa.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_trans_affine.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_trans_affine.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_vcgen_contour.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_contour.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_vcgen_stroke.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_stroke.o
clang++ -bundle -undefined dynamic_lookup -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk build/temp.macosx-10.12-x86_64-2.7/aggdraw.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_arc.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_bezier_arc.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_curves.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_path_storage.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_rasterizer_scanline_aa.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_trans_affine.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_contour.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_stroke.o -L/usr/local/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/sqlite/lib -o /Users/USERNAME/aggdraw-64bits/aggdraw.so


Command:

$ python setup.py install


Result:

=== freetype support disabled
running install
running build
running build_ext
building 'aggdraw' extension
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c aggdraw.cxx -o build/temp.macosx-10.12-x86_64-2.7/aggdraw.o
aggdraw.cxx:1122:5: warning: delete called on 'draw_adaptor_base' that is abstract but has non-virtual destructor [-Wdelete-non-virtual-dtor]
    delete self->draw;
    ^
aggdraw.cxx:169:21: warning: unused variable 'FontType' [-Wunused-variable]
static PyTypeObject FontType = {
                    ^
2 warnings generated.
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_arc.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_arc.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_bezier_arc.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_bezier_arc.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_curves.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_curves.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_path_storage.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_path_storage.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_rasterizer_scanline_aa.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_rasterizer_scanline_aa.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_trans_affine.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_trans_affine.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_vcgen_contour.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_contour.o
clang -fno-strict-aliasing -fno-common -dynamic -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk -I/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk/System/Library/Frameworks/Tk.framework/Versions/8.5/Headers -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -Iagg2/include -I/usr/local/include -I/usr/local/opt/openssl/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c agg2/src/agg_vcgen_stroke.cpp -o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_stroke.o
creating build/lib.macosx-10.12-x86_64-2.7
clang++ -bundle -undefined dynamic_lookup -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.12.sdk build/temp.macosx-10.12-x86_64-2.7/aggdraw.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_arc.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_bezier_arc.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_curves.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_path_storage.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_rasterizer_scanline_aa.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_trans_affine.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_contour.o build/temp.macosx-10.12-x86_64-2.7/agg2/src/agg_vcgen_stroke.o -L/usr/local/lib -L/usr/local/opt/openssl/lib -L/usr/local/opt/sqlite/lib -o build/lib.macosx-10.12-x86_64-2.7/aggdraw.so
running install_lib
copying build/lib.macosx-10.12-x86_64-2.7/aggdraw.so -> /usr/local/lib/python2.7/site-packages
running install_egg_info
Writing /usr/local/lib/python2.7/site-packages/aggdraw-1.1_64bits-py2.7.egg-info

Thursday, October 27, 2016

macOS Sierra: Python Script Using Tor

Command:

$ /opt/local/bin/tor --hash-password "test"


Result:

16:3F088C0E24C9C9A460EAD2F1E2C15953A4FEECCB2FA2155C5458E778FC

Command:

$ cat /opt/local/etc/tor/torrc

## Configuration file for a typical Tor user
## Last updated 22 September 2015 for Tor 0.2.7.3-alpha.
## (may or may not work for much older or much newer versions of Tor.)
##
## Lines that begin with "## " try to explain what's going on. Lines
## that begin with just "#" are disabled commands: you can enable them
## by removing the "#" symbol.
##
## See 'man tor', or https://www.torproject.org/docs/tor-manual.html,
## for more options you can use in this file.
##
## Tor will look for this file in various places based on your platform:
## https://www.torproject.org/docs/faq#torrc

## Tor opens a SOCKS proxy on port 9050 by default -- even if you don't
## configure one below. Set "SOCKSPort 0" if you plan to run Tor only
## as a relay, and not make any local application connections yourself.
#SOCKSPort 9050 # Default: Bind to localhost:9050 for local connections.
#SOCKSPort 192.168.0.1:9100 # Bind to this address:port too.

## Entry policies to allow/deny SOCKS requests based on IP address.
## First entry that matches wins. If no SOCKSPolicy is set, we accept
## all (and only) requests that reach a SOCKSPort. Untrusted users who
## can access your SOCKSPort may be able to learn about the connections
## you make.
#SOCKSPolicy accept 192.168.0.0/16
#SOCKSPolicy accept6 FC00::/7
#SOCKSPolicy reject *

## Logs go to stdout at level "notice" unless redirected by something
## else, like one of the below lines. You can have as many Log lines as
## you want.
##
## We advise using "notice" in most cases, since anything more verbose
## may provide sensitive information to an attacker who obtains the logs.
##
## Send all messages of level 'notice' or higher to /opt/local/var/log/tor/notices.log
#Log notice file /opt/local/var/log/tor/notices.log
## Send every possible message to /opt/local/var/log/tor/debug.log
#Log debug file /opt/local/var/log/tor/debug.log
## Use the system log instead of Tor's logfiles
#Log notice syslog
## To send all messages to stderr:
#Log debug stderr

## Uncomment this to start the process in the background... or use
## --runasdaemon 1 on the command line. This is ignored on Windows;
## see the FAQ entry if you want Tor to run as an NT service.
#RunAsDaemon 1

## The directory for keeping all the keys/etc. By default, we store
## things in $HOME/.tor on Unix, and in Application Data\tor on Windows.
#DataDirectory /opt/local/var/lib/tor

## The port on which Tor will listen for local connections from Tor
## controller applications, as documented in control-spec.txt.
ControlPort 9051
## If you enable the controlport, be sure to enable one of these
## authentication methods, to prevent attackers from accessing it.
HashedControlPassword 16:3F088C0E24C9C9A460EAD2F1E2C15953A4FEECCB2FA2155C5458E778FC
CookieAuthentication 1

############### This section is just for location-hidden services ###

## Once you have configured a hidden service, you can look at the
## contents of the file ".../hidden_service/hostname" for the address
## to tell people.
##
## HiddenServicePort x y:z says to redirect requests on port x to the
## address y:z.

#HiddenServiceDir /opt/local/var/lib/tor/hidden_service/
#HiddenServicePort 80 127.0.0.1:80

#HiddenServiceDir /opt/local/var/lib/tor/other_hidden_service/
#HiddenServicePort 80 127.0.0.1:80
#HiddenServicePort 22 127.0.0.1:22

################ This section is just for relays #####################
#
## See https://www.torproject.org/docs/tor-doc-relay for details.

## Required: what port to advertise for incoming Tor connections.
#ORPort 9001
## If you want to listen on a port other than the one advertised in
## ORPort (e.g. to advertise 443 but bind to 9090), you can do it as
## follows.  You'll need to do ipchains or other port forwarding
## yourself to make this work.
#ORPort 443 NoListen
#ORPort 127.0.0.1:9090 NoAdvertise

## The IP address or full DNS name for incoming connections to your
## relay. Leave commented out and Tor will guess.
#Address noname.example.com

## If you have multiple network interfaces, you can specify one for
## outgoing traffic to use.
# OutboundBindAddress 10.0.0.5

## A handle for your relay, so people don't have to refer to it by key.
#Nickname ididnteditheconfig

## Define these to limit how much relayed traffic you will allow. Your
## own traffic is still unthrottled. Note that RelayBandwidthRate must
## be at least 20 kilobytes per second.
## Note that units for these config options are bytes (per second), not
## bits (per second), and that prefixes are binary prefixes, i.e. 2^10,
## 2^20, etc.
#RelayBandwidthRate 100 KBytes  # Throttle traffic to 100KB/s (800Kbps)
#RelayBandwidthBurst 200 KBytes # But allow bursts up to 200KB (1600Kb)

## Use these to restrict the maximum traffic per day, week, or month.
## Note that this threshold applies separately to sent and received bytes,
## not to their sum: setting "40 GB" may allow up to 80 GB total before
## hibernating.
##
## Set a maximum of 40 gigabytes each way per period.
#AccountingMax 40 GBytes
## Each period starts daily at midnight (AccountingMax is per day)
#AccountingStart day 00:00
## Each period starts on the 3rd of the month at 15:00 (AccountingMax
## is per month)
#AccountingStart month 3 15:00

## Administrative contact information for this relay or bridge. This line
## can be used to contact you if your relay or bridge is misconfigured or
## something else goes wrong. Note that we archive and publish all
## descriptors containing these lines and that Google indexes them, so
## spammers might also collect them. You may want to obscure the fact that
## it's an email address and/or generate a new address for this purpose.
#ContactInfo Random Person <nobody AT example dot com>
## You might also include your PGP or GPG fingerprint if you have one:
#ContactInfo 0xFFFFFFFF Random Person <nobody AT example dot com>

## Uncomment this to mirror directory information for others. Please do
## if you have enough bandwidth.
#DirPort 9030 # what port to advertise for directory connections
## If you want to listen on a port other than the one advertised in
## DirPort (e.g. to advertise 80 but bind to 9091), you can do it as
## follows.  below too. You'll need to do ipchains or other port
## forwarding yourself to make this work.
#DirPort 80 NoListen
#DirPort 127.0.0.1:9091 NoAdvertise
## Uncomment to return an arbitrary blob of html on your DirPort. Now you
## can explain what Tor is if anybody wonders why your IP address is
## contacting them. See contrib/tor-exit-notice.html in Tor's source
## distribution for a sample.
#DirPortFrontPage /opt/local/etc/tor/tor-exit-notice.html

## Uncomment this if you run more than one Tor relay, and add the identity
## key fingerprint of each Tor relay you control, even if they're on
## different networks. You declare it here so Tor clients can avoid
## using more than one of your relays in a single circuit. See
## https://www.torproject.org/docs/faq#MultipleRelays
## However, you should never include a bridge's fingerprint here, as it would
## break its concealability and potentially reveal its IP/TCP address.
#MyFamily $keyid,$keyid,...

## A comma-separated list of exit policies. They're considered first
## to last, and the first match wins.
##
## If you want to allow the same ports on IPv4 and IPv6, write your rules
## using accept/reject *. If you want to allow different ports on IPv4 and
## IPv6, write your IPv6 rules using accept6/reject6 *6, and your IPv4 rules
## using accept/reject *4.
##
## If you want to _replace_ the default exit policy, end this with either a
## reject *:* or an accept *:*. Otherwise, you're _augmenting_ (prepending to)
## the default exit policy. Leave commented to just use the default, which is
## described in the man page or at
## https://www.torproject.org/documentation.html
##
## Look at https://www.torproject.org/faq-abuse.html#TypicalAbuses
## for issues you might encounter if you use the default exit policy.
##
## If certain IPs and ports are blocked externally, e.g. by your firewall,
## you should update your exit policy to reflect this -- otherwise Tor
## users will be told that those destinations are down.
##
## For security, by default Tor rejects connections to private (local)
## networks, including to the configured primary public IPv4 and IPv6 addresses,
## and any public IPv4 and IPv6 addresses on any interface on the relay.
## See the man page entry for ExitPolicyRejectPrivate if you want to allow
## "exit enclaving".
##
#ExitPolicy accept *:6660-6667,reject *:* # allow irc ports on IPv4 and IPv6 but no more
#ExitPolicy accept *:119 # accept nntp ports on IPv4 and IPv6 as well as default exit policy
#ExitPolicy accept *4:119 # accept nntp ports on IPv4 only as well as default exit policy
#ExitPolicy accept6 *6:119 # accept nntp ports on IPv6 only as well as default exit policy
#ExitPolicy reject *:* # no exits allowed

## Bridge relays (or "bridges") are Tor relays that aren't listed in the
## main directory. Since there is no complete public list of them, even an
## ISP that filters connections to all the known Tor relays probably
## won't be able to block all the bridges. Also, websites won't treat you
## differently because they won't know you're running Tor. If you can
## be a real relay, please do; but if not, be a bridge!
#BridgeRelay 1
## By default, Tor will advertise your bridge to users through various
## mechanisms like https://bridges.torproject.org/. If you want to run
## a private bridge, for example because you'll give out your bridge
## address manually to your friends, uncomment this line:
#PublishServerDescriptor 0


Command:

$ /opt/local/bin/tor &


Result:

[1] 6463
Oct 27 15:00:19.225 [notice] Tor v0.2.8.9 running on Darwin with Libevent 2.0.22-stable, OpenSSL 1.0.2j and Zlib 1.2.8.
Oct 27 15:00:19.226 [notice] Tor can't help you if you use it wrong! Learn how to be safe at https://www.torproject.org/download/download#warning
Oct 27 15:00:19.226 [notice] Read configuration file "/opt/local/etc/tor/torrc".
Oct 27 15:00:19.229 [notice] Opening Socks listener on 127.0.0.1:9050
Oct 27 15:00:19.229 [notice] Opening Control listener on 127.0.0.1:9051
Oct 27 15:00:19.000 [notice] Parsing GEOIP IPv4 file /opt/local/share/tor/geoip.
Oct 27 15:00:19.000 [notice] Parsing GEOIP IPv6 file /opt/local/share/tor/geoip6.
Oct 27 15:00:19.000 [notice] Bootstrapped 0%: Starting
Oct 27 15:00:19.000 [notice] Bootstrapped 80%: Connecting to the Tor network
Oct 27 15:00:20.000 [notice] Bootstrapped 85%: Finishing handshake with first hop
Oct 27 15:00:21.000 [notice] Bootstrapped 90%: Establishing a Tor circuit
Oct 27 15:00:23.000 [notice] Tor has successfully opened a circuit. Looks like client functionality is working.
Oct 27 15:00:23.000 [notice] Bootstrapped 100%: Done


Command:

$ cat tor.py


Result:

from stem.control import Controller

with Controller.from_port(port = 9051) as controller:
    controller.authenticate()

    bytes_read = controller.get_info("traffic/read")
    bytes_written = controller.get_info("traffic/written")

    print("My Tor relay has read %s bytes and written %s." % (bytes_read, bytes_written))


Command:

$ python tor.py


Result:

Oct 27 15:02:42.000 [notice] New control connection opened from 127.0.0.1.
My Tor relay has read 687342 bytes and written 42071.

macOS Sierra: Tor (anonymity network): Installing ARM (The anonymizing relay monitor): Incomplete

Command:

$ git clone https://git.torproject.org/nyx.git


Result:

Cloning into 'nyx'...
remote: Counting objects: 11674, done.
remote: Compressing objects: 100% (76/76), done.
remote: Total 11674 (delta 42), reused 0 (delta 0)
Receiving objects: 100% (11674/11674), 2.71 MiB | 446.00 KiB/s, done.
Resolving deltas: 100% (9078/9078), done.


Command:

$ cd nyx
$ python setup.py


Result (Error):

Traceback (most recent call last):
  File "setup.py", line 10, in <module>
    import nyx
  File "/Users/USERNAME/nyx/nyx/__init__.py", line 41, in <module>
    import stem
ImportError: No module named stem


Command:

$ sudo pip install stem
Password:


Result:

The directory '/Users/USERNAME/Library/Caches/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
The directory '/Users/USERNAME/Library/Caches/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.
Collecting stem
  Downloading stem-1.4.0.tar.bz2 (1.6MB)
    100% |████████████████████████████████| 1.6MB 718kB/s
Installing collected packages: stem
  Running setup.py install for stem ... done
Successfully installed stem-1.4.0


Command:

$ python setup.py


Result (Error):

Traceback (most recent call last):
  File "setup.py", line 10, in <module>
    import nyx
  File "/Users/USERNAME/nyx/nyx/__init__.py", line 521, in <module>
    import nyx.panel.config
  File "/Users/USERNAME/nyx/nyx/panel/config.py", line 17, in <module>
    import stem.manual
ImportError: No module named manual


Command:

$ python


Result:

Python 2.7.12 (default, Oct 19 2016, 01:11:34)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.


Command:

>>> import sys
>>> sys.path


Result:

['', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python27.zip', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old', '/usr/local/Cellar/python/2.7.12_2/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/site-packages', '/usr/local/Cellar/matplotlib/1.5.1/libexec/lib/python2.7/site-packages', '/usr/local/Cellar/numpy/1.11.2/libexec/nose/lib/python2.7/site-packages', '/Library/Python/2.7/site-packages/pip-8.1.1-py2.7.egg', '/Library/Python/2.7/site-packages']


Command:

>>> quit()
$ ls -al /usr/local/lib/python2.7/site-packages/stem/


Result (Missing stem.manual):

total 1136
drwxr-xr-x  22 root  wheel     748 Oct 27 12:06 .
drwxr-xr-x  43 USERNAME  wheel    1462 Oct 27 12:06 ..
-rw-r--r--   1 root  wheel   25346 May 14  2015 __init__.py
-rw-r--r--   1 root  wheel   27294 Oct 27 12:06 __init__.pyc
-rw-r--r--   1 root  wheel   48656 May 14  2015 connection.py
-rw-r--r--   1 root  wheel   45507 Oct 27 12:06 connection.pyc
-rw-r--r--   1 root  wheel  128760 May 14  2015 control.py
-rw-r--r--   1 root  wheel  118390 Oct 27 12:06 control.pyc
drwxr-xr-x  24 root  wheel     816 Oct 27 12:06 descriptor
-rw-r--r--   1 root  wheel   34569 May 14  2015 exit_policy.py
-rw-r--r--   1 root  wheel   31176 Oct 27 12:06 exit_policy.pyc
drwxr-xr-x  13 root  wheel     442 Oct 27 12:06 interpreter
-rw-r--r--   1 root  wheel    3430 May 14  2015 prereq.py
-rw-r--r--   1 root  wheel    4029 Oct 27 12:06 prereq.pyc
-rw-r--r--   1 root  wheel    8996 May 14  2015 process.py
-rw-r--r--   1 root  wheel    7768 Oct 27 12:06 process.pyc
drwxr-xr-x  18 root  wheel     612 Oct 27 12:06 response
-rw-r--r--   1 root  wheel   21337 May 14  2015 socket.py
-rw-r--r--   1 root  wheel   19283 Oct 27 12:06 socket.pyc
drwxr-xr-x  29 root  wheel     986 Oct 27 12:06 util
-rw-r--r--   1 root  wheel   12810 May 14  2015 version.py
-rw-r--r--   1 root  wheel   14866 Oct 27 12:06 version.pyc

Monday, October 3, 2016

Python: ONIOFF - Onion URL Inspector: Installing and Running

Command:

$ git clone https://github.com/k4m4/onioff


Result:

Cloning into 'onioff'...
remote: Counting objects: 57, done.
remote: Compressing objects: 100% (27/27), done.
remote: Total 57 (delta 30), reused 52 (delta 25), pack-reused 0
Unpacking objects: 100% (57/57), done.


Command:

$ cd onioff
$ ls


Result:

CHANGES.rst README.rst onioff.py requirements.txt
LICENSE VERSION reports termcolor.py


Command:

$ cat requirements.txt


Result:

requests
pysocks


Command:

$ pip install -r requirements.txt


Result:

Collecting requests (from -r requirements.txt (line 1))
  Downloading requests-2.11.1-py2.py3-none-any.whl (514kB)
    100% |████████████████████████████████| 522kB 1.5MB/s
Collecting pysocks (from -r requirements.txt (line 2))
  Downloading PySocks-1.5.7.tar.gz
Collecting beautifulsoup4 (from -r requirements.txt (line 3))
  Downloading beautifulsoup4-4.5.1-py2-none-any.whl (83kB)
    100% |████████████████████████████████| 92kB 4.1MB/s
Building wheels for collected packages: pysocks
  Running setup.py bdist_wheel for pysocks ... done
  Stored in directory: /Users/USERNAME/Library/Caches/pip/wheels/cf/81/67/77884514e566867d5223e5530e27ce9b9433b78c766a400313
Successfully built pysocks
Installing collected packages: requests, pysocks, beautifulsoup4
Successfully installed beautifulsoup4-4.5.1 pysocks-1.5.7 requests-2.11.1


Command:

$ python onioff.py -h


Result:

 ██████╗ ███╗   ██╗██╗ ██████╗ ███████╗███████╗
██╔═══██╗████╗  ██║██║██╔═══██╗██╔════╝██╔════╝
██║   ██║██╔██╗ ██║██║██║   ██║█████╗  █████╗
██║   ██║██║╚██╗██║██║██║   ██║██╔══╝  ██╔══╝
╚██████╔╝██║ ╚████║██║╚██████╔╝██║     ██║
 ╚═════╝ ╚═╝  ╚═══╝╚═╝ ╚═════╝ ╚═╝     ╚═╝ v0.1

          Onion URL Inspector (ONIOFF)        
  Made With <3 by: Nikolaos Kamarinakis (k4m4)
                  Version: 0.1                
Usage: python onioff.py {onion} [options]

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -f FILE, --file=FILE  onion filename
  -o OUTPUT_FILE, --output=OUTPUT_FILE
                        output filename

Examples:
  python onioff.py http://xmh57jrzrnw6insl.onion/
  python onioff.py -f ~/onions.txt -o ~/report.txt
  python onioff.py https://facebookcorewwwi.onion/ -o ~/report.txt


Command:

$ python onioff.py -f ~/onions.txt -o ~/report.txt


Result:

 ██████╗ ███╗   ██╗██╗ ██████╗ ███████╗███████╗
██╔═══██╗████╗  ██║██║██╔═══██╗██╔════╝██╔════╝
██║   ██║██╔██╗ ██║██║██║   ██║█████╗  █████╗
██║   ██║██║╚██╗██║██║██║   ██║██╔══╝  ██╔══╝
╚██████╔╝██║ ╚████║██║╚██████╔╝██║     ██║
 ╚═════╝ ╚═╝  ╚═══╝╚═╝ ╚═════╝ ╚═╝     ╚═╝ v0.1

          Onion URL Inspector (ONIOFF)        
  Made With <3 by: Nikolaos Kamarinakis (k4m4)
                  Version: 0.1                

[+] Commencing Onion Inspection
[-] Tor Offline --> Please Make Sure Tor Is Running
[-] System Exit




Thursday, September 29, 2016

Python: Matplotlib: Mathtext Examples

Noteworthy:

matplotlib.pyplot.fill_between()


Command:

$ cat Downloads/mathtext_examples.py


Result:

"""
Selected features of Matplotlib's math rendering engine.
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import os
import sys
import re
import gc

# Selection of features following "Writing mathematical expressions" tutorial
mathtext_titles = {
    0: "Header demo",
    1: "Subscripts and superscripts",
    2: "Fractions, binomials and stacked numbers",
    3: "Radicals",
    4: "Fonts",
    5: "Accents",
    6: "Greek, Hebrew",
    7: "Delimiters, functions and Symbols"}
n_lines = len(mathtext_titles)

# Randomly picked examples
mathext_demos = {
    0: r"$W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = "
    r"U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} "
    r"\int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ "
    r"U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_"
    r"{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$",

    1: r"$\alpha_i > \beta_i,\ "
    r"\alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ "
    r"\ldots$",

    2: r"$\frac{3}{4},\ \binom{3}{4},\ \stackrel{3}{4},\ "
    r"\left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$",

    3: r"$\sqrt{2},\ \sqrt[3]{x},\ \ldots$",

    4: r"$\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ "
    r"\mathrm{or}\ \mathcal{CALLIGRAPHY}$",

    5: r"$\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ "
    r"\hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ "
    r"\ldots$",

    6: r"$\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ "
    r"\Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ "
    r"\aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$",

    7: r"$\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ "
    r"\log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ "
    r"\infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$"}


def doall():
    # Colors used in mpl online documentation.
    mpl_blue_rvb = (191./255., 209./256., 212./255.)
    mpl_orange_rvb = (202/255., 121/256., 0./255.)
    mpl_grey_rvb = (51./255., 51./255., 51./255.)

    # Creating figure and axis.
    plt.figure(figsize=(6, 7))
    plt.axes([0.01, 0.01, 0.98, 0.90], axisbg="white", frameon=True)
    plt.gca().set_xlim(0., 1.)
    plt.gca().set_ylim(0., 1.)
    plt.gca().set_title("Matplotlib's math rendering engine",
                        color=mpl_grey_rvb, fontsize=14, weight='bold')
    plt.gca().set_xticklabels("", visible=False)
    plt.gca().set_yticklabels("", visible=False)

    # Gap between lines in axes coords
    line_axesfrac = (1. / (n_lines))

    # Plotting header demonstration formula
    full_demo = mathext_demos[0]
    plt.annotate(full_demo,
                 xy=(0.5, 1. - 0.59*line_axesfrac),
                 xycoords='data', color=mpl_orange_rvb, ha='center',
                 fontsize=20)

    # Plotting features demonstration formulae
    for i_line in range(1, n_lines):
        baseline = 1. - (i_line)*line_axesfrac
        baseline_next = baseline - line_axesfrac*1.
        title = mathtext_titles[i_line] + ":"
        fill_color = ['white', mpl_blue_rvb][i_line % 2]
        plt.fill_between([0., 1.], [baseline, baseline],
                         [baseline_next, baseline_next],
                         color=fill_color, alpha=0.5)
        plt.annotate(title,
                     xy=(0.07, baseline - 0.3*line_axesfrac),
                     xycoords='data', color=mpl_grey_rvb, weight='bold')
        demo = mathext_demos[i_line]
        plt.annotate(demo,
                     xy=(0.05, baseline - 0.75*line_axesfrac),
                     xycoords='data', color=mpl_grey_rvb,
                     fontsize=16)

    for i in range(n_lines):
        s = mathext_demos[i]
        print(i, s)
    plt.savefig('pyplot_mathtext_examples.png')

if '--latex' in sys.argv:
    # Run: python mathtext_examples.py --latex
    # Need amsmath and amssymb packages.
    fd = open("mathtext_examples.ltx", "w")
    fd.write("\\documentclass{article}\n")
    fd.write("\\usepackage{amsmath, amssymb}\n")
    fd.write("\\begin{document}\n")
    fd.write("\\begin{enumerate}\n")

    for i in range(n_lines):
        s = mathext_demos[i]
        s = re.sub(r"(?<!\\)\$", "$$", s)
        fd.write("\\item %s\n" % s)

    fd.write("\\end{enumerate}\n")
    fd.write("\\end{document}\n")
    fd.close()

    os.system("pdflatex mathtext_examples.ltx")
else:
    doall()


Command:

$ python Downloads/mathtext_examples.py


Result:

0 $W^{3\beta}_{\delta_1 \rho_1 \sigma_2} = U^{3\beta}_{\delta_1 \rho_1} + \frac{1}{8 \pi 2} \int^{\alpha_2}_{\alpha_2} d \alpha^\prime_2 \left[\frac{ U^{2\beta}_{\delta_1 \rho_1} - \alpha^\prime_2U^{1\beta}_{\rho_1 \sigma_2} }{U^{0\beta}_{\rho_1 \sigma_2}}\right]$
1 $\alpha_i > \beta_i,\ \alpha_{i+1}^j = {\rm sin}(2\pi f_j t_i) e^{-5 t_i/\tau},\ \ldots$
2 $\frac{3}{4},\ \binom{3}{4},\ \stackrel{3}{4},\ \left(\frac{5 - \frac{1}{x}}{4}\right),\ \ldots$
3 $\sqrt{2},\ \sqrt[3]{x},\ \ldots$
4 $\mathrm{Roman}\ , \ \mathit{Italic}\ , \ \mathtt{Typewriter} \ \mathrm{or}\ \mathcal{CALLIGRAPHY}$
5 $\acute a,\ \bar a,\ \breve a,\ \dot a,\ \ddot a, \ \grave a, \ \hat a,\ \tilde a,\ \vec a,\ \widehat{xyz},\ \widetilde{xyz},\ \ldots$
6 $\alpha,\ \beta,\ \chi,\ \delta,\ \lambda,\ \mu,\ \Delta,\ \Gamma,\ \Omega,\ \Phi,\ \Pi,\ \Upsilon,\ \nabla,\ \aleph,\ \beth,\ \daleth,\ \gimel,\ \ldots$
7 $\coprod,\ \int,\ \oint,\ \prod,\ \sum,\ \log,\ \sin,\ \approx,\ \oplus,\ \star,\ \varpropto,\ \infty,\ \partial,\ \Re,\ \leftrightsquigarrow, \ \ldots$


Graphical output:

pyplot_mathtext_examples.png


Python: Matplotlib: XKCD-Style Sketch Plot Example

Noteworthy:

matplotlib.pyplot.xkcd()
matplotlib.pyplot.annotate()


Command:

$ cat Downloads/xkcd.py


Result:

import matplotlib.pyplot as plt
import numpy as np

with plt.xkcd():
    # Based on "Stove Ownership" from XKCD by Randall Monroe
    # http://xkcd.com/418/

    fig = plt.figure()
    ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    plt.xticks([])
    plt.yticks([])
    ax.set_ylim([-30, 10])

    data = np.ones(100)
    data[70:] -= np.arange(30)

    plt.annotate(
        'THE DAY I REALIZED\nI COULD COOK BACON\nWHENEVER I WANTED',
        xy=(70, 1), arrowprops=dict(arrowstyle='->'), xytext=(15, -10))

    plt.plot(data)

    plt.xlabel('time')
    plt.ylabel('my overall health')
    fig.text(
        0.5, 0.05,
        '"Stove Ownership" from xkcd by Randall Monroe',
        ha='center')

    plt.savefig('pyplot_xkcd_figure1.png')

    # Based on "The Data So Far" from XKCD by Randall Monroe
    # http://xkcd.com/373/

    fig = plt.figure()
    ax = fig.add_axes((0.1, 0.2, 0.8, 0.7))
    ax.bar([-0.125, 1.0 - 0.125], [0, 100], 0.25)
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    ax.xaxis.set_ticks_position('bottom')
    ax.set_xticks([0, 1])
    ax.set_xlim([-0.5, 1.5])
    ax.set_ylim([0, 110])
    ax.set_xticklabels(['CONFIRMED BY\nEXPERIMENT', 'REFUTED BY\nEXPERIMENT'])
    plt.yticks([])

    plt.title("CLAIMS OF SUPERNATURAL POWERS")

    fig.text(
        0.5, 0.05,
        '"The Data So Far" from xkcd by Randall Monroe',
        ha='center')
   
    plt.savefig('pyplot_xkcd_figure2.png')

plt.show()


Graphical output:

pyplot_xkcd_figure1.png
pyplot_xkcd_figure2.png

Python: Matplotlib: Polar Plot Example

Noteworthy:

ax.set_rmax()


Command:

$ cat Downloads/polar_demo.py


Result:

"""
Demo of a line plot on a polar axis.
"""
import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')
r = np.arange(0, 3.0, 0.01)
theta = 2 * np.pi * r

ax = plt.subplot(111, projection='polar')
ax.plot(theta, r, color='r', linewidth=3)
ax.set_rmax(2.0)
ax.grid(True)

ax.set_title("A line plot on a polar axis", va='bottom')
plt.savefig('pyplot_polar_demo.png')


Graphical output:

pyplot_polar_demo.png

Python: Matplotlib: Logarithm Example

Noteworthy:

matplotlib.pyplot.subplots_adjust()
numpy.arange()
matplotlib.pyplot.semilogy()
matplotlib.pyplot.semilogx()
matplotlib.pyplot.loglog()
matplotlib.pyplot.errorbar()


Command:

$ cat Downloads/log_demo.py


Result:

import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')
plt.subplots_adjust(hspace=0.4)
t = np.arange(0.01, 20.0, 0.01)

# log y axis
plt.subplot(221)
plt.semilogy(t, np.exp(-t/5.0))
plt.title('semilogy')
plt.grid(True)

# log x axis
plt.subplot(222)
plt.semilogx(t, np.sin(2*np.pi*t))
plt.title('semilogx')
plt.grid(True)

# log x and y axis
plt.subplot(223)
plt.loglog(t, 20*np.exp(-t/10.0), basex=2)
plt.grid(True)
plt.title('loglog base 4 on x')

# with errorbars: clip non-positive values
ax = plt.subplot(224)
ax.set_xscale("log", nonposx='clip')
ax.set_yscale("log", nonposy='clip')

x = 10.0**np.linspace(0.0, 2.0, 20)
y = x**2.0
plt.errorbar(x, y, xerr=0.1*x, yerr=5.0 + 0.75*y)
ax.set_ylim(ymin=0.1)
ax.set_title('Errorbars go negative')

plt.savefig('pyplot_log_demo.png')


Command:

$ python Downloads/log_demo.py


Graphical output:

pyplot_log_demo..png


Python: Matplotlib: Finance Example

Noteworthy:

datetime.date(2006, 1, 1)
datetime.date.today()
finance.fetch_historical_yahoo(ticker, startdate, enddate)
mlab.csv2rec(fh)
fh.close()
r.sort()
np.asarray(x)
np.ones(n)
weights.sum()
np.convolve(x, weights, mode='full')[:len(x)]
np.diff(prices)
np.zeros_like(prices)
...


Command:

$ cat Downloads/finance_work2.py


Result:

import datetime
import numpy as np
import matplotlib.colors as colors
import matplotlib.finance as finance
import matplotlib.dates as mdates
import matplotlib.ticker as mticker
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import matplotlib.font_manager as font_manager

plt.style.use('dark_background')

startdate = datetime.date(2006, 1, 1)
today = enddate = datetime.date.today()
ticker = 'SPY'

fh = finance.fetch_historical_yahoo(ticker, startdate, enddate)
# a numpy record array with fields: date, open, high, low, close, volume, adj_close)

r = mlab.csv2rec(fh)
fh.close()
r.sort()

def moving_average(x, n, type='simple'):
    """
    compute an n period moving average.

    type is 'simple' | 'exponential'

    """
    x = np.asarray(x)
    if type == 'simple':
        weights = np.ones(n)
    else:
        weights = np.exp(np.linspace(-1., 0., n))

    weights /= weights.sum()

    a = np.convolve(x, weights, mode='full')[:len(x)]
    a[:n] = a[n]
    return a

def relative_strength(prices, n=14):
    """
    compute the n period relative strength indicator
    http://stockcharts.com/school/doku.php?id=chart_school:glossary_r#relativestrengthindex
    http://www.investopedia.com/terms/r/rsi.asp
    """

    deltas = np.diff(prices)
    seed = deltas[:n+1]
    up = seed[seed >= 0].sum()/n
    down = -seed[seed < 0].sum()/n
    rs = up/down
    rsi = np.zeros_like(prices)
    rsi[:n] = 100. - 100./(1. + rs)

    for i in range(n, len(prices)):
        delta = deltas[i - 1]  # cause the diff is 1 shorter

        if delta > 0:
            upval = delta
            downval = 0.
        else:
            upval = 0.
            downval = -delta

        up = (up*(n - 1) + upval)/n
        down = (down*(n - 1) + downval)/n

        rs = up/down
        rsi[i] = 100. - 100./(1. + rs)

    return rsi

def moving_average_convergence(x, nslow=26, nfast=12):
    """
    compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
    return value is emaslow, emafast, macd which are len(x) arrays
    """
    emaslow = moving_average(x, nslow, type='exponential')
    emafast = moving_average(x, nfast, type='exponential')
    return emaslow, emafast, emafast - emaslow

plt.rc('axes', grid=True)
plt.rc('grid', color='0.75', linestyle='-', linewidth=0.5)

textsize = 9
left, width = 0.1, 0.8
rect1 = [left, 0.7, width, 0.2]
rect2 = [left, 0.3, width, 0.4]
rect3 = [left, 0.1, width, 0.2]

fig = plt.figure(facecolor='white')
axescolor = '#f6f6f6'  # the axes background color

ax1 = fig.add_axes(rect1, axisbg=axescolor)  # left, bottom, width, height
ax2 = fig.add_axes(rect2, axisbg=axescolor, sharex=ax1)
ax2t = ax2.twinx()
ax3 = fig.add_axes(rect3, axisbg=axescolor, sharex=ax1)

# plot the relative strength indicator
prices = r.adj_close
rsi = relative_strength(prices)
fillcolor = 'darkgoldenrod'

ax1.plot(r.date, rsi, color=fillcolor)
ax1.axhline(70, color=fillcolor)
ax1.axhline(30, color=fillcolor)
ax1.fill_between(r.date, rsi, 70, where=(rsi >= 70), facecolor=fillcolor, edgecolor=fillcolor)
ax1.fill_between(r.date, rsi, 30, where=(rsi <= 30), facecolor=fillcolor, edgecolor=fillcolor)
ax1.text(0.6, 0.9, '>70 = overbought', va='top', transform=ax1.transAxes, fontsize=textsize)
ax1.text(0.6, 0.1, '<30 = oversold', transform=ax1.transAxes, fontsize=textsize)
ax1.set_ylim(0, 100)
ax1.set_yticks([30, 70])
ax1.text(0.025, 0.95, 'RSI (14)', va='top', transform=ax1.transAxes, fontsize=textsize)
ax1.set_title('%s daily' % ticker)

# plot the price and volume data
dx = r.adj_close - r.close
low = r.low + dx
high = r.high + dx

deltas = np.zeros_like(prices)
deltas[1:] = np.diff(prices)
up = deltas > 0
ax2.vlines(r.date[up], low[up], high[up], color='black', label='_nolegend_')
ax2.vlines(r.date[~up], low[~up], high[~up], color='black', label='_nolegend_')
ma20 = moving_average(prices, 20, type='simple')
ma200 = moving_average(prices, 200, type='simple')

linema20, = ax2.plot(r.date, ma20, color='blue', lw=2, label='MA (20)')
linema200, = ax2.plot(r.date, ma200, color='red', lw=2, label='MA (200)')

last = r[-1]
s = '%s O:%1.2f H:%1.2f L:%1.2f C:%1.2f, V:%1.1fM Chg:%+1.2f' % (
    today.strftime('%d-%b-%Y'),
    last.open, last.high,
    last.low, last.close,
    last.volume*1e-6,
    last.close - last.open)
t4 = ax2.text(0.3, 0.9, s, transform=ax2.transAxes, fontsize=textsize)

props = font_manager.FontProperties(size=10)
leg = ax2.legend(loc='center left', shadow=True, fancybox=True, prop=props)
leg.get_frame().set_alpha(0.5)

volume = (r.close*r.volume)/1e6  # dollar volume in millions
vmax = volume.max()
poly = ax2t.fill_between(r.date, volume, 0, label='Volume', facecolor=fillcolor, edgecolor=fillcolor)
ax2t.set_ylim(0, 5*vmax)
ax2t.set_yticks([])

# compute the MACD indicator
fillcolor = 'darkslategrey'
nslow = 26
nfast = 12
nema = 9
emaslow, emafast, macd = moving_average_convergence(prices, nslow=nslow, nfast=nfast)
ema9 = moving_average(macd, nema, type='exponential')
ax3.plot(r.date, macd, color='black', lw=2)
ax3.plot(r.date, ema9, color='blue', lw=1)
ax3.fill_between(r.date, macd - ema9, 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)

ax3.text(0.025, 0.95, 'MACD (%d, %d, %d)' % (nfast, nslow, nema), va='top',
         transform=ax3.transAxes, fontsize=textsize)

#ax3.set_yticks([])
# turn off upper axis tick labels, rotate the lower ones, etc
for ax in ax1, ax2, ax2t, ax3:
    if ax != ax3:
        for label in ax.get_xticklabels():
            label.set_visible(False)
    else:
        for label in ax.get_xticklabels():
            label.set_rotation(30)
            label.set_horizontalalignment('right')

    ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')

class MyLocator(mticker.MaxNLocator):
    def __init__(self, *args, **kwargs):
        mticker.MaxNLocator.__init__(self, *args, **kwargs)

    def __call__(self, *args, **kwargs):
        return mticker.MaxNLocator.__call__(self, *args, **kwargs)

# at most 5 ticks, pruning the upper and lower so they don't overlap
# with other ticks
#ax2.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both'))
#ax3.yaxis.set_major_locator(mticker.MaxNLocator(5, prune='both'))

ax2.yaxis.set_major_locator(MyLocator(5, prune='both'))
ax3.yaxis.set_major_locator(MyLocator(5, prune='both'))

plt.savefig("pyplot_finance_work2.png")


Graphical output:

pyplot_finance_work2.png


Python: Matplotlib: Fill Example

Noteworthy:

matplotlib.pyplot.fill()


Command:

$ cat Downloads/fill_demo.py


Result:

"""
Simple demo of the fill function.
"""
import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')

x = np.linspace(0, 1)
y = np.sin(4 * np.pi * x) * np.exp(-5 * x)

plt.fill(x, y, 'r')
plt.grid(True)

plt.savefig("pyplot_fill.png")


Command:

$ python Downloads/fill_demo.py 
$ open pyplot_fill.png 


Graphical output:



Python: Matplotlib: Pie Chart Example

Noteworthy:

matplotlib.pyplot.pie()
ax.pie()
ax.set_xticks()
ax.set_yticks()
ax.set_xticklabels()
ax.set_yticklabels()
ax.set_xlim()
ax.set_ylim()
ax.set_aspect()


Command:

$ cat Downloads/pie_demo_features.py


Result:

"""
Demo of a basic pie chart plus a few additional features.

In addition to the basic pie chart, this demo shows a few optional features:

    * slice labels
    * auto-labeling the percentage
    * offsetting a slice with "explode"
    * drop-shadow
    * custom start angle

Note about the custom start angle:

The default ``startangle`` is 0, which would start the "Frogs" slice on the
positive x-axis. This example sets ``startangle = 90`` such that everything is
rotated counter-clockwise by 90 degrees, and the frog slice starts on the
positive y-axis.
"""
import matplotlib.pyplot as plt

plt.style.use('dark_background')

# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, colors=colors,
        autopct='%1.1f%%', shadow=True, startangle=90)
# Set aspect ratio to be equal so that pie is drawn as a circle.
plt.axis('equal')

fig = plt.figure()
ax = fig.gca()
import numpy as np

ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90,
       radius=0.25, center=(0, 0), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90,
       radius=0.25, center=(1, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90,
       radius=0.25, center=(0, 1), frame=True)
ax.pie(np.random.random(4), explode=explode, labels=labels, colors=colors,
       autopct='%1.1f%%', shadow=True, startangle=90,
       radius=0.25, center=(1, 0), frame=True)

ax.set_xticks([0, 1])
ax.set_yticks([0, 1])
ax.set_xticklabels(["Sunny", "Cloudy"])
ax.set_yticklabels(["Dry", "Rainy"])
ax.set_xlim((-0.5, 1.5))
ax.set_ylim((-0.5, 1.5))

# Set aspect ratio to be equal so that pie is drawn as a circle.
ax.set_aspect('equal')

plt.show()


Command:

$ python Downloads/pie_demo_features.py


Graphical output:

Figure 1
Figure 2


Python: Matplotlib: Path Example

Noteworthy:

matplotlib.path.Path
Path.MOVETO
Path.CURVE4
Path.LINETO
Path.CLOSEPOLY
matplotlib.patches.PathPatch()
ax.add_patch()
zip()
path.vertices
ax.grid()
ax.axis()


Command:

$ cat Downloads/path_patch_demo.py


Result:

"""
Demo of a PathPatch object.
"""
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

plt.style.use('dark_background')

fig, ax = plt.subplots()

Path = mpath.Path
path_data = [
    (Path.MOVETO, (1.58, -2.57)),
    (Path.CURVE4, (0.35, -1.1)),
    (Path.CURVE4, (-1.75, 2.0)),
    (Path.CURVE4, (0.375, 2.0)),
    (Path.LINETO, (0.85, 1.15)),
    (Path.CURVE4, (2.2, 3.2)),
    (Path.CURVE4, (3, 0.05)),
    (Path.CURVE4, (2.0, -0.5)),
    (Path.CLOSEPOLY, (1.58, -2.57)),
    ]
codes, verts = zip(*path_data)
path = mpath.Path(verts, codes)
patch = mpatches.PathPatch(path, facecolor='r', alpha=0.5)
ax.add_patch(patch)

# plot control points and connecting lines
x, y = zip(*path.vertices)
line, = ax.plot(x, y, 'go-')

ax.grid()
ax.axis('equal')
plt.show()


Command:

$ python Downloads/path_patch_demo.py


Graphical output:






Wednesday, September 28, 2016

Python: Matplotlib: Streamplot (2D Vector Field) Example

Noteworthy:

numpy.mgrid
numpy.sqrt
matplotlib.pyplot.subplots()
matplotlib.pyplot.cm.autumn
streamplot()
strm.linesspeed.max()


Command:

$ cat Downloads/streamplot_demo_features.py


Result:

"""
Demo of the `streamplot` function.

A streamplot, or streamline plot, is used to display 2D vector fields. This
example shows a few features of the stream plot function:

    * Varying the color along a streamline.
    * Varying the density of streamlines.
    * Varying the line width along a stream line.
"""
import numpy as np
import matplotlib.pyplot as plt

plt.style.use('dark_background')

Y, X = np.mgrid[-3:3:100j, -3:3:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
speed = np.sqrt(U*U + V*V)

fig0, ax0 = plt.subplots()
strm = ax0.streamplot(X, Y, U, V, color=U, linewidth=2, cmap=plt.cm.autumn)
fig0.colorbar(strm.lines)

fig1, (ax1, ax2) = plt.subplots(ncols=2)
ax1.streamplot(X, Y, U, V, density=[0.5, 1])

lw = 5*speed / speed.max()
ax2.streamplot(X, Y, U, V, density=0.6, color='k', linewidth=lw)

plt.show()


Command:

$ python Downloads/streamplot_demo_features.py


Graphical output:

fig0

fig1 (w/ unknown error on right side)
fig1 (Normal background style)


Python: Matplotlib: Sine Function Example

Noteworthy:

numpy.sin()
numpy.pi


Command:

$ cat Downloads/simple_plot.py


Result:

import matplotlib.pyplot as plt
import numpy as np

t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2*np.pi*t)
plt.plot(t, s)

plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.savefig("test.png")
plt.show()


Command:

$ python Downloads/simple_plot.py


Graphical output:

Python: Matplotlib: Lorenz Attractor Example

Noteworthy:

def
for in
range()
numpy.empty()
set_xlabel()
set_ylabel()
set_zlabel()
set_title()


Command:

$ cat Downloads/lorenz_attractor.py


Result:

# Plot of the Lorenz Attractor based on Edward Lorenz's 1963 "Deterministic
# Nonperiodic Flow" publication.
# http://journals.ametsoc.org/doi/abs/10.1175/1520-0469%281963%29020%3C0130%3ADNF%3E2.0.CO%3B2
#
# Note: Because this is a simple non-linear ODE, it would be more easily
#       done using SciPy's ode solver, but this approach depends only
#       upon NumPy.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

plt.style.use('dark_background')

def lorenz(x, y, z, s=10, r=28, b=2.667):
    x_dot = s*(y - x)
    y_dot = r*x - y - x*z
    z_dot = x*y - b*z
    return x_dot, y_dot, z_dot


dt = 0.01
stepCnt = 10000

# Need one more for the initial values
xs = np.empty((stepCnt + 1,))
ys = np.empty((stepCnt + 1,))
zs = np.empty((stepCnt + 1,))

# Setting initial values
xs[0], ys[0], zs[0] = (0., 1., 1.05)

# Stepping through "time".
for i in range(stepCnt):
    # Derivatives of the X, Y, Z state
    x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i])
    xs[i + 1] = xs[i] + (x_dot * dt)
    ys[i + 1] = ys[i] + (y_dot * dt)
    zs[i + 1] = zs[i] + (z_dot * dt)

fig = plt.figure()
ax = fig.gca(projection='3d')

ax.plot(xs, ys, zs)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")

plt.show()


Command:

$ python Downloads/lorenz_attractor.py


Graphical output: