-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrescalefactors_GUI.py
More file actions
716 lines (573 loc) · 26.4 KB
/
Copy pathrescalefactors_GUI.py
File metadata and controls
716 lines (573 loc) · 26.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
import tkinter as tk
from tkinter import filedialog, messagebox
from PIL import Image, ImageDraw, ImageTk
import numpy as np
import anndata
import scanpy as sc
import os
import json
import gc
from shapely.geometry import Point, MultiPoint, LineString
from shapely.ops import unary_union, polygonize
from scipy.spatial import Delaunay
from sklearn.cluster import DBSCAN
from shapely.geometry import mapping
# import matplotlib.pyplot as plt
class CollapsibleSection(tk.Frame):
def __init__(self, parent, title="Section", *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.is_expanded = False
self.toggle_btn = tk.Button(self, text="▶ " + title, command=self.toggle)
self.toggle_btn.pack(anchor="w")
self.content = tk.Frame(self)
self.content.pack(fill="x", expand=True)
self.content.forget() # hide initially
def toggle(self):
if self.is_expanded:
self.content.forget()
self.toggle_btn.config(text="▶ " + self.toggle_btn.cget("text")[2:])
else:
self.content.pack(fill="x", expand=True)
self.toggle_btn.config(text="▼ " + self.toggle_btn.cget("text")[2:])
self.is_expanded = not self.is_expanded
class SpotOverlayApp:
def __init__(self, root):
self.root = root
self.root.title("Spot Overlay Viewer")
screen_width = self.root.winfo_screenwidth()
screen_height = self.root.winfo_screenheight()
self.max_display_size = (screen_height*0.9, screen_width*0.9)
# Use grid layout
root.rowconfigure(0, weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=0)
# Image frame (left)
self.image_frame = tk.Frame(root)
self.image_frame.grid(row=0, column=0, sticky="nsew")
# Canvas inside image frame
self.canvas = tk.Canvas(self.image_frame, bg="black")
self.canvas.pack(fill=tk.BOTH, expand=True)
# Drag n drop
self._dragging = False
self._drag_start = (0, 0)
# self.enable_canvas_zoom()
self.canvas.bind("<ButtonPress-1>", self.on_canvas_press)
self.canvas.bind("<B1-Motion>", self.on_canvas_drag)
self.canvas.bind("<ButtonRelease-1>", self.on_canvas_release)
# Control panel (right)
# Container for the scrollable side panel
side_container = tk.Frame(root, width=250)
side_container.grid(row=0, column=1, sticky="ns")
side_container.grid_propagate(False) # Prevent it from resizing to contents
# Canvas and scrollbar inside side container
side_canvas = tk.Canvas(side_container, width=250, borderwidth=0, highlightthickness=0)
scrollbar = tk.Scrollbar(side_container, orient="vertical", command=side_canvas.yview)
scrollbar.pack(side="right", fill="y")
side_canvas.pack(side="left", fill="both", expand=True)
# Frame that holds the actual controls
self.control_frame = tk.Frame(side_canvas, padx=10, pady=10)
side_window = side_canvas.create_window((0, 0), window=self.control_frame, anchor="nw")
def on_canvas_configure(event):
# Match embedded frame width to canvas width
side_canvas.itemconfig(side_window, width=event.width)
side_canvas.bind("<Configure>", on_canvas_configure)
# Configure scrolling region
def on_frame_configure(event):
side_canvas.configure(scrollregion=side_canvas.bbox("all"))
self.control_frame.bind("<Configure>", on_frame_configure)
side_canvas.configure(yscrollcommand=scrollbar.set)
# Enable mouse wheel scrolling
def _on_mousewheel(event):
side_canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
side_canvas.bind_all("<MouseWheel>", _on_mousewheel)
# Load Data button
load_btn = tk.Button(self.control_frame, text="Load AnnData", command=self.load_anndata)
load_btn.pack(pady=10, fill="x")
# Zoom canvas
self.add_zoom_buttons()
# Transformation sliders
tk.Button(self.control_frame, text="Reset to Default", command=self.reset_transformations).pack(pady=10, fill="x")
self.show_spots = tk.IntVar(value=1)
tk.Checkbutton(
self.control_frame,
text="Show Spots",
variable=self.show_spots,
command=self.redraw
).pack(anchor="w")
# self.show_clusters = tk.IntVar()
# tk.Checkbutton(
# self.control_frame,
# text="Show Cluster Outlines",
# variable=self.show_clusters,
# command=self.redraw
# ).pack(anchor="w")
# self.shapely_alpha = self.create_slider_with_entry("alpha", 0.01, 100, 0.1, resolution=0.01)
self.scalef_multiplier_log2 = self.create_momentum_slider("scalef multiplier", initial=0.0, speed=0.2)
self.shift_x = self.create_momentum_slider("Shift X", initial=0.0, speed=100)
self.shift_y = self.create_momentum_slider("Shift Y", initial=0.0, speed=100)
# Advanced
transform_section = CollapsibleSection(self.control_frame, title="Advanced")
transform_section.pack(fill="x", pady=5)
# Add transform widgets into section.content
self.spot_radius_multiplier_log2 = self.create_momentum_slider("spot_diameter_fullres multiplier", initial=0.0, speed=0.2, parent=transform_section.content)
self.scale_x_log2 = self.create_momentum_slider("Scale X", initial=0.0, speed=0.2, parent=transform_section.content)
self.scale_y_log2 = self.create_momentum_slider("Scale Y", initial=0.0, speed=0.2, parent=transform_section.content)
self.rotation = self.create_rotation_control(parent=transform_section.content)
self.flip_h = tk.IntVar()
self.flip_v = tk.IntVar()
tk.Checkbutton(transform_section.content, text="Flip Horizontally", variable=self.flip_h, command=self.redraw).pack(anchor="w")
tk.Checkbutton(transform_section.content, text="Flip Vertically", variable=self.flip_v, command=self.redraw).pack(anchor="w")
# Export
tk.Button(
self.control_frame,
text="Export TSVs",
command=self.export_transformed_data,
bg="#007BFF", # Bootstrap-style blue
fg="white", # White text for contrast
activebackground="#0056b3", # Darker blue on hover/click
activeforeground="white"
).pack(pady=10, fill="x")
tk.Button(
self.control_frame,
text="Export H5AD",
bg="#007BFF",
fg="white",
command=self.export_to_h5ad,
activebackground="#0056b3", # Darker blue on hover/click
activeforeground="white"
).pack(fill=tk.X, pady=5)
self.anndata = None
self.hires_image = None
self.spots = None
self.spot_ids = None
self.tk_image = None
self.spot_drawings = []
def add_zoom_buttons(self, parent=None):
parent = parent or self.control_frame
zoom_frame = tk.Frame(parent)
zoom_frame.pack(pady=5)
tk.Label(zoom_frame, text="Zoom:").pack(side=tk.LEFT)
tk.Button(zoom_frame, text="+", width=3, command=lambda: self.change_zoom(1.25)).pack(side=tk.LEFT)
tk.Button(zoom_frame, text="-", width=3, command=lambda: self.change_zoom(0.8)).pack(side=tk.LEFT)
# self.display_scale = 1
self.zoom_scale = 1
def change_zoom(self, factor):
self.zoom_scale *= factor
self.redraw(update_image=True)
def on_canvas_press(self, event):
self._dragging = True
self._drag_start = (event.x, event.y)
def on_canvas_drag(self, event):
if self._dragging:
dx = event.x - self._drag_start[0]
dy = event.y - self._drag_start[1]
self._drag_start = (event.x, event.y)
# Adjust shift_x and shift_y (in canvas units)
self.shift_x.set(self.shift_x.get() + dx)
self.shift_y.set(self.shift_y.get() + dy)
self.redraw()
def on_canvas_release(self, event):
self._dragging = False
def create_slider_with_entry(self, text, from_, to, initial, resolution=0.1, on_change=None, parent=None):
parent = parent or self.control_frame
frame = tk.Frame(parent)
frame.pack(fill=tk.X, pady=2)
label = tk.Label(frame, text=text)
label.pack(anchor="w")
var = tk.DoubleVar(value=initial)
def on_var_change(val=None):
if on_change:
on_change(var.get())
self.redraw()
slider = tk.Scale(frame, variable=var, from_=from_, to=to,
orient=tk.HORIZONTAL, resolution=resolution,
command=lambda e: on_var_change())
slider.pack(fill=tk.X)
entry = tk.Entry(frame, textvariable=var, width=6)
entry.pack(anchor="e")
entry.bind("<Return>", lambda e: on_var_change())
return var
def create_momentum_slider(self, text, initial=1.0, speed=0.1, parent=None):
parent = parent or self.control_frame
frame = tk.Frame(parent)
frame.pack(fill=tk.X, pady=5)
label = tk.Label(frame, text=text)
label.pack(anchor="w")
value_var = tk.DoubleVar(value=initial)
slider_var = tk.IntVar(value=0) # Centered
entry = tk.Entry(frame, textvariable=value_var, width=6)
entry.pack(anchor="e")
slider = tk.Scale(frame, from_=-100, to=100, variable=slider_var,
orient=tk.HORIZONTAL, showvalue=False)
slider.pack(fill="x")
running = {"active": False}
def update_value():
if not running["active"]:
return
delta = slider_var.get()
if delta != 0:
scale = (abs(delta) / 100) ** 1.5
step = speed * scale * (1 if delta > 0 else -1)
new_val = value_var.get() + step
value_var.set(round(new_val, 4)) # round for clarity
self.redraw()
slider.after(50, update_value)
def on_press(event):
running["active"] = True
update_value()
def on_release(event):
running["active"] = False
slider_var.set(0)
def on_entry(event=None):
try:
val = float(entry.get())
value_var.set(val)
self.redraw()
except ValueError:
pass # ignore bad input
slider.bind("<ButtonPress-1>", on_press)
slider.bind("<ButtonRelease-1>", on_release)
entry.bind("<Return>", on_entry)
return value_var
def create_rotation_control(self, parent=None):
parent = parent or self.control_frame
frame = tk.Frame(parent)
frame.pack(fill="x", pady=5)
label = tk.Label(frame, text="Rotation (°)")
label.pack(anchor="w")
self.rotation_var = tk.DoubleVar(value=0)
entry = tk.Entry(frame, textvariable=self.rotation_var, width=6)
entry.pack(anchor="e")
entry.bind("<Return>", lambda e: self.redraw())
btn_frame = tk.Frame(frame)
btn_frame.pack()
def rotate(delta):
self.rotation_var.set(self.rotation_var.get() + delta)
self.redraw()
tk.Button(btn_frame, text="⟲ CCW", command=lambda: rotate(-90)).pack(side=tk.LEFT)
tk.Button(btn_frame, text="⟳ CW", command=lambda: rotate(90)).pack(side=tk.LEFT)
return self.rotation_var
def reset_transformations(self):
self.shift_x.set(0)
self.shift_y.set(0)
self.spot_radius_multiplier_log2.set(0)
self.scalef_multiplier_log2.set(0)
self.scale_x_log2.set(0)
self.scale_y_log2.set(0)
self.flip_h.set(0)
self.flip_v.set(0)
self.rotation_var.set(0)
self.spots_scaled = self.original_spots_scaled.copy()
self.redraw()
def load_anndata(self):
file_path = filedialog.askopenfilename(filetypes=[("h5ad files", "*.h5ad")])
if not file_path:
return
# Clean cache
self.anndata = None
self.tk_image = None
self.canvas.delete("all")
gc.collect()
self.anndata = anndata.read_h5ad(file_path)
if len(self.anndata.uns["spatial"]) == 1:
self.lib_id = list(self.anndata.uns["spatial"].keys())[0]
else:
raise Exception('Check lib_id')
# Get hires image and coordinates
img_data = self.anndata.uns["spatial"]
lib_id = list(img_data.keys())[0]
image_info = img_data[lib_id]["images"]["hires"]
# image_path = img_data[lib_id]["metadata"].get("source_image_path", None)
# Load image as PIL.Image
if isinstance(image_info, np.ndarray):
image = Image.fromarray(image_info)
# elif image_path:
# image = Image.open(image_path)
else:
raise ValueError("No valid hires image found.")
self.original_image = image
original_size = image.size
# Resize for display
image = self.resize_image(image)
self.tk_image = ImageTk.PhotoImage(image)
self.canvas.config(width=image.width, height=image.height)
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.tk_image)
# Compute scale factor for spot coordinate display
self.display_scale = image.width / original_size[0]
self.zoom_scale = 1
# Load and scale coordinates
self.spots = self.anndata.obsm["spatial"]
self.spots = self.spots[~np.isnan(self.spots).any(axis=1)]
try:
self.spot_radius = img_data[lib_id]["scalefactors"]["spot_diameter_fullres"] / 2
except KeyError:
self.spot_radius = 1
try:
self.scalefactor = img_data[lib_id]["scalefactors"]["tissue_hires_scalef"]
except KeyError:
self.scalefactor = 1
self.spots_scaled = self.spots * self.scalefactor * self.display_scale
self.original_spots_scaled = self.spots_scaled.copy()
# Normalize spots to fit canvas if needed
# canvas_w = self.tk_image.width()
# canvas_h = self.tk_image.height()
# if self.all_spots_outside_canvas(self.spots_scaled, canvas_w, canvas_h):
# print("[INFO] All spots outside canvas — normalizing to fit")
# self.spots_scaled = self.normalize_spots_to_canvas(
# self.spots_scaled, canvas_w, canvas_h
# )
self.update_window_title()
self.redraw()
def resize_image(self, image, zoom_scale=1.0):
max_w, max_h = self.max_display_size
w, h = image.size
scale = min(max_w / w, max_h / h, 1.0)
new_size = (int(w * scale * zoom_scale), int(h * scale * zoom_scale))
return image.resize(new_size, Image.LANCZOS)
def all_spots_outside_canvas(self, coords, canvas_w, canvas_h, margin=0):
x_valid = (coords[:, 0] >= -margin) & (coords[:, 0] <= canvas_w + margin)
y_valid = (coords[:, 1] >= -margin) & (coords[:, 1] <= canvas_h + margin)
inside = x_valid & y_valid
return not np.any(inside)
def normalize_spots_to_canvas(self, coords, canvas_width, canvas_height, padding=20):
# 1. Get bounding box
min_x, min_y = coords.min(axis=0)
max_x, max_y = coords.max(axis=0)
# 2. Compute scale
spot_width = max_x - min_x
spot_height = max_y - min_y
scale_x = (canvas_width - 2 * padding) / spot_width
scale_y = (canvas_height - 2 * padding) / spot_height
scale = min(scale_x, scale_y) # Uniform scale to preserve aspect
# 3. Apply scale and shift
coords_norm = (coords - [min_x, min_y]) * scale + [padding, padding]
return coords_norm
def transform_spots(self, spots, mode=None):
spots = spots.copy()
# Apply shift
shift_x = self.shift_x.get()
shift_y = self.shift_y.get()
if mode == 'export':
shift_x = shift_x / self.scalefactor / self.display_scale
shift_y = shift_y / self.scalefactor / self.display_scale
spots[:, 0] += shift_x
spots[:, 1] += shift_y
# Apply flip (screen-aligned)
if self.flip_h.get():
spots[:, 0] = 2 * np.mean(spots[:, 0]) - spots[:, 0]
if self.flip_v.get():
spots[:, 1] = 2 * np.mean(spots[:, 1]) - spots[:, 1]
# Apply scale (screen-aligned)
cx, cy = np.mean(spots[:, 0]), np.mean(spots[:, 1])
spots[:, 0] = cx + (spots[:, 0] - cx) * 2**self.scale_x_log2.get()
spots[:, 1] = cy + (spots[:, 1] - cy) * 2**self.scale_y_log2.get()
# Now apply rotation (final)
angle = np.deg2rad(self.rotation_var.get())
R = np.array([
[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)],
])
centered = spots - [cx, cy]
rotated = centered @ R.T
transformed = rotated + [cx, cy]
return transformed
def __draw_cluster_outlines(self, spots, min_samples=3):
# Filter out NaNs
valid = ~np.isnan(spots).any(axis=1)
spots = spots[valid]
if len(spots) < 3:
return
# Try auto-increasing EPS until we find at least one cluster
max_eps = 200
for eps in range(1, max_eps + 1, 5):
clustering = DBSCAN(eps=eps, min_samples=min_samples).fit(spots)
labels = clustering.labels_
if len(set(labels)) > 1 and any(l != -1 for l in labels):
break # Found valid clusters
# self.cluster_eps.set(eps) # Update slider if shown
# Cluster with DBSCAN
eps = self.shapely_alpha.get()
clustering = DBSCAN(eps=eps, min_samples=min_samples).fit(spots)
labels = clustering.labels_
for label in set(labels):
if label == -1:
continue # noise
cluster_pts = spots[labels == label]
if len(cluster_pts) < 3:
continue
shape = __alpha_shape(cluster_pts, alpha=self.shapely_alpha.get()) # Adjust alpha as needed
if not shape.is_empty:
coords = list(mapping(shape)["coordinates"])
for ring in coords:
flat = [coord for point in ring for coord in point]
self.canvas.create_polygon(*flat, outline="red", fill="", width=2)
def __draw_spots_outline(self, transformed_spots, r):
r = self.shapely_alpha.get()
# Only take valid points
valid_points = [(x, y) for x, y in transformed_spots if not np.isnan(x) and not np.isnan(y)]
if not valid_points:
return
# Expand each point into a small circle for more natural outline
circles = [Point(x, y).buffer(r) for x, y in valid_points]
merged_shape = unary_union(circles)
# Get exterior coordinates of the merged polygon
if merged_shape.geom_type == "Polygon":
coords = list(merged_shape.exterior.coords)
flat_coords = [coord for xy in coords for coord in xy]
self.canvas.create_line(*flat_coords, fill="blue", width=2)
else:
for poly in merged_shape.geoms: # MultiPolygon
coords = list(poly.exterior.coords)
flat_coords = [coord for xy in coords for coord in xy]
self.canvas.create_line(*flat_coords, fill="blue", width=2)
def __render_spots_image(self):
# Create blank RGBA image the size of your canvas
img = Image.new("RGBA", (self.image_width, self.image_height), (0, 0, 0, 0))
draw = ImageDraw.Draw(img)
# Draw all spots
for x, y in self.spots:
r = self.spot_radius
draw.ellipse([x-r, y-r, x+r, y+r], fill=(255, 0, 0, 128))
return ImageTk.PhotoImage(img)
def redraw(self, update_image=False):
# Resize image according to zoom
if update_image:
scaled_image = self.resize_image(self.original_image, self.zoom_scale)
self.tk_image = ImageTk.PhotoImage(scaled_image)
self.canvas.create_image(0, 0, anchor=tk.NW, image=self.tk_image)
# Draw image boundary
self.canvas.delete("canvas_frame")
self.canvas.create_rectangle(
0, 0,
self.tk_image.width(), self.tk_image.height(),
outline="blue", width=2, tags=("canvas_frame")
)
# Remove old spots without touching background
self.canvas.delete("spot")
# Transform and draw spots (scale coordinates by zoom)
transformed_spots = self.transform_spots(self.spots_scaled) * 2**self.scalef_multiplier_log2.get()
transformed_spots *= self.zoom_scale
# Spot radius also scaled by zoom
r = self.spot_radius * 2**self.spot_radius_multiplier_log2.get() \
* self.scalefactor * 2**self.scalef_multiplier_log2.get() \
* self.zoom_scale \
* self.display_scale
self.spot_drawings.clear()
if self.show_spots.get():
for x, y in transformed_spots:
if not np.isnan(x) and not np.isnan(y):
oval = self.canvas.create_oval(x - r, y - r, x + r, y + r,
fill="blue", outline="black", tags=("spot"))
self.spot_drawings.append(oval)
# if self.show_clusters.get():
# self.draw_cluster_outlines(transformed_spots)
# self.draw_spots_outline(transformed_spots, r)
def export_transformed_data(self):
import os
from tkinter import filedialog
import json
# Ask for save directory
out_dir = filedialog.askdirectory(title="Choose export directory")
if not out_dir:
return
# Create original + transformed coords
full_spots = self.anndata.obsm["spatial"]
valid_mask = ~np.isnan(full_spots).any(axis=1)
transformed_coords = np.full_like(full_spots, np.nan)
# Transform only valid spots
valid_spots = full_spots[valid_mask]
scalefactor_hires = self.scalefactor * 2**self.scalef_multiplier_log2.get()
# Working but shift x shift y
spots_scaled = valid_spots
transformed = self.transform_spots(spots_scaled, mode='export')
transformed_coords[valid_mask] = transformed
# Get barcodes
barcodes = self.anndata.obs_names
# Save TSV
tsv_path = os.path.join(out_dir, "transformed_coords.tsv")
with open(tsv_path, "w") as f:
f.write("barcode\tx\ty\n")
for bc, coord in zip(barcodes, transformed_coords):
x, y = coord
x_str = "" if np.isnan(x) else f"{x:.2f}"
y_str = "" if np.isnan(y) else f"{y:.2f}"
f.write(f"{bc}\t{x_str}\t{y_str}\n")
print(f"[INFO] Saved coordinates to: {tsv_path}")
# Save scalefactors.json
json_path = os.path.join(out_dir, "scalefactors_json.json")
scalefactors = {
"spot_diameter_fullres": 2 * self.spot_radius * 2**self.spot_radius_multiplier_log2.get(),
"tissue_hires_scalef": float(scalefactor_hires),
"tissue_lowres_scalef": 1.0 # You can change this if needed
}
with open(json_path, "w") as jf:
json.dump(scalefactors, jf, indent=2)
print(f"[INFO] Saved scalefactors to: {json_path}")
messagebox.showinfo("Export Complete", f"Data exported successfully:\n{out_dir}")
def export_to_h5ad(self):
if not hasattr(self, "anndata"):
print("[ERROR] No AnnData object loaded.")
return
# Ask where to save the new h5ad
current_filename = f"{self.lib_id}.h5ad"
save_path = filedialog.asksaveasfilename(
title="Save transformed AnnData",
initialfile=os.path.basename(current_filename),
defaultextension=".h5ad",
filetypes=[("H5AD files", "*.h5ad"), ("All files", "*.*")])
if not save_path:
return
adata = self.anndata.copy()
# Extract original coords
full_spots = adata.obsm["spatial"]
valid_mask = ~np.isnan(full_spots).any(axis=1)
transformed_coords = np.full_like(full_spots, np.nan, dtype=np.float64)
# Scale factor
scalefactor_hires = self.scalefactor * 2**self.scalef_multiplier_log2.get()
# Transform only valid spots
spots_scaled = full_spots[valid_mask].astype(np.float64, copy=True)
transformed = self.transform_spots(spots_scaled, mode='export')
transformed_coords[valid_mask] = transformed
# Update the AnnData object
adata.obsm["spatial"] = transformed_coords
# Update scalefactors if stored in uns
if "scalefactors" not in adata.uns["spatial"][self.lib_id]:
adata.uns["spatial"][self.lib_id]["scalefactors"] = {}
adata.uns["spatial"][self.lib_id]["scalefactors"].update({
"spot_diameter_fullres": float(2 * self.spot_radius * 2**self.spot_radius_multiplier_log2.get()),
"tissue_hires_scalef": float(scalefactor_hires),
"tissue_lowres_scalef": 1.0
})
# Save updated AnnData
adata.write_h5ad(save_path)
print(f"[INFO] Saved updated h5ad: {save_path}")
messagebox.showinfo("Export Complete", f"Data exported successfully:\n{save_path}")
def update_window_title(self):
if getattr(self, "lib_id", None):
self.root.title(f"Spot Overlay Viewer - {self.lib_id}")
else:
self.root.title("Spot Overlay Viewer")
def __alpha_shape(points, alpha):
if len(points) < 4:
return MultiPoint(points).convex_hull
tri = Delaunay(points)
edges = set()
for ia, ib, ic in tri.simplices:
pa, pb, pc = points[ia], points[ib], points[ic]
a = np.linalg.norm(pa - pb)
b = np.linalg.norm(pb - pc)
c = np.linalg.norm(pc - pa)
s = (a + b + c) / 2.0
area = max(s * (s - a) * (s - b) * (s - c), 1e-10)
circum_r = a * b * c / (4.0 * np.sqrt(area))
if circum_r < 1.0 / alpha:
edges.update([(ia, ib), (ib, ic), (ic, ia)])
edge_points = [(points[i], points[j]) for i, j in edges]
m = unary_union([LineString([p1, p2]) for p1, p2 in edge_points])
triangles = list(polygonize(m))
return unary_union(triangles)
if __name__ == "__main__":
root = tk.Tk()
app = SpotOverlayApp(root)
print('[INFO] App started\n')
root.mainloop()