Started Python3 compatibility changes

This commit is contained in:
Luke Campagnola 2012-05-11 18:05:41 -04:00
parent 13b201bebb
commit fc9b3dee4d
109 changed files with 2225 additions and 2218 deletions

View File

@ -1,11 +1,17 @@
from pyqtgraph.Qt import QtCore, QtGui, QtOpenGL, QtSvg
from pyqtgraph.Qt import QtCore, QtGui
#try:
#from PyQt4 import QtOpenGL
#HAVE_OPENGL = True
#except ImportError:
#HAVE_OPENGL = False
import weakref
from pyqtgraph.Point import Point
import pyqtgraph.functions as fn
import pyqtgraph.ptime as ptime
from mouseEvents import *
from .mouseEvents import *
import pyqtgraph.debug as debug
import exportDialog
from . import exportDialog
try:
import sip
@ -216,7 +222,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
items = self.itemsNearEvent(event)
self.sigMouseHover.emit(items)
prevItems = self.hoverItems.keys()
prevItems = list(self.hoverItems.keys())
for item in items:
if hasattr(item, 'hoverEvent'):
@ -352,7 +358,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
items = QtGui.QGraphicsScene.items(self, *args)
## PyQt bug: items() returns a list of QGraphicsItem instances. If the item is subclassed from QGraphicsObject,
## then the object returned will be different than the actual item that was originally added to the scene
items2 = map(self.translateGraphicsItem, items)
items2 = list(map(self.translateGraphicsItem, items))
#if HAVE_SIP and isinstance(self, sip.wrapper):
#items2 = []
#for i in items:
@ -374,7 +380,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
#i2 = GraphicsScene._addressCache.get(addr, i)
##print i, "==>", i2
#items2.append(i2)
items2 = map(self.translateGraphicsItem, items)
items2 = list(map(self.translateGraphicsItem, items))
#print 'items:', items
return items2
@ -430,7 +436,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
return 0
return item.zValue() + absZValue(item.parentItem())
items2.sort(lambda a,b: cmp(absZValue(b), absZValue(a)))
sortList(items2, lambda a,b: cmp(absZValue(b), absZValue(a)))
return items2
@ -543,7 +549,7 @@ class GraphicsScene(QtGui.QGraphicsScene):
@staticmethod
def translateGraphicsItems(items):
return map(GraphicsScene.translateGraphicsItem, items)
return list(map(GraphicsScene.translateGraphicsItem, items))

View File

@ -1 +1 @@
from GraphicsScene import *
from .GraphicsScene import *

View File

@ -1,4 +1,4 @@
import exportDialogTemplate
from . import exportDialogTemplate
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
import pyqtgraph.exporters as exporters

View File

@ -5,7 +5,7 @@ Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.
"""
from Qt import QtCore
from .Qt import QtCore
import numpy as np
def clip(x, mn, mx):

11
Qt.py
View File

@ -1,6 +1,15 @@
## Do all Qt imports from here to allow easier PyQt / PySide compatibility
#from PySide import QtGui, QtCore, QtOpenGL, QtSvg
from PyQt4 import QtGui, QtCore, QtOpenGL, QtSvg
from PyQt4 import QtGui, QtCore
try:
from PyQt4 import QtSvg
except ImportError:
pass
try:
from PyQt4 import QtOpenGL
except ImportError:
pass
if not hasattr(QtCore, 'Signal'):
QtCore.Signal = QtCore.pyqtSignal

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from Qt import QtCore
from ptime import time
import ThreadsafeTimer
from .Qt import QtCore
from .ptime import time
from . import ThreadsafeTimer
__all__ = ['SignalProxy']
@ -99,7 +99,7 @@ class SignalProxy(QtCore.QObject):
if __name__ == '__main__':
from Qt import QtGui
from .Qt import QtGui
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
spin = QtGui.QSpinBox()
@ -107,9 +107,9 @@ if __name__ == '__main__':
win.show()
def fn(*args):
print "Raw signal:", args
print("Raw signal:", args)
def fn2(*args):
print "Delayed signal:", args
print("Delayed signal:", args)
spin.valueChanged.connect(fn)

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from Qt import QtCore, QtGui
from Point import Point
from .Qt import QtCore, QtGui
from .Point import Point
import numpy as np
class Transform(QtGui.QTransform):
@ -141,9 +141,9 @@ class Transform(QtGui.QTransform):
return np.array([[self.m11(), self.m12(), self.m13()],[self.m21(), self.m22(), self.m23()],[self.m31(), self.m32(), self.m33()]])
if __name__ == '__main__':
import widgets
from . import widgets
import GraphicsView
from functions import *
from .functions import *
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
win.show()
@ -189,23 +189,23 @@ if __name__ == '__main__':
tr3 = QtGui.QTransform()
tr3.translate(20, 0)
tr3.rotate(45)
print "QTransform -> Transform:", Transform(tr3)
print("QTransform -> Transform:", Transform(tr3))
print "tr1:", tr1
print("tr1:", tr1)
tr2.translate(20, 0)
tr2.rotate(45)
print "tr2:", tr2
print("tr2:", tr2)
dt = tr2/tr1
print "tr2 / tr1 = ", dt
print("tr2 / tr1 = ", dt)
print "tr2 * tr1 = ", tr2*tr1
print("tr2 * tr1 = ", tr2*tr1)
tr4 = Transform()
tr4.scale(-1, 1)
tr4.rotate(30)
print "tr1 * tr4 = ", tr1*tr4
print("tr1 * tr4 = ", tr1*tr4)
w1 = widgets.TestROI((19,19), (22, 22), invertible=True)
#w2 = widgets.TestROI((0,0), (150, 150))

View File

@ -8,7 +8,7 @@ This class addresses the problem of having to save and restore the state
of a large group of widgets.
"""
from Qt import QtCore, QtGui
from .Qt import QtCore, QtGui
import weakref, inspect
@ -24,7 +24,7 @@ def restoreSplitter(w, s):
elif type(s) is str:
w.restoreState(QtCore.QByteArray.fromPercentEncoding(s))
else:
print "Can't configure QSplitter using object of type", type(s)
print("Can't configure QSplitter using object of type", type(s))
if w.count() > 0: ## make sure at least one item is not collapsed
for i in w.sizes():
if i > 0:
@ -44,7 +44,7 @@ def comboState(w):
except AttributeError:
pass
if data is None:
return unicode(w.itemText(ind))
return asUnicode(w.itemText(ind))
else:
return data
@ -133,7 +133,7 @@ class WidgetGroup(QtCore.QObject):
for w in widgetList:
self.addWidget(*w)
elif isinstance(widgetList, dict):
for name, w in widgetList.iteritems():
for name, w in widgetList.items():
self.addWidget(w, name)
elif widgetList is None:
return
@ -258,7 +258,7 @@ class WidgetGroup(QtCore.QObject):
## if the getter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(getFunc) and getFunc.im_self is not None:
if inspect.ismethod(getFunc) and getFunc.__self__ is not None:
val = getFunc()
else:
val = getFunc(w)
@ -284,7 +284,7 @@ class WidgetGroup(QtCore.QObject):
## if the setter function provided in the interface is a bound method,
## then just call the method directly. Otherwise, pass in the widget as the first arg
## to the function.
if inspect.ismethod(setFunc) and setFunc.im_self is not None:
if inspect.ismethod(setFunc) and setFunc.__self__ is not None:
setFunc(v)
else:
setFunc(w, v)

View File

@ -3,21 +3,25 @@
## 'Qt' is a local module; it is intended mainly to cover up the differences
## between PyQt4 and PySide.
from Qt import QtGui
from .Qt import QtGui
## not really safe.
## not really safe--If we accidentally create another QApplication, the process hangs (and it is very difficult to trace the cause)
#if QtGui.QApplication.instance() is None:
#app = QtGui.QApplication([])
## in general openGL is poorly supported in Qt.
## we only enable it where the performance benefit is critical.
## Note this only applies to 2D graphics; 3D graphics always use OpenGL.
import sys
## check python version
if sys.version_info[0] != 2 or sys.version_info[1] != 7:
if sys.version_info[0] < 2 or (sys.version_info[0] == 2 and sys.version_info[1] != 7):
raise Exception("Pyqtgraph requires Python version 2.7 (this is %d.%d)" % (sys.version_info[0], sys.version_info[1]))
## helpers for 2/3 compatibility
from . import python2_3
## in general openGL is poorly supported in Qt.
## we only enable it where the performance benefit is critical.
## Note this only applies to 2D graphics; 3D graphics always use OpenGL.
if 'linux' in sys.platform: ## linux has numerous bugs in opengl implementation
useOpenGL = False
elif 'darwin' in sys.platform: ## openGL greatly speeds up display on mac
@ -27,8 +31,11 @@ else:
CONFIG_OPTIONS = {
'useOpenGL': useOpenGL, ## by default, this is platform-dependent (see widgets/GraphicsView). Set to True or False to explicitly enable/disable opengl.
'leftButtonPan': True ## if false, left button drags a rubber band for zooming in viewbox
}
'leftButtonPan': True, ## if false, left button drags a rubber band for zooming in viewbox
'foregroundColor': (200,200,200),
'backgroundColor': (0,0,0),
'antialias': False,
}
def setConfigOption(opt, value):
CONFIG_OPTIONS[opt] = value
@ -47,13 +54,15 @@ def renamePyc(startDir):
printed = False
startDir = os.path.abspath(startDir)
for path, dirs, files in os.walk(startDir):
if '__pycache__' in path:
continue
for f in files:
fileName = os.path.join(path, f)
base, ext = os.path.splitext(fileName)
py = base + ".py"
if ext == '.pyc' and not os.path.isfile(py):
if not printed:
print "NOTE: Renaming orphaned .pyc files:"
print("NOTE: Renaming orphaned .pyc files:")
printed = True
n = 1
while True:
@ -61,8 +70,8 @@ def renamePyc(startDir):
if not os.path.exists(name2):
break
n += 1
print " " + fileName + " ==>"
print " " + name2
print(" " + fileName + " ==>")
print(" " + name2)
os.rename(fileName, name2)
import os
@ -78,7 +87,7 @@ def importAll(path, excludes=()):
d = os.path.join(os.path.split(__file__)[0], path)
files = []
for f in os.listdir(d):
if os.path.isdir(os.path.join(d, f)):
if os.path.isdir(os.path.join(d, f)) and f != '__pycache__':
files.append(f)
elif f[-3:] == '.py' and f != '__init__.py':
files.append(f[:-3])
@ -98,14 +107,14 @@ def importAll(path, excludes=()):
importAll('graphicsItems')
importAll('widgets', excludes=['MatplotlibWidget'])
from imageview import *
from WidgetGroup import *
from Point import Point
from Transform import Transform
from functions import *
from graphicsWindows import *
from SignalProxy import *
from ptime import time
from .imageview import *
from .WidgetGroup import *
from .Point import Point
from .Transform import Transform
from .functions import *
from .graphicsWindows import *
from .SignalProxy import *
from .ptime import time

View File

@ -5,7 +5,7 @@ if __name__ == '__main__':
sys.path = [os.path.dirname(md), os.path.join(md, '..', '..', '..')] + sys.path
#print md
from CanvasTemplate import *
from .CanvasTemplate import *
#from pyqtgraph.GraphicsView import GraphicsView
#import pyqtgraph.graphicsItems as graphicsItems
#from pyqtgraph.PlotWidget import PlotWidget
@ -18,9 +18,9 @@ import numpy as np
from pyqtgraph import debug
#import pyqtgraph as pg
import weakref
from CanvasManager import CanvasManager
from .CanvasManager import CanvasManager
#import items
from CanvasItem import CanvasItem, GroupCanvasItem
from .CanvasItem import CanvasItem, GroupCanvasItem
class Canvas(QtGui.QWidget):
@ -154,7 +154,7 @@ class Canvas(QtGui.QWidget):
if parent is None:
tree = li.treeWidget()
if tree is None:
print "Skipping item", i, i.name
print("Skipping item", i, i.name)
continue
tree.removeTopLevelItem(li)
else:
@ -365,7 +365,7 @@ class Canvas(QtGui.QWidget):
parent = parent.listItem
## set Z value above all other siblings if none was specified
siblings = [parent.child(i).canvasItem for i in xrange(parent.childCount())]
siblings = [parent.child(i).canvasItem for i in range(parent.childCount())]
z = citem.zValue()
if z is None:
zvals = [i.zValue() for i in siblings]
@ -462,7 +462,7 @@ class Canvas(QtGui.QWidget):
item.canvasItem.setParentItem(self.view.childGroup)
else:
item.canvasItem.setParentItem(parent.canvasItem)
siblings = [parent.child(i).canvasItem for i in xrange(parent.childCount())]
siblings = [parent.child(i).canvasItem for i in range(parent.childCount())]
zvals = [i.zValue() for i in siblings]
zvals.sort(reverse=True)

View File

@ -2,7 +2,7 @@
from pyqtgraph.Qt import QtGui, QtCore, QtSvg
from pyqtgraph.graphicsItems.ROI import ROI
import pyqtgraph as pg
import TransformGuiTemplate
from . import TransformGuiTemplate
from pyqtgraph import debug
class SelectBox(ROI):

View File

@ -36,7 +36,7 @@ class CanvasManager(QtCore.QObject):
self.sigCanvasListChanged.emit()
def listCanvases(self):
return self.canvases.keys()
return list(self.canvases.keys())
def getCanvas(self, name):
return self.canvases[name]

View File

@ -96,5 +96,5 @@ class Ui_Form(object):
self.reflectSelectionBtn.setText(QtGui.QApplication.translate("Form", "MirrorXY", None, QtGui.QApplication.UnicodeUTF8))
from pyqtgraph.widgets.GraphicsView import GraphicsView
from CanvasManager import CanvasCombo
from .CanvasManager import CanvasCombo
from pyqtgraph.widgets.TreeWidget import TreeWidget

View File

@ -1,3 +1,3 @@
# -*- coding: utf-8 -*-
from Canvas import *
from CanvasItem import *
from .Canvas import *
from .CanvasItem import *

View File

@ -12,7 +12,7 @@ as it can be converted to/from a string using repr and eval.
import re, os, sys
from collections import OrderedDict
GLOBAL_PATH = None # so not thread safe.
import units
from . import units
class ParseError(Exception):
def __init__(self, message, lineNum, line, fileName=None):
@ -51,7 +51,7 @@ def readConfigFile(fname):
try:
#os.chdir(newDir) ## bad.
fd = open(fname)
s = unicode(fd.read(), 'UTF-8')
s = asUnicode(fd.read(), 'UTF-8')
fd.close()
s = s.replace("\r\n", "\n")
s = s.replace("\r", "\n")
@ -60,7 +60,7 @@ def readConfigFile(fname):
sys.exc_info()[1].fileName = fname
raise
except:
print "Error while reading config file %s:"% fname
print("Error while reading config file %s:"% fname)
raise
#finally:
#os.chdir(cwd)
@ -78,10 +78,10 @@ def genString(data, indent=''):
for k in data:
sk = str(k)
if len(sk) == 0:
print data
print(data)
raise Exception('blank dict keys not allowed (see data above)')
if sk[0] == ' ' or ':' in sk:
print data
print(data)
raise Exception('dict keys must not contain ":" or start with spaces [offending key is "%s"]' % sk)
if isinstance(data[k], dict):
s += indent + sk + ':\n'
@ -95,7 +95,7 @@ def parseString(lines, start=0):
data = OrderedDict()
if isinstance(lines, basestring):
lines = lines.split('\n')
lines = filter(lambda l: re.search(r'\S', l) and not re.match(r'\s*#', l), lines) ## remove empty lines
lines = [l for l in lines if re.search(r'\S', l) and not re.match(r'\s*#', l)] ## remove empty lines
indent = measureIndent(lines[start])
ln = start - 1
@ -189,13 +189,13 @@ key2: ##comment
"""
tf.write(cf)
tf.close()
print "=== Test:==="
print("=== Test:===")
num = 1
for line in cf.split('\n'):
print "%02d %s" % (num, line)
print("%02d %s" % (num, line))
num += 1
print cf
print "============"
print(cf)
print("============")
data = readConfigFile(fn)
print data
print(data)
os.remove(fn)

114
debug.py
View File

@ -6,9 +6,9 @@ Distributed under MIT/X11 license. See license.txt for more infomation.
"""
import sys, traceback, time, gc, re, types, weakref, inspect, os, cProfile
import ptime
from . import ptime
from numpy import ndarray
from Qt import QtCore, QtGui
from .Qt import QtCore, QtGui
__ftraceDepth = 0
def ftrace(func):
@ -18,13 +18,13 @@ def ftrace(func):
def w(*args, **kargs):
global __ftraceDepth
pfx = " " * __ftraceDepth
print pfx + func.__name__ + " start"
print(pfx + func.__name__ + " start")
__ftraceDepth += 1
try:
rv = func(*args, **kargs)
finally:
__ftraceDepth -= 1
print pfx + func.__name__ + " done"
print(pfx + func.__name__ + " done")
return rv
return w
@ -39,20 +39,20 @@ def printExc(msg='', indent=4, prefix='|'):
"""Print an error message followed by an indented exception backtrace
(This function is intended to be called within except: blocks)"""
exc = getExc(indent, prefix + ' ')
print "[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)
print " "*indent + prefix + '='*30 + '>>'
print exc
print " "*indent + prefix + '='*30 + '<<'
print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg))
print(" "*indent + prefix + '='*30 + '>>')
print(exc)
print(" "*indent + prefix + '='*30 + '<<')
def printTrace(msg='', indent=4, prefix='|'):
"""Print an error message followed by an indented stack trace"""
trace = backtrace(1)
#exc = getExc(indent, prefix + ' ')
print "[%s] %s\n" % (time.strftime("%H:%M:%S"), msg)
print " "*indent + prefix + '='*30 + '>>'
print("[%s] %s\n" % (time.strftime("%H:%M:%S"), msg))
print(" "*indent + prefix + '='*30 + '>>')
for line in trace.split('\n'):
print " "*indent + prefix + " " + line
print " "*indent + prefix + '='*30 + '<<'
print(" "*indent + prefix + " " + line)
print(" "*indent + prefix + '='*30 + '<<')
def backtrace(skip=0):
@ -107,12 +107,12 @@ def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ig
#print prefix+" LOOP", objChainString([r]+path)
continue
except:
print r
print path
print(r)
print(path)
raise
if r is startObj:
refs.append([r])
print refPathString([startObj]+path)
print(refPathString([startObj]+path))
continue
if maxLen == 0:
#print prefix+" END:", objChainString([r]+path)
@ -125,7 +125,7 @@ def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ig
if cache[0] >= maxLen:
tree = cache[1]
for p in tree:
print refPathString(p+path)
print(refPathString(p+path))
except KeyError:
pass
@ -147,14 +147,14 @@ def findRefPath(startObj, endObj, maxLen=8, restart=True, seen={}, path=None, ig
def objString(obj):
"""Return a short but descriptive string for any object"""
try:
if type(obj) in [int, long, float]:
if type(obj) in [int, float]:
return str(obj)
elif isinstance(obj, dict):
if len(obj) > 5:
return "<dict {%s,...}>" % (",".join(obj.keys()[:5]))
return "<dict {%s,...}>" % (",".join(list(obj.keys())[:5]))
else:
return "<dict {%s}>" % (",".join(obj.keys()))
elif isinstance(obj, basestring):
return "<dict {%s}>" % (",".join(list(obj.keys())))
elif isinstance(obj, str):
if len(obj) > 50:
return '"%s..."' % obj[:50]
else:
@ -261,19 +261,19 @@ def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False):
if recursive:
if type(obj) in [list, tuple]:
if verbose:
print indent+"list:"
print(indent+"list:")
for o in obj:
s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1)
if verbose:
print indent+' +', s
print(indent+' +', s)
size += s
elif isinstance(obj, dict):
if verbose:
print indent+"list:"
print(indent+"list:")
for k in obj:
s = objectSize(obj[k], ignore=ignore, verbose=verbose, depth=depth+1)
if verbose:
print indent+' +', k, s
print(indent+' +', k, s)
size += s
#elif isinstance(obj, QtCore.QObject):
#try:
@ -291,7 +291,7 @@ def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False):
#if isinstance(obj, types.InstanceType):
gc.collect()
if verbose:
print indent+'attrs:'
print(indent+'attrs:')
for k in dir(obj):
if k in ['__dict__']:
continue
@ -311,7 +311,7 @@ def objectSize(obj, ignore=None, verbose=False, depth=0, recursive=False):
s = objectSize(o, ignore=ignore, verbose=verbose, depth=depth+1)
size += s
if verbose:
print indent + " +", k, s
print(indent + " +", k, s)
#else:
#if verbose:
#print indent + ' -', k, len(refs)
@ -349,8 +349,8 @@ class GarbageWatcher:
for k in self.objs:
dead.remove(k)
alive.append(k)
print "Deleted objects:", dead
print "Live objects:", alive
print("Deleted objects:", dead)
print("Live objects:", alive)
def __getitem__(self, item):
return self.objs[item]
@ -379,20 +379,20 @@ class Profiler:
self.t0 = ptime.time()
self.t1 = self.t0
self.msg = " "*self.depth + msg
print self.msg, ">>> Started"
print(self.msg, ">>> Started")
def mark(self, msg=''):
if self.disabled:
return
t1 = ptime.time()
print " "+self.msg, msg, "%gms" % ((t1-self.t1)*1000)
print(" "+self.msg, msg, "%gms" % ((t1-self.t1)*1000))
self.t1 = t1
def finish(self):
if self.disabled:
return
t1 = ptime.time()
print self.msg, '<<< Finished, total time:', "%gms" % ((t1-self.t0)*1000)
print(self.msg, '<<< Finished, total time:', "%gms" % ((t1-self.t0)*1000))
def __del__(self):
Profiler.depth -= 1
@ -419,7 +419,7 @@ def _getr(slist, olist, first=True):
oid = id(e)
typ = type(e)
if oid in olist or typ is int or typ is long: ## or e in olist: ## since we're excluding all ints, there is no longer a need to check for olist keys
if oid in olist or typ is int: ## or e in olist: ## since we're excluding all ints, there is no longer a need to check for olist keys
continue
olist[oid] = e
if first and (i%1000) == 0:
@ -565,23 +565,23 @@ class ObjTracker:
self.persistentRefs.update(persistentRefs)
print "----------- Count changes since start: ----------"
print("----------- Count changes since start: ----------")
c1 = count.copy()
for k in self.startCount:
c1[k] = c1.get(k, 0) - self.startCount[k]
typs = c1.keys()
typs = list(c1.keys())
typs.sort(lambda a,b: cmp(c1[a], c1[b]))
for t in typs:
if c1[t] == 0:
continue
num = "%d" % c1[t]
print " " + num + " "*(10-len(num)) + str(t)
print(" " + num + " "*(10-len(num)) + str(t))
print "----------- %d Deleted since last diff: ------------" % len(delRefs)
print("----------- %d Deleted since last diff: ------------" % len(delRefs))
self.report(delRefs, objs, **kargs)
print "----------- %d Created since last diff: ------------" % len(createRefs)
print("----------- %d Created since last diff: ------------" % len(createRefs))
self.report(createRefs, objs, **kargs)
print "----------- %d Created since start (persistent): ------------" % len(persistentRefs)
print("----------- %d Created since start (persistent): ------------" % len(persistentRefs))
self.report(persistentRefs, objs, **kargs)
@ -600,14 +600,14 @@ class ObjTracker:
return type(o) is cls or id(o) in cls.allObjs
def collect(self):
print "Collecting list of all objects..."
print("Collecting list of all objects...")
gc.collect()
objs = get_all_objects()
frame = sys._getframe()
del objs[id(frame)] ## ignore the current frame
del objs[id(frame.f_code)]
ignoreTypes = [int, long]
ignoreTypes = [int]
refs = {}
count = {}
for k in objs:
@ -628,7 +628,7 @@ class ObjTracker:
ObjTracker.allObjs[id(typStr)] = None
count[typ] = count.get(typ, 0) + 1
print "All objects: %d Tracked objects: %d" % (len(objs), len(refs))
print("All objects: %d Tracked objects: %d" % (len(objs), len(refs)))
return refs, count, objs
def forgetRef(self, ref):
@ -669,14 +669,14 @@ class ObjTracker:
rev[typ].append(oid)
c = count.get(typ, [0,0])
count[typ] = [c[0]+1, c[1]+objectSize(obj)]
typs = count.keys()
typs = list(count.keys())
typs.sort(lambda a,b: cmp(count[a][1], count[b][1]))
for t in typs:
line = " %d\t%d\t%s" % (count[t][0], count[t][1], t)
if showIDs:
line += "\t"+",".join(map(str,rev[t]))
print line
print(line)
def findTypes(self, refs, regex):
allObjs = get_all_objects()
@ -709,21 +709,21 @@ def describeObj(obj, depth=4, path=None, ignore=None):
for ref in refs:
if id(ref) in ignore:
continue
if id(ref) in map(id, path):
print "Cyclic reference: " + refPathString([ref]+path)
if id(ref) in list(map(id, path)):
print("Cyclic reference: " + refPathString([ref]+path))
printed = True
continue
newPath = [ref]+path
if len(newPath) >= depth:
refStr = refPathString(newPath)
if '[_]' not in refStr: ## ignore '_' references generated by the interactive shell
print refStr
print(refStr)
printed = True
else:
describeObj(ref, depth, newPath, ignore)
printed = True
if not printed:
print "Dead end: " + refPathString(path)
print("Dead end: " + refPathString(path))
@ -773,18 +773,18 @@ def searchRefs(obj, *args):
ignore[id(refs)] = None
refs = [r for r in refs if id(r) not in ignore]
elif a == 't':
print map(typeStr, refs)
print(list(map(typeStr, refs)))
elif a == 'i':
print map(id, refs)
print(list(map(id, refs)))
elif a == 'l':
def slen(o):
if hasattr(o, '__len__'):
return len(o)
else:
return None
print map(slen, refs)
print(list(map(slen, refs)))
elif a == 'o':
print obj
print(obj)
elif a == 'ro':
return obj
elif a == 'rr':
@ -820,14 +820,14 @@ def findObj(regex):
def listRedundantModules():
"""List modules that have been imported more than once via different paths."""
mods = {}
for name, mod in sys.modules.iteritems():
for name, mod in sys.modules.items():
if not hasattr(mod, '__file__'):
continue
mfile = os.path.abspath(mod.__file__)
if mfile[-1] == 'c':
mfile = mfile[:-1]
if mfile in mods:
print "module at %s has 2 names: %s, %s" % (mfile, name, mods[mfile])
print("module at %s has 2 names: %s, %s" % (mfile, name, mods[mfile]))
else:
mods[mfile] = name
@ -841,7 +841,7 @@ def walkQObjectTree(obj, counts=None, verbose=False, depth=0):
"""
if verbose:
print " "*depth + typeStr(obj)
print(" "*depth + typeStr(obj))
report = False
if counts is None:
counts = {}
@ -871,12 +871,12 @@ def qObjectReport(verbose=False):
QObjCache[oid] += " " + obj.text()
except:
pass
print "check obj", oid, unicode(QObjCache[oid])
print("check obj", oid, str(QObjCache[oid]))
if obj.parent() is None:
walkQObjectTree(obj, count, verbose)
typs = count.keys()
typs = list(count.keys())
typs.sort()
for t in typs:
print count[t], "\t", t
print(count[t], "\t", t)

View File

@ -264,4 +264,4 @@ class TContainer(Container, QtGui.QWidget):
QtGui.QStackedWidget.childEvent(self.stack, ev)
Container.childEvent(self, ev)
import Dock
from . import Dock

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtCore, QtGui
from DockDrop import *
from .DockDrop import *
from pyqtgraph.widgets.VerticalLabel import VerticalLabel
class Dock(QtGui.QWidget, DockDrop):

View File

@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from pyqtgraph.Qt import QtCore, QtGui
from Container import *
from DockDrop import *
from .Container import *
from .DockDrop import *
import pyqtgraph.debug as debug
import weakref
@ -202,7 +202,7 @@ class DockArea(Container, QtGui.QWidget, DockDrop):
a.win.setGeometry(*s[1])
## 4) Add any remaining docks to the bottom
for d in docks.itervalues():
for d in docks.values():
self.moveDock(d, 'below', None)
#print "\nKill old containers:"

View File

@ -126,4 +126,4 @@ class DropAreaOverlay(QtGui.QWidget):
p.setPen(QtGui.QPen(QtGui.QColor(50, 50, 150), 3))
p.drawRect(rgn)
import Dock
from . import Dock

View File

@ -1,2 +1,2 @@
from DockArea import DockArea
from Dock import Dock
from .DockArea import DockArea
from .Dock import Dock

View File

@ -7,15 +7,15 @@ sys.path.insert(0, p)
from pyqtgraph.Qt import QtCore, QtGui
from DockArea import *
from Dock import *
from .DockArea import *
from .Dock import *
app = QtGui.QApplication([])
win = QtGui.QMainWindow()
area = DockArea()
win.setCentralWidget(area)
win.resize(800,800)
from Dock import Dock
from .Dock import Dock
d1 = Dock("Dock1", size=(200,200))
d2 = Dock("Dock2", size=(100,100))
d3 = Dock("Dock3", size=(1,1))
@ -32,7 +32,7 @@ area.addDock(d6, 'top', d4)
area.moveDock(d6, 'above', d4)
d3.hideTitleBar()
print "===build complete===="
print("===build complete====")
for d in [d1, d2, d3, d4, d5]:
w = QtGui.QWidget()
@ -51,7 +51,7 @@ import pyqtgraph as pg
p = pg.PlotWidget()
d6.addWidget(p)
print "===widgets added==="
print("===widgets added===")
#s = area.saveState()

View File

@ -41,8 +41,8 @@ source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
project = u'pyqtgraph'
copyright = u'2011, Luke Campagnola'
project = 'pyqtgraph'
copyright = '2011, Luke Campagnola'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@ -179,8 +179,8 @@ htmlhelp_basename = 'pyqtgraphdoc'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'pyqtgraph.tex', u'pyqtgraph Documentation',
u'Luke Campagnola', 'manual'),
('index', 'pyqtgraph.tex', 'pyqtgraph Documentation',
'Luke Campagnola', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@ -212,6 +212,6 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'pyqtgraph', u'pyqtgraph Documentation',
[u'Luke Campagnola'], 1)
('index', 'pyqtgraph', 'pyqtgraph Documentation',
['Luke Campagnola'], 1)
]

View File

@ -37,12 +37,12 @@ def psi(i, j, k, offset=(25, 25, 50)):
#return ((1./81.) * (1./np.pi)**0.5 * (1./a0)**(3/2) * (r/a0)**2 * (r/a0) * np.exp(-r/(3*a0)) * np.sin(th) * np.cos(th) * np.exp(2 * 1j * phi))**2
print "Generating scalar field.."
print("Generating scalar field..")
data = np.abs(np.fromfunction(psi, (50,50,100)))
#data = np.fromfunction(lambda i,j,k: np.sin(0.2*((i-25)**2+(j-15)**2+k**2)**0.5), (50,50,50));
print "Generating isosurface.."
print("Generating isosurface..")
faces = pg.isosurface(data, data.max()/4.)
m = gl.GLMeshItem(faces)
w.addItem(m)

View File

@ -26,9 +26,9 @@ class Obj(QtGui.QGraphicsObject):
def mouseClickEvent(self, ev):
if ev.double():
print "double click"
print("double click")
else:
print "click"
print("click")
ev.accept()
#def mouseDragEvent(self, ev):
@ -48,7 +48,7 @@ obj2 = Obj()
win.addItem(obj2)
def clicked():
print "button click"
print("button click")
btn = QtGui.QPushButton("BTN")
btn.clicked.connect(clicked)
prox = QtGui.QGraphicsProxyWidget()

View File

@ -13,7 +13,7 @@ from pyqtgraph import MultiPlotWidget
try:
from metaarray import *
except:
print "MultiPlot is only used with MetaArray for now (and you do not have the metaarray package)"
print("MultiPlot is only used with MetaArray for now (and you do not have the metaarray package)")
exit()
app = QtGui.QApplication([])

View File

@ -70,7 +70,7 @@ curve.setPen('w') ## white pen
curve.setShadowPen(pg.mkPen((70,70,30), width=6, cosmetic=True))
def clicked():
print "curve clicked"
print("curve clicked")
curve.sigClicked.connect(clicked)
lr = pg.LinearRegionItem([1, 30], bounds=[0,100], movable=True)
@ -79,8 +79,6 @@ line = pg.InfiniteLine(angle=90, movable=True)
pw3.addItem(line)
line.setBounds([0,200])
import initExample ## Add path to library (just for examples; you do not need this)
## Start Qt event loop unless running in interactive mode or using pyside.
import sys
if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'):

View File

@ -21,7 +21,7 @@ w2.setAspectLocked(True)
view.nextRow()
w3 = view.addPlot()
w4 = view.addPlot()
print "Generating data, this takes a few seconds..."
print("Generating data, this takes a few seconds...")
## There are a few different ways we can draw scatter plots; each is optimized for different types of data:
@ -43,7 +43,7 @@ def clicked(plot, points):
global lastClicked
for p in lastClicked:
p.resetPen()
print "clicked points", points
print("clicked points", points)
for p in points:
p.setPen('b', width=2)
lastClicked = points
@ -57,7 +57,7 @@ s1.sigClicked.connect(clicked)
s2 = pg.ScatterPlotItem(size=10, pen=pg.mkPen('w'), pxMode=True)
pos = np.random.normal(size=(2,n), scale=1e-5)
spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 5+i/10.} for i in xrange(n)]
spots = [{'pos': pos[:,i], 'data': 1, 'brush':pg.intColor(i, n), 'symbol': i%5, 'size': 5+i/10.} for i in range(n)]
s2.addPoints(spots)
w2.addItem(s2)
w2.setRange(s2.boundingRect())

View File

@ -71,7 +71,7 @@ l.addItem(xScale, 1, 1)
yScale = pg.AxisItem(orientation='left', linkView=vb)
l.addItem(yScale, 0, 0)
xScale.setLabel(text=u"<span style='color: #ff0000; font-weight: bold'>X</span> <i>Axis</i>", units="s")
xScale.setLabel(text="<span style='color: #ff0000; font-weight: bold'>X</span> <i>Axis</i>", units="s")
yScale.setLabel('Y Axis', units='V')
def rand(n):

View File

@ -38,7 +38,7 @@ examples = OrderedDict([
#('SpinBox', '../widgets/SpinBox.py'),
('TreeWidget', '../widgets/TreeWidget.py'),
('DataTreeWidget', '../widgets/DataTreeWidget.py'),
('GradientWidget', '../widgets/GradientWidget.py'),
('GradientWidget', 'GradientWidget.py'),
#('TableWidget', '../widgets/TableWidget.py'),
('ColorButton', '../widgets/ColorButton.py'),
#('CheckTable', '../widgets/CheckTable.py'),
@ -75,7 +75,7 @@ class ExampleLoader(QtGui.QMainWindow):
def populateTree(self, root, examples):
for key, val in examples.iteritems():
for key, val in examples.items():
item = QtGui.QTreeWidgetItem([key])
if isinstance(val, basestring):
item.file = val

View File

@ -1,6 +1,6 @@
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
from Exporter import Exporter
from .Exporter import Exporter
from pyqtgraph.parametertree import Parameter

View File

@ -1,4 +1,4 @@
from Exporter import Exporter
from .Exporter import Exporter
from pyqtgraph.parametertree import Parameter
from pyqtgraph.Qt import QtGui, QtCore, QtSvg
import pyqtgraph as pg

View File

@ -1,6 +1,6 @@
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
from Exporter import Exporter
from .Exporter import Exporter
__all__ = ['MatplotlibExporter']

View File

@ -1,4 +1,4 @@
from Exporter import Exporter
from .Exporter import Exporter
from pyqtgraph.parametertree import Parameter
from pyqtgraph.Qt import QtGui, QtCore, QtSvg
import re

View File

@ -1,4 +1,4 @@
from Exporter import Exporter
from .Exporter import Exporter
from pyqtgraph.parametertree import Parameter
from pyqtgraph.Qt import QtGui, QtCore, QtSvg
import re
@ -57,7 +57,7 @@ class SVGExporter(Exporter):
if m is not None:
#print "Matched group:", line
g = m.groups()
matrix = map(float, g[2].split(','))
matrix = list(map(float, g[2].split(',')))
#print "matrix:", matrix
scale = max(abs(matrix[0]), abs(matrix[3]))
if scale == 0 or scale == 1.0:

View File

@ -4,7 +4,7 @@ import os, sys
d = os.path.split(__file__)[0]
files = []
for f in os.listdir(d):
if os.path.isdir(os.path.join(d, f)):
if os.path.isdir(os.path.join(d, f)) and f != '__pycache__':
files.append(f)
elif f[-3:] == '.py' and f not in ['__init__.py', 'Exporter.py']:
files.append(f[:-3])

View File

@ -3,24 +3,24 @@ from pyqtgraph.Qt import QtCore, QtGui
#from PyQt4 import QtCore, QtGui
#from PySide import QtCore, QtGui
#import Node as NodeMod
from Node import *
from .Node import *
#import functions
from collections import OrderedDict
from pyqtgraph.widgets.TreeWidget import *
#from .. DataTreeWidget import *
import FlowchartTemplate
import FlowchartCtrlTemplate
from Terminal import Terminal
from . import FlowchartTemplate
from . import FlowchartCtrlTemplate
from .Terminal import Terminal
from numpy import ndarray
import library
from . import library
from pyqtgraph.debug import printExc
import pyqtgraph.configfile as configfile
import pyqtgraph.dockarea as dockarea
import pyqtgraph as pg
import FlowchartGraphicsView
from . import FlowchartGraphicsView
def strDict(d):
return dict([(str(k), v) for k, v in d.iteritems()])
return dict([(str(k), v) for k, v in d.items()])
def toposort(deps, nodes=None, seen=None, stack=None, depth=0):
@ -33,7 +33,7 @@ def toposort(deps, nodes=None, seen=None, stack=None, depth=0):
if nodes is None:
## run through deps to find nodes that are not depended upon
rem = set()
for dep in deps.itervalues():
for dep in deps.values():
rem |= set(dep)
nodes = set(deps.keys()) - rem
if seen is None:
@ -99,7 +99,7 @@ class Flowchart(Node):
self.viewBox.autoRange(padding = 0.04)
for name, opts in terminals.iteritems():
for name, opts in terminals.items():
self.addTerminal(name, **opts)
def setInput(self, **args):
@ -267,7 +267,7 @@ class Flowchart(Node):
#print "ORDER:", order
## Record inputs given to process()
for n, t in self.inputNode.outputs().iteritems():
for n, t in self.inputNode.outputs().items():
if n not in args:
raise Exception("Parameter %s required to process this chart." % n)
data[t] = args[n]
@ -285,8 +285,8 @@ class Flowchart(Node):
## get input and output terminals for this node
outs = node.outputs().values()
ins = node.inputs().values()
outs = list(node.outputs().values())
ins = list(node.inputs().values())
## construct input value dictionary
args = {}
@ -308,7 +308,7 @@ class Flowchart(Node):
else:
result = node.process(display=False, **args)
except:
print "Error processing node %s. Args are: %s" % (str(node), str(args))
print("Error processing node %s. Args are: %s" % (str(node), str(args)))
raise
for out in outs:
#print " Output:", out, out.name()
@ -316,7 +316,7 @@ class Flowchart(Node):
try:
data[out] = result[out.name()]
except:
print out, out.name()
print(out, out.name())
raise
elif c == 'd': ## delete a terminal result (no longer needed; may be holding a lot of memory)
#print "===> delete", arg
@ -334,9 +334,9 @@ class Flowchart(Node):
## first collect list of nodes/terminals and their dependencies
deps = {}
tdeps = {} ## {terminal: [nodes that depend on terminal]}
for name, node in self._nodes.iteritems():
for name, node in self._nodes.items():
deps[node] = node.dependentNodes()
for t in node.outputs().itervalues():
for t in node.outputs().values():
tdeps[t] = t.dependentNodes()
#print "DEPS:", deps
@ -350,7 +350,7 @@ class Flowchart(Node):
## determine when it is safe to delete terminal values
dels = []
for t, nodes in tdeps.iteritems():
for t, nodes in tdeps.items():
lastInd = 0
lastNode = None
for n in nodes: ## determine which node is the last to be processed according to order
@ -385,9 +385,9 @@ class Flowchart(Node):
self.processing = True
try:
deps = {}
for name, node in self._nodes.iteritems():
for name, node in self._nodes.items():
deps[node] = []
for t in node.outputs().itervalues():
for t in node.outputs().values():
deps[node].extend(t.dependentNodes())
## determine order of updates
@ -401,9 +401,9 @@ class Flowchart(Node):
#print "Order:", order
for node in order[1:]:
#print "Processing node", node
for term in node.inputs().values():
for term in list(node.inputs().values()):
#print " checking terminal", term
deps = term.connections().keys()
deps = list(term.connections().keys())
update = False
for d in deps:
if d in terms:
@ -446,9 +446,9 @@ class Flowchart(Node):
def listConnections(self):
conn = set()
for n in self._nodes.itervalues():
for n in self._nodes.values():
terms = n.outputs()
for n, t in terms.iteritems():
for n, t in terms.items():
for c in t.connections():
conn.add((t, c))
return conn
@ -459,7 +459,7 @@ class Flowchart(Node):
state['connects'] = []
state['terminals'] = self.saveTerminals()
for name, node in self._nodes.iteritems():
for name, node in self._nodes.items():
cls = type(node)
if hasattr(cls, 'nodeName'):
clsName = cls.nodeName
@ -503,8 +503,8 @@ class Flowchart(Node):
try:
self.connectTerminals(self._nodes[n1][t1], self._nodes[n2][t2])
except:
print self._nodes[n1].terminals
print self._nodes[n2].terminals
print(self._nodes[n1].terminals)
print(self._nodes[n2].terminals)
printExc("Error connecting terminals %s.%s - %s.%s:" % (n1, t1, n2, t2))
@ -554,7 +554,7 @@ class Flowchart(Node):
self.sigFileSaved.emit(fileName)
def clear(self):
for n in self._nodes.values():
for n in list(self._nodes.values()):
if n is self.inputNode or n is self.outputNode:
continue
n.close() ## calls self.nodeClosed(n) by signal
@ -583,7 +583,7 @@ class FlowchartGraphicsItem(GraphicsObject):
inp = self.chart.inputs()
dy = bounds.height() / (len(inp)+1)
y = dy
for n, t in inp.iteritems():
for n, t in inp.items():
item = t.graphicsItem()
self.terminals[n] = item
item.setParentItem(self)
@ -592,7 +592,7 @@ class FlowchartGraphicsItem(GraphicsObject):
out = self.chart.outputs()
dy = bounds.height() / (len(out)+1)
y = dy
for n, t in out.iteritems():
for n, t in out.items():
item = t.graphicsItem()
self.terminals[n] = item
item.setParentItem(self)
@ -840,7 +840,7 @@ class FlowchartWidget(dockarea.DockArea):
def buildMenu(self, pos=None):
self.nodeMenu = QtGui.QMenu()
self.subMenus = []
for section, nodes in library.getNodeTree().iteritems():
for section, nodes in library.getNodeTree().items():
menu = QtGui.QMenu(section)
self.nodeMenu.addMenu(menu)
for name in nodes:

View File

@ -56,4 +56,4 @@ class Ui_Form(object):
Form.setWindowTitle(QtGui.QApplication.translate("Form", "Form", None, QtGui.QApplication.UnicodeUTF8))
from pyqtgraph.widgets.DataTreeWidget import DataTreeWidget
from FlowchartGraphicsView import FlowchartGraphicsView
from .FlowchartGraphicsView import FlowchartGraphicsView

View File

@ -3,17 +3,17 @@ from pyqtgraph.Qt import QtCore, QtGui
#from PySide import QtCore, QtGui
from pyqtgraph.graphicsItems.GraphicsObject import GraphicsObject
import pyqtgraph.functions as fn
from Terminal import *
from .Terminal import *
from collections import OrderedDict
from pyqtgraph.debug import *
import numpy as np
#from pyqtgraph.ObjectWorkaround import QObjectWorkaround
from eq import *
from .eq import *
#TETRACYCLINE = True
def strDict(d):
return dict([(str(k), v) for k, v in d.iteritems()])
return dict([(str(k), v) for k, v in d.items()])
class Node(QtCore.QObject):
@ -41,7 +41,7 @@ class Node(QtCore.QObject):
self.exception = None
if terminals is None:
return
for name, opts in terminals.iteritems():
for name, opts in terminals.items():
self.addTerminal(name, **opts)
@ -156,7 +156,7 @@ class Node(QtCore.QObject):
def dependentNodes(self):
"""Return the list of nodes which provide direct input to this node"""
nodes = set()
for t in self.inputs().itervalues():
for t in self.inputs().values():
nodes |= set([i.node() for i in t.inputTerminals()])
return nodes
#return set([t.inputTerminals().node() for t in self.listInputs().itervalues()])
@ -180,7 +180,7 @@ class Node(QtCore.QObject):
"""Set the values on input terminals. For most nodes, this will happen automatically through Terminal.inputChanged.
This is normally only used for nodes with no connected inputs."""
changed = False
for k, v in args.iteritems():
for k, v in args.items():
term = self._inputs[k]
oldVal = term.value()
if not eq(oldVal, v):
@ -191,13 +191,13 @@ class Node(QtCore.QObject):
def inputValues(self):
vals = {}
for n, t in self.inputs().iteritems():
for n, t in self.inputs().items():
vals[n] = t.value()
return vals
def outputValues(self):
vals = {}
for n, t in self.outputs().iteritems():
for n, t in self.outputs().items():
vals[n] = t.value()
return vals
@ -224,12 +224,12 @@ class Node(QtCore.QObject):
self.setOutput(**out)
else:
self.setOutputNoSignal(**out)
for n,t in self.inputs().iteritems():
for n,t in self.inputs().items():
t.setValueAcceptable(True)
self.clearException()
except:
#printExc( "Exception while processing %s:" % self.name())
for n,t in self.outputs().iteritems():
for n,t in self.outputs().items():
t.setValue(None)
self.setException(sys.exc_info())
@ -239,7 +239,7 @@ class Node(QtCore.QObject):
def processBypassed(self, args):
result = {}
for term in self.outputs().values():
for term in list(self.outputs().values()):
byp = term.bypassValue()
if byp is None:
result[term.name()] = None
@ -253,7 +253,7 @@ class Node(QtCore.QObject):
self.sigOutputChanged.emit(self) ## triggers flowchart to propagate new data
def setOutputNoSignal(self, **vals):
for k, v in vals.iteritems():
for k, v in vals.items():
term = self.outputs()[k]
term.setValue(v)
#targets = term.connections()
@ -287,15 +287,15 @@ class Node(QtCore.QObject):
def saveTerminals(self):
terms = OrderedDict()
for n, t in self.terminals.iteritems():
for n, t in self.terminals.items():
terms[n] = (t.saveState())
return terms
def restoreTerminals(self, state):
for name in self.terminals.keys():
for name in list(self.terminals.keys()):
if name not in state:
self.removeTerminal(name)
for name, opts in state.iteritems():
for name, opts in state.items():
if name in self.terminals:
continue
try:
@ -306,7 +306,7 @@ class Node(QtCore.QObject):
def clearTerminals(self):
for t in self.terminals.itervalues():
for t in self.terminals.values():
t.close()
self.terminals = OrderedDict()
self._inputs = {}
@ -410,7 +410,7 @@ class NodeGraphicsItem(GraphicsObject):
inp = self.node.inputs()
dy = bounds.height() / (len(inp)+1)
y = dy
for i, t in inp.iteritems():
for i, t in inp.items():
item = t.graphicsItem()
item.setParentItem(self)
#item.setZValue(self.zValue()+1)
@ -422,7 +422,7 @@ class NodeGraphicsItem(GraphicsObject):
out = self.node.outputs()
dy = bounds.height() / (len(out)+1)
y = dy
for i, t in out.iteritems():
for i, t in out.items():
item = t.graphicsItem()
item.setParentItem(self)
item.setZValue(self.zValue())
@ -508,7 +508,7 @@ class NodeGraphicsItem(GraphicsObject):
def itemChange(self, change, val):
if change == self.ItemPositionHasChanged:
for k, t in self.terminals.iteritems():
for k, t in self.terminals.items():
t[1].nodeMoved()
return QtGui.QGraphicsItem.itemChange(self, change, val)

View File

@ -5,7 +5,7 @@ from pyqtgraph.graphicsItems.GraphicsObject import GraphicsObject
import pyqtgraph.functions as fn
from pyqtgraph.Point import Point
#from PySide import QtCore, QtGui
from eq import *
from .eq import *
class Terminal:
def __init__(self, node, name, io, optional=False, multi=False, pos=None, renamable=False, removable=False, multiable=False, bypass=None):
@ -192,7 +192,7 @@ class Terminal:
raise Exception("Can't connect to terminal on same node.")
for t in [self, term]:
if t.isInput() and not t._multi and len(t.connections()) > 0:
raise Exception("Cannot connect %s <-> %s: Terminal %s is already connected to %s (and does not allow multiple connections)" % (self, term, t, t.connections().keys()))
raise Exception("Cannot connect %s <-> %s: Terminal %s is already connected to %s (and does not allow multiple connections)" % (self, term, t, list(t.connections().keys())))
#if self.hasInput() and term.hasInput():
#raise Exception('Target terminal already has input')
@ -244,7 +244,7 @@ class Terminal:
def disconnectAll(self):
for t in self._connections.keys():
for t in list(self._connections.keys()):
self.disconnectFrom(t)
def recolor(self, color=None, recurse=True):
@ -372,7 +372,7 @@ class TerminalGraphicsItem(GraphicsObject):
self.updateConnections()
def updateConnections(self):
for t, c in self.term.connections().iteritems():
for t, c in self.term.connections().items():
c.updateLine()
def mousePressEvent(self, ev):
@ -484,7 +484,7 @@ class TerminalGraphicsItem(GraphicsObject):
return self.mapToView(self.mapFromItem(self.box, self.box.boundingRect().center()))
def nodeMoved(self):
for t, item in self.term.connections().iteritems():
for t, item in self.term.connections().items():
item.updateLine()

View File

@ -1,4 +1,4 @@
# -*- coding: utf-8 -*-
from Flowchart import *
from .Flowchart import *
from library import getNodeType, registerNodeType, getNodeTree
from .library import getNodeType, registerNodeType, getNodeTree

View File

@ -10,8 +10,8 @@ def eq(a, b):
except AttributeError:
return False
except:
print "a:", str(type(a)), str(a)
print "b:", str(type(b)), str(b)
print("a:", str(type(a)), str(a))
print("b:", str(type(b)), str(b))
raise
t = type(e)
if t is bool:

View File

@ -2,13 +2,13 @@
from ..Node import Node
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
from common import *
from .common import *
from pyqtgraph.Transform import Transform
from pyqtgraph.Point import Point
from pyqtgraph.widgets.TreeWidget import TreeWidget
from pyqtgraph.graphicsItems.LinearRegionItem import LinearRegionItem
import functions
from . import functions
try:
import metaarray
@ -55,7 +55,7 @@ class ColumnSelectNode(Node):
cols = set(cols[ax])
break
else:
cols = data.dtype.fields.keys()
cols = list(data.dtype.fields.keys())
rem = set()
for c in self.columns:
@ -124,11 +124,11 @@ class RegionSelectNode(CtrlNode):
self.ctrls['movable'].toggled.connect(self.movableToggled)
def displayToggled(self, b):
for item in self.items.itervalues():
for item in self.items.values():
item.setVisible(b)
def movableToggled(self, b):
for item in self.items.itervalues():
for item in self.items.values():
item.setMovable(b)
@ -225,7 +225,7 @@ class EvalNode(Node):
text = str(self.text.toPlainText())
if text != self.lastText:
self.lastText = text
print "eval node update"
print("eval node update")
self.update()
return QtGui.QTextEdit.focusOutEvent(self.text, ev)

View File

@ -7,7 +7,7 @@ from pyqtgraph.graphicsItems.ScatterPlotItem import ScatterPlotItem
from pyqtgraph.graphicsItems.PlotCurveItem import PlotCurveItem
from pyqtgraph import PlotDataItem
from common import *
from .common import *
import numpy as np
class PlotWidgetNode(Node):
@ -37,7 +37,7 @@ class PlotWidgetNode(Node):
if display:
#self.plot.clearPlots()
items = set()
for name, vals in In.iteritems():
for name, vals in In.items():
if vals is None:
continue
if type(vals) is not list:
@ -61,14 +61,14 @@ class PlotWidgetNode(Node):
item = self.plot.plot(val)
self.items[vid] = item
items.add(vid)
for vid in self.items.keys():
for vid in list(self.items.keys()):
if vid not in items:
#print "remove", self.items[vid]
self.plot.removeItem(self.items[vid])
del self.items[vid]
def processBypassed(self, args):
for item in self.items.values():
for item in list(self.items.values()):
self.plot.removeItem(item)
self.items = {}
@ -101,7 +101,7 @@ class CanvasNode(Node):
def process(self, In, display=True):
if display:
items = set()
for name, vals in In.iteritems():
for name, vals in In.items():
if vals is None:
continue
if type(vals) is not list:
@ -116,7 +116,7 @@ class CanvasNode(Node):
item = val
self.items[vid] = item
items.add(vid)
for vid in self.items.keys():
for vid in list(self.items.keys()):
if vid not in items:
#print "remove", self.items[vid]
self.canvas.removeItem(self.items[vid])
@ -214,16 +214,16 @@ class ScatterPlot(CtrlNode):
def updateKeys(self, data):
if isinstance(data, dict):
keys = data.keys()
keys = list(data.keys())
elif isinstance(data, list) or isinstance(data, tuple):
keys = data
elif isinstance(data, np.ndarray) or isinstance(data, np.void):
keys = data.dtype.names
else:
print "Unknown data type:", type(data), data
print("Unknown data type:", type(data), data)
return
for c in self.ctrls.itervalues():
for c in self.ctrls.values():
c.blockSignals(True)
for c in [self.ctrls['x'], self.ctrls['y'], self.ctrls['size']]:
cur = str(c.currentText())
@ -234,7 +234,7 @@ class ScatterPlot(CtrlNode):
c.setCurrentIndex(c.count()-1)
for c in [self.ctrls['color'], self.ctrls['border']]:
c.setArgList(keys)
for c in self.ctrls.itervalues():
for c in self.ctrls.values():
c.blockSignals(False)
self.keys = keys

View File

@ -4,8 +4,8 @@ from ..Node import Node
from scipy.signal import detrend
from scipy.ndimage import median_filter, gaussian_filter
#from pyqtgraph.SignalProxy import SignalProxy
import functions
from common import *
from . import functions
from .common import *
import numpy as np
try:

View File

@ -67,7 +67,7 @@ def loadLibrary(reloadLibs=False, libPath=None):
for f in os.listdir(libPath):
pathName, ext = os.path.splitext(f)
if ext != '.py' or '__init__' in pathName:
if ext != '.py' or '__init__' in pathName or '__pycache__' in pathName:
continue
try:
#print "importing from", f

View File

@ -258,9 +258,9 @@ def concatenateColumns(data):
try:
out[name] = element[name]
except:
print "Column:", name
print "Input shape:", element.shape, element.dtype
print "Output shape:", out.shape, out.dtype
print("Column:", name)
print("Input shape:", element.shape, element.dtype)
print("Output shape:", out.shape, out.dtype)
raise
else:
name, type, d = element
@ -279,7 +279,7 @@ def suggestDType(x):
return x.dtype
elif isinstance(x, float):
return float
elif isinstance(x, int) or isinstance(x, long):
elif isinstance(x, int):
return int
#elif isinstance(x, basestring): ## don't try to guess correct string length; use object instead.
#return '<U%d' % len(x)

View File

@ -16,18 +16,22 @@ Colors = {
'w': (255,255,255,255),
}
SI_PREFIXES = u'yzafpnµm kMGTPEZY'
SI_PREFIXES = asUnicode('yzafpnµm kMGTPEZY')
SI_PREFIXES_ASCII = 'yzafpnum kMGTPEZY'
USE_WEAVE = True
from Qt import QtGui, QtCore
from .Qt import QtGui, QtCore
import numpy as np
import scipy.ndimage
import decimal, re
import scipy.weave
import debug
try:
import scipy.weave
USE_WEAVE = True
except ImportError:
USE_WEAVE = False
from . import debug
def siScale(x, minVal=1e-25, allowUnicode=True):
"""
@ -46,7 +50,7 @@ def siScale(x, minVal=1e-25, allowUnicode=True):
if np.isnan(x) or np.isinf(x):
return(1, '')
except:
print x, type(x)
print(x, type(x))
raise
if abs(x) < minVal:
m = 0
@ -90,7 +94,7 @@ def siFormat(x, precision=3, suffix='', space=True, error=None, minVal=1e-25, al
return fmt % (x*p, pref, suffix)
else:
if allowUnicode:
plusminus = space + u"±" + space
plusminus = space + asUnicode("±") + space
else:
plusminus = " +/- "
fmt = "%." + str(precision) + "g%s%s%s%s"
@ -105,7 +109,7 @@ def siEval(s):
siEval("100 μV") # returns 0.0001
"""
s = unicode(s)
s = asUnicode(s)
m = re.match(r'(-?((\d+(\.\d*)?)|(\.\d+))([eE]-?\d+)?)\s*([u' + SI_PREFIXES + r']?)$', s)
if m is None:
raise Exception("Can't convert string '%s' to number." % s)
@ -208,8 +212,8 @@ def mkColor(*args):
raise Exception(err)
args = [r,g,b,a]
args = map(lambda a: 0 if np.isnan(a) or np.isinf(a) else a, args)
args = map(int, args)
args = [0 if np.isnan(a) or np.isinf(a) else a for a in args]
args = list(map(int, args))
return QtGui.QColor(*args)
@ -371,10 +375,10 @@ def affineSlice(data, shape, origin, vectors, axes, **kargs):
if len(v) != len(axes):
raise Exception("each vector must be same length as axes.")
shape = map(np.ceil, shape)
shape = list(map(np.ceil, shape))
## transpose data so slice axes come first
trAx = range(data.ndim)
trAx = list(range(data.ndim))
for x in axes:
trAx.remove(x)
tr1 = tuple(axes) + tuple(trAx)
@ -403,7 +407,7 @@ def affineSlice(data, shape, origin, vectors, axes, **kargs):
#print data[ind].shape, x.shape, output[ind].shape, output.shape
output[ind] = scipy.ndimage.map_coordinates(data[ind], x, **kargs)
tr = range(output.ndim)
tr = list(range(output.ndim))
trb = []
for i in range(min(axes)):
ind = tr1.index(i) + (len(shape)-len(axes))
@ -503,13 +507,13 @@ def makeARGB(data, lut=None, levels=None, useRGBA=False):
else:
if data.ndim == 2:
newData = np.empty(data.shape+(levels.shape[0],), dtype=np.uint32)
for i in xrange(levels.shape[0]):
for i in range(levels.shape[0]):
scale = float(lutLength / (levels[i,1]-levels[i,0]))
offset = float(levels[i,0])
newData[...,i] = rescaleData(data, scale, offset)
elif data.ndim == 3:
newData = np.empty(data.shape, dtype=np.uint32)
for i in xrange(data.shape[2]):
for i in range(data.shape[2]):
scale = float(lutLength / (levels[i,1]-levels[i,0]))
offset = float(levels[i,0])
#print scale, offset, data.shape, newData.shape, levels.shape
@ -596,10 +600,10 @@ def makeARGB(data, lut=None, levels=None, useRGBA=False):
order = [2,1,0,3] ## for some reason, the colors line up as BGR in the final image.
if data.shape[2] == 1:
for i in xrange(3):
for i in range(3):
imgData[..., order[i]] = data[..., 0]
else:
for i in xrange(0, data.shape[2]):
for i in range(0, data.shape[2]):
imgData[..., order[i]] = data[..., i]
prof.mark('5')
@ -802,8 +806,8 @@ def isocurve(data, level):
#print index
## add lines
for i in xrange(index.shape[0]): # data x-axis
for j in xrange(index.shape[1]): # data y-axis
for i in range(index.shape[0]): # data x-axis
for j in range(index.shape[1]): # data y-axis
sides = sideTable[index[i,j]]
for l in range(0, len(sides), 2): ## faces for this grid cell
edges = sides[l:l+2]
@ -1179,9 +1183,9 @@ def isosurface(data, level):
#print index
## add facets
for i in xrange(index.shape[0]): # data x-axis
for j in xrange(index.shape[1]): # data y-axis
for k in xrange(index.shape[2]): # data z-axis
for i in range(index.shape[0]): # data x-axis
for j in range(index.shape[1]): # data y-axis
for k in range(index.shape[2]): # data z-axis
tris = triTable[index[i,j,k]]
for l in range(0, len(tris), 3): ## faces for this grid cell
edges = tris[l:l+3]

View File

@ -4,7 +4,7 @@ from pyqtgraph.Point import Point
import pyqtgraph.debug as debug
import weakref
import pyqtgraph.functions as fn
from GraphicsWidget import GraphicsWidget
from .GraphicsWidget import GraphicsWidget
__all__ = ['AxisItem']
class AxisItem(GraphicsWidget):
@ -159,16 +159,16 @@ class AxisItem(GraphicsWidget):
if self.scale == 1.0:
units = ''
else:
units = u'(x%g)' % (1.0/self.scale)
units = asUnicode('(x%g)') % (1.0/self.scale)
else:
#print repr(self.labelUnitPrefix), repr(self.labelUnits)
units = u'(%s%s)' % (self.labelUnitPrefix, self.labelUnits)
units = asUnicode('(%s%s)') % (self.labelUnitPrefix, self.labelUnits)
s = u'%s %s' % (self.labelText, units)
s = asUnicode('%s %s') % (self.labelText, units)
style = ';'.join(['%s: "%s"' % (k, self.labelStyle[k]) for k in self.labelStyle])
return u"<span style='%s'>%s</span>" % (style, s)
return asUnicode("<span style='%s'>%s</span>") % (style, s)
def setHeight(self, h=None):
if h is None:
@ -364,12 +364,12 @@ class AxisItem(GraphicsWidget):
def logTickValues(self, minVal, maxVal, size):
v1 = int(np.floor(minVal))
v2 = int(np.ceil(maxVal))
major = range(v1+1, v2)
major = list(range(v1+1, v2))
minor = []
for v in range(v1, v2):
minor.extend(v + np.log10(np.arange(1, 10)))
minor = filter(lambda x: x>minVal and x<maxVal, minor)
minor = [x for x in minor if x>minVal and x<maxVal]
return [(1.0, major), (None, minor)]
def tickStrings(self, values, scale, spacing):
@ -450,7 +450,7 @@ class AxisItem(GraphicsWidget):
p.translate(0.5,0) ## resolves some damn pixel ambiguity
## determine size of this item in pixels
points = map(self.mapToDevice, span)
points = list(map(self.mapToDevice, span))
lengthInPixels = Point(points[1] - points[0]).length()
if lengthInPixels == 0:
return

View File

@ -1,5 +1,5 @@
from pyqtgraph.Qt import QtGui, QtCore
from GraphicsObject import GraphicsObject
from .GraphicsObject import GraphicsObject
__all__ = ['ButtonItem']
class ButtonItem(GraphicsObject):

View File

@ -1,9 +1,9 @@
from pyqtgraph.Qt import QtGui, QtCore
import ArrowItem
from . import ArrowItem
import numpy as np
from pyqtgraph.Point import Point
import weakref
from GraphicsObject import GraphicsObject
from .GraphicsObject import GraphicsObject
__all__ = ['CurvePoint', 'CurveArrow']
class CurvePoint(GraphicsObject):

View File

@ -1,7 +1,7 @@
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.functions as fn
from GraphicsObject import GraphicsObject
from GraphicsWidget import GraphicsWidget
from .GraphicsObject import GraphicsObject
from .GraphicsWidget import GraphicsWidget
import weakref, collections
import numpy as np
@ -185,7 +185,7 @@ class TickSliderItem(GraphicsWidget):
def setLength(self, newLen):
#private
for t, x in self.ticks.items():
for t, x in list(self.ticks.items()):
t.setPos(x * newLen, t.pos().y())
self.length = float(newLen)
@ -325,8 +325,8 @@ class TickSliderItem(GraphicsWidget):
def listTicks(self):
"""Return a sorted list of all the Tick objects on the slider."""
## public
ticks = self.ticks.items()
ticks.sort(lambda a,b: cmp(a[1], b[1]))
ticks = list(self.ticks.items())
sortList(ticks, lambda a,b: cmp(a[1], b[1])) ## see pyqtgraph.python2_3.sortList
return ticks
@ -420,7 +420,7 @@ class GradientEditorItem(TickSliderItem):
self.menu.addAction(self.hsvAction)
for t in self.ticks.keys():
for t in list(self.ticks.keys()):
self.removeTick(t)
self.addTick(0, QtGui.QColor(0,0,0), True)
self.addTick(1, QtGui.QColor(255,0,0), True)
@ -720,7 +720,7 @@ class GradientEditorItem(TickSliderItem):
"""
## public
self.setColorMode(state['mode'])
for t in self.ticks.keys():
for t in list(self.ticks.keys()):
self.removeTick(t)
for t in state['ticks']:
c = QtGui.QColor(*t[1])

View File

@ -1,5 +1,5 @@
from pyqtgraph.Qt import QtGui, QtCore
from UIGraphicsItem import *
from .UIGraphicsItem import *
import pyqtgraph.functions as fn
__all__ = ['GradientLegend']

View File

@ -259,7 +259,7 @@ class GraphicsItem(object):
def childItems(self):
## PyQt bug -- some child items are returned incorrectly.
return map(GraphicsScene.translateGraphicsItem, QtGui.QGraphicsObject.childItems(self))
return list(map(GraphicsScene.translateGraphicsItem, QtGui.QGraphicsObject.childItems(self)))
def sceneTransform(self):

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.functions as fn
from GraphicsWidget import GraphicsWidget
from .GraphicsWidget import GraphicsWidget
__all__ = ['GraphicsLayout']
class GraphicsLayout(GraphicsWidget):
@ -127,11 +127,11 @@ class GraphicsLayout(GraphicsWidget):
def clear(self):
items = []
for i in self.items.keys():
for i in list(self.items.keys()):
self.removeItem(i)
## Must be imported at the end to avoid cyclic-dependency hell:
from ViewBox import ViewBox
from PlotItem import PlotItem
from LabelItem import LabelItem
from .ViewBox import ViewBox
from .PlotItem import PlotItem
from .LabelItem import LabelItem

View File

@ -1,5 +1,5 @@
from pyqtgraph.Qt import QtGui, QtCore
from GraphicsItem import GraphicsItem
from .GraphicsItem import GraphicsItem
__all__ = ['GraphicsObject']
class GraphicsObject(GraphicsItem, QtGui.QGraphicsObject):

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
from pyqtgraph.GraphicsScene import GraphicsScene
from GraphicsItem import GraphicsItem
from .GraphicsItem import GraphicsItem
__all__ = ['GraphicsWidget']

View File

@ -1,5 +1,5 @@
from pyqtgraph.Qt import QtGui, QtCore
from UIGraphicsItem import *
from .UIGraphicsItem import *
import numpy as np
from pyqtgraph.Point import Point

View File

@ -5,13 +5,13 @@ GraphicsWidget displaying an image histogram along with gradient editor. Can be
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.functions as fn
from GraphicsWidget import GraphicsWidget
from ViewBox import *
from GradientEditorItem import *
from LinearRegionItem import *
from PlotDataItem import *
from AxisItem import *
from GridItem import *
from .GraphicsWidget import GraphicsWidget
from .ViewBox import *
from .GradientEditorItem import *
from .LinearRegionItem import *
from .PlotDataItem import *
from .AxisItem import *
from .GridItem import *
from pyqtgraph.Point import Point
import pyqtgraph.functions as fn
import numpy as np

View File

@ -1,5 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import collections
try:
import scipy.weave as weave
from scipy.weave import converters
@ -7,7 +8,7 @@ except:
pass
import pyqtgraph.functions as fn
import pyqtgraph.debug as debug
from GraphicsObject import GraphicsObject
from .GraphicsObject import GraphicsObject
__all__ = ['ImageItem']
class ImageItem(GraphicsObject):
@ -254,7 +255,7 @@ class ImageItem(GraphicsObject):
prof = debug.Profiler('ImageItem.render', disabled=True)
if self.image is None:
return
if callable(self.lut):
if isinstance(self.lut, collections.Callable):
lut = self.lut(self.image)
else:
lut = self.lut
@ -339,9 +340,9 @@ class ImageItem(GraphicsObject):
pass
def tabletEvent(self, ev):
print ev.device()
print ev.pointerType()
print ev.pressure()
print(ev.device())
print(ev.pointerType())
print(ev.pressure())
def drawAt(self, pos, ev=None):
pos = [int(pos.x()), int(pos.y())]
@ -378,7 +379,7 @@ class ImageItem(GraphicsObject):
src = dk
#print self.image[ts].shape, src.shape
if callable(self.drawMode):
if isinstance(self.drawMode, collections.Callable):
self.drawMode(dk, self.image, mask, ss, ts, ev)
else:
src = src[ss]

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
from pyqtgraph.Point import Point
from UIGraphicsItem import UIGraphicsItem
from .UIGraphicsItem import UIGraphicsItem
import pyqtgraph.functions as fn
import numpy as np
import weakref

View File

@ -1,6 +1,6 @@
from GraphicsObject import *
from .GraphicsObject import *
import pyqtgraph.functions as fn
from pyqtgraph.Qt import QtGui, QtCore

View File

@ -1,5 +1,5 @@
from pyqtgraph.Qt import QtGui, QtCore
from GraphicsObject import GraphicsObject
from .GraphicsObject import GraphicsObject
__all__ = ['ItemGroup']
class ItemGroup(GraphicsObject):

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.functions as fn
from GraphicsWidget import GraphicsWidget
from .GraphicsWidget import GraphicsWidget
__all__ = ['LabelItem']

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
from UIGraphicsItem import UIGraphicsItem
from InfiniteLine import InfiniteLine
from .UIGraphicsItem import UIGraphicsItem
from .InfiniteLine import InfiniteLine
import pyqtgraph.functions as fn
import pyqtgraph.debug as debug

View File

@ -6,7 +6,7 @@ Distributed under MIT/X11 license. See license.txt for more infomation.
"""
from numpy import ndarray
import GraphicsLayout
from . import GraphicsLayout
try:
from metaarray import *

View File

@ -2,11 +2,11 @@ from pyqtgraph.Qt import QtGui, QtCore
from scipy.fftpack import fft
import numpy as np
import scipy.stats
from GraphicsObject import GraphicsObject
from .GraphicsObject import GraphicsObject
import pyqtgraph.functions as fn
from pyqtgraph import debug
from pyqtgraph.Point import Point
import struct
import struct, sys
__all__ = ['PlotCurveItem']
class PlotCurveItem(GraphicsObject):
@ -267,32 +267,37 @@ class PlotCurveItem(GraphicsObject):
## 0(i4)
##
## All values are big endian--pack using struct.pack('>d') or struct.pack('>i')
if sys.version_info.major == 2:
n = x.shape[0]
# create empty array, pad with extra space on either end
arr = np.empty(n+2, dtype=[('x', '>f8'), ('y', '>f8'), ('c', '>i4')])
# write first two integers
prof.mark('allocate empty')
arr.data[12:20] = struct.pack('>ii', n, 0)
prof.mark('pack header')
# Fill array with vertex values
arr[1:-1]['x'] = x
arr[1:-1]['y'] = y
arr[1:-1]['c'] = 1
prof.mark('fill array')
# write last 0
lastInd = 20*(n+1)
arr.data[lastInd:lastInd+4] = struct.pack('>i', 0)
prof.mark('footer')
# create datastream object and stream into path
buf = QtCore.QByteArray(arr.data[12:lastInd+4]) # I think one unnecessary copy happens here
prof.mark('create buffer')
ds = QtCore.QDataStream(buf)
prof.mark('create datastream')
ds >> path
prof.mark('load')
prof.finish()
else:
path.moveTo(x[0], y[0])
for i in range(1, y.shape[0]):
path.lineTo(x[i], y[i])
n = x.shape[0]
# create empty array, pad with extra space on either end
arr = np.empty(n+2, dtype=[('x', '>f8'), ('y', '>f8'), ('c', '>i4')])
# write first two integers
prof.mark('allocate empty')
arr.data[12:20] = struct.pack('>ii', n, 0)
prof.mark('pack header')
# Fill array with vertex values
arr[1:-1]['x'] = x
arr[1:-1]['y'] = y
arr[1:-1]['c'] = 1
prof.mark('fill array')
# write last 0
lastInd = 20*(n+1)
arr.data[lastInd:lastInd+4] = struct.pack('>i', 0)
prof.mark('footer')
# create datastream object and stream into path
buf = QtCore.QByteArray(arr.data[12:lastInd+4]) # I think one unnecessary copy happens here
prof.mark('create buffer')
ds = QtCore.QDataStream(buf)
prof.mark('create datastream')
ds >> path
prof.mark('load')
prof.finish()
return path

View File

@ -5,9 +5,9 @@ except:
HAVE_METAARRAY = False
from pyqtgraph.Qt import QtCore
from GraphicsObject import GraphicsObject
from PlotCurveItem import PlotCurveItem
from ScatterPlotItem import ScatterPlotItem
from .GraphicsObject import GraphicsObject
from .PlotCurveItem import PlotCurveItem
from .ScatterPlotItem import ScatterPlotItem
import numpy as np
import scipy
import pyqtgraph.functions as fn
@ -307,7 +307,7 @@ class PlotDataItem(GraphicsObject):
if 'brush' in kargs:
kargs['fillBrush'] = kargs['brush']
for k in self.opts.keys():
for k in list(self.opts.keys()):
if k in kargs:
self.opts[k] = kargs[k]

View File

@ -17,7 +17,7 @@ This class is very heavily featured:
display, power spectrum, svg/png export, plot linking, and more.
"""
#from graphicsItems import *
from plotConfigTemplate import *
from .plotConfigTemplate import *
from pyqtgraph.Qt import QtGui, QtCore, QtSvg
import pyqtgraph.functions as fn
from pyqtgraph.widgets.FileDialog import FileDialog
@ -314,7 +314,7 @@ class PlotItem(GraphicsWidget):
#self.registerPlot(name)
if labels is None:
labels = {}
for label in self.scales.keys():
for label in list(self.scales.keys()):
if label in kargs:
labels[label] = kargs[label]
del kargs[label]
@ -703,7 +703,7 @@ class PlotItem(GraphicsWidget):
"""
Enable auto-scaling. The plot will continuously scale to fit the boundaries of its data.
"""
print "Warning: enableAutoScale is deprecated. Use enableAutoRange(axis, enable) instead."
print("Warning: enableAutoScale is deprecated. Use enableAutoRange(axis, enable) instead.")
self.vb.enableAutoRange(self.vb.XYAxes)
#self.ctrl.xAutoRadio.setChecked(True)
#self.ctrl.yAutoRadio.setChecked(True)
@ -815,11 +815,11 @@ class PlotItem(GraphicsWidget):
#self.plotChanged()
def addDataItem(self, item, *args):
print "PlotItem.addDataItem is deprecated. Use addItem instead."
print("PlotItem.addDataItem is deprecated. Use addItem instead.")
self.addItem(item, *args)
def addCurve(self, c, params=None):
print "PlotItem.addCurve is deprecated. Use addItem instead."
print("PlotItem.addCurve is deprecated. Use addItem instead.")
self.addItem(c, params)
def removeItem(self, item):
@ -970,7 +970,7 @@ class PlotItem(GraphicsWidget):
#print "paramList:", self.paramList
for c in self.curves:
#print " curve:", c
for p in self.itemMeta.get(c, {}).keys():
for p in list(self.itemMeta.get(c, {}).keys()):
#print " param:", p
if type(p) is tuple:
p = '.'.join(p)
@ -1054,7 +1054,7 @@ class PlotItem(GraphicsWidget):
#fh.write('<g fill="none" stroke="#%s" stroke-opacity="1" stroke-width="1">\n' % color)
fh.write('<path fill="none" stroke="#%s" stroke-opacity="%f" stroke-width="1" d="M%f,%f ' % (color, opacity, x[0], y[0]))
for i in xrange(1, len(x)):
for i in range(1, len(x)):
fh.write('L%f,%f ' % (x[i], y[i]))
fh.write('"/>')
@ -1121,7 +1121,7 @@ class PlotItem(GraphicsWidget):
if m is not None:
#print "Matched group:", line
g = m.groups()
matrix = map(float, g[2].split(','))
matrix = list(map(float, g[2].split(',')))
#print "matrix:", matrix
scale = max(abs(matrix[0]), abs(matrix[3]))
if scale == 0 or scale == 1.0:
@ -1361,7 +1361,7 @@ class PlotItem(GraphicsWidget):
def _checkScaleKey(self, key):
if key not in self.scales:
raise Exception("Scale '%s' not found. Scales are: %s" % (key, str(self.scales.keys())))
raise Exception("Scale '%s' not found. Scales are: %s" % (key, str(list(self.scales.keys()))))
def getScale(self, key):
return self.getAxis(key)
@ -1426,7 +1426,7 @@ class PlotItem(GraphicsWidget):
self.showAxis(axis, False)
def showScale(self, *args, **kargs):
print "Deprecated. use showAxis() instead"
print("Deprecated. use showAxis() instead")
return self.showAxis(*args, **kargs)
def hideButtons(self):

View File

@ -1 +1 @@
from PlotItem import PlotItem
from .PlotItem import PlotItem

File diff suppressed because it is too large Load Diff

View File

@ -1,5 +1,5 @@
from pyqtgraph.Qt import QtGui, QtCore
from UIGraphicsItem import *
from .UIGraphicsItem import *
import numpy as np
import pyqtgraph.functions as fn

View File

@ -1,8 +1,8 @@
from pyqtgraph.Qt import QtGui, QtCore
from pyqtgraph.Point import Point
import pyqtgraph.functions as fn
from GraphicsItem import GraphicsItem
from GraphicsObject import GraphicsObject
from .GraphicsItem import GraphicsItem
from .GraphicsObject import GraphicsObject
import numpy as np
import scipy.stats
import weakref
@ -26,7 +26,7 @@ coords = {
(0.05, -0.05), (0.05, -0.5), (-0.05, -0.5), (-0.05, -0.05)
],
}
for k, c in coords.iteritems():
for k, c in coords.items():
Symbols[k].moveTo(*c[0])
for x,y in c[1:]:
Symbols[k].lineTo(x, y)
@ -190,7 +190,7 @@ class ScatterPlotItem(GraphicsObject):
if 'spots' in kargs:
spots = kargs['spots']
for i in xrange(len(spots)):
for i in range(len(spots)):
spot = spots[i]
for k in spot:
#if k == 'pen':
@ -518,7 +518,7 @@ class SpotItem(GraphicsItem):
symbol = self._plot.opts['symbol']
try:
n = int(symbol)
symbol = Symbols.keys()[n % len(Symbols)]
symbol = list(Symbols.keys())[n % len(Symbols)]
except:
pass
return symbol

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph as pg
from UIGraphicsItem import *
from .UIGraphicsItem import *
class TextItem(UIGraphicsItem):
"""

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
import weakref
from GraphicsObject import GraphicsObject
from .GraphicsObject import GraphicsObject
__all__ = ['UIGraphicsItem']
class UIGraphicsItem(GraphicsObject):

View File

@ -6,7 +6,7 @@ if __name__ == '__main__':
from pyqtgraph.Qt import QtGui, QtCore
import pyqtgraph.functions as fn
import weakref
from UIGraphicsItem import UIGraphicsItem
from .UIGraphicsItem import UIGraphicsItem
__all__ = ['VTickGroup']
class VTickGroup(UIGraphicsItem):

View File

@ -278,7 +278,7 @@ class ViewBox(GraphicsWidget):
vr1 = self.state['viewRange'][1]
return QtCore.QRectF(vr0[0], vr1[0], vr0[1]-vr0[0], vr1[1] - vr1[0])
except:
print "make qrectf failed:", self.state['viewRange']
print("make qrectf failed:", self.state['viewRange'])
raise
#def viewportTransform(self):
@ -299,7 +299,7 @@ class ViewBox(GraphicsWidget):
tr1 = self.state['targetRange'][1]
return QtCore.QRectF(tr0[0], tr1[0], tr0[1]-tr0[0], tr1[1] - tr1[0])
except:
print "make qrectf failed:", self.state['targetRange']
print("make qrectf failed:", self.state['targetRange'])
raise
def setRange(self, rect=None, xRange=None, yRange=None, padding=0.02, update=True, disableAutoRange=True):
@ -330,7 +330,7 @@ class ViewBox(GraphicsWidget):
raise Exception("Must specify at least one of rect, xRange, or yRange.")
changed = [False, False]
for ax, range in changes.iteritems():
for ax, range in changes.items():
mn = min(range)
mx = max(range)
if mn == mx: ## If we requested 0 range, try to preserve previous scale. Otherwise just pick an arbitrary scale.
@ -366,7 +366,7 @@ class ViewBox(GraphicsWidget):
if update:
self.updateMatrix(changed)
for ax, range in changes.iteritems():
for ax, range in changes.items():
link = self.state['linkedViews'][ax]
if link is not None:
link.linkedViewChanged(self, ax)
@ -1105,8 +1105,9 @@ class ViewBox(GraphicsWidget):
return wins + alpha
## make a sorted list of all named views
nv = ViewBox.NamedViews.values()
nv.sort(cmpViews)
nv = list(ViewBox.NamedViews.values())
sortList(nv, cmpViews) ## see pyqtgraph.python2_3.sortList
if self in nv:
nv.remove(self)
@ -1121,4 +1122,4 @@ class ViewBox(GraphicsWidget):
from ViewBoxMenu import ViewBoxMenu
from .ViewBoxMenu import ViewBoxMenu

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtCore, QtGui
from pyqtgraph.WidgetGroup import WidgetGroup
from axisCtrlTemplate import Ui_Form as AxisCtrlTemplate
from .axisCtrlTemplate import Ui_Form as AxisCtrlTemplate
class ViewBoxMenu(QtGui.QMenu):
def __init__(self, view):
@ -87,7 +87,7 @@ class ViewBoxMenu(QtGui.QMenu):
def setExportMethods(self, methods):
self.exportMethods = methods
self.export.clear()
for opt, fn in methods.iteritems():
for opt, fn in methods.items():
self.export.addAction(opt, self.exportMethod)
@ -224,7 +224,7 @@ class ViewBoxMenu(QtGui.QMenu):
views = [''] + views
for i in [0,1]:
c = self.ctrl[i].linkCombo
current = unicode(c.currentText())
current = asUnicode(c.currentText())
c.blockSignals(True)
changed = True
try:
@ -241,6 +241,6 @@ class ViewBoxMenu(QtGui.QMenu):
c.setCurrentIndex(0)
c.currentIndexChanged.emit(c.currentIndex())
from ViewBox import ViewBox
from .ViewBox import ViewBox

View File

@ -1 +1 @@
from ViewBox import ViewBox
from .ViewBox import ViewBox

View File

@ -5,11 +5,11 @@ Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.
"""
from Qt import QtCore, QtGui
from widgets.PlotWidget import *
from imageview import *
from widgets.GraphicsLayoutWidget import GraphicsLayoutWidget
from widgets.GraphicsView import GraphicsView
from .Qt import QtCore, QtGui
from .widgets.PlotWidget import *
from .imageview import *
from .widgets.GraphicsLayoutWidget import GraphicsLayoutWidget
from .widgets.GraphicsView import GraphicsView
QAPP = None
def mkQApp():

View File

@ -13,7 +13,7 @@ Widget used for displaying 2D or 3D data. Features:
- Image normalization through a variety of methods
"""
from ImageViewTemplate import *
from .ImageViewTemplate import *
from pyqtgraph.graphicsItems.ImageItem import *
from pyqtgraph.graphicsItems.ROI import *
from pyqtgraph.graphicsItems.LinearRegionItem import *
@ -322,7 +322,7 @@ class ImageView(QtGui.QWidget):
if self.imageDisp is None:
image = self.normalize(self.image)
self.imageDisp = image
self.levelMin, self.levelMax = map(float, ImageView.quickMinMax(self.imageDisp))
self.levelMin, self.levelMax = list(map(float, ImageView.quickMinMax(self.imageDisp)))
self.ui.histogram.setHistogramRange(self.levelMin, self.levelMax)
return self.imageDisp
@ -383,7 +383,7 @@ class ImageView(QtGui.QWidget):
def evalKeyState(self):
if len(self.keysPressed) == 1:
key = self.keysPressed.keys()[0]
key = list(self.keysPressed.keys())[0]
if key == QtCore.Qt.Key_Right:
self.play(20)
self.jumpFrames(1)
@ -526,7 +526,7 @@ class ImageView(QtGui.QWidget):
if image.ndim == 3:
self.roiCurve.setData(y=data, x=self.tVals)
else:
self.roiCurve.setData(y=data, x=range(len(data)))
self.roiCurve.setData(y=data, x=list(range(len(data))))
#self.ui.roiPlot.replot()

View File

@ -3,4 +3,4 @@ Widget used for display and analysis of 2D and 3D image data.
Includes ROI plotting over time and image normalization.
"""
from ImageView import ImageView
from .ImageView import ImageView

View File

@ -13,6 +13,7 @@ More info at http://www.scipy.org/Cookbook/MetaArray
import numpy as np
import types, copy, threading, os, re
import pickle
from functools import reduce
#import traceback
## By default, the library will use HDF5 when writing files.
@ -39,7 +40,7 @@ def axis(name=None, cols=None, values=None, units=None):
if cols is not None:
ax['cols'] = []
for c in cols:
if type(c) != types.ListType and type(c) != types.TupleType:
if type(c) != list and type(c) != tuple:
c = [c]
col = {}
for i in range(0,len(c)):
@ -111,7 +112,7 @@ class MetaArray(np.ndarray):
def __new__(subtype, data=None, file=None, info=None, dtype=None, copy=False, **kwargs):
if data is not None:
if type(data) is types.TupleType:
if type(data) is tuple:
subarr = np.empty(data, dtype=dtype)
else:
subarr = np.array(data, dtype=dtype, copy=copy)
@ -134,14 +135,14 @@ class MetaArray(np.ndarray):
info[i] = {}
else:
raise Exception("Axis specification must be Dict or None")
if i < subarr.ndim and info[i].has_key('values'):
if type(info[i]['values']) is types.ListType:
if i < subarr.ndim and 'values' in info[i]:
if type(info[i]['values']) is list:
info[i]['values'] = np.array(info[i]['values'])
elif type(info[i]['values']) is not np.ndarray:
raise Exception("Axis values must be specified as list or ndarray")
if info[i]['values'].ndim != 1 or info[i]['values'].shape[0] != subarr.shape[i]:
raise Exception("Values array for axis %d has incorrect shape. (given %s, but should be %s)" % (i, str(info[i]['values'].shape), str((subarr.shape[i],))))
if i < subarr.ndim and info[i].has_key('cols'):
if i < subarr.ndim and 'cols' in info[i]:
if not isinstance(info[i]['cols'], list):
info[i]['cols'] = list(info[i]['cols'])
if len(info[i]['cols']) != subarr.shape[i]:
@ -272,7 +273,7 @@ class MetaArray(np.ndarray):
try:
return np.ndarray.__setitem__(self.view(np.ndarray), nInd, val)
except:
print self, nInd, val
print(self, nInd, val)
raise
#def __getattr__(self, attr):
@ -283,7 +284,7 @@ class MetaArray(np.ndarray):
def axisValues(self, axis):
"""Return the list of values for an axis"""
ax = self._interpretAxis(axis)
if self._info[ax].has_key('values'):
if 'values' in self._info[ax]:
return self._info[ax]['values']
else:
raise Exception('Array axis %s (%d) has no associated values.' % (str(axis), ax))
@ -294,21 +295,21 @@ class MetaArray(np.ndarray):
def axisHasValues(self, axis):
ax = self._interpretAxis(axis)
return self._info[ax].has_key('values')
return 'values' in self._info[ax]
def axisHasColumns(self, axis):
ax = self._interpretAxis(axis)
return self._info[ax].has_key('cols')
return 'cols' in self._info[ax]
def axisUnits(self, axis):
"""Return the units for axis"""
ax = self._info[self._interpretAxis(axis)]
if ax.has_key('units'):
if 'units' in ax:
return ax['units']
def hasColumn(self, axis, col):
ax = self._info[self._interpretAxis(axis)]
if ax.has_key('cols'):
if 'cols' in ax:
for c in ax['cols']:
if c['name'] == col:
return True
@ -339,7 +340,7 @@ class MetaArray(np.ndarray):
def columnUnits(self, axis, column):
"""Return the units for column in axis"""
ax = self._info[self._interpretAxis(axis)]
if ax.has_key('cols'):
if 'cols' in ax:
for c in ax['cols']:
if c['name'] == column:
return c['units']
@ -353,10 +354,10 @@ class MetaArray(np.ndarray):
keyList = self[key]
order = keyList.argsort()
if type(axis) == types.IntType:
if type(axis) == int:
ind = [slice(None)]*axis
ind.append(order)
elif type(axis) == types.StringType:
elif isinstance(axis, basestring):
ind = (slice(axis, order),)
return self[tuple(ind)]
@ -422,7 +423,7 @@ class MetaArray(np.ndarray):
return tuple(nInd)
def _interpretAxis(self, axis):
if type(axis) in [types.StringType, types.TupleType]:
if isinstance(axis, basestring) or isinstance(axis, tuple):
return self._getAxis(axis)
else:
return axis
@ -510,15 +511,15 @@ class MetaArray(np.ndarray):
def _getAxis(self, name):
for i in range(0, len(self._info)):
axis = self._info[i]
if axis.has_key('name') and axis['name'] == name:
if 'name' in axis and axis['name'] == name:
return i
raise Exception("No axis named %s.\n info=%s" % (name, self._info))
def _getIndex(self, axis, name):
ax = self._info[axis]
if ax is not None and ax.has_key('cols'):
if ax is not None and 'cols' in ax:
for i in range(0, len(ax['cols'])):
if ax['cols'][i].has_key('name') and ax['cols'][i]['name'] == name:
if 'name' in ax['cols'][i] and ax['cols'][i]['name'] == name:
return i
raise Exception("Axis %d has no column named %s.\n info=%s" % (axis, name, self._info))
@ -527,16 +528,16 @@ class MetaArray(np.ndarray):
def _axisSlice(self, i, cols):
#print "axisSlice", i, cols
if self._info[i].has_key('cols') or self._info[i].has_key('values'):
if 'cols' in self._info[i] or 'values' in self._info[i]:
ax = self._axisCopy(i)
if ax.has_key('cols'):
if 'cols' in ax:
#print " slicing columns..", array(ax['cols']), cols
sl = np.array(ax['cols'])[cols]
if isinstance(sl, np.ndarray):
sl = list(sl)
ax['cols'] = sl
#print " result:", ax['cols']
if ax.has_key('values'):
if 'values' in ax:
ax['values'] = np.array(ax['values'])[cols]
else:
ax = self._info[i]
@ -617,14 +618,14 @@ class MetaArray(np.ndarray):
order = args
order = [self._interpretAxis(ax) for ax in order]
infoOrder = order + range(len(order), len(self._info))
infoOrder = order + list(range(len(order), len(self._info)))
info = [self._info[i] for i in infoOrder]
order = order + range(len(order), self.ndim)
order = order + list(range(len(order), self.ndim))
try:
return MetaArray(self.view(np.ndarray).transpose(order), info=info)
except:
print order
print(order)
raise
#### File I/O Routines
@ -652,7 +653,7 @@ class MetaArray(np.ndarray):
## read in axis values for any axis that specifies a length
frameSize = 1
for ax in meta['info']:
if ax.has_key('values_len'):
if 'values_len' in ax:
ax['values'] = np.fromstring(fd.read(ax['values_len']), dtype=ax['values_type'])
frameSize *= ax['values_len']
del ax['values_len']
@ -675,7 +676,7 @@ class MetaArray(np.ndarray):
## read in axis values for any axis that specifies a length
for i in range(len(meta['info'])):
ax = meta['info'][i]
if ax.has_key('values_len'):
if 'values_len' in ax:
if ax['values_len'] == 'dynamic':
if dynAxis is not None:
raise Exception("MetaArray has more than one dynamic axis! (this is not allowed)")
@ -779,7 +780,7 @@ class MetaArray(np.ndarray):
f = h5py.File(fileName, 'r')
ver = f.attrs['MetaArray']
if ver > MetaArray.version:
print "Warning: This file was written with MetaArray version %s, but you are using version %s. (Will attempt to read anyway)" % (str(ver), str(MetaArray.version))
print("Warning: This file was written with MetaArray version %s, but you are using version %s. (Will attempt to read anyway)" % (str(ver), str(MetaArray.version)))
meta = MetaArray.readHDF5Meta(f['info'])
if mmap:
@ -974,12 +975,12 @@ class MetaArray(np.ndarray):
else:
gr.attrs['_metaType_'] = 'tuple'
#n = int(np.log10(len(data))) + 1
for i in xrange(len(data)):
for i in range(len(data)):
self.writeHDF5Meta(gr, str(i), data[i], **dsOpts)
elif isinstance(data, dict):
gr = root.create_group(name)
gr.attrs['_metaType_'] = 'dict'
for k, v in data.iteritems():
for k, v in data.items():
self.writeHDF5Meta(gr, k, v, **dsOpts)
elif isinstance(data, int) or isinstance(data, float) or isinstance(data, np.integer) or isinstance(data, np.floating):
root.attrs[name] = data
@ -987,7 +988,7 @@ class MetaArray(np.ndarray):
try: ## strings, bools, None are stored as repr() strings
root.attrs[name] = repr(data)
except:
print "Can not store meta data of type '%s' in HDF5. (key is '%s')" % (str(type(data)), str(name))
print("Can not store meta data of type '%s' in HDF5. (key is '%s')" % (str(type(data)), str(name)))
raise
@ -1053,7 +1054,7 @@ class MetaArray(np.ndarray):
if fileName is not None:
file = open(fileName, 'w')
ret = ''
if self._info[0].has_key('cols'):
if 'cols' in self._info[0]:
s = ','.join([x['name'] for x in self._info[0]['cols']]) + '\n'
if fileName is not None:
file.write(s)
@ -1177,91 +1178,91 @@ if __name__ == '__main__':
ma = MetaArray(arr, info=info)
print "==== Original Array ======="
print ma
print "\n\n"
print("==== Original Array =======")
print(ma)
print("\n\n")
#### Tests follow:
#### Index/slice tests: check that all values and meta info are correct after slice
print "\n -- normal integer indexing\n"
print("\n -- normal integer indexing\n")
print "\n ma[1]"
print ma[1]
print("\n ma[1]")
print(ma[1])
print "\n ma[1, 2:4]"
print ma[1, 2:4]
print("\n ma[1, 2:4]")
print(ma[1, 2:4])
print "\n ma[1, 1:5:2]"
print ma[1, 1:5:2]
print("\n ma[1, 1:5:2]")
print(ma[1, 1:5:2])
print "\n -- named axis indexing\n"
print("\n -- named axis indexing\n")
print "\n ma['Axis2':3]"
print ma['Axis2':3]
print("\n ma['Axis2':3]")
print(ma['Axis2':3])
print "\n ma['Axis2':3:5]"
print ma['Axis2':3:5]
print("\n ma['Axis2':3:5]")
print(ma['Axis2':3:5])
print "\n ma[1, 'Axis2':3]"
print ma[1, 'Axis2':3]
print("\n ma[1, 'Axis2':3]")
print(ma[1, 'Axis2':3])
print "\n ma[:, 'Axis2':3]"
print ma[:, 'Axis2':3]
print("\n ma[:, 'Axis2':3]")
print(ma[:, 'Axis2':3])
print "\n ma['Axis2':3, 'Axis4':0:2]"
print ma['Axis2':3, 'Axis4':0:2]
print("\n ma['Axis2':3, 'Axis4':0:2]")
print(ma['Axis2':3, 'Axis4':0:2])
print "\n -- column name indexing\n"
print("\n -- column name indexing\n")
print "\n ma['Axis3':'Ax3Col1']"
print ma['Axis3':'Ax3Col1']
print("\n ma['Axis3':'Ax3Col1']")
print(ma['Axis3':'Ax3Col1'])
print "\n ma['Axis3':('Ax3','Col3')]"
print ma['Axis3':('Ax3','Col3')]
print("\n ma['Axis3':('Ax3','Col3')]")
print(ma['Axis3':('Ax3','Col3')])
print "\n ma[:, :, 'Ax3Col2']"
print ma[:, :, 'Ax3Col2']
print("\n ma[:, :, 'Ax3Col2']")
print(ma[:, :, 'Ax3Col2'])
print "\n ma[:, :, ('Ax3','Col3')]"
print ma[:, :, ('Ax3','Col3')]
print("\n ma[:, :, ('Ax3','Col3')]")
print(ma[:, :, ('Ax3','Col3')])
print "\n -- axis value range indexing\n"
print("\n -- axis value range indexing\n")
print "\n ma['Axis2':1.5:4.5]"
print ma['Axis2':1.5:4.5]
print("\n ma['Axis2':1.5:4.5]")
print(ma['Axis2':1.5:4.5])
print "\n ma['Axis4':1.15:1.45]"
print ma['Axis4':1.15:1.45]
print("\n ma['Axis4':1.15:1.45]")
print(ma['Axis4':1.15:1.45])
print "\n ma['Axis4':1.15:1.25]"
print ma['Axis4':1.15:1.25]
print("\n ma['Axis4':1.15:1.25]")
print(ma['Axis4':1.15:1.25])
print "\n -- list indexing\n"
print("\n -- list indexing\n")
print "\n ma[:, [0,2,4]]"
print ma[:, [0,2,4]]
print("\n ma[:, [0,2,4]]")
print(ma[:, [0,2,4]])
print "\n ma['Axis4':[0,2,4]]"
print ma['Axis4':[0,2,4]]
print("\n ma['Axis4':[0,2,4]]")
print(ma['Axis4':[0,2,4]])
print "\n ma['Axis3':[0, ('Ax3','Col3')]]"
print ma['Axis3':[0, ('Ax3','Col3')]]
print("\n ma['Axis3':[0, ('Ax3','Col3')]]")
print(ma['Axis3':[0, ('Ax3','Col3')]])
print "\n -- boolean indexing\n"
print("\n -- boolean indexing\n")
print "\n ma[:, array([True, True, False, True, False])]"
print ma[:, np.array([True, True, False, True, False])]
print("\n ma[:, array([True, True, False, True, False])]")
print(ma[:, np.array([True, True, False, True, False])])
print "\n ma['Axis4':array([True, False, False, False])]"
print ma['Axis4':np.array([True, False, False, False])]
print("\n ma['Axis4':array([True, False, False, False])]")
print(ma['Axis4':np.array([True, False, False, False])])
@ -1278,18 +1279,18 @@ if __name__ == '__main__':
#### File I/O tests
print "\n================ File I/O Tests ===================\n"
print("\n================ File I/O Tests ===================\n")
import tempfile
tf = tempfile.mktemp()
tf = 'test.ma'
# write whole array
print "\n -- write/read test"
print("\n -- write/read test")
ma.write(tf)
ma2 = MetaArray(file=tf)
#print ma2
print "\nArrays are equivalent:", (ma == ma2).all()
print("\nArrays are equivalent:", (ma == ma2).all())
#print "Meta info is equivalent:", ma.infoCopy() == ma2.infoCopy()
os.remove(tf)
@ -1298,7 +1299,7 @@ if __name__ == '__main__':
# append mode
print "\n================append test (%s)===============" % tf
print("\n================append test (%s)===============" % tf)
ma['Axis2':0:2].write(tf, appendAxis='Axis2')
for i in range(2,ma.shape[1]):
ma['Axis2':[i]].write(tf, appendAxis='Axis2')
@ -1306,7 +1307,7 @@ if __name__ == '__main__':
ma2 = MetaArray(file=tf)
#print ma2
print "\nArrays are equivalent:", (ma == ma2).all()
print("\nArrays are equivalent:", (ma == ma2).all())
#print "Meta info is equivalent:", ma.infoCopy() == ma2.infoCopy()
os.remove(tf)
@ -1314,9 +1315,9 @@ if __name__ == '__main__':
## memmap test
print "\n==========Memmap test============"
print("\n==========Memmap test============")
ma.write(tf, mappable=True)
ma2 = MetaArray(file=tf, mmap=True)
print "\nArrays are equivalent:", (ma == ma2).all()
print("\nArrays are equivalent:", (ma == ma2).all())
os.remove(tf)

View File

@ -1 +1 @@
from MetaArray import *
from .MetaArray import *

View File

@ -102,7 +102,7 @@ class GLViewWidget(QtOpenGL.QGLWidget):
except:
import sys
sys.excepthook(*sys.exc_info())
print "Error while drawing item", i
print("Error while drawing item", i)
finally:
glPopAttrib(GL_ALL_ATTRIB_BITS)
else:

View File

@ -133,7 +133,7 @@ class MeshData(object):
faceNorms = self.faceNormals()
vertFaces = self.vertexFaces()
self._vertexNormals = []
for vindex in xrange(len(self._vertexes)):
for vindex in range(len(self._vertexes)):
#print vertFaces[vindex]
norms = [faceNorms[findex] for findex in vertFaces[vindex]]
norm = QtGui.QVector3D()

View File

@ -1,11 +1,11 @@
from GLViewWidget import GLViewWidget
from .GLViewWidget import GLViewWidget
import os
def importAll(path):
d = os.path.join(os.path.split(__file__)[0], path)
files = []
for f in os.listdir(d):
if os.path.isdir(os.path.join(d, f)):
if os.path.isdir(os.path.join(d, f)) and f != '__pycache__':
files.append(f)
elif f[-3:] == '.py' and f != '__init__.py':
files.append(f[:-3])

View File

@ -105,7 +105,7 @@ class GLVolumeItem(GLGraphicsItem):
vp[3][imax[0]] = 0
vp[3][imax[1]] = self.data.shape[imax[1]]
slices = self.data.shape[ax] * self.sliceDensity
r = range(slices)
r = list(range(slices))
if d == -1:
r = r[::-1]

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui, QtCore
import collections, os, weakref, re
from ParameterItem import ParameterItem
from .ParameterItem import ParameterItem
PARAM_TYPES = {}

View File

@ -76,9 +76,9 @@ class ParameterTree(TreeWidget):
index = root.indexOfChild(startItem) - 1
if forward:
inds = range(index, root.childCount())
inds = list(range(index, root.childCount()))
else:
inds = range(index, -1, -1)
inds = list(range(index, -1, -1))
for i in inds:
item = root.child(i)

View File

@ -1,5 +1,5 @@
from Parameter import Parameter, registerParameterType
from ParameterTree import ParameterTree
from ParameterItem import ParameterItem
from .Parameter import Parameter, registerParameterType
from .ParameterTree import ParameterTree
from .ParameterItem import ParameterItem
import parameterTypes as types
from . import parameterTypes as types

View File

@ -111,9 +111,9 @@ params = [
#p = pTypes.ParameterSet("params", params)
p = Parameter(name='params', type='group', children=params)
def change(param, changes):
print "tree changes:"
print("tree changes:")
for param, change, data in changes:
print " [" + '.'.join(p.childPath(param))+ "] ", change, data
print(" [" + '.'.join(p.childPath(param))+ "] ", change, data)
p.sigTreeStateChanged.connect(change)

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtCore, QtGui
from Parameter import Parameter, registerParameterType
from ParameterItem import ParameterItem
from .Parameter import Parameter, registerParameterType
from .ParameterItem import ParameterItem
from pyqtgraph.widgets.SpinBox import SpinBox
from pyqtgraph.widgets.ColorButton import ColorButton
import pyqtgraph as pg
@ -105,8 +105,8 @@ class WidgetParameterItem(ParameterItem):
elif t == 'str':
w = QtGui.QLineEdit()
w.sigChanged = w.editingFinished
w.value = lambda: unicode(w.text())
w.setValue = lambda v: w.setText(unicode(v))
w.value = lambda: asUnicode(w.text())
w.setValue = lambda v: w.setText(asUnicode(v))
w.sigChanging = w.textChanged
elif t == 'color':
w = ColorButton()
@ -117,7 +117,7 @@ class WidgetParameterItem(ParameterItem):
self.hideWidget = False
w.setFlat(True)
else:
raise Exception("Unknown type '%s'" % unicode(t))
raise Exception("Unknown type '%s'" % asUnicode(t))
return w
def widgetEventFilter(self, obj, ev):
@ -165,11 +165,11 @@ class WidgetParameterItem(ParameterItem):
value = self.param.value()
opts = self.param.opts
if isinstance(self.widget, QtGui.QAbstractSpinBox):
text = unicode(self.widget.lineEdit().text())
text = asUnicode(self.widget.lineEdit().text())
elif isinstance(self.widget, QtGui.QComboBox):
text = self.widget.currentText()
else:
text = unicode(value)
text = asUnicode(value)
self.displayLabel.setText(text)
def widgetValueChanged(self):
@ -342,7 +342,7 @@ class GroupParameterItem(ParameterItem):
"""
if self.addWidget.currentIndex() == 0:
return
typ = unicode(self.addWidget.currentText())
typ = asUnicode(self.addWidget.currentText())
self.param.addNew(typ)
self.addWidget.setCurrentIndex(0)
@ -400,7 +400,7 @@ class ListParameterItem(WidgetParameterItem):
def value(self):
#vals = self.param.opts['limits']
key = unicode(self.widget.currentText())
key = asUnicode(self.widget.currentText())
#if isinstance(vals, dict):
#return vals[key]
#else:
@ -431,18 +431,18 @@ class ListParameterItem(WidgetParameterItem):
self.forward = collections.OrderedDict() ## name: value
self.reverse = collections.OrderedDict() ## value: name
if isinstance(limits, dict):
for k, v in limits.iteritems():
for k, v in limits.items():
self.forward[k] = v
self.reverse[v] = k
else:
for v in limits:
n = unicode(v)
n = asUnicode(v)
self.forward[n] = v
self.reverse[v] = n
try:
self.widget.blockSignals(True)
val = unicode(self.widget.currentText())
val = asUnicode(self.widget.currentText())
self.widget.clear()
for k in self.forward:
self.widget.addItem(k)
@ -469,19 +469,19 @@ class ListParameter(Parameter):
self.forward = collections.OrderedDict() ## name: value
self.reverse = collections.OrderedDict() ## value: name
if isinstance(limits, dict):
for k, v in limits.iteritems():
for k, v in limits.items():
self.forward[k] = v
self.reverse[v] = k
else:
for v in limits:
n = unicode(v)
n = asUnicode(v)
self.forward[n] = v
self.reverse[v] = n
Parameter.setLimits(self, limits)
#print self.name(), self.value(), limits
if self.value() not in self.reverse and len(self.reverse) > 0:
self.setValue(self.reverse.keys()[0])
self.setValue(list(self.reverse.keys())[0])
registerParameterType('list', ListParameter, override=True)

View File

@ -13,4 +13,4 @@ for path, sd, files in os.walk('.'):
ui = os.path.join(path, f)
py = os.path.join(path, base + '.py')
os.system('%s %s > %s' % (uic, ui, py))
print py
print(py)

View File

@ -22,15 +22,19 @@ Does NOT:
"""
import inspect, os, sys, __builtin__, gc, traceback
from debug import printExc
import inspect, os, sys, gc, traceback
try:
import __builtin__ as builtins
except ImportError:
import builtins
from .debug import printExc
def reloadAll(prefix=None, debug=False):
"""Automatically reload everything whose __file__ begins with prefix.
- Skips reload if the file has not been updated (if .pyc is newer than .py)
- if prefix is None, checks all loaded modules
"""
for modName, mod in sys.modules.items(): ## don't use iteritems; size may change during reload
for modName, mod in list(sys.modules.items()): ## don't use iteritems; size may change during reload
if not inspect.ismodule(mod):
continue
if modName == '__main__':
@ -65,11 +69,11 @@ def reload(module, debug=False, lists=False, dicts=False):
- Requires that class and function names have not changed
"""
if debug:
print "Reloading", module
print("Reloading", module)
## make a copy of the old module dictionary, reload, then grab the new module dictionary for comparison
oldDict = module.__dict__.copy()
__builtin__.reload(module)
builtins.reload(module)
newDict = module.__dict__
## Allow modules access to the old dictionary after they reload
@ -85,7 +89,7 @@ def reload(module, debug=False, lists=False, dicts=False):
if inspect.isclass(old):
if debug:
print " Updating class %s.%s (0x%x -> 0x%x)" % (module.__name__, k, id(old), id(new))
print(" Updating class %s.%s (0x%x -> 0x%x)" % (module.__name__, k, id(old), id(new)))
updateClass(old, new, debug)
elif inspect.isfunction(old):
@ -94,7 +98,7 @@ def reload(module, debug=False, lists=False, dicts=False):
extra = ""
if depth > 0:
extra = " (and %d previous versions)" % depth
print " Updating function %s.%s%s" % (module.__name__, k, extra)
print(" Updating function %s.%s%s" % (module.__name__, k, extra))
elif lists and isinstance(old, list):
l = old.len()
old.extend(new)
@ -150,7 +154,7 @@ def updateClass(old, new, debug):
if isinstance(ref, old) and ref.__class__ is old:
ref.__class__ = new
if debug:
print " Changed class for", safeStr(ref)
print(" Changed class for", safeStr(ref))
elif inspect.isclass(ref) and issubclass(ref, old) and old in ref.__bases__:
ind = ref.__bases__.index(old)
@ -166,12 +170,12 @@ def updateClass(old, new, debug):
## (and I presume this may slow things down?)
ref.__bases__ = ref.__bases__[:ind] + (new,old) + ref.__bases__[ind+1:]
if debug:
print " Changed superclass for", safeStr(ref)
print(" Changed superclass for", safeStr(ref))
#else:
#if debug:
#print " Ignoring reference", type(ref)
except:
print "Error updating reference (%s) for class change (%s -> %s)" % (safeStr(ref), safeStr(old), safeStr(new))
print("Error updating reference (%s) for class change (%s -> %s)" % (safeStr(ref), safeStr(old), safeStr(new)))
raise
## update all class methods to use new code.
@ -184,23 +188,23 @@ def updateClass(old, new, debug):
na = getattr(new, attr)
except AttributeError:
if debug:
print " Skipping method update for %s; new class does not have this attribute" % attr
print(" Skipping method update for %s; new class does not have this attribute" % attr)
continue
if hasattr(oa, 'im_func') and hasattr(na, 'im_func') and oa.im_func is not na.im_func:
depth = updateFunction(oa.im_func, na.im_func, debug)
if hasattr(oa, 'im_func') and hasattr(na, 'im_func') and oa.__func__ is not na.__func__:
depth = updateFunction(oa.__func__, na.__func__, debug)
#oa.im_class = new ## bind old method to new class ## not allowed
if debug:
extra = ""
if depth > 0:
extra = " (and %d previous versions)" % depth
print " Updating method %s%s" % (attr, extra)
print(" Updating method %s%s" % (attr, extra))
## And copy in new functions that didn't exist previously
for attr in dir(new):
if not hasattr(old, attr):
if debug:
print " Adding missing attribute", attr
print(" Adding missing attribute", attr)
setattr(old, attr, getattr(new, attr))
## finally, update any previous versions still hanging around..
@ -240,7 +244,7 @@ if __name__ == '__main__':
btn = Btn()
except:
raise
print "Error; skipping Qt tests"
print("Error; skipping Qt tests")
doQtTest = False
@ -291,7 +295,7 @@ def fn():
open(modFile2, 'w').write(modCode2%"message 1")
import test1.test1 as test1
import test2
print "Test 1 originals:"
print("Test 1 originals:")
A1 = test1.A
B1 = test1.B
a1 = test1.A("a1")
@ -304,17 +308,17 @@ def fn():
from test2 import fn, C
if doQtTest:
print "Button test before:"
print("Button test before:")
btn.sig.connect(fn)
btn.sig.connect(a1.fn)
btn.emit()
#btn.sig.emit()
print ""
print("")
#print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func)
print "Test2 before reload:"
print("Test2 before reload:")
fn()
oldfn = fn
@ -325,39 +329,39 @@ def fn():
os.remove(modFile1+'c')
open(modFile1, 'w').write(modCode1%(2,2))
print "\n----RELOAD test1-----\n"
print("\n----RELOAD test1-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True)
print "Subclass test:"
print("Subclass test:")
c2 = test2.C('c2')
c2.fn()
os.remove(modFile2+'c')
open(modFile2, 'w').write(modCode2%"message 2")
print "\n----RELOAD test2-----\n"
print("\n----RELOAD test2-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True)
if doQtTest:
print "Button test after:"
print("Button test after:")
btn.emit()
#btn.sig.emit()
#print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func)
print "Test2 after reload:"
print("Test2 after reload:")
fn()
test2.a1.fn()
test2.b1.fn()
print "\n==> Test 1 Old instances:"
print("\n==> Test 1 Old instances:")
a1.fn()
b1.fn()
c1.fn()
#print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class))
print "\n==> Test 1 New instances:"
print("\n==> Test 1 New instances:")
a2 = test1.A("a2")
b2 = test1.B("b2")
a2.fn()
@ -374,32 +378,32 @@ def fn():
open(modFile1, 'w').write(modCode1%(3,3))
open(modFile2, 'w').write(modCode2%"message 3")
print "\n----RELOAD-----\n"
print("\n----RELOAD-----\n")
reloadAll(os.path.abspath(__file__)[:10], debug=True)
if doQtTest:
print "Button test after:"
print("Button test after:")
btn.emit()
#btn.sig.emit()
#print "a1.fn referrers:", sys.getrefcount(a1.fn.im_func), gc.get_referrers(a1.fn.im_func)
print "Test2 after reload:"
print("Test2 after reload:")
fn()
test2.a1.fn()
test2.b1.fn()
print "\n==> Test 1 Old instances:"
print("\n==> Test 1 Old instances:")
a1.fn()
b1.fn()
print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class))
print("function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.__func__), id(a1.fn.__self__.__class__), id(b1.fn.__func__), id(b1.fn.__self__.__class__)))
print "\n==> Test 1 New instances:"
print("\n==> Test 1 New instances:")
a2 = test1.A("a2")
b2 = test1.B("b2")
a2.fn()
b2.fn()
print "function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.im_func), id(a1.fn.im_class), id(b1.fn.im_func), id(b1.fn.im_class))
print("function IDs a1 bound method: %d a1 func: %d a1 class: %d b1 func: %d b1 class: %d" % (id(a1.fn), id(a1.fn.__func__), id(a1.fn.__self__.__class__), id(b1.fn.__func__), id(b1.fn.__self__.__class__)))
os.remove(modFile1)

View File

@ -1,6 +1,6 @@
# -*- coding: utf-8 -*-
from pyqtgraph.Qt import QtGui, QtCore
import VerticalLabel
from . import VerticalLabel
__all__ = ['CheckTable']

View File

@ -91,9 +91,9 @@ if __name__ == '__main__':
win.show()
def change(btn):
print "change", btn.color()
print("change", btn.color())
def done(btn):
print "done", btn.color()
print("done", btn.color())
btn.sigColorChanging.connect(change)
btn.sigColorChanged.connect(done)

View File

@ -49,7 +49,7 @@ class DataTreeWidget(QtGui.QTreeWidget):
parent.addChild(node)
if isinstance(data, types.TracebackType): ## convert traceback to a list of strings
data = map(str.strip, traceback.format_list(traceback.extract_tb(data)))
data = list(map(str.strip, traceback.format_list(traceback.extract_tb(data))))
elif HAVE_METAARRAY and isinstance(data, metaarray.MetaArray):
data = {
'data': data.view(np.ndarray),

View File

@ -1,12 +1,6 @@
# -*- coding: utf-8 -*-
if __name__ == '__main__':
import os, sys
path = os.path.join(os.path.dirname(__file__), '..', '..')
sys.path = [path] + sys.path
from pyqtgraph.Qt import QtGui, QtCore
from GraphicsView import GraphicsView
from .GraphicsView import GraphicsView
from pyqtgraph.graphicsItems.GradientEditorItem import GradientEditorItem
import weakref
import numpy as np
@ -581,41 +575,3 @@ class GradientWidget(GraphicsView):
if __name__ == '__main__':
app = QtGui.QApplication([])
w = QtGui.QMainWindow()
w.show()
w.resize(400,400)
cw = QtGui.QWidget()
w.setCentralWidget(cw)
l = QtGui.QGridLayout()
l.setSpacing(0)
cw.setLayout(l)
w1 = GradientWidget(orientation='top')
w2 = GradientWidget(orientation='right', allowAdd=False)
#w2.setTickColor(1, QtGui.QColor(255,255,255))
w3 = GradientWidget(orientation='bottom')
w4 = GradientWidget(orientation='left')
label = QtGui.QLabel("""
- Click a triangle to change its color
- Drag triangles to move
- Click in an empty area to add a new color
(adding is disabled for the right-side widget)
- Right click a triangle to remove
""")
l.addWidget(w1, 0, 1)
l.addWidget(w2, 1, 2)
l.addWidget(w3, 2, 1)
l.addWidget(w4, 1, 0)
l.addWidget(label, 1, 1)
## Start Qt event loop unless running in interactive mode.
import sys
if sys.flags.interactive != 1:
app.exec_()

View File

@ -1,6 +1,6 @@
from pyqtgraph.Qt import QtGui
from pyqtgraph.graphicsItems.GraphicsLayout import GraphicsLayout
from GraphicsView import GraphicsView
from .GraphicsView import GraphicsView
__all__ = ['GraphicsLayoutWidget']
class GraphicsLayoutWidget(GraphicsView):

Some files were not shown because too many files have changed in this diff Show More