Page History
...
Parsing the pathname
Code Block |
---|
path = '/reg/d/psdm/cxi/cxif5315/calib/pnccd/pnccd-123456.data' root, ext = os.path.splitext(path) # i.e. path='root-part.tail-part' ('/reg/d/psdm/cxi/cxif5315/calib/pnccd/pnccd-123456', '.data') # or '' if something is missing basename = os.path.basename(path) # pnccd-123456.data dirname = os.path.dirname(path) # /reg/d/psdm/cxi/cxif5315/calib/pnccd lexist lexist = os.path.lexists(path) # False isfile = os.path.isfile(path) # False isdir = os.path.isdir(path) # False head, tail= os.path.split(path) # i.e. path='head-part/tail-part'('/reg/d/psdm/cxi/cxif5315/calib/pnccd', 'pnccd-123456.data') # or '' if something is missing ... |
http://docs.python.org/library/os.path.html
...
Join list of strings
Code Block |
---|
s = ' '.join(sys.argv) |
Join path and name
Code Block |
---|
path_name = os.path.join(path,fname) |
...
Code Block |
---|
exp = 'xpptut13' if 'tut' is in exp : <do something> |
String alignment
Code Block |
---|
msg = '%s' % (k.ljust(16)) |
Useful Useful string parsing options
http://docs.python.org/library/string.html
...
Code Block |
---|
my_string.replace("abcde","cde") |
...
String formatting
Code Block |
---|
s = 'some text %s %s' % (msg.ljust(30), str(val).rjust(30) |
List of comprehension
list_of_x2 = [x*x for x in list_of_x]
list_of_x_selected = [x for x,y in zip(list_of_x, list_of_y) if y>0]
map - built-in method
Code Block |
---|
def f(x,y) :
return x if y>0 else -x
list = map(f, arrX, arrY) |
Constructor, destructor etc.
Class string properties
Code Block |
---|
print 'string properties:'
print 'punctuation : ', string.punctuation
|
Code Block |
class PeakListFile : def __init__(self, fname) : print 'constructor' digits self.f=open(fname,'r') : def __del__(self) : ', string.digits print 'destructor' octdigits : try :', string.octdigits print 'hexdigits : self.f.close() ', string.hexdigits defprint __call__(self) : 'ascii_letters : ', string.ascii_letters print 'thisascii_lowercase: is a default method of this object called as obj()' |
Polymorphism
Derived class initialization
Code Block |
---|
class Base : def __init__(self) : ...', string.ascii_lowercase print 'ascii_uppercase: ', string.ascii_uppercase print 'lowercase : ', string.lowercase print 'uppercase class Derived(Base) : : ', string.uppercase print 'letters def __init__(self) : : ', string.letters print 'printable Base.__init__(self) : ', string.printable print 'whitespace #: OR ', string.whitespace super(Derived, self) |
Class name
Code Block |
---|
self.__class__.__initname__() |
Python - useful references
Built-in functions
http://docs.python.org/library/functions.html
setattr - gives dynamic variables in python
http://docs.python.org/library/functions.html#setattr
PyQt4
PyQt4 class references
All classes
Selected:
Open/close/move other GUI window
Try to close window if its object exists, othervise - open:
Code Block |
---|
def processConfigPars(self):
print 'processConfigPars'
try :
cp.confpars.guiconfigparameters.close()
except : # AttributeError: #NameError
cp.confpars.guiconfigparameters = guiconfigpars.GUIConfigParameters()
cp.confpars.guiconfigparameters.move(self.pos().__add__(QtCore.QPoint(100,330))) # window offset
# or use self.parentWidget().pos() for combined widgets:
# cp.guifilebrowser.move(self.parentWidget().pos().__add__(QtCore.QPoint(240,40)))
cp.confpars.guiconfigparameters.show()
|
Note |
---|
Sometime it looks like the window does not want to move in specified position... |
Close window and delete object
Function name
Code Block |
---|
sys._getframe().f_code.co_name |
Function parameters
Code Block |
---|
locals() # returns (dict) of method input parameters |
Converting integer to bin(), oct(), hex() string
using built-in functions
Code Block |
---|
ival = 123456
str_bin = bin(ival)
str_oct = oct(ival)
str_hex = hex(ival) |
Time stamp
Code Block |
---|
from time import localtime, gmtime, strftime, clock, time
time_sec = time() # epoch time
def get_current_local_time_stamp(fmt='%Y-%m-%d %H:%M:%S %Z'):
return strftime(fmt, localtime())
def get_current_gm_time_stamp(fmt='%Y-%m-%d %H:%M:%S %Z'):
return strftime(fmt, gmtime())
def get_local_time_str(time_sec, fmt='%Y-%m-%d %H:%M:%S %Z'):
return strftime(fmt, localtime(time_sec))
def get_gm_time_str(time_sec, fmt='%Y-%m-%d %H:%M:%S %Z'):
return strftime(fmt, gmtime(time_sec)) |
Set PYTHONPATH
In command-line:
Code Block |
---|
setenv PYTHONPATH /reg/neh/home1/dubrovin/LCLS/git-work/pyapps:${PYTHONPATH} |
In cshell script:
Code Block |
---|
alias setpp 'setenv PYTHONPATH /reg/neh/home1/dubrovin/LCLS/git-work/pyapps:${PYTHONPATH}' |
In code:
Code Block |
---|
import os
os.environ['PYTHONPATH'] = '/reg/neh/home1/dubrovin/LCLS/git-work/pyapps:%s' % os.environ.get('PYTHONPATH', '') |
Replace symbols in string
Code Block |
---|
text.replace("|",":").replace("-",".")
range.replace('9999','end')
msg.replace('\n',' ') |
List of comprehension
list_of_x2 = [x*x for x in list_of_x]
list_of_x_selected = [x for x,y in zip(list_of_x, list_of_y) if y>0]
map - built-in method
Code Block |
---|
def f(x,y) :
return x if y>0 else -x
list = map(f, arrX, arrY) |
Constructor, destructor etc.
Code Block |
---|
class PeakListFile :
def __init__(self, fname) :
print 'constructor'
self.f=open(fname,'r')
def __del__(self) :
print 'destructor'
try :
|
Code Block |
def closeEvent(self, event): try: # try to delete self object in the cp.confpars del cp.confpars.guiconfigparameters except # AttributeError: pass # silently ignore |
Change style of buttons depending on status
For particular QPushButton it works:
self.f.close()
def __call__(self) :
print 'this is a default method of this object called as obj()' |
Polymorphism
Derived class initialization
Code Block |
---|
class Base :
def __init__(self) :
|
Code Block |
self.but_path = QtGui.QPushButton('File:') self.but_path.setObjectName('but_path') self.but_path.setStyleSheet('QPushButton#but_path:pressed {color: black; background-color: green;}' + ... 'QPushButton#but_path:disabled {color: white; background-color: pink;}' + class Derived(Base) : def __init__(self) : Base.__init__(self) # OR 'QPushButton {color: blue; background-color: yellow;}') |
For entire application it should be like:
Code Block |
---|
app = QtGui.QApplication.instance()
app.setStyleSheet('QLabel{color: #fff;} QPushButton{background-color: #000; color: #fff}')
|
but does not work for me...
Make window visible on the top
Code Block |
---|
widg.raise_()
|
Scroll down text in
Assuming
Code Block |
---|
self.box_txt = QtGui.QTextEdit()
self.box_txt.setText('some text')
self.box_txt.append('a lot of additional text, exceeding the window size')
self.box_txt.ensureCursorVisible()
|
Scroll bar can be used, but result is not seen imidiately:
Code Block |
---|
scrol_bar_v = self.box_txt.verticalScrollBar() # QScrollBar
scrol_bar_v.setValue(scrol_bar_v.maximum())
|
Moving text cursor with repaint() works immidiately:
Code Block |
---|
self.box_txt.moveCursor(QtGui.QTextCursor.End)
self.box_txt.repaint()
|
Set optimal table-widget size
Code Block |
---|
self.table = QtGui.QTableWidget(rows, cols, self)
...
self.table.setFixedWidth(self.table.horizontalHeader().length() + 4)
self.table.setFixedHeight(self.table.verticalHeader().length() + 29)
|
Show image in QLabel
Assumes:
Code Block |
---|
class GUIImage ( QtGui.QLabel ) :
def __init__ (self, parent=None, app=None) :
QtGui.QLabel.__init__(self, parent)
self.setGeometry(200, 100, 100, 100)
self.setWindowTitle('Image For Grabber')
self.setFrame()
...
|
i.e. self
is an instance of QLabel
.
Set pixmap for image
Code Block |
---|
def setPixmapForImage(self):
if self.r_pixmap == None :
self.s_pixmap = None
self.clear()
else :
self.s_pixmap = self.r_pixmap.scaled(self.size(), QtCore.Qt.KeepAspectRatio)
self.setPixmap(self.s_pixmap)
self.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
self.setScailedMask()
|
Grab image from monitor
super(Derived, self).__init__() |
Create/save temporary file
Code Block |
---|
import tempfile
tmp_file = tempfile.NamedTemporaryFile(mode='r+b',suffix='.tiff')
tfile = tmp_file.name |
Good example of __main__
Code Block |
---|
import sys
def test_all() :
print _sep_, '\n%s' % sys._getframe().f_code.co_name
test_ricker()
test_morlet()
#------------------------------
if __name__ == "__main__" :
from time import time
tname = sys.argv[1] if len(sys.argv) > 1 else '0'
print 50*'_', '\nTest %s:' % tname
t0_sec = time()
if tname == '0': test_all()
elif tname == '1': test_ricker()
elif tname == '2': test_morlet()
else : print 'Not-recognized test name: %s' % tname
msg = 'End of test %s, consumed time (sec) = %.6f' % (tname, time()-t0_sec)
sys.exit(msg) |
Virtualenv
Code Block |
---|
virtualenv dir-name
source <directoryName>/bin/activate.csh # for tcsh
# or
source <directoryName>/bin/activate # for bash
pip install <packageName>
... work
deactivate |
Python - useful references
Built-in functions
http://docs.python.org/library/functions.html
setattr, getattr - set/get dynamic variables in python
http://docs.python.org/library/functions.html#setattr
PyQt4
Know How
- QGraphicsScene item priority is set by setZValue(v)
- All re-implemented Event methods like {{mouseMoveEvent(self, e)}} etc. in items will get control only if QGraphicsView their default version will be called.
PyQt4 class references
All classes
Selected:
Open/close/move other GUI window
Try to close window if its object exists, othervise - open:
Code Block |
---|
def processConfigPars(self): |
Code Block |
def grabImage(self): fname = tempfile.NamedTemporaryFile(mode='r+b',suffix='.ppm')print 'processConfigPars' if( 0 == os.system('import -trim -frame -border %s' % (fname.name))) :try : cp.confpars.guiconfigparameters.close() except : # AttributeError: #NameError self.r_pixmap = QtGui.QPixmap(QtGui.QImage(fname.name)) self.setPixmapForImage() cp.confpars.guiconfigparameters = guiconfigpars.GUIConfigParameters() cp.confpars.guiconfigparameters.move(self.pos().__add__(QtCore.QPoint(100,330))) # window offset # or use self.parentWidget().pos() for combined widgets: # cp.guifilebrowser.move(self.parentWidget().pos().__add__(QtCore.QPoint(240,40))) cp.confpars.guiconfigparameters.show() |
Note |
---|
Sometime it looks like the window does not want to move in specified position... |
Close window and delete object
Code Block |
---|
def closeEvent(self, event):
try: # try to delete self object in the cp.confpars
del cp.confpars.guiconfigparameters
except # AttributeError:
pass # silently ignore
|
Change style of buttons depending on status
For particular QPushButton it works:
Code Block |
---|
self.but_path = QtGui.QPushButton('File:')
self.but_path.setObjectName('but_path')
self.but_path.setStyleSheet('QPushButton#but_path:pressed {color: black; background-color: green;}' +
'QPushButton#but_path:disabled {color: white; background-color: pink;}' +
'QPushButton {color: blue; background-color: yellow;}')
|
For entire application it should be like:
Code Block |
---|
app = QtGui.QApplication.instance()
app.setStyleSheet('QLabel{color: #fff;} QPushButton{background-color: #000; color: #fff}')
|
but does not work for me...
Make window visible on the top
Code Block |
---|
widg.raise_()
|
Scroll down text in
Assuming
Code Block |
---|
self.box_txt = QtGui.QTextEdit()
self.box_txt.setText('some text')
self.box_txt.append('a lot of additional text, exceeding the window size')
self.box_txt.ensureCursorVisible()
|
Scroll bar can be used, but result is not seen imidiately:
Code Block |
---|
scrol_bar_v = self.box_txt.verticalScrollBar() # QScrollBar
scrol_bar_v.setValue(scrol_bar_v.maximum())
|
Moving text cursor with repaint() works immidiately:
Code Block |
---|
self.box_txt.moveCursor(QtGui.QTextCursor.End)
self.box_txt.repaint()
|
Set optimal table-widget size
Code Block |
---|
self.table = QtGui.QTableWidget(rows, cols, self)
...
self.table.setFixedWidth(self.table.horizontalHeader().length() + 4)
self.table.setFixedHeight(self.table.verticalHeader().length() + 29)
|
Show image in QLabel
Assumes:
Code Block |
---|
class GUIImage ( QtGui.QLabel ) :
def __init__ (self, parent=None, app=None) :
QtGui.QLabel.__init__(self, parent)
self.setGeometry(200, 100, 100, 100)
self.setWindowTitle('Image For Grabber')
self.setFrame()
...
|
i.e. self
is an instance of QLabel
.
Set pixmap for image
Code Block |
---|
def setPixmapForImage(self):
if self.r_pixmap == None :
self.s_pixmap = None
self.clear()
else :
self.s_pixmap = self.r_pixmap.scaled(self.size(), QtCore.Qt.KeepAspectRatio)
self.setPixmap(self.s_pixmap)
self.setAlignment(QtCore.Qt.AlignTop | QtCore.Qt.AlignLeft)
self.setScailedMask()
|
Grab image from monitor
Code Block |
---|
import tempfile
def grabImage(self):
fname = tempfile.NamedTemporaryFile(mode='r+b',suffix='.ppm')
if( 0 == os.system('import -trim -frame -border %s' % (fname.name))) :
self.r_pixmap = QtGui.QPixmap(QtGui.QImage(fname.name,'.ppm'))
self.setPixmapForImage()
|
Supported in QImage formats:
Format | Description | Qt's support |
---|---|---|
BMP | Windows Bitmap | Read/write |
GIF | Graphic Interchange Format (optional) | Read |
JPG | Joint Photographic Experts Group | Read/write |
JPEG | Joint Photographic Experts Group | Read/write |
PNG | Portable Network Graphics | Read/write |
PBM | Portable Bitmap | Read |
PGM | Portable Graymap | Read |
PPM | Portable Pixmap | Read/write |
TIFF | Tagged Image File Format | Read/write |
XBM | X11 Bitmap | Read/write |
XPM | X11 Pixmap | Read/write |
Grab entire monitor window
...
When QPushButton is pressed and connected method is called, all button properties stay unchanged until the method. In order to see current changes one has to repaint widget. For example:method. In order to see current changes one has to repaint widget. For example:
Code Block |
---|
self.but_elog.setStyleSheet(cp.styleButton)
self.but_elog.setEnabled(False)
self.repaint() |
Dialog boxes
For password
Code Block |
---|
app = QtGui.QApplication(sys.argv)
w = QtGui.QInputDialog()
w.show()
msg = 'To use %s and submitt messages in ELog\nauthentication for user %s is required\nPassword:' % (sys.argv[0], opts.usr)
text, ok = w.getText(None, 'Authentication', msg, QtGui.QLineEdit.Password)
w.close()
... |
Code Block |
self.but_elog.setStyleSheet(cp.styleButton)
self.but_elog.setEnabled(False)
self.repaint() |
Graphics in PyQt4
Code Block |
---|
... self.poi1 = QtCore.QPoint(0,0) self.poi2 = QtCore.QPoint(0,0) self.rect1 = QtCore.QRect() self.rect2 = QtCore.QRect() self.pen1 = QtGui.QPen(QtCore.Qt.black) self.pen2 = QtGui.QPen(QtCore.Qt.white) self.pen1.setStyle(QtCore.Qt.DashLine) self.pen2.setStyle(QtCore.Qt.DashLine) self.pen1.setWidthF(1) self.pen2.setWidthF(1) ... def paintEvent(self, e): super(GUIImage,self).paintEvent(e) qp = QtGui.QPainter() # or QPainter can be defined earlier and use it as qp = self.qp qp.begin(self) #self.drawPixmap(qp) self.drawRect(qp) qp.end() self.update() def setPen(self, qp): self.pen.setStyle(QtCore.Qt.DashLine) self.pen.setWidthF(1) def drawRect(self, qp): if self.r_pixmap == None: return p1x, p1y = self.poi1.x(), self.poi1.y() p2x, p2y = self.poi2.x(), self.poi2.y() R=1 if abs(p2x-p1x) < R : return if abs(p2y-p1y) < R : return self.rect1.setCoords( p1x, p1y, p2x, p2y) self.rect2.setCoords( p1x+1, p1y+1, p2x-1, p2y-1) qp.setPen (self.pen1) qp.drawRect(self.rect1); qp.setPen (self.pen2) qp.drawRect(self.rect2); def drawPixmap(self, qp): if self.r_pixmap != None: qp.drawPixmap(0,0,self.s_pixmap) |
...
Code Block |
---|
fig.clear() |
Graphic
Code Block |
---|
import pyimgalgos.Graphics as gr axes.clear() axes.plot(xarr1, yarr1, '-r', xarr2, yarr2, '-g') gr.show(mode='do_not_hold') |
Histogram
Code Block |
---|
axes.clear() axes.hist(arr, bins=100, range=(10,50), log=False) # log for vertical scale only |
Image (with colorbar)
Code Block |
---|
img = axes.imshow(arr2d, interpolation='nearest', origin='bottom', aspect='auto') img.set_clim(Amin,Amax) cbar = self.fig.colorbar(img, orientation='vertical', \ fraction=0.1, pad=0.01, shrink=1.0, aspect=20) # fraction - of the 2d plot occupied by the color bar # pad - is a space between 2d image and color bar # shrink - factor for the length of the color bar # aspect - ratio length/width of the color bar |
...
Other supported formats: gif, pdf, png, jpeg, eps
eps
Check tiff file
To check tiff file format one may use command:
% identify -verbose <file-name>.tiff
Save image in 16-bit TIFF file
...
Code Block |
---|
V = np.array(...) Vmin, Vmax, Nbins1 <--- scalar valuer indarr Vmin, Vmax, Nbins1 <--- scalar valuer indarr = np.int32( factor * (V-Vmin) ) arr = np.select([V==Vmax, indarr<0, indarr>Nbins1], [Nbins1, 0, 0], default=indarr) |
protected division:
Code Block |
---|
def divideZeroProteced(nda_num, nda_den, val_subst_zero=0) : pro_num = np.int32( factor * (V-Vmin) ) arrselect([nda_den==0], [val_subst_zero], default=nda_num) pro_den = np.select([Vnda_den==Vmax0], indarr<0, indarr>Nbins1], [Nbins1, 0, 0], default=indarr)[1], default=nda_den) return pro_num / pro_den |
SciPy
Import
Code Block |
---|
#!/usr/bin/env python import numpy as np from scipy.optimize import curve_fit |
...