Note that BornAgain Win/Mac requires Python 2.7
From command line:
git clone https://github.com/scgmlz/BornAgain-tutorial.git
Windows/Mac: can also use Github Desktop.
git clone https://github.com/scgmlz/BornAgain.git
mkdir build; cd build
cmake .. -DCMAKE_BUILD_TYPE=Release -DBORNAGAIN_USE_PYTHON3=ON
make && make install
Direct from command line:
$ python -c "print 'hello, world'"
hello, world
Run script from command line:
$ echo "print 'hello, world'" > hello.py
$ python hello.py
hello, world
Default interactive interpreter:
$ python
>>> x = 5
>>> x * x
25
IPython interactive interpreter:
$ ipython
In [1]: x = 5
In [2]: x * x
Out [2]: 25
IPython interactive notebook:
$ ipython notebook
Jupyter interactive notebook:
$ jupyter notebook
Notebook support is included by default with Anaconda, and can be installed as an optional package on most Linux distros.
In [1]:
from __future__ import print_function
In [2]:
# scratch area
In [3]:
# scratch area
In [4]:
# scratch area
In [5]:
# scratch area
In [6]:
# scratch area
In [7]:
# scratch area
In [8]:
# scratch area
Boolean types take the values True or False. The result of a comparison operator is boolean.
5 < 6 # evalutes to True
5 >= 6 # evaluates to False
5 == 6 # evaluates to False
Logical operations:
True and False # False
True or False # True
not True # False
True ^ False # True (exclusive or)
In [9]:
# scratch area
Functions are defined with def:
def hello():
print 'hello, world'
Note: Python uses indentation to denote blocks of code, rather than braces {} as in many other languages. It is common to use either 4 spaces or 2 spaces to indent. It doesn't matter, as long as you are consistent.
Use the return keyword for a function which returns a value:
def square(x):
return x**2
In [10]:
# scratch area
In [40]:
for i in range(10):
print(i**2)
It is also possible to use for..in to iterate through elements of a list:
In [42]:
for i in ['hello', 'world']:
print(i)
While loops have the form while condition:
In [13]:
i = 0
while i < 10:
print(i**2)
i = i + 1
The keywords break and continue can be used for flow control inside a loop
continue: skip to the next iteration of the loopbreak: jump out of the loop entirely
In [65]:
for i in range(10):
if i == 3:
continue
if i == 7:
break
print(i)
Use the keywords if, elif, else for branching
if 5 > 6:
# never reached
pass
elif 1 > 2:
# reached
pass
else:
# never reached
pass
In [15]:
# scratch area
In [16]:
# scratch area
In [17]:
import math
print(math.pi)
print(math.sin(math.pi/2.0))
Rename modules with as:
In [18]:
import math as m
print(m.pi)
Load specific functions or submodules:
In [19]:
from math import pi, sin
print(sin(pi/2.0))
In [20]:
# scratch area
Any code written in a separate file (with .py extension) can be imported as a module. Suppose we have a script my_module.py which defines a function do_something(). Then we can call it as
In [67]:
import my_module
my_module.do_something()
In [21]:
# scratch area
In [68]:
import numpy as np
x = np.array([1, 2, 3, 4])
print(x.sum())
print(x.mean())
The basic arithmetic operations work elementwise on numpy arrays:
In [69]:
x = np.array([1, 2, 3, 4])
y = np.array([5, 6, 7, 8])
print(x + y)
print(x * y)
print(x / y)
It is also possible to call functions on numpy arrays:
In [70]:
x = np.array([1, 2, 3, 4])
print(np.sin(x))
print(np.log(x))
In [22]:
# scratch area
In [71]:
print(np.zeros(4))
print(np.ones(3))
print(np.linspace(-1, 1, num=4))
print(np.random.rand(2))
In [72]:
# scratch area
In [73]:
import numpy as np
from matplotlib import pyplot as plt
x = np.linspace(-3.14, 3.14, num=100)
y = np.sin(x)
plt.plot(x, y)
plt.xlabel('x values')
plt.ylabel('y')
plt.title('y=sin(x)')
plt.show()
In [74]:
x = np.linspace(-10, 10, num=100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.arctan(x)
plt.plot(x, y1, x, y2, x, y3)
plt.show()
In [ ]:
todo array manipulation routines numpy.flipud, fliplr, transpose, rot90, flatten, ravel
In [81]:
x = np.linspace (-1, 1, num =100)
y = np.linspace (-1, 1, num =100)
xx, yy = np.meshgrid (x, y)
z = np.sin(xx**2 + yy**2 + yy)
plt.pcolormesh(x, y, z, shading = 'gouraud')
plt.show()
Or with imshow:
In [86]:
plt.imshow(z, aspect='auto')
plt.show()
Note that the image is flipped because images start from top left and go to bottom right. We can fix this with flipud:
In [87]:
plt.imshow(np.flipud(z), aspect='auto')
plt.show()
In [27]:
# scratch area
In [88]:
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
%matplotlib inline
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_surface(xx, yy, z, rstride=5, cstride=5, cmap=cm.coolwarm, linewidth=1, antialiased=True)
plt.show()
In [89]:
%matplotlib inline
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_wireframe(xx, yy, z, rstride=5, cstride=5, antialiased=True)
plt.show()
In [30]:
# scratch
In [90]:
x = np.linspace(-2, 2, num=100)
y = np.linspace(-2, 2, num=100)
result = np.flipud(np.array([[u*v for u in x] for v in y]))
fig = plt.figure()
plt.imshow(result, extent=[x.min(), x.max(), y.min(), y.max()], aspect='auto')
plt.show()
In [91]:
class SomeClass:
def __init__ (self, x):
self.x = x
def doSomething(self):
print("my x value is {}".format(self.x))
obj = SomeClass(5)
obj.doSomething()
In [33]:
# scratch area
In [34]:
class SomeOtherClass (SomeClass):
def __init__ (self, x, y):
SomeClass.__init__ (self, x)
self.y = y
def doSomethingElse(self):
print("my y value is {}".format(self.y))
other_obj = SomeOtherClass(5, 6)
other_obj.doSomething()
other_obj.doSomethingElse()
In [92]:
print('The type of obj is {}'.format(type(obj)))
print('The type of other_obj is {}'.format(type(other_obj)))
print('obj is instance of SomeClass? {}'.format(isinstance(obj, SomeClass)))
print('obj is instance of SomeOtherClass? {}'.format(isinstance(obj, SomeOtherClass)))
print('other_obj is instance of SomeClass? {}'.format(isinstance(obj, SomeClass)))
print('other_obj is instance of SomeOtherClass? {}'.format( isinstance(obj, SomeOtherClass)))
In [36]:
# scratch area
In [37]:
# todo
todo Python 2 vs. 3 Key differences include: print statement integer division int vs. long new style classes some standard modules/functions have been moved/renamed The “ future ” module can be used to write code compatible with both Python 2 and 3.
In [ ]: