• Stars
    star
    1,327
  • Rank 35,420 (Top 0.7 %)
  • Language
    Python
  • Created over 11 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

The book "Annotated Algorithms in Python" and the nlib.py library

Annotated Algorithms in Python (3.8)

With applications in Physics, Biology, and Finance

The complete book in PDF is now available under a Creative Commons BY-NC-ND License:

DOWNLOAD BOOK IN PDF

The book is also available in printed form from Amazon:

Amazon

The nlib library

The book builds a numerical library from the ground up, called src/nlib.py. It is a pure python library for numerical computations. It doesn't require numpy.

Usage

>>> from nlib import *

Linear algebra example

>>> A = Matrix([[1,2],[4,9]])
>>> print 1/A 
>>> print (A+2)*A
>>> B = Matrix(2,2,lambda i,j: i+j**2)

Fitting

>>> points = [(x0,y0,dy0), (x1,y1,dy1), (x2,y2,dy2), ...]
>>> coefficients, chi2, fitting_function = fit_least_squares(points,POLYNOMIAL(2))
>>> for x,y,dy in points:
>>>     print x, y, '~', fitting_function(x)

Solvers

>>> from math import sin
>>> def f(x): return sin(x)-1+x
>>> x0 = solve_newton(f, 0.0, ap=0.01, rp=0.01, ns=100)
>>> print 'f(%s)=%s ~ 0' % (x0, f(x0))

(ap is target absolute precision, rp is target relative precision, ns is max number of steps)

Optimizers

>>> def f(x): return (sin(x)-1+x)**2
>>> x0 = optimize_newton(f, 0.0, ap=0.01, rp=0.01, ns=100)
>>> print 'f(%s)=%s ~ min f' % (x0, f(x0))    
>>> print 'f'(%s)=%s ~ 0' % (x0, D(f)(x0))    

Statistics

>>> x = [random.random() for k in range(100)]
>>> print 'mu     =', mean(x)
>>> print 'sigma  =', sd(x)
>>> print 'E[x]   =', E(lambda x:x,    x)
>>> print 'E[x^2] =', E(lambda x:x**2, x)
>>> print 'E[x^3] =', E(lambda x:x**3, x)
>>> y = [random.random() for k in range(100)]
>>> print 'corr(x,y) = ', correlation(x,y)
>>> print 'cov(x,y)  = ', covariance(x,y)

Finance

>>> google = YStock('GOOG')
>>> current = google.current()
>>> print current['price']                                                                          
>>> print current['market_cap']                                                                
>>> for day in google.historical():
>>>     print day['date'], day['adjusted_close'], day['log_return']

Persistant Storage

>>> d = PersistentDictionary(path='test.sqlite')
>>> d['key'] = 'value'
>>> print d['key']
>>> del d['key']

d works like a drop-in preplacement for any normal Python dictionary except that the data is stored in a sqlite database in a file called "test.sqlite" so it is still there if you re-start the program. Kind of like the shelve module but shelve files cannot safely be accessed by multiple threads/processes unless locked and locking the entire file is not efficient.

Neural Network

>>> pat = [[[0,0], [0]], [[0,1], [1]], [[1,0], [1]], [[1,1], [0]]]
>>> n = NeuralNetwork(2, 2, 1)
>>> n.train(pat)
>>> n.test(pat)
[0, 0] -> [0.00...]
[0, 1] -> [0.98...]
[1, 0] -> [0.98...]
[1, 1] -> [-0.00...]

Plotting

>>> data = [(x0,y0), ...]
>>> Canvas(title='my plot').plot(data, color='red').save('myplot.png')

nlib plotting requires matplotlib/numpy for the Canvas object only plots are chainable. methods: .plot, .hist, .errorbar, .ellipses

Complete list of functions/classes

CONSTANT
CUBIC
Canvas
Cholesky
Cluster
D
DD
Dijkstra
DisjointSets
E
Ellipse
HAVE_MATPLOTLIB
Jacobi_eigenvalues
Kruskal
LINEAR
MCEngine
MCG
Markowitz
MarsenneTwister
Matrix
NeuralNetwork
POLYNOMIAL
PersistentDictionary
Prim
PrimVertex
QUADRATIC
QUARTIC
QuadratureIntegrator
RandomSource
StringIO
Trader
YStock
bootstrap
breadth_first_search
compute_correlation
condition_number
confidence_intervals
continuum_knapsack
correlation
covariance
decode_huffman
depth_first_search
encode_huffman
fib
fit
fit_least_squares
gradient
hessian
integrate
integrate_naive
integrate_quadrature_naive
invert_bicgstab
invert_minimum_residual
is_almost_symmetric
is_almost_zero
is_positive_definite
jacobian
lcs
leapfrog
make_maze
mean
memoize
memoize_persistent
needleman_wunsch
norm
optimize_bisection
optimize_golden_search
optimize_newton
optimize_newton_multi (multi-dimentional optimizer)
optimize_newton_multi_imporved
optimize_secant
partial
random
resample
sd
solve_bisection
solve_fixed_point
solve_newton
solve_newton_multi (multi-dimensional solver)
solve_secant
variance

License

Created by Massimo Di Pierro ([email protected]) @2016 BSDv3 License

More Repositories

1

workflow

minimalist file based workflow
Python
563
star
2

web2py-appliances

Set of Example Web2py Appliances
JavaScript
210
star
3

kryten

A shell tool to turn code into a video presentation
Python
148
star
4

evote

A system for secure, trusted, and verifiable voting on the web
Python
116
star
5

autoinstaller

Python
104
star
6

no.css

Tiny CSS framework with almost no classes and some pure CSS effects
CSS
99
star
7

stupid.css

HTML
92
star
8

gluino

Port of web2py to Bottle, Flask, Pyramid, Tornado, wsgiref and other frameworks
Python
82
star
9

ocl

Python to C99/OpenCL/JS compiler
Python
64
star
10

Plasmid

web app to clone, edit in-place, and republish any web site
Python
54
star
11

ulid

Python
48
star
12

canvas

canvas is a simple interface to most common matplotlib functions
Python
42
star
13

web2py-recipes-source

Source code from the web2py recipes book published by packt
Python
37
star
14

pacioli

double entry account system compatible with ledger and beancount (but BSD license)
HTML
32
star
15

web2py-haystack

A full-text search engine for web2py named after Django-Haystack (since serves a similar purpose)
Python
29
star
16

buckingham

A library for error propagation and metric conversions
Python
25
star
17

web3py

web3py (work in progress... an experiment)
Python
25
star
18

videomonitor

Python
20
star
19

markmin.js

markmin.js (yet another wiki markup language but different)
JavaScript
18
star
20

mdpcl

some exercises with pyopencl
Python
17
star
21

algorithms-animator

Algorithms Animator
Python
11
star
22

fermiqcd

Automatically exported from code.google.com/p/fermiqcd
HTML
10
star
23

w2cms

w2cms
JavaScript
10
star
24

collection2

Python
10
star
25

web2py-plugins

9
star
26

nsa

Python
8
star
27

human_security

simple rsa signing API
Python
7
star
28

regift

Python
7
star
29

kusoma

JavaScript
6
star
30

date_finder

Python
6
star
31

csvstudio

A tool for processing csv files
Python
6
star
32

web2py-cordova

Python
6
star
33

estore3

Python
5
star
34

markmin-reveal-slides

markmin-reveal-slides
Python
5
star
35

cylon

physics engine
C++
5
star
36

emte-trading

Automatically exported from code.google.com/p/emte-trading
Python
5
star
37

w3

JavaScript
5
star
38

kpar

k(onfiguration) paramaters
Python
4
star
39

qcl

qcl
Python
4
star
40

qcdutils

Automatically exported from code.google.com/p/qcdutils
Python
4
star
41

demo.python.org

demo.python.org
JavaScript
4
star
42

simplescreencast.py

Python
4
star
43

evote_ranking

Python
4
star
44

vision-controlled-arm

vision-controlled-arm
JavaScript
3
star
45

web2py-welcome-theme-stupid

Python
2
star
46

scientific-cms

JavaScript
2
star
47

mdipierro.github.io

TeX
2
star
48

iotcallme

Python
2
star
49

forgetful

Python
2
star
50

blockchain_logger

Python
2
star
51

depy2015-cats

Python
2
star
52

random_variable

library to compute expectation values of random variables
Python
1
star
53

countach

Yet another static site generator - but different
Python
1
star
54

taskutils

Python
1
star
55

p2p-toy

Python
1
star
56

compy

compy
1
star
57

my_first_project

1
star
58

xml_parser

Python
1
star