spacr 1.0.5__py3-none-any.whl → 1.0.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
spacr/gui_utils.py CHANGED
@@ -463,14 +463,13 @@ def function_gui_wrapper(function=None, settings={}, q=None, fig_queue=None, imp
463
463
  def run_function_gui(settings_type, settings, q, fig_queue, stop_requested):
464
464
 
465
465
  from .core import generate_image_umap, preprocess_generate_masks
466
- from .spacr_cellpose import identify_masks_finetune, check_cellpose_models, compare_cellpose_masks
466
+ from .spacr_cellpose import identify_masks_finetune, check_cellpose_models
467
467
  from .submodules import analyze_recruitment
468
468
  from .ml import generate_ml_scores, perform_regression
469
469
  from .submodules import train_cellpose, analyze_plaques
470
- from .io import process_non_tif_non_2D_images, generate_cellpose_train_test, generate_dataset
470
+ from .io import process_non_tif_non_2D_images
471
471
  from .measure import measure_crop
472
- from .sim import run_multiple_simulations
473
- from .deep_spacr import deep_spacr, apply_model_to_tar
472
+ from .deep_spacr import deep_spacr
474
473
  from .sequencing import generate_barecode_mapping
475
474
 
476
475
  process_stdout_stderr(q)
@@ -483,9 +482,6 @@ def run_function_gui(settings_type, settings, q, fig_queue, stop_requested):
483
482
  elif settings_type == 'measure':
484
483
  function = measure_crop
485
484
  imports = 1
486
- elif settings_type == 'simulation':
487
- function = run_multiple_simulations
488
- imports = 1
489
485
  elif settings_type == 'classify':
490
486
  function = deep_spacr
491
487
  imports = 1
spacr/io.py CHANGED
@@ -1,4 +1,4 @@
1
- import os, re, sqlite3, gc, torch, time, random, shutil, cv2, tarfile, cellpose, glob, queue, tifffile, czifile, atexit, datetime
1
+ import os, re, sqlite3, gc, torch, time, random, shutil, cv2, tarfile, cellpose, glob, queue, tifffile, czifile, atexit, datetime, readlif
2
2
  import numpy as np
3
3
  import pandas as pd
4
4
  from PIL import Image, ImageOps
@@ -22,7 +22,6 @@ import seaborn as sns
22
22
  from nd2reader import ND2Reader
23
23
  from torchvision import transforms
24
24
  from sklearn.model_selection import train_test_split
25
- import readlif
26
25
  from pylibCZIrw import czi as pyczi
27
26
 
28
27
  def process_non_tif_non_2D_images(folder):
@@ -1133,6 +1132,7 @@ def _normalize_img_batch(stack, channels, save_dtype, settings):
1133
1132
 
1134
1133
  def concatenate_and_normalize(src, channels, save_dtype=np.float32, settings={}):
1135
1134
  from .utils import print_progress
1135
+ from .plot import plot_arrays
1136
1136
 
1137
1137
  """
1138
1138
  Concatenates and normalizes channel data from multiple files and saves the normalized data.
@@ -1155,6 +1155,8 @@ def concatenate_and_normalize(src, channels, save_dtype=np.float32, settings={})
1155
1155
  """
1156
1156
 
1157
1157
  channels = [item for item in channels if item is not None]
1158
+
1159
+ print(f"Generating concatenated and normalized channel data for channels: {channels}")
1158
1160
 
1159
1161
  paths = []
1160
1162
  time_ls = []
@@ -1175,7 +1177,7 @@ def concatenate_and_normalize(src, channels, save_dtype=np.float32, settings={})
1175
1177
  name = parts[0] + '_' + parts[1] + '_' + parts[2]
1176
1178
  array = np.load(path)
1177
1179
  stack_region.append(array)
1178
- filenames_region.append(os.path.basename(path))
1180
+ filenames_region.append(os.path.basename(path))
1179
1181
  stop = time.time()
1180
1182
  duration = stop - start
1181
1183
  time_ls.append(duration)
@@ -1193,6 +1195,10 @@ def concatenate_and_normalize(src, channels, save_dtype=np.float32, settings={})
1193
1195
 
1194
1196
  save_loc = os.path.join(output_fldr, f'{name}_norm_timelapse.npz')
1195
1197
  np.savez(save_loc, data=normalized_stack, filenames=filenames_region)
1198
+
1199
+ if i == 0:
1200
+ plot_arrays(save_loc, settings['figuresize'], settings['cmap'], nr=settings['nr'], normalize=False)
1201
+
1196
1202
  print(save_loc)
1197
1203
  del stack, normalized_stack
1198
1204
  except Exception as e:
@@ -1250,7 +1256,11 @@ def concatenate_and_normalize(src, channels, save_dtype=np.float32, settings={})
1250
1256
  normalized_stack = normalized_stack[..., channels]
1251
1257
 
1252
1258
  save_loc = os.path.join(output_fldr, f'stack_{batch_index}_norm.npz')
1253
- np.savez(save_loc, data=normalized_stack, filenames=filenames_batch)
1259
+ np.savez(save_loc, data=normalized_stack, filenames=filenames_batch)
1260
+ if batch_index == 0:
1261
+ print(f"plotting: {save_loc}")
1262
+ plot_arrays(save_loc, settings['figuresize'], settings['cmap'], nr=settings['nr'], normalize=False)
1263
+
1254
1264
  batch_index += 1
1255
1265
  del stack, normalized_stack
1256
1266
  stack_ls = []
spacr/plot.py CHANGED
@@ -760,7 +760,63 @@ def _filter_objects_in_plot(stack, cell_mask_dim, nucleus_mask_dim, pathogen_mas
760
760
 
761
761
  return stack
762
762
 
763
+
763
764
  def plot_arrays(src, figuresize=10, cmap='inferno', nr=1, normalize=True, q1=1, q2=99):
765
+ """
766
+ Plot randomly selected arrays from a given directory or a single .npz/.npy file.
767
+
768
+ Parameters:
769
+ - src (str): The directory path or file path containing the arrays.
770
+ - figuresize (int): The size of the figure (default: 10).
771
+ - cmap (str): The colormap to use for displaying the arrays (default: 'inferno').
772
+ - nr (int): The number of arrays to plot (default: 1).
773
+ - normalize (bool): Whether to normalize the arrays (default: True).
774
+ - q1 (int): The lower percentile for normalization (default: 1).
775
+ - q2 (int): The upper percentile for normalization (default: 99).
776
+ """
777
+ from .utils import normalize_to_dtype
778
+
779
+ mask_cmap = random_cmap()
780
+ paths = []
781
+
782
+ if src.endswith('.npz') or src.endswith('.npy'):
783
+ paths = [src]
784
+ else:
785
+ paths = [os.path.join(src, f) for f in os.listdir(src) if f.endswith(('.npy', '.npz'))]
786
+ paths = random.sample(paths, min(nr, len(paths)))
787
+
788
+ for path in paths:
789
+ print(f'Image path: {path}')
790
+ if path.endswith('.npz'):
791
+ with np.load(path) as data:
792
+ key = list(data.keys())[0] # assume first key
793
+ img = data[key][0] # get first image in batch
794
+ else:
795
+ img = np.load(path)
796
+
797
+ if normalize:
798
+ img = normalize_to_dtype(array=img, p1=q1, p2=q2)
799
+
800
+ if img.ndim == 3:
801
+ array_nr = img.shape[2]
802
+ fig, axs = plt.subplots(1, array_nr, figsize=(figuresize, figuresize))
803
+ if array_nr == 1:
804
+ axs = [axs] # ensure iterable
805
+ for channel in range(array_nr):
806
+ i = img[:, :, channel]
807
+ axs[channel].imshow(i, cmap=plt.get_cmap(cmap))
808
+ axs[channel].set_title(f'Channel {channel}', size=24)
809
+ axs[channel].axis('off')
810
+ else:
811
+ fig, ax = plt.subplots(1, 1, figsize=(figuresize, figuresize))
812
+ ax.imshow(img, cmap=plt.get_cmap(cmap))
813
+ ax.set_title('Channel 0', size=24)
814
+ ax.axis('off')
815
+
816
+ fig.tight_layout()
817
+ plt.show()
818
+
819
+ def plot_arrays_v1(src, figuresize=10, cmap='inferno', nr=1, normalize=True, q1=1, q2=99):
764
820
  """
765
821
  Plot randomly selected arrays from a given directory.
766
822
 
@@ -780,6 +836,7 @@ def plot_arrays(src, figuresize=10, cmap='inferno', nr=1, normalize=True, q1=1,
780
836
 
781
837
  mask_cmap = random_cmap()
782
838
  paths = []
839
+
783
840
  for file in os.listdir(src):
784
841
  if file.endswith('.npy'):
785
842
  path = os.path.join(src, file)