-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathutils.py
222 lines (191 loc) · 6.34 KB
/
utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import os
import sys
import numpy as np
PY2 = sys.version[0] == '2'
from qtpy import PYQT5
from qtpy.QtCore import QVariant
from qtpy.QtGui import QIcon, QColor, QFont, QKeySequence
from qtpy.QtWidgets import QAction, QDialog, QVBoxLayout
if PYQT5:
from matplotlib.backends.backend_qt5agg import FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
else:
from matplotlib.backends.backend_qt4agg import FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
# Note: string and unicode data types will be formatted with '%s' (see below)
SUPPORTED_FORMATS = {
'object': '%s',
'single': '%.2f',
'double': '%.2f',
'float_': '%.2f',
'longfloat': '%.2f',
'float32': '%.2f',
'float64': '%.2f',
'float96': '%.2f',
'float128': '%.2f',
'csingle': '%r',
'complex_': '%r',
'clongfloat': '%r',
'complex64': '%r',
'complex128': '%r',
'complex192': '%r',
'complex256': '%r',
'byte': '%d',
'short': '%d',
'intc': '%d',
'int_': '%d',
'longlong': '%d',
'intp': '%d',
'int8': '%d',
'int16': '%d',
'int32': '%d',
'int64': '%d',
'ubyte': '%d',
'ushort': '%d',
'uintc': '%d',
'uint': '%d',
'ulonglong': '%d',
'uintp': '%d',
'uint8': '%d',
'uint16': '%d',
'uint32': '%d',
'uint64': '%d',
'bool_': '%r',
'bool8': '%r',
'bool': '%r',
}
def _get_font(family, size, bold=False, italic=False):
weight = QFont.Bold if bold else QFont.Normal
font = QFont(family, size, weight)
if italic:
font.setItalic(True)
return to_qvariant(font)
def is_float(dtype):
"""Return True if datatype dtype is a float kind"""
return ('float' in dtype.name) or dtype.name in ['single', 'double']
def is_number(dtype):
"""Return True is datatype dtype is a number kind"""
return is_float(dtype) or ('int' in dtype.name) or ('long' in dtype.name) or ('short' in dtype.name)
def get_font(section):
return _get_font('Calibri', 11)
def to_qvariant(obj=None):
return obj
def from_qvariant(qobj=None, pytype=None):
# FIXME: force API level 2 instead of handling this
if isinstance(qobj, QVariant):
assert pytype is str
return pytype(qobj.toString())
return qobj
def _(text):
return text
def to_text_string(obj, encoding=None):
"""Convert `obj` to (unicode) text string"""
if PY2:
# Python 2
if encoding is None:
return unicode(obj)
else:
return unicode(obj, encoding)
else:
# Python 3
if encoding is None:
return str(obj)
elif isinstance(obj, str):
# In case this function is not used properly, this could happen
return obj
else:
return str(obj, encoding)
def keybinding(attr):
"""Return keybinding"""
ks = getattr(QKeySequence, attr)
return QKeySequence.keyBindings(ks)[0]
def create_action(parent, text, icon=None, triggered=None, shortcut=None, statustip=None):
"""Create a QAction"""
action = QAction(text, parent)
if triggered is not None:
action.triggered.connect(triggered)
if icon is not None:
action.setIcon(icon)
if shortcut is not None:
action.setShortcut(shortcut)
if statustip is not None:
action.setStatusTip(statustip)
# action.setShortcutContext(Qt.WidgetShortcut)
return action
def clear_layout(layout):
for i in reversed(range(layout.count())):
item = layout.itemAt(i)
widget = item.widget()
if widget is not None:
# widget.setParent(None)
widget.deleteLater()
layout.removeItem(item)
def get_idx_rect(index_list):
"""Extract the boundaries from a list of indexes"""
rows = [i.row() for i in index_list]
cols = [i.column() for i in index_list]
return min(rows), max(rows), min(cols), max(cols)
class IconManager(object):
_icons = {'larray': 'larray.ico'}
_icon_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'images')
def icon(self, ref):
if ref in self._icons:
icon_path = os.path.join(self._icon_dir, self._icons[ref])
return QIcon(icon_path)
else:
# By default, only X11 will support themed icons. In order to use
# themed icons on Mac and Windows, you will have to bundle a compliant
# theme in one of your PySide.QtGui.QIcon.themeSearchPaths() and set the
# appropriate PySide.QtGui.QIcon.themeName() .
return QIcon.fromTheme(ref)
ima = IconManager()
class LinearGradient(object):
"""
I cannot believe I had to roll my own class for this when PyQt already
contains QLinearGradient... but you cannot get intermediate values out of
QLinearGradient!
"""
def __init__(self, stop_points=None):
if stop_points is None:
stop_points = []
# sort by position
stop_points = sorted(stop_points, key=lambda x: x[0])
positions, colors = zip(*stop_points)
self.positions = np.array(positions)
assert len(np.unique(self.positions)) == len(self.positions)
self.colors = np.array(colors)
def __getitem__(self, key):
"""
Parameters
----------
key : float
Returns
-------
QColor
"""
if key != key:
key = self.positions[0]
pos_idx = np.searchsorted(self.positions, key, side='right') - 1
# if we are exactly on one of the bounds
if pos_idx > 0 and key in self.positions:
pos_idx -= 1
pos0, pos1 = self.positions[pos_idx:pos_idx + 2]
# col0 and col1 are ndarrays
col0, col1 = self.colors[pos_idx:pos_idx + 2]
assert pos0 != pos1
color = col0 + (col1 - col0) * (key - pos0) / (pos1 - pos0)
return to_qvariant(QColor.fromHsvF(*color))
class PlotDialog(QDialog):
def __init__(self, canvas, parent=None):
super(PlotDialog, self).__init__(parent)
toolbar = NavigationToolbar(canvas, self)
# set the layout
layout = QVBoxLayout()
layout.addWidget(toolbar)
layout.addWidget(canvas)
self.setLayout(layout)
canvas.draw()
def show_figure(parent, figure):
canvas = FigureCanvas(figure)
main = PlotDialog(canvas, parent)
main.show()