Skip to content

Commit

Permalink
[#159] Cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
dvezinet committed Nov 14, 2024
1 parent b255f15 commit 7e7f71d
Showing 1 changed file with 60 additions and 50 deletions.
110 changes: 60 additions & 50 deletions datastock/_class02.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@ def add_mobile(
else:
msg = (
f"In dmobile['{key}']:\n"
"Nb. of different dtypes must match nb of different data!\n"
"Nb. of diff. dtypes must match nb of diff. data!\n"
f"\t- dtype: {dtype}\n"
f"\t- data: {data}\n"
)
Expand Down Expand Up @@ -192,23 +192,23 @@ def add_axes(
# check refx, refy

# if refx is None and refy is None:
# msg = f"Please provide at least refx or refy for axes {key}!"
# raise Exception(msg)
# msg = f"Please provide at least refx or refy for axes {key}!"
# raise Exception(msg)

if isinstance(refx, str):
refx = [refx]
if isinstance(refy, str):
refy = [refy]

c0 =(
c0 = (
isinstance(refx, list)
and all([rr in self._dref.keys() for rr in refx])
)
if refx is not None and not c0:
msg = "Arg refx must be a list of valid ref keys!"
raise Exception(msg)

c0 =(
c0 = (
isinstance(refy, list)
and all([rr in self._dref.keys() for rr in refy])
)
Expand Down Expand Up @@ -388,8 +388,9 @@ def setup_interactivity(
# add indices to ref
for k0, v0 in self._dref.items():
if drefgroup[k0] is not None:
zeros = np.zeros((dgroup[drefgroup[k0]]['nmax'],), dtype=int)
self.add_indices_per_ref(
indices=np.zeros((dgroup[drefgroup[k0]]['nmax'],), dtype=int),
indices=zeros,
ref=k0,
distribute=False,
)
Expand Down Expand Up @@ -459,7 +460,7 @@ def setup_interactivity(
# --------------------
# axes mobile, refs and canvas

daxcan = dict.fromkeys(self._dobj['axes'].keys())
# daxcan = dict.fromkeys(self._dobj['axes'].keys())
for k0, v0 in self._dobj['axes'].items():

# Update mobile
Expand Down Expand Up @@ -599,53 +600,53 @@ def connect(self):
if self._warn_ifnotInteractive():
return
for k0, v0 in self._dobj['canvas'].items():
keyp = v0['handle'].mpl_connect('key_press_event', self.onkeypress)
keyr = v0['handle'].mpl_connect('key_release_event', self.onkeypress)
butp = v0['handle'].mpl_connect('button_press_event', self.mouseclic)
res = v0['handle'].mpl_connect('resize_event', self.resize)
butr = v0['handle'].mpl_connect('button_release_event', self.mouserelease)
close = v0['handle'].mpl_connect('close_event', self.on_close)
draw = v0['handle'].mpl_connect('draw_event', self.on_draw)
hand = v0['handle']
keyp = hand.mpl_connect('key_press_event', self.onkeypress)
keyr = hand.mpl_connect('key_release_event', self.onkeypress)
butp = hand.mpl_connect('button_press_event', self.mouseclic)
res = hand.mpl_connect('resize_event', self.resize)
butr = hand.mpl_connect('button_release_event', self.mouserelease)
close = hand.mpl_connect('close_event', self.on_close)
# draw = hand.mpl_connect('draw_event', self.on_draw)
# Make sure resizing is doen before resize_event
# works without re-initializing because not a Qt Action
v0['handle'].manager.toolbar.release = self.mouserelease
hand.manager.toolbar.release = self.mouserelease
# v0['handle'].manager.toolbar.release_zoom = self.mouserelease
# v0['handle'].manager.toolbar.release_pan = self.mouserelease

# make sure home button triggers background update
# requires re-initializing because home is a Qt Action
# only created by toolbar.addAction()
v0['handle'].manager.toolbar.home = self.new_home
hand.manager.toolbar.home = self.new_home

# if _init_toolbar() implemented (matplotlib > )
error = False
if hasattr(v0['handle'].manager.toolbar, '_init_toolbar'):
if hasattr(hand.manager.toolbar, '_init_toolbar'):
try:
v0['handle'].manager.toolbar._init_toolbar()
hand.manager.toolbar._init_toolbar()
except NotImplementedError:
v0['handle'].manager.toolbar.__init__(
v0['handle'],
v0['handle'].parent(),
hand.manager.toolbar.__init__(
hand,
hand.parent(),
)
except Exception as err:
error = err
elif hasattr(v0['handle'], 'parent'):
elif hasattr(hand, 'parent'):
try:
v0['handle'].manager.toolbar.__init__(
v0['handle'],
v0['handle'].parent(),
hand.manager.toolbar.__init__(
hand,
hand.parent(),
)
except Exception as err:
except Exception:
error = True
else:
error = True

if error is not False:
import platform
import sys
import inspect
lstr0 = [f"\t- {k1}" for k1 in dir(v0['handle'])]
lstr1 = [f"\t- {k1}" for k1 in dir(v0['handle'].manager.toolbar)]
lstr0 = [f"\t- {k1}" for k1 in dir(hand)]
lstr1 = [f"\t- {k1}" for k1 in dir(hand.manager.toolbar)]
msg = (
f"platform: {platform.platform()}\n"
f"python: {sys.version}\n"
Expand All @@ -656,7 +657,7 @@ def connect(self):
+ "\n".join(lstr1)
)
if error is not True:
msg += '\n' + str(err)
msg += '\n' + str(error)
warnings.warn(msg)

self._dobj['canvas'][k0]['cid'] = {
Expand Down Expand Up @@ -725,8 +726,8 @@ def _get_current_grouprefdata_from_kax(self, kax=None):
# Get current group and ref
groupx = self._dobj['axes'][kax]['groupx']
groupy = self._dobj['axes'][kax]['groupy']
refx = self._dobj['axes'][kax]['refx']
refy = self._dobj['axes'][kax]['refy']
# refx = self._dobj['axes'][kax]['refx']
# refy = self._dobj['axes'][kax]['refy']

# Get kinter
kinter = list(self._dobj['interactivity'].keys())[0]
Expand Down Expand Up @@ -801,7 +802,7 @@ def _getset_current_axref(self, event):
types=str,
allowed=lkax,
)
ax = self._dobj['axes'][kax]['handle']
# ax = self._dobj['axes'][kax]['handle']

# Check axes is relevant and toolbar not active
lc = [
Expand Down Expand Up @@ -830,8 +831,8 @@ def update_interactivity(self):
cur_groupy = self._dobj['interactivity'][self.kinter]['cur_groupy']
cur_refx = self._dobj['interactivity'][self.kinter]['cur_refx']
cur_refy = self._dobj['interactivity'][self.kinter]['cur_refy']
cur_datax = self._dobj['interactivity'][self.kinter]['cur_datax']
cur_datay = self._dobj['interactivity'][self.kinter]['cur_datay']
# cur_datax = self._dobj['interactivity'][self.kinter]['cur_datax']
# cur_datay = self._dobj['interactivity'][self.kinter]['cur_datay']

# Propagate indices through refs
if cur_refx is not None:
Expand Down Expand Up @@ -870,7 +871,7 @@ def update_interactivity(self):
])
]

self._update_mobiles(lmobiles=lmobiles) # 0.2 s
self._update_mobiles(lmobiles=lmobiles) # 0.2 s

if self.debug:
self.show_debug()
Expand Down Expand Up @@ -912,20 +913,21 @@ def _update_mobiles(self, lmobiles=None):

# --- Redraw all objects (due to background restore) --- 25 ms
for k0, v0 in self._dobj['mobile'].items():
v0['handle'].set_visible(v0['visible'])
hand = v0['handle']
hand.set_visible(v0['visible'])
try:
self._dobj['axes'][v0['axes']]['handle'].draw_artist(v0['handle'])
self._dobj['axes'][v0['axes']]['handle'].draw_artist(hand)
except Exception as err:
print()
print(0, k0) # DB
print(1, v0['axes']) # DB
print(2, self._dobj['axes'][v0['axes']]['handle']) # DB
print(3, v0['handle']) # DB
print(3, hand) # DB
print(
4, 'x and y data shapes: ',
[vv.shape for vv in v0['handle'].get_data()]
[vv.shape for vv in hand.get_data()]
) # DB
print(5, 'data: ', v0['handle'].get_data())
print(5, 'data: ', hand.get_data())
print(err) # DB
print() # DB

Expand Down Expand Up @@ -1003,7 +1005,9 @@ def mouseclic(self, event):
cur_datay = self._dobj['interactivity'][kinter]['cur_datay']

shift = self._dobj['key']['shift']['val']
ctrl = any([self._dobj['key'][ss]['val'] for ss in ['control', 'ctrl']])
ctrl = any([
self._dobj['key'][ss]['val'] for ss in ['control', 'ctrl']
])

# Update number of indices (for visibility)
gax = []
Expand Down Expand Up @@ -1119,15 +1123,15 @@ def mouserelease(self, event):
if v0['handle'] == event.inaxes.figure.canvas
][0]
mode = self._dobj['canvas'][can]['handle'].manager.toolbar.mode.lower()
c0 = 'pan' in mode
c0 = 'pan' in mode
c1 = 'zoom' in mode

if c0 or c1:
kax = self._dobj['interactivity'][self.kinter]['cur_ax_panzoom']
if kax is None:
msg = (
"Make sure you release the mouse button on an axes !"
"\n Otherwise the background plot cannot be properly updated !"
"Make sure you release the mouse button on an axes!"
"\n Otherwise background plot can't be properly updated!"
)
raise Exception(msg)
ax = self._dobj['axes'][kax]['handle']
Expand Down Expand Up @@ -1192,7 +1196,7 @@ def onkeypress(self, event):
ln = np.r_[ngen, nmov, ngrp, nind]
if np.any(ln > 1) or np.sum(ln) > 2:
return
if np.sum(ln) == 2 and (ngrp == 1 or nind ==1 ):
if np.sum(ln) == 2 and (ngrp == 1 or nind == 1):
return

# only keep relevant keys
Expand Down Expand Up @@ -1221,7 +1225,7 @@ def onkeypress(self, event):
# group
group = self._dobj['key'][event.key]['group']
cx = any([
v0['groupx'] is not None and group in v0['groupx']
v0['groupx'] is not None and group in v0['groupx']
for v0 in self._dobj['axes'].values()
])
if cx:
Expand Down Expand Up @@ -1275,7 +1279,10 @@ def onkeypress(self, event):
imax = self._dobj['group'][groupx]['nmaxcur']
ii = int(event.key)
if ii > imax:
msg = "Set to current max index for group '{groupx}': {imax}"
msg = (
f"Set to current max index for group '{groupx}':"
f" {imax}"
)
print(msg)
ii = min(ii, imax)
self._dobj['group'][groupx]['indcur'] = ii
Expand All @@ -1285,7 +1292,10 @@ def onkeypress(self, event):
imax = self._dobj['group'][groupy]['nmaxcur']
ii = int(event.key)
if ii > imax:
msg = "Set to current max index for group '{groupy}': {imax}"
msg = (
f"Set to current max index for group '{groupy}':"
f" {imax}"
)
print(msg)
ii = min(ii, imax)
self._dobj['group'][groupy]['indcur'] = ii
Expand Down Expand Up @@ -1379,7 +1389,7 @@ def onkeypress(self, event):
# -------------------

def on_close(self, event):
self.remove_all(excluded=['canvas']) # to avoid crash
self.remove_all(excluded=['canvas']) # to avoid crash
print("\n---- CLOSING interactive figure ----")
print(f"\tleft in dax: {self.get_nbytes()[0]/1000} Ko\n")

Expand Down

0 comments on commit 7e7f71d

Please sign in to comment.