Skip to content

Commit

Permalink
minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
renerichter committed Jul 18, 2022
1 parent c3776d3 commit 5eb2006
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 26 deletions.
2 changes: 1 addition & 1 deletion MicroPy/deconvolution.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def default_dict_deconv(**kwargs) -> dict:

deconv_dict = {
# deconv defaults
'NIter': 40,
'NIter': 200,
'regl': ['TV', ], # ['TV', 'GR', 'GS']
'lambdal': [10**(-2.5), ], # [2e-4, 1e-3, 2e-4]
'regEps': 1e-5,
Expand Down
41 changes: 30 additions & 11 deletions MicroPy/inout.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import subprocess
from io import StringIO
import untangle
from copy import deepcopy


# mipy imports
Expand Down Expand Up @@ -798,10 +799,31 @@ def add_coordinate_axis(ax, apos=[[120, 10], [120, 10]], alen=[[-40, 0], [0, 40]
ax.text(x=pos[1]+1.1*alenA[1], y=pos[0]+1.1*alenA[0],
s=text[p], color=tcolor, fontsize=tsize)

def plot_value_in_box(ax, ys, box_text, box_prop={}, text_prop={}):
# default
box_xy = [ys[-1]//3, ys[-2]//8]
box_prop_default = {'xy': [ys[-1]-box_xy[0], ys[-2]-box_xy[1]], 'width': box_xy[0] -
3, 'height': box_xy[1]-3, 'color': 'white', 'facecolor': 'none', 'fill': False}
text_prop_default = {'x': box_prop_default['xy'][0]+1, 'y': ys[-2] -
6, 'color': 'white', 'fontsize': 40}

bp = box_prop_default if box_prop == {} else fill_dict1_with_dict2(
box_prop_default, box_prop)
tp = text_prop_default if box_prop == {
} else fill_dict1_with_dict2(text_prop_default, text_prop)
tpp = deepcopy(tp)
del tpp['x'], tpp['y']

for m, bname in enumerate(box_text):
ax[m].add_patch(Rectangle(**bp)) # 'none
ax[m].text(tp['x'], tp['y'], bname, **tpp)

return ax


def default_grid_param(plt_raster):
return {'pos': 111, 'nrows_ncols': (
plt_raster[0], plt_raster[1]), 'axes_pad': 0.4, 'cbar_mode': 'single', 'cbar_location': 'right', 'cbar_pad': 0.1,'cbar_font_size':0.5,'cbar_va':'bottom','cbar_rotation':90,'cbar_label':''}
plt_raster[0], plt_raster[1]), 'axes_pad': 0.1, 'cbar_mode': 'single', 'cbar_location': 'right', 'cbar_pad': 0.1,'cbar_font_size':0.5,'cbar_va':'top','cbar_rotation':90,'cbar_label':''}


def default_coord_axis(imshape):
Expand Down Expand Up @@ -852,7 +874,7 @@ def print_stack2subplot(imstack, im_minmax=[None, None], imdir='row', inplace=Fa
# sanity
grid_param_default = default_grid_param(plt_raster)
gp = grid_param = grid_param_default if grid_param is None else fill_dict1_with_dict2(
grid_param, grid_param_default)
grid_param_default,grid_param)

# generate grid
fig = plt.figure(figsize=plt_format)
Expand Down Expand Up @@ -935,7 +957,7 @@ def print_stack2subplot(imstack, im_minmax=[None, None], imdir='row', inplace=Fa
elif titlestack == False:
pass
else:
axm.set_title(titlestack[m], fontsize=nbrs_psize/2)
axm.set_title(titlestack[m], fontsize=nbrs_psize*4/5)

# add numbers to panels
if nbrs:
Expand All @@ -954,12 +976,12 @@ def print_stack2subplot(imstack, im_minmax=[None, None], imdir='row', inplace=Fa
#axm.set_xticks(yx_ticks[1])
#axm.set_xticklabels(yx_labels[1],fontsize=nbrs_psize/2)
axm.xaxis.set_ticks(yx_ticks[1])
axm.xaxis.set_ticklabels(yx_labels[1],fontsize=nbrs_psize/2)
axm.xaxis.set_ticklabels(yx_labels[1],fontsize=nbrs_psize*4/5)
#axm.yaxis.set_tick_params(labelsize=nbrs_psize)
#axm.set_yticks(yx_ticks[0])
#axm.set_yticklabels(yx_labels[0],fontsize=nbrs_psize/2)
axm.yaxis.set_ticks(yx_ticks[0])
axm.yaxis.set_ticklabels(yx_labels[0],fontsize=nbrs_psize/2)
axm.yaxis.set_ticklabels(yx_labels[0],fontsize=nbrs_psize*4/5)

# plot axis according to selection -> in case of 'bottom','left' axis-names are only plotted at bottom-left panel
if use_axis == None:
Expand Down Expand Up @@ -1172,7 +1194,7 @@ def print_stack2subplot(imstack, im_minmax=[None, None], imdir='row', inplace=Fa
#


def stack2plot(x:np.ndarray, ystack:Union[list,np.ndarray], refs:list=None, title:str=None, xl:list=None, xlabel:str=None, ylabel:str=None, colors:list=None, mmarker:str='', mlinestyle:str='-', mlinewidth:list=None, legend:Union[str,list]=[1, 1.05], legend_col:int=1,xlims:Union[list,np.ndarray]=None, ylims:Union[list,np.ndarray]=None, ax_inside:dict=None, figsize:tuple=(8, 8), show_plot:bool=True, ptight:bool=True, ax=None, nbrs:bool=True, nbrs_color:list=[1, 1, 1], nbrs_size:float=None, nbrs_text:str=None, err_bar:Union[list,np.ndarray]=None, err_capsize:int=3, fonts_labels:list=[None,],fonts_sizes:list=[None,],set_clipon:bool=False) -> tuple:
def stack2plot(x:np.ndarray, ystack:Union[list,np.ndarray], refs:list=None, title:str=None, xl:list=None, xlabel:str=None, ylabel:str=None, colors:list=None, mmarker:str='', mlinestyle:str='-', mlinewidth:list=None, legend:Union[str,list]=[1, 1.05], legend_col:int=1,xlims:Union[list,np.ndarray]=None, ylims:Union[list,np.ndarray]=None, ax_inside:dict=None, figsize:tuple=(8, 8), show_plot:bool=True, ptight:bool=True, ax=None, nbrs:bool=True, nbrs_color:list=[1, 1, 1], nbrs_size:float=None, nbrs_text:str=None, nbrs_offset:list=[],err_bar:Union[list,np.ndarray]=None, err_capsize:int=3, fonts_labels:list=[None,],fonts_sizes:list=[None,],set_clipon:bool=False) -> tuple:
'''
Prints a 1d-"ystack" into 1 plot and assigns legends + titles.
Expand Down Expand Up @@ -1281,12 +1303,9 @@ def stack2plot(x:np.ndarray, ystack:Union[list,np.ndarray], refs:list=None, titl
if nbrs:
text_size_factor = ax.figure.bbox_inches.bounds[-1]*ax.figure.dpi
nbrs_psize = text_size_factor * 0.05 if nbrs_size is None else text_size_factor*nbrs_size
x_offset = np.mean(ax.get_xticks()[:2])
# ax.get_yticks()[-1] - 4*nbrs_psize/text_size_factor*(ylims[1]-ylims[0])
# y_offset = ax.get_yticks()[-2]
y_offset = ylims[1]-ylims_dist/5.0
nbrs_offset = [np.mean(ax.get_xticks()[:2]),ylims[1]-ylims_dist/5.0] if nbrs_offset == [] else nbrs_offset
nbrs_text = chr(97+np.random.randint(26))+')' if nbrs_text is None else nbrs_text
ax.text(x_offset, y_offset, nbrs_text, fontsize=nbrs_psize,
ax.text(nbrs_offset[0], nbrs_offset[1], nbrs_text, fontsize=nbrs_psize,
color=nbrs_color, fontname='Helvetica', weight='normal')

# legend
Expand Down
23 changes: 10 additions & 13 deletions MicroPy/processingISM.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
from scipy.ndimage import binary_closing
from typing import Union
from tiler import Tiler,Merger
from itertools import product as iterprod

# mipy imports
from .general_imports import *
from .transformations import irft3dz, ft_correct, get_cross_correlations, lp_norm
from .utility import avoid_division_by_zero, convert_slices_2_pads, findshift, midVallist, pinhole_getcenter, add_multi_newaxis, shiftby_list, subslice_arbitrary, get_slices_from_shiftmap, normNoff, len_slice, pad_boundaries, convert_slices_2_pads, extent_slicing
from .utility import avoid_division_by_zero, convert_slices_2_pads, findshift, midVallist, pinhole_getcenter, add_multi_newaxis, shiftby_list, subslice_arbitrary, get_slices_from_shiftmap, normNoff, len_slice, pad_boundaries, convert_slices_2_pads, extent_slicing,center_of_mass
from .inout import stack2tiles, format_list, load_data, fix_dict_pixelsize
from .filters import savgol_filter_nd, stf_basic
from .fitting import extract_multiPSF
Expand Down Expand Up @@ -79,7 +80,7 @@ def get_pincenter(im, nbr_det, imfunc=np.max, rfunc=np.round, im_axes=(-2, -1),
pincenter_CoM = rfunc(pincenter_CoM_raw).astype('int')
return pincenter_CoM[0]*nbr_det[1]+pincenter_CoM[1]

def recon_genShiftmap(im, pincenter, im_ref=None, nbr_det=None, pinmask=None, shift_method='nearest', shiftval_theory=None, roi=None, shift_axes=None, cross_mask_len=[4,4], period=[],factors=[], sg_para=[13,2,0,1,'wrap'],subpix_lim=2,printmap=False):
def recon_genShiftmap(im, pincenter, im_ref=None, nbr_det=None, pinmask=None, shift_method='nearest', shift_det=False,det_pos=[], shiftval_theory=None, roi=None, shift_axes=None, cross_mask_len=[4,4], period=[],factors=[], sg_para=[13,2,0,1,'wrap'],subpix_lim=2,printmap=False):
"""Generates Shiftmap for ISM SheppardSUM-reconstruction.
Assumes shape: [Pinhole-Dimension , M] where M stands for arbitrary mD-image.
Fills shift_map from right-most dimension to left, hence errors could be evoked in case of only shifts along dim=[1,2] applied, but array has spatial dim=[1,2,3]. Hence shifts will be applied along [2,3] with their respective period factors.
Expand All @@ -100,6 +101,9 @@ def recon_genShiftmap(im, pincenter, im_ref=None, nbr_det=None, pinmask=None, sh
'mask': all pinholes that reside within mask ; needs pinmask
'complete': calculate shifts for all detectors
'theory': generates shifts from shiftval_theory provided
shift_det : bool, optional
TRUE: Shift the detector position $h^{det}$ (in scan coordinates) to the most likely emission position h^{ism}
FALSE: Shift the most likely emission position $h^{ISM}$ towards the central pixel $h^{ex}$
shiftval_theory: list, optional
if shift_method 'theory' is active, generates shiftmap from these factors. In pixel-dimensions und unit-vector notation, hence eg [[-0.5,0],[0,-0.5]] generates "back-shift" for pixel-reassignments by half the distance to the pincenter, by default None
roi : list, optional
Expand Down Expand Up @@ -152,6 +156,7 @@ def recon_genShiftmap(im, pincenter, im_ref=None, nbr_det=None, pinmask=None, sh
if shift_method == 'nearest':
shifth, _, _, _ = findshift(im_ref,
im[np.mod(pincenter+perioda, im.shape[0])], 10**subpix_lim)
shifth=np.sign(shifth)*(np.abs(det_pos[np.mod(pincenter+perioda, im.shape[0])])-np.abs(shifth)) if shift_det else shifth
elif shift_method == 'cross':
cmask=np.zeros(im.shape[0],dtype='bool')
direct_pixel_dist=np.arange(-cross_mask_len[m],cross_mask_len[m]+1)#+cmask.shape[m]
Expand Down Expand Up @@ -187,7 +192,7 @@ def recon_genShiftmap(im, pincenter, im_ref=None, nbr_det=None, pinmask=None, sh
#if not pinmask is None:
# shift_map = shift_map[pinmask]
else:
shift_map=np.array([m[0]*shiftvec[0]+m[1]*shiftvec[1] for m in factors])
shift_map=np.array([fac[0]*shiftvec[0]+fac[1]*shiftvec[1] for fac in factors])
elif shift_method == 'mask':
imh = im[pinmask]
# shift_map = np.array([[0, ]*im.ndim]*im.shape[0])
Expand Down Expand Up @@ -500,7 +505,7 @@ def ism_recon(im, method='wf', **kwargs):
return pinsize


def recon_sheppardSUM(im, nbr_det, pincenter, im_ref=None, shift_method='nearest', shift_map=[], shift_roi=None, shiftval_theory=None, shift_axes=(-2,-1), shift_extract=False, pinmask=None, pinfo=False, sum_method='normal', shift_style='parallel', shift_use_copy=True, ret_nonSUM=False,cross_mask_len=[4,4], period=[],factors=[],subpix_lim=2):
def recon_sheppardSUM(im, nbr_det, pincenter, im_ref=None, shift_method='nearest', shift_map=[], shift_roi=None, shift_det=False,det_pos=[],shiftval_theory=None, shift_axes=(-2,-1), shift_extract=False, pinmask=None, pinfo=False, sum_method='normal', shift_style='parallel', shift_use_copy=True, ret_nonSUM=False,cross_mask_len=[4,4], period=[],factors=[],subpix_lim=2):
"""Calculates sheppardSUM on image (for arbitrary detector arrangement). The 0th-Dimension is assumed as detector-dimension and hence allows for arbitrary, but flattened detector geometries.
The algorithm does:
Expand Down Expand Up @@ -552,7 +557,7 @@ def recon_sheppardSUM(im, nbr_det, pincenter, im_ref=None, shift_method='nearest
# find shift-list -> Note: 'nearest' is standard
if shift_map == []:
shift_map, rdict = recon_genShiftmap(
im=im, im_ref=im_ref, pincenter=pincenter, nbr_det=nbr_det, pinmask=pinmask, shift_method=shift_method, shiftval_theory=shiftval_theory, roi=shift_roi, shift_axes=shift_axes,cross_mask_len=cross_mask_len,period=period,factors=factors,subpix_lim=subpix_lim)
im=im, im_ref=im_ref, pincenter=pincenter, nbr_det=nbr_det, pinmask=pinmask, shift_method=shift_method, shift_det=shift_det,det_pos=det_pos,shiftval_theory=shiftval_theory, roi=shift_roi, shift_axes=shift_axes,cross_mask_len=cross_mask_len,period=period,factors=factors,subpix_lim=subpix_lim)
else:
rdict={'im_ref':[]}

Expand Down Expand Up @@ -1521,14 +1526,6 @@ def thickslice_unmix(ims_ft: nip.image, otfs: nip.image, pad: dict, otfs_dict:di
# ---------------------------------------------------------------
# DSAX-ISM
# ---------------------------------------------------------------
def dsax_isolateOrder_prefactors(Iex, Isat, tau, order=3,):
Gamma = tau/(1+Isat*tau)
Iex = np.array(Iex)
orderl = np.arange(order)+1
Iexn = ((Gamma*(np.e/orderl)*(Iex-Isat))**orderl)/(tau*np.sqrt(2*np.pi*orderl))
return Iexn


def dsax_isolateOrder(ims: Union[nip.image, np.ndarray], Iex: list, order: int = 2, shield: bool = False, ret_summands: bool = False):
'''
Calculate dsax non-linear order reconstruction.
Expand Down
9 changes: 8 additions & 1 deletion MicroPy/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1043,7 +1043,7 @@ def fwd_add_noise(pad, prd):

def dsax_fwd_model(pad, prd={}, psd={}):
'''Alias for fwd_model'''
pad['ism_method'] == 'dsax'
pad['ism_method'] = 'dsax'
return fwd_model(pad=pad, prd=prd, psd=psd)

def fwd_model_default_param(dolist=[1,0,1,1]):
Expand Down Expand Up @@ -1239,6 +1239,13 @@ def saturation_curve(Iex, ψmax: float = 0, Imax: float = 1000, tau: float = 1,
else:
return Ifluo

def dsax_isolateOrder_prefactors(Iex, Isat, tau, order=3,):
Gamma = tau/(1+Isat*tau)
Iex = np.array(Iex)
orderl = np.arange(order)+1
Iexn = ((Gamma*(np.e/orderl)*(Iex-Isat))**orderl)/(tau*np.sqrt(2*np.pi*orderl))
return Iexn

# %%
# ------------------------------------------------------------------
# Stack-Generators
Expand Down

0 comments on commit 5eb2006

Please sign in to comment.