spacr 0.0.17__py3-none-any.whl → 0.0.20__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_temp.py DELETED
@@ -1,212 +0,0 @@
1
- import sys, ctypes, csv, matplotlib
2
- import tkinter as tk
3
- from tkinter import ttk, scrolledtext
4
- from ttkthemes import ThemedTk
5
- from matplotlib.figure import Figure
6
- from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
7
- from matplotlib.figure import Figure
8
- matplotlib.use('Agg')
9
- from tkinter import filedialog
10
- from multiprocessing import Process, Queue, Value
11
- import traceback
12
-
13
- try:
14
- ctypes.windll.shcore.SetProcessDpiAwareness(True)
15
- except AttributeError:
16
- pass
17
-
18
- from .logger import log_function_call
19
- from .gui_utils import ScrollableFrame, StdoutRedirector, create_dark_mode, set_dark_style, set_default_font, mask_variables, generate_fields, check_mask_gui_settings, add_mask_gui_defaults, preprocess_generate_masks_wrapper, process_stdout_stderr
20
- from .gui_utils import safe_literal_eval, clear_canvas, main_thread_update_function
21
-
22
- thread_control = {"run_thread": None, "stop_requested": False}
23
-
24
- @log_function_call
25
- def initiate_abort():
26
- global thread_control
27
- if thread_control.get("stop_requested") is not None:
28
- thread_control["stop_requested"].value = 1
29
-
30
- if thread_control.get("run_thread") is not None:
31
- thread_control["run_thread"].join(timeout=5)
32
- if thread_control["run_thread"].is_alive():
33
- thread_control["run_thread"].terminate()
34
- thread_control["run_thread"] = None
35
-
36
- @log_function_call
37
- def run_mask_gui(q, fig_queue, stop_requested):
38
- global vars_dict
39
- process_stdout_stderr(q)
40
- try:
41
- settings = check_mask_gui_settings(vars_dict)
42
- settings = add_mask_gui_defaults(settings)
43
- #for key in settings:
44
- # value = settings[key]
45
- # print(key, value, type(value))
46
- preprocess_generate_masks_wrapper(settings, q, fig_queue)
47
- except Exception as e:
48
- q.put(f"Error during processing: {e}")
49
- traceback.print_exc()
50
- finally:
51
- stop_requested.value = 1
52
-
53
- @log_function_call
54
- def start_process(q, fig_queue):
55
- global thread_control
56
- if thread_control.get("run_thread") is not None:
57
- initiate_abort()
58
-
59
- stop_requested = Value('i', 0) # multiprocessing shared value for inter-process communication
60
- thread_control["stop_requested"] = stop_requested
61
- thread_control["run_thread"] = Process(target=run_mask_gui, args=(q, fig_queue, stop_requested))
62
- thread_control["run_thread"].start()
63
-
64
- def import_settings(scrollable_frame):
65
- global vars_dict, original_variables_structure
66
-
67
- csv_file_path = filedialog.askopenfilename(filetypes=[("CSV files", "*.csv")])
68
-
69
- if not csv_file_path:
70
- return
71
-
72
- imported_variables = {}
73
-
74
- with open(csv_file_path, newline='') as csvfile:
75
- reader = csv.DictReader(csvfile)
76
- for row in reader:
77
- key = row['Key']
78
- value = row['Value']
79
- # Evaluate the value safely using safe_literal_eval
80
- imported_variables[key] = safe_literal_eval(value)
81
-
82
- # Track changed variables and apply the imported ones, printing changes as we go
83
- for key, var in vars_dict.items():
84
- if key in imported_variables and var.get() != imported_variables[key]:
85
- print(f"Updating '{key}' from '{var.get()}' to '{imported_variables[key]}'")
86
- var.set(imported_variables[key])
87
-
88
- @log_function_call
89
- def initiate_mask_root(width, height):
90
- global root, vars_dict, q, canvas, fig_queue, canvas_widget, thread_control
91
-
92
- theme = 'breeze'
93
-
94
- if theme in ['clam']:
95
- root = tk.Tk()
96
- style = ttk.Style(root)
97
- style.theme_use(theme) #plastik, clearlooks, elegance, default was clam #alt, breeze, arc
98
- set_dark_style(style)
99
- elif theme in ['breeze']:
100
- root = ThemedTk(theme="breeze")
101
- style = ttk.Style(root)
102
- set_dark_style(style)
103
-
104
- set_default_font(root, font_name="Arial", size=10)
105
- #root.state('zoomed') # For Windows to maximize the window
106
- root.attributes('-fullscreen', True)
107
- root.geometry(f"{width}x{height}")
108
- root.title("SpaCer: generate masks")
109
- fig_queue = Queue()
110
-
111
- def _process_fig_queue():
112
- global canvas
113
- try:
114
- while not fig_queue.empty():
115
- clear_canvas(canvas)
116
- fig = fig_queue.get_nowait()
117
- #set_fig_text_properties(fig, font_size=8)
118
- for ax in fig.get_axes():
119
- ax.set_xticks([]) # Remove x-axis ticks
120
- ax.set_yticks([]) # Remove y-axis ticks
121
- ax.xaxis.set_visible(False) # Hide the x-axis
122
- ax.yaxis.set_visible(False) # Hide the y-axis
123
- #ax.title.set_fontsize(14)
124
- #disable_interactivity(fig)
125
- fig.tight_layout()
126
- fig.set_facecolor('#333333')
127
- canvas.figure = fig
128
- fig_width, fig_height = canvas_widget.winfo_width(), canvas_widget.winfo_height()
129
- fig.set_size_inches(fig_width / fig.dpi, fig_height / fig.dpi, forward=True)
130
- canvas.draw_idle()
131
- except Exception as e:
132
- traceback.print_exc()
133
- #pass
134
- finally:
135
- canvas_widget.after(100, _process_fig_queue)
136
-
137
- # Process queue for console output
138
- def _process_console_queue():
139
- while not q.empty():
140
- message = q.get_nowait()
141
- console_output.insert(tk.END, message)
142
- console_output.see(tk.END)
143
- console_output.after(100, _process_console_queue)
144
-
145
- # Vertical container for settings and console
146
- vertical_container = tk.PanedWindow(root, orient=tk.HORIZONTAL) #VERTICAL
147
- vertical_container.pack(fill=tk.BOTH, expand=True)
148
-
149
- # Scrollable Frame for user settings
150
- scrollable_frame = ScrollableFrame(vertical_container, bg='#333333')
151
- vertical_container.add(scrollable_frame, stretch="always")
152
-
153
- # Setup for user input fields (variables)
154
- variables = mask_variables()
155
- vars_dict = generate_fields(variables, scrollable_frame)
156
-
157
- # Horizontal container for Matplotlib figure and the vertical pane (for settings and console)
158
- horizontal_container = tk.PanedWindow(vertical_container, orient=tk.VERTICAL) #HORIZONTAL
159
- vertical_container.add(horizontal_container, stretch="always")
160
-
161
- # Matplotlib figure setup
162
- figure = Figure(figsize=(30, 4), dpi=100, facecolor='#333333')
163
- plot = figure.add_subplot(111)
164
- plot.plot([], []) # This creates an empty plot.
165
- plot.axis('off')
166
-
167
- # Embedding the Matplotlib figure in the Tkinter window
168
- canvas = FigureCanvasTkAgg(figure, master=horizontal_container)
169
- canvas.get_tk_widget().configure(cursor='arrow', background='#333333', highlightthickness=0)
170
- #canvas.get_tk_widget().configure(cursor='arrow')
171
- canvas_widget = canvas.get_tk_widget()
172
- horizontal_container.add(canvas_widget, stretch="always")
173
- canvas.draw()
174
-
175
- # Console output setup below the settings
176
- console_output = scrolledtext.ScrolledText(vertical_container, height=10)
177
- vertical_container.add(console_output, stretch="always")
178
-
179
- # Queue and redirection setup for updating console output safely
180
- q = Queue()
181
- sys.stdout = StdoutRedirector(console_output)
182
- sys.stderr = StdoutRedirector(console_output)
183
-
184
- # This is your GUI setup where you create the Run button
185
- run_button = ttk.Button(scrollable_frame.scrollable_frame, text="Run",command=lambda: start_process(q, fig_queue))
186
- run_button.grid(row=40, column=0, pady=10)
187
-
188
- abort_button = ttk.Button(scrollable_frame.scrollable_frame, text="Abort", command=initiate_abort)
189
- abort_button.grid(row=40, column=1, pady=10)
190
-
191
- progress_label = ttk.Label(scrollable_frame.scrollable_frame, text="Processing: 0%", background="#333333", foreground="white")
192
- progress_label.grid(row=41, column=0, columnspan=2, sticky="ew", pady=(5, 0))
193
-
194
- # Create the Import Settings button
195
- import_btn = tk.Button(root, text="Import Settings", command=lambda: import_settings(scrollable_frame))
196
- import_btn.pack(pady=20)
197
-
198
- _process_console_queue()
199
- _process_fig_queue()
200
- create_dark_mode(root, style, console_output)
201
-
202
- root.after(100, lambda: main_thread_update_function(root, q, fig_queue, canvas_widget, progress_label))
203
-
204
- return root, vars_dict
205
-
206
- def gui_mask():
207
- global vars_dict, root
208
- root, vars_dict = initiate_mask_root(1000, 1500)
209
- root.mainloop()
210
-
211
- if __name__ == "__main__":
212
- gui_mask()
@@ -1,58 +0,0 @@
1
- import unittest
2
- from unittest.mock import MagicMock
3
- from annotate_app import ImageApp
4
- from PIL import Image
5
-
6
- class TestImageApp(unittest.TestCase):
7
- def setUp(self):
8
- self.root = MagicMock()
9
- self.db_path = '/path/to/database.db'
10
- self.image_type = 'png'
11
- self.channels = ['r', 'g']
12
- self.grid_rows = 2
13
- self.grid_cols = 2
14
- self.image_size = (200, 200)
15
- self.annotation_column = 'annotate'
16
- self.image_app = ImageApp(self.root, self.db_path, self.image_type, self.channels, self.grid_rows, self.grid_cols, self.image_size, self.annotation_column)
17
-
18
- def test_normalize_image(self):
19
- img = Image.open('/path/to/image.png')
20
- normalized_img = self.image_app.normalize_image(img)
21
- self.assertIsInstance(normalized_img, Image.Image)
22
- self.assertEqual(normalized_img.mode, 'RGB')
23
-
24
- def test_add_colored_border(self):
25
- img = Image.open('/path/to/image.png')
26
- border_width = 5
27
- border_color = 'teal'
28
- bordered_img = self.image_app.add_colored_border(img, border_width, border_color)
29
- self.assertIsInstance(bordered_img, Image.Image)
30
- self.assertEqual(bordered_img.mode, 'RGB')
31
-
32
- def test_filter_channels(self):
33
- img = Image.open('/path/to/image.png')
34
- filtered_img = self.image_app.filter_channels(img)
35
- self.assertIsInstance(filtered_img, Image.Image)
36
- self.assertEqual(filtered_img.mode, 'L')
37
-
38
- def test_load_single_image(self):
39
- path_annotation_tuple = ('/path/to/image.png', 1)
40
- img, annotation = self.image_app.load_single_image(path_annotation_tuple)
41
- self.assertIsInstance(img, Image.Image)
42
- self.assertEqual(img.mode, 'RGB')
43
- self.assertEqual(annotation, 1)
44
-
45
- def test_get_on_image_click(self):
46
- path = '/path/to/image.png'
47
- label = MagicMock()
48
- img = Image.open('/path/to/image.png')
49
- callback = self.image_app.get_on_image_click(path, label, img)
50
- event = MagicMock(num=1)
51
- callback(event)
52
- self.assertEqual(self.image_app.pending_updates[path], 1)
53
- event = MagicMock(num=3)
54
- callback(event)
55
- self.assertEqual(self.image_app.pending_updates[path], 2)
56
-
57
- if __name__ == '__main__':
58
- unittest.main()
spacr/test_plot.py DELETED
@@ -1,43 +0,0 @@
1
- import unittest
2
- from unittest.mock import MagicMock
3
- from spacr.plot import _save_scimg_plot
4
- from unittest.mock import patch
5
-
6
- class TestSaveScimgPlot(unittest.TestCase):
7
- def setUp(self):
8
- self.src = "/path/to/images"
9
- self.nr_imgs = 16
10
- self.channel_indices = [0, 1, 2]
11
- self.um_per_pixel = 0.1
12
- self.scale_bar_length_um = 10
13
- self.standardize = True
14
- self.fontsize = 8
15
- self.show_filename = True
16
- self.channel_names = None
17
- self.dpi = 300
18
- self.plot = False
19
- self.i = 1
20
- self.all_folders = 1
21
-
22
- def test_save_scimg_plot(self):
23
- # Mock necessary dependencies
24
- _save_figure_mock = MagicMock()
25
- _visualize_scimgs_mock = MagicMock(return_value="mocked_figure")
26
- _plot_images_on_grid_mock = MagicMock(return_value="mocked_figure")
27
-
28
- # Patch the dependencies
29
- with patch('spacr.plot._save_figure', _save_figure_mock), \
30
- patch('spacr.plot._visualize_scimgs', _visualize_scimgs_mock), \
31
- patch('spacr.plot._plot_images_on_grid', _plot_images_on_grid_mock):
32
-
33
- # Call the function
34
- _save_scimg_plot(self.src, self.nr_imgs, self.channel_indices, self.um_per_pixel, self.scale_bar_length_um, self.standardize, self.fontsize, self.show_filename, self.channel_names, self.dpi, self.plot, self.i, self.all_folders)
35
-
36
- # Add your assertions here
37
- _visualize_scimgs_mock.assert_called_with(self.src, self.channel_indices, self.um_per_pixel, self.scale_bar_length_um, self.show_filename, self.standardize, self.nr_imgs, self.fontsize, self.channel_names, self.plot)
38
- _save_figure_mock.assert_called_with("mocked_figure", self.src, text='all_channels')
39
- _plot_images_on_grid_mock.assert_called_with("mocked_figure", self.channel_indices, self.um_per_pixel, self.scale_bar_length_um, self.fontsize, self.show_filename, self.channel_names, self.plot)
40
- # Add more assertions for other function calls if needed
41
-
42
- if __name__ == '__main__':
43
- unittest.main()
spacr/test_train.py DELETED
@@ -1,39 +0,0 @@
1
- import unittest
2
- from unittest.mock import MagicMock
3
- from spacr.train import train_model
4
-
5
- class TestTrainModel(unittest.TestCase):
6
- def test_train_model_erm(self):
7
- # Mock necessary dependencies
8
- train_loaders = [
9
- MagicMock(), # training data loader 1
10
- MagicMock() # training data loader 2
11
- ]
12
- val_loaders = [
13
- MagicMock() # validation data loader
14
- ]
15
- test_loaders = [
16
- MagicMock() # test data loader
17
- ]
18
-
19
- # Call the function
20
- train_model('/path/to/save', 'model_type', train_loaders, ['loader1', 'loader2'], train_mode='erm', epochs=100, val_loaders=val_loaders, test_loaders=test_loaders)
21
-
22
- # Add your assertions here
23
- # ...
24
-
25
- def test_train_model_irm(self):
26
- # Mock necessary dependencies
27
- train_loaders = [
28
- MagicMock(), # training data loader 1
29
- MagicMock() # training data loader 2
30
- ]
31
-
32
- # Call the function
33
- train_model('/path/to/save', 'model_type', train_loaders, ['loader1', 'loader2'], train_mode='irm', epochs=100)
34
-
35
- # Add your assertions here
36
- # ...
37
-
38
- if __name__ == '__main__':
39
- unittest.main()
spacr/test_utils.py DELETED
@@ -1,33 +0,0 @@
1
- import unittest
2
- import numpy as np
3
- from spacr.utils import _filter_cp_masks
4
-
5
- class TestFilterCPMasks(unittest.TestCase):
6
- def test_filter_cp_masks(self):
7
- # Create dummy inputs
8
- masks = [np.array([[1, 1, 0], [1, 0, 0], [0, 0, 0]]), np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])]
9
- flows = [np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]])]
10
- filter_size = True
11
- minimum_size = 2
12
- maximum_size = 5
13
- remove_border_objects = True
14
- merge = True
15
- filter_dimm = True
16
- batch = np.zeros((2, 3, 3, 3))
17
- moving_avg_q1 = 0.0
18
- moving_avg_q3 = 0.0
19
- moving_count = 0
20
- plot = False
21
- figuresize = (10, 10)
22
-
23
- # Call the function
24
- filtered_masks = _filter_cp_masks(masks, flows, filter_size, minimum_size, maximum_size, remove_border_objects, merge, filter_dimm, batch, moving_avg_q1, moving_avg_q3, moving_count, plot, figuresize)
25
-
26
- # Add your assertions here
27
- self.assertEqual(len(filtered_masks), 2)
28
- self.assertTrue(np.array_equal(filtered_masks[0], np.array([[1, 1, 0], [1, 0, 0], [0, 0, 0]])))
29
- self.assertTrue(np.array_equal(filtered_masks[1], np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])))
30
- # Add more assertions as needed
31
-
32
- if __name__ == '__main__':
33
- unittest.main()
@@ -1,34 +0,0 @@
1
- spacr/__init__.py,sha256=Ma3U6mJeP3-2AYPWfsz70NByMY5q6r6AbaRZzgL_E8g,826
2
- spacr/__main__.py,sha256=_qRkhbFrH_cXr7AZs6KHL8Hh4VApqNdpNCtiKn2ePTo,285
3
- spacr/annotate_app.py,sha256=IPgZfS4TrSqbJr81P1FWUNOgCPPcS6EdQjUsXRwY-4E,19932
4
- spacr/cli.py,sha256=-cmIoI_E9UY_yimlMlSJDZrJGWOYwLZvnu8wU4lbC-A,12273
5
- spacr/core.py,sha256=r-i3EwmFXnLDidxmkWTs5-RwGZ-wy4IcnKJF5ntYf-M,109296
6
- spacr/graph_learning.py,sha256=IcjucYUjam8Oxck0h_pKSeyJ8ccYGniLqY-V8VUpUR8,3645
7
- spacr/gui_classify_app.py,sha256=vbweYUe4o4kF5aSvfHjIrAfMKq-6kFlO7otiZji1jZc,8439
8
- spacr/gui_mask_app.py,sha256=YSo72KqcQ3hlMwTerJmk4yS3c6Xt6Hcdc85GGluMlQE,8964
9
- spacr/gui_measure_app.py,sha256=157tCdhe__RViwj5pPUXP1g22HIgArAskaq5TmwIiM0,8534
10
- spacr/gui_sim_app.py,sha256=92pdbUb8n7hdNdPgXibtsBaMMFJTnzgdwajmzi6xsC4,8409
11
- spacr/gui_temp.py,sha256=pq286z2oULO6ed97YoHxv7RfdbY2enGoFQWpHC2JyH8,8473
12
- spacr/gui_utils.py,sha256=HlsTg98PvaM4AYEkVpqkAMbxDtneHtzogIQ01T2r3ZE,28582
13
- spacr/io.py,sha256=cvvAn9268jomFGfOFUtCZb1kPfvsbvmWqbvw2BMVRpw,95523
14
- spacr/logger.py,sha256=7Zqr3TuuOQLWT32gYr2q1qvv7x0a2JhLANmZcnBXAW8,670
15
- spacr/mask_app.py,sha256=B6-zYXVFg-cc58gLcz-Ry6LClO2jxLitL6B2ACb0HTw,39278
16
- spacr/measure.py,sha256=WFaPOysbCVM5f48NbBjBJj5JR-hZOWi4iFpai350Cqs,51366
17
- spacr/old_code.py,sha256=dbgDULLqhDQhB7ASWJZk3W9pm2MSA-8t-IR-mn70-mw,3280
18
- spacr/plot.py,sha256=9PNQNuI83SNzw3guEHGfrWJ2rCxdSP_jtO09dQaronI,54566
19
- spacr/sim.py,sha256=tl40lgTMeeJSyBq_c-Rn54C9Ri0FJ2zLkLLLPLSjz3o,51534
20
- spacr/test_annotate_app.py,sha256=yBWl_80PgP9jo1ClN0E1zSJVvzDeLCZHrlAvciS5KaY,2283
21
- spacr/test_plot.py,sha256=K2LhpbWtrpQ0BWhEKZOJi4E-NsmS0U8yjBdKxCwwAAc,2075
22
- spacr/test_train.py,sha256=qN3N6UvgeK2P-nQlG1HGgsTVZu4XYxXYI-oY7B5AioM,1217
23
- spacr/test_utils.py,sha256=0MUYmaqEJqUpTXKgj4mhdhUwWtzYkJLFV11T3wR826Q,1307
24
- spacr/timelapse.py,sha256=_j6cSVaxOhM7mTfJuNNRKogJaIGz_fM92MIegE6Ykh0,25355
25
- spacr/train.py,sha256=r77zLvLFMzx6MJxXG3JjynD8qTWYM9pNgrChEXYQhtY,25631
26
- spacr/umap.py,sha256=4QSrQ16Og-Ijq-SwguMQT2f20UWz1LE5HQeSLmzSl8c,29370
27
- spacr/utils.py,sha256=cyk0MMxCKCOUU3-vuGVxV9VUp0OOF7LaLs-UBCXAI3w,116764
28
- spacr/version.py,sha256=axH5tnGwtgSnJHb5IDhiu4Zjk5GhLyAEDRe-rnaoFOA,409
29
- spacr-0.0.17.dist-info/LICENSE,sha256=SR-2MeGc6SCM1UORJYyarSWY_A-JaOMFDj7ReSs9tRM,1083
30
- spacr-0.0.17.dist-info/METADATA,sha256=GuZ8EJR5Gxzv4mrXh4s8njEkMLty3eYGPksfh8q6yog,4108
31
- spacr-0.0.17.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
32
- spacr-0.0.17.dist-info/entry_points.txt,sha256=5uyJaAxWCbjWYwP15InAKU1yFxTwyuvCGtIGceso1es,290
33
- spacr-0.0.17.dist-info/top_level.txt,sha256=GJPU8FgwRXGzKeut6JopsSRY2R8T3i9lDgya42tLInY,6
34
- spacr-0.0.17.dist-info/RECORD,,