spacr 0.1.50__py3-none-any.whl → 0.1.61__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_wrappers.py ADDED
@@ -0,0 +1,137 @@
1
+ import traceback, matplotlib, spacr
2
+ import matplotlib.pyplot as plt
3
+ matplotlib.use('Agg')
4
+
5
+ fig_queue = None
6
+
7
+ def my_show():
8
+ """
9
+ Replacement for plt.show() that queues figures instead of displaying them.
10
+ """
11
+ fig = plt.gcf()
12
+ fig_queue.put(fig)
13
+ plt.close(fig)
14
+
15
+ def measure_crop_wrapper(settings, q, fig_queue):
16
+ """
17
+ Wraps the measure_crop function to integrate with GUI processes.
18
+
19
+ Parameters:
20
+ - settings: dict, The settings for the measure_crop function.
21
+ - q: multiprocessing.Queue, Queue for logging messages to the GUI.
22
+ - fig_queue: multiprocessing.Queue, Queue for sending figures to the GUI.
23
+ """
24
+
25
+ # Temporarily override plt.show
26
+ original_show = plt.show
27
+ plt.show = my_show
28
+
29
+ try:
30
+ print('start')
31
+ spacr.measure.measure_crop(settings=settings)
32
+ except Exception as e:
33
+ errorMessage = f"Error during processing: {e}"
34
+ q.put(errorMessage)
35
+ traceback.print_exc()
36
+ finally:
37
+ plt.show = original_show
38
+
39
+ def preprocess_generate_masks_wrapper(settings, q, fig_queue):
40
+ """
41
+ Wraps the measure_crop function to integrate with GUI processes.
42
+
43
+ Parameters:
44
+ - settings: dict, The settings for the measure_crop function.
45
+ - q: multiprocessing.Queue, Queue for logging messages to the GUI.
46
+ - fig_queue: multiprocessing.Queue, Queue for sending figures to the GUI.
47
+ """
48
+
49
+ # Temporarily override plt.show
50
+ original_show = plt.show
51
+ plt.show = my_show
52
+
53
+ try:
54
+ spacr.core.preprocess_generate_masks(src=settings['src'], settings=settings)
55
+ except Exception as e:
56
+ errorMessage = f"Error during processing: {e}"
57
+ q.put(errorMessage)
58
+ traceback.print_exc()
59
+ finally:
60
+ plt.show = original_show
61
+
62
+ def sequencing_wrapper(settings, q, fig_queue):
63
+
64
+ # Temporarily override plt.show
65
+ original_show = plt.show
66
+ plt.show = my_show
67
+
68
+ try:
69
+ spacr.sequencing.analyze_reads(settings=settings)
70
+ except Exception as e:
71
+ errorMessage = f"Error during processing: {e}"
72
+ q.put(errorMessage)
73
+ traceback.print_exc()
74
+ finally:
75
+ plt.show = original_show
76
+
77
+ def umap_wrapper(settings, q, fig_queue):
78
+
79
+ # Temporarily override plt.show
80
+ original_show = plt.show
81
+ plt.show = my_show
82
+
83
+ try:
84
+ spacr.core.generate_image_umap(settings=settings)
85
+ except Exception as e:
86
+ errorMessage = f"Error during processing: {e}"
87
+ q.put(errorMessage)
88
+ traceback.print_exc()
89
+ finally:
90
+ plt.show = original_show
91
+
92
+ def train_test_model_wrapper(settings, q, fig_queue):
93
+ """
94
+ Wraps the measure_crop function to integrate with GUI processes.
95
+
96
+ Parameters:
97
+ - settings: dict, The settings for the measure_crop function.
98
+ - q: multiprocessing.Queue, Queue for logging messages to the GUI.
99
+ - fig_queue: multiprocessing.Queue, Queue for sending figures to the GUI.
100
+ """
101
+
102
+ # Temporarily override plt.show
103
+ original_show = plt.show
104
+ plt.show = my_show
105
+
106
+ try:
107
+ spacr.core.train_test_model(settings['src'], settings=settings)
108
+ except Exception as e:
109
+ errorMessage = f"Error during processing: {e}"
110
+ q.put(errorMessage) # Send the error message to the GUI via the queue
111
+ traceback.print_exc()
112
+ finally:
113
+ plt.show = original_show # Restore the original plt.show function
114
+
115
+
116
+ def run_multiple_simulations_wrapper(settings, q, fig_queue):
117
+ """
118
+ Wraps the run_multiple_simulations function to integrate with GUI processes.
119
+
120
+ Parameters:
121
+ - settings: dict, The settings for the run_multiple_simulations function.
122
+ - q: multiprocessing.Queue, Queue for logging messages to the GUI.
123
+ - fig_queue: multiprocessing.Queue, Queue for sending figures to the GUI.
124
+ """
125
+
126
+ # Temporarily override plt.show
127
+ original_show = plt.show
128
+ plt.show = my_show
129
+
130
+ try:
131
+ spacr.sim.run_multiple_simulations(settings=settings)
132
+ except Exception as e:
133
+ errorMessage = f"Error during processing: {e}"
134
+ q.put(errorMessage) # Send the error message to the GUI via the queue
135
+ traceback.print_exc()
136
+ finally:
137
+ plt.show = original_show # Restore the original plt.show function
spacr/measure.py CHANGED
@@ -16,12 +16,6 @@ from skimage.util import img_as_bool
16
16
 
17
17
  from .logger import log_function_call
18
18
 
19
- #from .io import create_database, _save_settings_to_db
20
- #from .timelapse import _timelapse_masks_to_gif, _scmovie
21
- #from .plot import _plot_cropped_arrays, _save_scimg_plot
22
- #from .utils import _merge_overlapping_objects, _filter_object, _relabel_parent_with_child_labels, _exclude_objects
23
- #from .utils import _merge_and_save_to_database, _crop_center, _find_bounding_box, _generate_names, _get_percentiles, normalize_to_dtype, _map_wells_png, _list_endpoint_subdirectories, _generate_representative_images
24
-
25
19
  def get_components(cell_mask, nucleus_mask, pathogen_mask):
26
20
  """
27
21
  Get the components (nucleus and pathogens) for each cell in the given masks.
@@ -626,8 +620,13 @@ def _measure_crop_core(index, time_ls, file, settings):
626
620
 
627
621
  file_name = os.path.splitext(file)[0]
628
622
  data = np.load(os.path.join(settings['input_folder'], file))
629
-
630
623
  data_type = data.dtype
624
+ if data_type not in ['uint8','uint16']:
625
+ data_type_before = data_type
626
+ data = data.astype(np.uint16)
627
+ data_type = data.dtype
628
+ print(f'Converted data from {data_type_before} to {data_type}')
629
+
631
630
  if settings['save_measurements']:
632
631
  os.makedirs(source_folder+'/measurements', exist_ok=True)
633
632
  _create_database(source_folder+'/measurements/measurements.db')
@@ -832,7 +831,6 @@ def _measure_crop_core(index, time_ls, file, settings):
832
831
  png_channels = normalize_to_dtype(png_channels, settings['normalize'][0], settings['normalize'][1], percentile_list=percentile_list)
833
832
  else:
834
833
  png_channels = normalize_to_dtype(png_channels, 0, 100)
835
-
836
834
  os.makedirs(png_folder, exist_ok=True)
837
835
 
838
836
  if png_channels.shape[2] == 2:
spacr/plot.py CHANGED
@@ -1565,4 +1565,56 @@ def plot_feature_importance(feature_importance_df):
1565
1565
  ax.set_xlabel('Feature Importance', fontsize=font_size)
1566
1566
  ax.tick_params(axis='both', which='major', labelsize=font_size)
1567
1567
  plt.tight_layout()
1568
- return fig
1568
+ return fig
1569
+
1570
+ def read_and_plot__vision_results(base_dir, y_axis='accuracy', name_split='_time', y_lim=[0.8, 0.9]):
1571
+ # List to store data from all CSV files
1572
+ data_frames = []
1573
+
1574
+ dst = os.path.join(base_dir, 'result')
1575
+ os.mkdir(dst,exists=True)
1576
+
1577
+ # Walk through the directory
1578
+ for root, dirs, files in os.walk(base_dir):
1579
+ for file in files:
1580
+ if file.endswith("_test_result.csv"):
1581
+ file_path = os.path.join(root, file)
1582
+ # Extract model information from the file name
1583
+ file_name = os.path.basename(file_path)
1584
+ model = file_name.split(f'{name_split}')[0]
1585
+
1586
+ # Extract epoch information from the file name
1587
+ epoch_info = file_name.split('_time')[1]
1588
+ base_folder = os.path.dirname(file_path)
1589
+ epoch = os.path.basename(base_folder)
1590
+
1591
+ # Read the CSV file
1592
+ df = pd.read_csv(file_path)
1593
+ df['model'] = model
1594
+ df['epoch'] = epoch
1595
+
1596
+ # Append the data frame to the list
1597
+ data_frames.append(df)
1598
+
1599
+ # Concatenate all data frames
1600
+ if data_frames:
1601
+ result_df = pd.concat(data_frames, ignore_index=True)
1602
+
1603
+ # Calculate average y_axis per model
1604
+ avg_metric = result_df.groupby('model')[y_axis].mean().reset_index()
1605
+ avg_metric = avg_metric.sort_values(by=y_axis)
1606
+ print(avg_metric)
1607
+
1608
+ # Plotting the results
1609
+ plt.figure(figsize=(10, 6))
1610
+ plt.bar(avg_metric['model'], avg_metric[y_axis])
1611
+ plt.xlabel('Model')
1612
+ plt.ylabel(f'{y_axis}')
1613
+ plt.title(f'Average {y_axis.capitalize()} per Model')
1614
+ plt.xticks(rotation=45)
1615
+ plt.tight_layout()
1616
+ if y_lim is not None:
1617
+ plt.ylim(y_lim)
1618
+ plt.show()
1619
+ else:
1620
+ print("No CSV files found in the specified directory.")
spacr/sequencing.py CHANGED
@@ -37,22 +37,6 @@ def analyze_reads(settings):
37
37
  None
38
38
  """
39
39
 
40
- def save_chunk_to_hdf5_v1(output_file_path, data_chunk, chunk_counter):
41
- """
42
- Save a data chunk to an HDF5 file.
43
-
44
- Parameters:
45
- - output_file_path (str): The path to the output HDF5 file.
46
- - data_chunk (list): The data chunk to be saved.
47
- - chunk_counter (int): The counter for the current chunk.
48
-
49
- Returns:
50
- None
51
- """
52
- df = pd.DataFrame(data_chunk, columns=['combined_read', 'grna', 'plate_row', 'column', 'sample'])
53
- with pd.HDFStore(output_file_path, mode='a', complevel=5, complib='blosc') as store:
54
- store.put(f'reads/chunk_{chunk_counter}', df, format='table', append=True)
55
-
56
40
  def save_chunk_to_hdf5(output_file_path, data_chunk, chunk_counter):
57
41
  """
58
42
  Save a data chunk to an HDF5 file.
@@ -306,7 +290,7 @@ def analyze_reads(settings):
306
290
  qc_df = pd.DataFrame([qc])
307
291
  qc_df.to_csv(qc_file_path, index=False)
308
292
 
309
- from .utils import get_analyze_reads_default_settings
293
+ from .settings import get_analyze_reads_default_settings
310
294
 
311
295
  settings = get_analyze_reads_default_settings(settings)
312
296