50% found this document useful (2 votes)
232 views2 pages

Itom Cheat Sheet Python 3: Zerodivisionerror

This cheat sheet summarizes common Python syntax structures like assignment, selection, repetition, functions, exceptions, operators, and built-in functions. It provides examples of common data types like integers, floats, strings, lists, tuples, and dictionaries. It also covers importing modules and calling functions from the math and itom modules.

Uploaded by

vikas_2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
50% found this document useful (2 votes)
232 views2 pages

Itom Cheat Sheet Python 3: Zerodivisionerror

This cheat sheet summarizes common Python syntax structures like assignment, selection, repetition, functions, exceptions, operators, and built-in functions. It provides examples of common data types like integers, floats, strings, lists, tuples, and dictionaries. It also covers importing modules and calling functions from the math and itom modules.

Uploaded by

vikas_2
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

itom cheat sheet Common Syntax Structures Common Functions of Module math (from math import *)

exp [any expression], stmt [(sequence of) command(s)] cos(x), sin(x), tan(x) Cosine, sine, tangent of x radians
Python 3 Note: Indentation is important for control sequences! sqrt(x) Positive square root of x
Assignment a = 1 a=1 degrees(x), radians(x) Convert from rad to deg, deg to rad
Help
a, b = 1, 2 a=1,b=2 exp(x) e ** x
help(m) Display help for module, function…
1 c = [1,2,3]; c[1] = 4 c=[1,4,3] floor(x) Largest whole number <= x
pluginHelp(“name”) Display information for plugin
1 Output print(exp [,expr2…]) print(“test”) pow(x,y) x ** y
filterHelp(“name”) Display information for itom-filter
1 Comment #single line ‘’’multi pi Math constant (15 sig figs)
widgetHelp(“name”) Display information for widget in plugin
line’’’ e Math constant e (15 sig figs)
dir(m) Display names in module m
Selection if(boolean_exp): if(2>1):
stmt print(“2>1”) Common List (L) and Tuple (T) Methods
Common Data Types [elif (boolean_exp): else: LT[idx], LT[idx1:idx2] get items or slice of items from list/tuple
int Integer (32/64bit) 3, -4, 0 stmt] print(“what?”) LT.count(obj) number of occurrences of obj in LT
float Floating point number 3.0, -6.55, float(‘nan’) [else: LT.index(obj) index of first occurrence of obj in LT;
complex Complex number 2+3j, 4j, 5-0j stmt] raises ValueError if does not occur
bool Boolean True, False Repetition while(boolean_exp): repeat while bool_exp L[idx]=obj assigns new value to index (list only)
str String of characters “Python” stmt is True L.append(obj) Appends obj to end of list L
byte Sequence of integers b”Python” L.remove(obj) Removes first occurrence of obj from L
tuple Immutable sequence (2,), (2.3,”a”), (2.3,-1) Traversal for var in obj: Iterate over all
list Mutable sequence [2], [2.3,”a”], [2.3,-1] stmt elements in traversable
Common List (L) or Tuple (T) Methods, (LT both)
dict Mapping, dictionary {“x”:-2, “name”:”a”} obj.
LT[idx], LT[idx1:idx2] get items or slice of items from list/tuple
numpy.array Numpy-Array Loop for i in range(0,5): Use range for creating
LT.count(obj) number of occurrences of obj in LT
dataObject
1
itom data object compatible to np.array print(i) an iterable list
LT.index(obj) index of first occurrence of obj in LT;
[0,1,2,3,4]
raises ValueError if does not occur
Exception try: try:
Module Import L[idx]=obj assigns new value to index (list only)
Handling stmt … 1/0
Example: How to call method plot of module itom L.append(obj) Appends obj to end of list L
except [exc_type] [,var]: except ZeroDivisionError:
import itom itom.plot(args,…) L.remove(obj) Removes first occurrence of obj from L
stmt … print(“uups”)
from itom import plot plot(args,…) Function def fctname(params): def test(i,j=4):
from itom import * plot(args,…) [Import all] Definition ‘’’doc-string’’’ a=i+j Common Dictionary (D) Methods
from itom import plot as fct fct(args,…) [Alias] stmt #j has default 4 D[“key”] returns value corresponding to key
return obj return [a,”done”] D[“key”] = obj replaces/adds obj under given key
Function ret = fctname(args) ret = test(2) “key” in D True if key exists in D, else False
Operators and their Precedence D.clear() clears dictionary
Call #ret is [6,”done”]
func_name(args,kwds) Function call D.keys() Returns list of D’s keys
x[startIdx : endIdx] Slicing (startIdx incl., endIdx excl.) D.values() Returns list of D’s values
x[index] Indexing (index zero-based) Common Built-in Functions
x.attribute Attribute reference abs(x) Absolute value of x Formatting Numbers as Strings
** Exponentation float(x), int(x) Convert x to float / int (if possible) Syntax: “%width.precision type” % expression
*, /, % Multiply, Divide, Mod len(s) Number of items in sequence (list, tuple,...)
width (optional) total width (+/-: right/left aligned)
+, - Add, Subtract str(obj) String representation of obj
precision (optional) specified digits of float precision
&, |, ^, ~ Binary And, Or, Xor, Not range(x,y) A list [x, x+1, x+2, …, y-1] (y excluded)
type (required) d (int), f (float), s (string), e (exp. Notation)
>, <, <=, >=, !=, == Comparison dict() Empty dictionary
Examples: “%6d” % 123 -> …123
in, not in Membership tests [2 in (1,2,3)]->True list() Empty list
“%04d” % 1 -> 0001
not, and, or Boolean operators tuple() Empty tuple
“%8.2f” % 456.789 -> ..456.79
“%8.2e” % 456.789 -> 4.57e+02
1
only available in itom
1 1
Working with dataIO-Devices (Grabber, AD-Converter…) Numpy.array (import numpy as np, np.array), DataObject (import itom, itom.dataObject)
pluginHelp(“name”) Prints information about plugin arr=np.ndarray([2,3],’uint8’) dObj=dataObject([2,3],’uint8’) create a randomly filled 2x3 array with type uint8
dataIO(“name”,params) Creates obj (instance) of device arr=np.array([[1,2,3],[4,5,6]]) dObj =dataObject([2,3],data=(1,2,3,4,5,6)) create the 2x3 array [1,2,3 ; 4,5,6]
obj.getParam(“name”) Returns value of parameter arr=np.array(dObj, copy=False) dObj =dataObject(arr) convert np.array <-> dataObject
obj.setParam(“name”,val) Sets parameter to val arr.ndim dObj.dims Returns number of dimensions (here: 2)
obj.startDevice() Starts device (camera…) arr.shape dObj.shape Returns size tuple (here: [2,3])
obj.stopDevice() Stops device (camera…) arr.shape[0] dObj.size(0) or dObj.shape[0] Returns size of first dimensions (here: y-axis)
st nd
obj.acquire() triggers image acquisition c=arr[0,1]; arr[0,1]=7 dObj [0,1]; b[0,1]=7 Gets or sets the element in the 1 row, 2 col
nd
obj.getVal(dObj) after call, dataObject dObj c=arr[:,1:3] or c=dObj[:,1:3] or Returns shallow copy of array containing the 2 and
rd
references to last acquired image c=arr[0:2,1:3] c= dObj [0:2,1:3] 3 columns
obj.copyVal(dObj) after call, dObj contains deep copy arr[:,:]=7 dObj [:,:]=7 sets all values of array to value 7
of last acquired image arr.transpose() (shallow copy) dObj.trans() (deep copy) transpose of array
obj.setAutoGrabbing(bool) En-/Disables continuous grab for np.dot(arr1,arr2) dObj1 * dObj2 (float only) matrix multiplication
connected live views arr1 * arr2 dObj1.mul(dObj2) element-wise multiply
arr1 / arr2 dObj1.div(dObj2) element-wise divide
1 arr1 +,- arr2 dObj1 +,- dObj2 sum/difference of elements
Working with actuator-Devices (Motors, Stages…)
Position units are in mm arr1 +,- scalar dObj1 +,- scalar adds/subtracts scalar from every element in array
pluginHelp(“name”) Prints information about plugin arr1 &,| arr2 dObj1 &,| dObj2 element-wise, bitwise AND/OR operator
actuator(“name”,params) Creates obj (instance) of device arr2 = arr1 dObj2 = dObj1 referencing (both still point to the same array)
obj.getParam(“name”) Returns value of parameter arr2 = arr1.copy() dObj2 = dObj1.copy() deep copy (entire data is copied)
obj.setParam(“name”,val) Sets parameter to val arr2 = arr1.astype(newtype) dObj2 = dObj1.astype(‘newtypestring’) type conversion
obj.getPos(idx1[,idx2…]) Returns current position for all arr = np.zeros([3,4],’float32’) dObj = dataObject.zeros([3,4], ’float32’) 3x4 array filled with zeros of type float32
given axes indices (0-based) arr = np.ones([3,4],’float32’) dObj = dataObject.ones([3,4], ’float32’) 3x4 array filled with ones of type float32
obj.setPosRel(idx1,pos1,…) Relatively moves axis idx1 by pos1 arr = np.eye(3,dtype=’float32’) dObj = dataObject.eye(3, ’float32’) 3x3 identity matrix (type: float32)
obj.setPosAbs(idx1,pos1,…) Moves axis idx1 to pos1 arr2 = arr1.squeeze() dObj2 = dObj1.squeeze() converts array to an array where dimensions of size
1 are eliminated (deep copy if necessary)
1 np.linspace(1,3,4) - 4 equally spaced samples between 1 and 3, inclusive
Working with itom-Filters
[x,y] = np.meshgrid(0:2,1:5) - two 2D arrays: one of x values, the other of y values
filterHelp(“name”) Lists all algorithms/filters
np.linalg.inv(a) - inverse of square matrix a
containing name or detailed
x=np.linalg.solve(a,b) - solution of ax=b (using pseudo inverse)
information about filter that
[U,S,V] = np.linalg.svd(a) - singular value decomposition of a (V is transposed!)
matches name
np.fft.fft2(a), np.fft.ifft2(a) filter available (Inverse) 2D fourier transform of a
ret=filter(“name”,param1,…) Calls filter name with given
a[a>0]=5 a[a>0]=5 sets all elements > 0 of a to 5
parameters and returns tuple of
a[np.isnan(a)]=5 a[np.isnan(a)]=5 sets all NaN elements of a to 5
output parameters (or None)
arr2 = arr1.reshape([3,2]) arr2 = arr1.reshape([3,2]) reshapes arr1 to new size (equal number of items)
1
Plots
plot(dObj) 1D or 2D plot of dObj Subject Matlab Python/Numpy-Arrays/DataObjects
(depending on its size) Data Copying Matlab always uses deep copying. Python usually creates shallow copies (deep copy only if
liveImage(dataIO-instance) Live view of camera b = a -> b and a contain separated data in memory necessary). Therefore a and b share the same data.
Indexing Matlab uses one-based indexing Python always uses zero-based indexing
1
Common DataObject and Numpy.Array Data Types Ranges 1:4 means the items at one-based indices [1,2,3,4] In Python the same is achieved by 0:4 -> [0,1,2,3]
Both boundaries are included in the range. The second boundary is always excluded!
“uint8”, “int8”, “uint16”, (Un-)Signed integer 8,16,32 bit
“int16”, “uint32”, “int32”
“float32”, “float64” Floating point numbers
“complex64”, “complex128” Complex values (64 = 2x32 bit)
“rgba32” Color value (type itom.rgba)

You might also like