spacr 0.0.36__py3-none-any.whl → 0.0.62__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/__init__.py +11 -4
- spacr/__main__.py +0 -2
- spacr/alpha.py +514 -2
- spacr/annotate_app.py +112 -116
- spacr/core.py +864 -728
- spacr/deep_spacr.py +696 -0
- spacr/foldseek.py +2 -16
- spacr/graph_learning.py +297 -253
- spacr/gui.py +9 -8
- spacr/gui_2.py +90 -0
- spacr/gui_classify_app.py +3 -4
- spacr/gui_mask_app.py +9 -9
- spacr/gui_measure_app.py +3 -5
- spacr/gui_utils.py +132 -33
- spacr/io.py +308 -464
- spacr/mask_app.py +109 -5
- spacr/measure.py +15 -1
- spacr/models/cp/toxo_pv_lumen.CP_model +0 -0
- spacr/old_code.py +69 -1
- spacr/plot.py +23 -6
- spacr/sequencing.py +1130 -0
- spacr/sim.py +0 -42
- spacr/timelapse.py +0 -1
- spacr/train.py +172 -13
- spacr/umap.py +0 -689
- spacr/utils.py +1322 -75
- {spacr-0.0.36.dist-info → spacr-0.0.62.dist-info}/METADATA +14 -29
- spacr-0.0.62.dist-info/RECORD +39 -0
- {spacr-0.0.36.dist-info → spacr-0.0.62.dist-info}/entry_points.txt +1 -0
- spacr-0.0.36.dist-info/RECORD +0 -35
- {spacr-0.0.36.dist-info → spacr-0.0.62.dist-info}/LICENSE +0 -0
- {spacr-0.0.36.dist-info → spacr-0.0.62.dist-info}/WHEEL +0 -0
- {spacr-0.0.36.dist-info → spacr-0.0.62.dist-info}/top_level.txt +0 -0
spacr/__init__.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1
1
|
from spacr.version import version, version_str
|
2
2
|
import logging
|
3
|
+
import torch
|
3
4
|
|
4
5
|
from . import core
|
5
6
|
from . import io
|
@@ -8,10 +9,9 @@ from . import plot
|
|
8
9
|
from . import measure
|
9
10
|
from . import sim
|
10
11
|
from . import timelapse
|
11
|
-
from . import
|
12
|
+
from . import deep_spacr
|
12
13
|
from . import mask_app
|
13
14
|
from . import annotate_app
|
14
|
-
from . import graph_learning
|
15
15
|
from . import gui_utils
|
16
16
|
from . import gui_mask_app
|
17
17
|
from . import gui_measure_app
|
@@ -26,9 +26,8 @@ __all__ = [
|
|
26
26
|
"measure",
|
27
27
|
"sim",
|
28
28
|
"timelapse",
|
29
|
-
"
|
29
|
+
"deep_spacr",
|
30
30
|
"annotate_app",
|
31
|
-
"graph_learning",
|
32
31
|
"gui_utils",
|
33
32
|
"mask_app",
|
34
33
|
"gui_mask_app",
|
@@ -37,5 +36,13 @@ __all__ = [
|
|
37
36
|
"logger"
|
38
37
|
]
|
39
38
|
|
39
|
+
# Check for CUDA GPU availability
|
40
|
+
if torch.cuda.is_available():
|
41
|
+
from . import graph_learning
|
42
|
+
__all__.append("graph_learning")
|
43
|
+
logging.info("CUDA GPU detected. Graph learning module loaded.")
|
44
|
+
else:
|
45
|
+
logging.info("No CUDA GPU detected. Graph learning module not loaded.")
|
46
|
+
|
40
47
|
logging.basicConfig(filename='spacr.log', level=logging.INFO,
|
41
48
|
format='%(asctime)s:%(levelname)s:%(message)s')
|
spacr/__main__.py
CHANGED
spacr/alpha.py
CHANGED
@@ -1,7 +1,6 @@
|
|
1
1
|
from skimage import measure, feature
|
2
2
|
from skimage.filters import gabor
|
3
3
|
from skimage.color import rgb2gray
|
4
|
-
from skimage.feature.texture import greycomatrix, greycoprops, local_binary_pattern
|
5
4
|
from skimage.util import img_as_ubyte
|
6
5
|
import numpy as np
|
7
6
|
import pandas as pd
|
@@ -11,13 +10,15 @@ import pywt
|
|
11
10
|
import os
|
12
11
|
import pandas as pd
|
13
12
|
from PIL import Image
|
14
|
-
from torchvision import transforms
|
15
13
|
import torch
|
16
14
|
import torch.nn as nn
|
17
15
|
import torch.nn.functional as F
|
18
16
|
from torch_geometric.data import Data, DataLoader
|
19
17
|
from torch_geometric.nn import GCNConv, global_mean_pool
|
20
18
|
from torch.optim import Adam
|
19
|
+
import os
|
20
|
+
import shutil
|
21
|
+
import random
|
21
22
|
|
22
23
|
# Step 1: Data Preparation
|
23
24
|
|
@@ -149,6 +150,10 @@ def spacr_transformer(image_dir, seq_file, nr_grnas=1350, lr=0.001, mode='train'
|
|
149
150
|
else:
|
150
151
|
raise ValueError('Invalid mode. Use "train" or "eval".')
|
151
152
|
|
153
|
+
from skimage.feature import greycomatrix
|
154
|
+
|
155
|
+
from skimage.feature import greycoprops
|
156
|
+
|
152
157
|
def _calculate_glcm_features(intensity_image):
|
153
158
|
glcm = greycomatrix(img_as_ubyte(intensity_image), distances=[1, 2, 3, 4], angles=[0, np.pi/4, np.pi/2, 3*np.pi/4], symmetric=True, normed=True)
|
154
159
|
features = {}
|
@@ -158,6 +163,8 @@ def _calculate_glcm_features(intensity_image):
|
|
158
163
|
features[f'glcm_{prop}_d{distance}_a{angle}'] = greycoprops(glcm, prop)[i, j]
|
159
164
|
return features
|
160
165
|
|
166
|
+
from skimage.feature import local_binary_pattern
|
167
|
+
|
161
168
|
def _calculate_lbp_features(intensity_image, P=8, R=1):
|
162
169
|
lbp = local_binary_pattern(intensity_image, P, R, method='uniform')
|
163
170
|
lbp_hist, _ = np.histogram(lbp, density=True, bins=np.arange(0, P + 3), range=(0, P + 2))
|
@@ -293,3 +300,508 @@ def _intensity_measurements(cell_mask, nucleus_mask, pathogen_mask, cytoplasm_ma
|
|
293
300
|
|
294
301
|
return pd.concat(cell_dfs, axis=1), pd.concat(nucleus_dfs, axis=1), pd.concat(pathogen_dfs, axis=1), pd.concat(cytoplasm_dfs, axis=1)
|
295
302
|
|
303
|
+
def sample_and_copy_images(folder_list, nr_of_images, dst):
|
304
|
+
|
305
|
+
if isinstance(folder_list, str):
|
306
|
+
folder_list = [folder_list]
|
307
|
+
|
308
|
+
# Create the destination folder if it does not exist
|
309
|
+
if not os.path.exists(dst):
|
310
|
+
os.makedirs(dst)
|
311
|
+
|
312
|
+
# Calculate the number of images to sample from each folder
|
313
|
+
nr_of_images_per_folder = nr_of_images // len(folder_list)
|
314
|
+
|
315
|
+
print(f"Sampling {nr_of_images_per_folder} images from {len(folder_list)} folders...")
|
316
|
+
# Initialize a list to hold the paths of the images to be copied
|
317
|
+
images_to_copy = []
|
318
|
+
|
319
|
+
for folder in folder_list:
|
320
|
+
# Get a list of all files in the current folder
|
321
|
+
all_files = [os.path.join(folder, file) for file in os.listdir(folder)]
|
322
|
+
|
323
|
+
# Filter out non-image files
|
324
|
+
image_files = [file for file in all_files if file.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp', '.gif', '.tiff', '.tif'))]
|
325
|
+
|
326
|
+
# Sample images randomly from the list
|
327
|
+
sampled_images = random.sample(image_files, min(nr_of_images_per_folder, len(image_files)))
|
328
|
+
|
329
|
+
# Add the sampled images to the list of images to copy
|
330
|
+
images_to_copy.extend(sampled_images)
|
331
|
+
|
332
|
+
# Copy the sampled images to the destination folder
|
333
|
+
for image in images_to_copy:
|
334
|
+
shutil.copy(image, os.path.join(dst, os.path.basename(image)))
|
335
|
+
|
336
|
+
import os
|
337
|
+
import torch
|
338
|
+
import torch.nn as nn
|
339
|
+
import torch.nn.functional as F
|
340
|
+
from collections import defaultdict
|
341
|
+
from torch.utils.data import Dataset, DataLoader
|
342
|
+
import pandas as pd
|
343
|
+
import numpy as np
|
344
|
+
import torch.optim as optim
|
345
|
+
|
346
|
+
def generate_graphs(sequencing, scores, cell_min, gene_min_read):
|
347
|
+
# Load and preprocess sequencing (gene) data
|
348
|
+
gene_df = pd.read_csv(sequencing)
|
349
|
+
gene_df = gene_df.rename(columns={'prc': 'well_id', 'grna': 'gene_id', 'count': 'read_count'})
|
350
|
+
# Filter out genes with read counts less than gene_min_read
|
351
|
+
gene_df = gene_df[gene_df['read_count'] >= gene_min_read]
|
352
|
+
total_reads_per_well = gene_df.groupby('well_id')['read_count'].sum().reset_index(name='total_reads')
|
353
|
+
gene_df = gene_df.merge(total_reads_per_well, on='well_id')
|
354
|
+
gene_df['well_read_fraction'] = gene_df['read_count'] / gene_df['total_reads']
|
355
|
+
|
356
|
+
# Load and preprocess cell score data
|
357
|
+
cell_df = pd.read_csv(scores)
|
358
|
+
cell_df = cell_df[['prcfo', 'prc', 'pred']].rename(columns={'prcfo': 'cell_id', 'prc': 'well_id', 'pred': 'score'})
|
359
|
+
|
360
|
+
# Create a global mapping of gene IDs to indices
|
361
|
+
unique_genes = gene_df['gene_id'].unique()
|
362
|
+
gene_id_to_index = {gene_id: index for index, gene_id in enumerate(unique_genes)}
|
363
|
+
|
364
|
+
graphs = []
|
365
|
+
for well_id in pd.unique(gene_df['well_id']):
|
366
|
+
well_genes = gene_df[gene_df['well_id'] == well_id]
|
367
|
+
well_cells = cell_df[cell_df['well_id'] == well_id]
|
368
|
+
|
369
|
+
# Skip wells with no cells or genes or with fewer cells than threshold
|
370
|
+
if well_cells.empty or well_genes.empty or len(well_cells) < cell_min:
|
371
|
+
continue
|
372
|
+
|
373
|
+
# Initialize gene features tensor with zeros for all unique genes
|
374
|
+
gene_features = torch.zeros((len(gene_id_to_index), 1), dtype=torch.float)
|
375
|
+
|
376
|
+
# Update gene features tensor with well_read_fraction for genes present in this well
|
377
|
+
for _, row in well_genes.iterrows():
|
378
|
+
gene_index = gene_id_to_index[row['gene_id']]
|
379
|
+
gene_features[gene_index] = torch.tensor([[row['well_read_fraction']]])
|
380
|
+
|
381
|
+
# Prepare cell features (scores)
|
382
|
+
cell_features = torch.tensor(well_cells['score'].values, dtype=torch.float).view(-1, 1)
|
383
|
+
|
384
|
+
num_genes = len(gene_id_to_index)
|
385
|
+
num_cells = cell_features.size(0)
|
386
|
+
num_nodes = num_genes + num_cells
|
387
|
+
|
388
|
+
# Create adjacency matrix connecting each cell to all genes in the well
|
389
|
+
adj = torch.zeros((num_nodes, num_nodes), dtype=torch.float)
|
390
|
+
for _, row in well_genes.iterrows():
|
391
|
+
gene_index = gene_id_to_index[row['gene_id']]
|
392
|
+
adj[num_genes:, gene_index] = 1
|
393
|
+
|
394
|
+
graph = {
|
395
|
+
'adjacency_matrix': adj,
|
396
|
+
'gene_features': gene_features,
|
397
|
+
'cell_features': cell_features,
|
398
|
+
'num_cells': num_cells,
|
399
|
+
'num_genes': num_genes
|
400
|
+
}
|
401
|
+
graphs.append(graph)
|
402
|
+
|
403
|
+
print(f'Generated dataset with {len(graphs)} graphs')
|
404
|
+
return graphs, gene_id_to_index
|
405
|
+
|
406
|
+
def print_graphs_info(graphs, gene_id_to_index):
|
407
|
+
# Invert the gene_id_to_index mapping for easy lookup
|
408
|
+
index_to_gene_id = {v: k for k, v in gene_id_to_index.items()}
|
409
|
+
|
410
|
+
for i, graph in enumerate(graphs, start=1):
|
411
|
+
print(f"Graph {i}:")
|
412
|
+
num_genes = graph['num_genes']
|
413
|
+
num_cells = graph['num_cells']
|
414
|
+
gene_features = graph['gene_features']
|
415
|
+
cell_features = graph['cell_features']
|
416
|
+
|
417
|
+
print(f" Number of Genes: {num_genes}")
|
418
|
+
print(f" Number of Cells: {num_cells}")
|
419
|
+
|
420
|
+
# Identify genes present in the graph based on non-zero feature values
|
421
|
+
present_genes = [index_to_gene_id[idx] for idx, feature in enumerate(gene_features) if feature.item() > 0]
|
422
|
+
print(" Genes present in this Graph:", present_genes)
|
423
|
+
|
424
|
+
# Display gene features for genes present in the graph
|
425
|
+
print(" Gene Features:")
|
426
|
+
for gene_id in present_genes:
|
427
|
+
idx = gene_id_to_index[gene_id]
|
428
|
+
print(f" {gene_id}: {gene_features[idx].item()}")
|
429
|
+
|
430
|
+
# Display a sample of cell features, for brevity
|
431
|
+
print(" Cell Features (sample):")
|
432
|
+
for idx, feature in enumerate(cell_features[:min(5, len(cell_features))]):
|
433
|
+
print(f"Cell {idx+1}: {feature.item()}")
|
434
|
+
|
435
|
+
print("-" * 40)
|
436
|
+
|
437
|
+
class Attention(nn.Module):
|
438
|
+
def __init__(self, feature_dim, attn_dim, dropout_rate=0.1):
|
439
|
+
super(Attention, self).__init__()
|
440
|
+
self.query = nn.Linear(feature_dim, attn_dim)
|
441
|
+
self.key = nn.Linear(feature_dim, attn_dim)
|
442
|
+
self.value = nn.Linear(feature_dim, feature_dim)
|
443
|
+
self.scale = 1.0 / (attn_dim ** 0.5)
|
444
|
+
self.dropout = nn.Dropout(dropout_rate)
|
445
|
+
|
446
|
+
def forward(self, gene_features, cell_features):
|
447
|
+
# Queries come from the cell features
|
448
|
+
q = self.query(cell_features)
|
449
|
+
# Keys and values come from the gene features
|
450
|
+
k = self.key(gene_features)
|
451
|
+
v = self.value(gene_features)
|
452
|
+
|
453
|
+
# Compute attention weights
|
454
|
+
attn_weights = torch.matmul(q, k.transpose(-2, -1)) * self.scale
|
455
|
+
attn_weights = F.softmax(attn_weights, dim=-1)
|
456
|
+
# Apply dropout to attention weights
|
457
|
+
attn_weights = self.dropout(attn_weights)
|
458
|
+
|
459
|
+
# Apply attention weights to the values
|
460
|
+
attn_output = torch.matmul(attn_weights, v)
|
461
|
+
|
462
|
+
return attn_output, attn_weights
|
463
|
+
|
464
|
+
class GraphTransformer(nn.Module):
|
465
|
+
def __init__(self, gene_feature_size, cell_feature_size, hidden_dim, output_dim, attn_dim, dropout_rate=0.1):
|
466
|
+
super(GraphTransformer, self).__init__()
|
467
|
+
self.gene_transform = nn.Linear(gene_feature_size, hidden_dim)
|
468
|
+
self.cell_transform = nn.Linear(cell_feature_size, hidden_dim)
|
469
|
+
self.dropout = nn.Dropout(dropout_rate)
|
470
|
+
|
471
|
+
# Attention layer to let each cell attend to all genes
|
472
|
+
self.attention = Attention(hidden_dim, attn_dim)
|
473
|
+
|
474
|
+
# This layer is used to transform the combined features after attention
|
475
|
+
self.combine_transform = nn.Linear(2 * hidden_dim, hidden_dim)
|
476
|
+
|
477
|
+
# Output layer for predicting cell scores, ensuring it matches the number of cells
|
478
|
+
self.cell_output = nn.Linear(hidden_dim, output_dim)
|
479
|
+
|
480
|
+
def forward(self, adjacency_matrix, gene_features, cell_features):
|
481
|
+
# Apply initial transformation to gene and cell features
|
482
|
+
transformed_gene_features = F.relu(self.gene_transform(gene_features))
|
483
|
+
transformed_cell_features = F.relu(self.cell_transform(cell_features))
|
484
|
+
|
485
|
+
# Incorporate attention mechanism
|
486
|
+
attn_output, attn_weights = self.attention(transformed_gene_features, transformed_cell_features)
|
487
|
+
|
488
|
+
# Combine the transformed cell features with the attention output features
|
489
|
+
combined_cell_features = torch.cat((transformed_cell_features, attn_output), dim=1)
|
490
|
+
|
491
|
+
# Apply dropout here as well
|
492
|
+
combined_cell_features = self.dropout(combined_cell_features)
|
493
|
+
|
494
|
+
combined_cell_features = F.relu(self.combine_transform(combined_cell_features))
|
495
|
+
|
496
|
+
# Combine gene and cell features for message passing
|
497
|
+
combined_features = torch.cat((transformed_gene_features, combined_cell_features), dim=0)
|
498
|
+
|
499
|
+
# Apply message passing via adjacency matrix multiplication
|
500
|
+
message_passed_features = torch.matmul(adjacency_matrix, combined_features)
|
501
|
+
|
502
|
+
# Predict cell scores from the post-message passed cell features
|
503
|
+
cell_scores = self.cell_output(message_passed_features[-cell_features.size(0):])
|
504
|
+
|
505
|
+
return cell_scores, attn_weights
|
506
|
+
|
507
|
+
def train_graph_transformer(graphs, lr=0.01, dropout_rate=0.1, weight_decay=0.00001, epochs=100, save_fldr='', acc_threshold = 0.1):
|
508
|
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
509
|
+
model = GraphTransformer(gene_feature_size=1, cell_feature_size=1, hidden_dim=256, output_dim=1, attn_dim=128, dropout_rate=dropout_rate).to(device)
|
510
|
+
|
511
|
+
criterion = nn.MSELoss()
|
512
|
+
#optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
513
|
+
optimizer = optim.AdamW(model.parameters(), lr=lr, weight_decay=weight_decay)
|
514
|
+
|
515
|
+
training_log = []
|
516
|
+
|
517
|
+
accumulate_grad_batches=1
|
518
|
+
threshold=acc_threshold
|
519
|
+
|
520
|
+
for epoch in range(epochs):
|
521
|
+
model.train()
|
522
|
+
total_loss = 0
|
523
|
+
total_correct = 0
|
524
|
+
total_samples = 0
|
525
|
+
optimizer.zero_grad()
|
526
|
+
batch_count = 0 # Initialize batch_count
|
527
|
+
|
528
|
+
for graph in graphs:
|
529
|
+
adjacency_matrix = graph['adjacency_matrix'].to(device)
|
530
|
+
gene_features = graph['gene_features'].to(device)
|
531
|
+
cell_features = graph['cell_features'].to(device)
|
532
|
+
num_cells = graph['num_cells']
|
533
|
+
predictions, attn_weights = model(adjacency_matrix, gene_features, cell_features)
|
534
|
+
predictions = predictions.squeeze()
|
535
|
+
true_scores = cell_features[:num_cells, 0]
|
536
|
+
loss = criterion(predictions, true_scores) / accumulate_grad_batches
|
537
|
+
loss.backward()
|
538
|
+
|
539
|
+
# Calculate "accuracy"
|
540
|
+
with torch.no_grad():
|
541
|
+
correct_predictions = (torch.abs(predictions - true_scores) / true_scores <= threshold).sum().item()
|
542
|
+
total_correct += correct_predictions
|
543
|
+
total_samples += num_cells
|
544
|
+
|
545
|
+
batch_count += 1 # Increment batch_count
|
546
|
+
if batch_count % accumulate_grad_batches == 0 or batch_count == len(graphs):
|
547
|
+
optimizer.step()
|
548
|
+
optimizer.zero_grad()
|
549
|
+
|
550
|
+
total_loss += loss.item() * accumulate_grad_batches
|
551
|
+
|
552
|
+
accuracy = total_correct / total_samples
|
553
|
+
training_log.append({"Epoch": epoch+1, "Average Loss": total_loss / len(graphs), "Accuracy": accuracy})
|
554
|
+
print(f"Epoch {epoch+1}, Loss: {total_loss / len(graphs)}, Accuracy: {accuracy}", end="\r", flush=True)
|
555
|
+
|
556
|
+
# Save the training log and model as before
|
557
|
+
os.makedirs(save_fldr, exist_ok=True)
|
558
|
+
log_path = os.path.join(save_fldr, 'training_log.csv')
|
559
|
+
training_log_df = pd.DataFrame(training_log)
|
560
|
+
training_log_df.to_csv(log_path, index=False)
|
561
|
+
print(f"Training log saved to {log_path}")
|
562
|
+
|
563
|
+
model_path = os.path.join(save_fldr, 'model.pth')
|
564
|
+
torch.save(model.state_dict(), model_path)
|
565
|
+
print(f"Model saved to {model_path}")
|
566
|
+
|
567
|
+
return model
|
568
|
+
|
569
|
+
def annotate_cells_with_genes(graphs, model, gene_id_to_index):
|
570
|
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
571
|
+
model.to(device)
|
572
|
+
model.eval()
|
573
|
+
annotated_data = []
|
574
|
+
|
575
|
+
with torch.no_grad():
|
576
|
+
for graph in graphs:
|
577
|
+
adjacency_matrix = graph['adjacency_matrix'].to(device)
|
578
|
+
gene_features = graph['gene_features'].to(device)
|
579
|
+
cell_features = graph['cell_features'].to(device)
|
580
|
+
|
581
|
+
predictions, attn_weights = model(adjacency_matrix, gene_features, cell_features)
|
582
|
+
predictions = np.atleast_1d(predictions.squeeze().cpu().numpy())
|
583
|
+
attn_weights = np.atleast_2d(attn_weights.squeeze().cpu().numpy())
|
584
|
+
|
585
|
+
# This approach assumes all genes in gene_id_to_index are used in the model.
|
586
|
+
# Create a list of gene IDs present in this specific graph.
|
587
|
+
present_gene_ids = [key for key, value in gene_id_to_index.items() if value < gene_features.size(0)]
|
588
|
+
|
589
|
+
for cell_idx in range(cell_features.size(0)):
|
590
|
+
true_score = cell_features[cell_idx, 0].item()
|
591
|
+
predicted_score = predictions[cell_idx]
|
592
|
+
|
593
|
+
# Find the index of the most probable gene.
|
594
|
+
most_probable_gene_idx = attn_weights[cell_idx].argmax()
|
595
|
+
|
596
|
+
if len(present_gene_ids) > most_probable_gene_idx: # Ensure index is within the range
|
597
|
+
most_probable_gene_id = present_gene_ids[most_probable_gene_idx]
|
598
|
+
most_probable_gene_score = attn_weights[cell_idx, most_probable_gene_idx] if attn_weights.ndim > 1 else attn_weights[most_probable_gene_idx]
|
599
|
+
|
600
|
+
annotated_data.append({
|
601
|
+
"Cell ID": cell_idx,
|
602
|
+
"Most Probable Gene": most_probable_gene_id,
|
603
|
+
"Cell Score": true_score,
|
604
|
+
"Predicted Cell Score": predicted_score,
|
605
|
+
"Probability Score for Highest Gene": most_probable_gene_score
|
606
|
+
})
|
607
|
+
else:
|
608
|
+
# Handle the case where the index is out of bounds - this should not happen but is here for robustness
|
609
|
+
print("Error: Gene index out of bounds. This might indicate a mismatch in the model's output.")
|
610
|
+
|
611
|
+
return pd.DataFrame(annotated_data)
|
612
|
+
|
613
|
+
import torch
|
614
|
+
import torch.nn as nn
|
615
|
+
import torch.nn.functional as F
|
616
|
+
from torch.utils.data import Dataset, DataLoader, TensorDataset
|
617
|
+
|
618
|
+
# Let's assume that the feature embedding part and the dataset loading part
|
619
|
+
# has already been taken care of, and your data is already in the format
|
620
|
+
# suitable for PyTorch (i.e., Tensors).
|
621
|
+
|
622
|
+
class FeatureEmbedder(nn.Module):
|
623
|
+
def __init__(self, vocab_sizes, embedding_size):
|
624
|
+
super(FeatureEmbedder, self).__init__()
|
625
|
+
self.embeddings = nn.ModuleDict({
|
626
|
+
key: nn.Embedding(num_embeddings=vocab_size+1,
|
627
|
+
embedding_dim=embedding_size,
|
628
|
+
padding_idx=vocab_size)
|
629
|
+
for key, vocab_size in vocab_sizes.items()
|
630
|
+
})
|
631
|
+
# Adding the 'visit' embedding
|
632
|
+
self.embeddings['visit'] = nn.Parameter(torch.zeros(1, embedding_size))
|
633
|
+
|
634
|
+
def forward(self, feature_map, max_num_codes):
|
635
|
+
# Implementation will depend on how you want to handle sparse data
|
636
|
+
# This is just a placeholder
|
637
|
+
embeddings = {}
|
638
|
+
masks = {}
|
639
|
+
for key, tensor in feature_map.items():
|
640
|
+
embeddings[key] = self.embeddings[key](tensor.long())
|
641
|
+
mask = torch.ones_like(tensor, dtype=torch.float32)
|
642
|
+
masks[key] = mask.unsqueeze(-1)
|
643
|
+
|
644
|
+
# Batch size hardcoded for simplicity in example
|
645
|
+
batch_size = 1 # Replace with actual batch size
|
646
|
+
embeddings['visit'] = self.embeddings['visit'].expand(batch_size, -1, -1)
|
647
|
+
masks['visit'] = torch.ones(batch_size, 1)
|
648
|
+
|
649
|
+
return embeddings, masks
|
650
|
+
|
651
|
+
class GraphConvolutionalTransformer(nn.Module):
|
652
|
+
def __init__(self, embedding_size=128, num_attention_heads=1, **kwargs):
|
653
|
+
super(GraphConvolutionalTransformer, self).__init__()
|
654
|
+
# Transformer Blocks
|
655
|
+
self.layers = nn.ModuleList([
|
656
|
+
nn.TransformerEncoderLayer(
|
657
|
+
d_model=embedding_size,
|
658
|
+
nhead=num_attention_heads,
|
659
|
+
batch_first=True)
|
660
|
+
for _ in range(kwargs.get('num_transformer_stack', 3))
|
661
|
+
])
|
662
|
+
# Output Layer for Classification
|
663
|
+
self.output_layer = nn.Linear(embedding_size, 1)
|
664
|
+
|
665
|
+
def feedforward(self, features, mask=None, training=None):
|
666
|
+
# Implement feedforward logic (placeholder)
|
667
|
+
pass
|
668
|
+
|
669
|
+
def forward(self, embeddings, masks, mask=None, training=False):
|
670
|
+
features = embeddings
|
671
|
+
attentions = [] # Storing attentions if needed
|
672
|
+
|
673
|
+
# Pass through each Transformer block
|
674
|
+
for layer in self.layers:
|
675
|
+
features = layer(features) # Apply transformer encoding here
|
676
|
+
|
677
|
+
if mask is not None:
|
678
|
+
features = features * mask
|
679
|
+
|
680
|
+
logits = self.output_layer(features[:, 0, :]) # Using the 'visit' embedding for classification
|
681
|
+
return logits, attentions
|
682
|
+
|
683
|
+
# Usage Example
|
684
|
+
#vocab_sizes = {'dx_ints':3249, 'proc_ints':2210}
|
685
|
+
#embedding_size = 128
|
686
|
+
#gct_params = {
|
687
|
+
# 'embedding_size': embedding_size,
|
688
|
+
# 'num_transformer_stack': 3,
|
689
|
+
# 'num_attention_heads': 1
|
690
|
+
#}
|
691
|
+
#feature_embedder = FeatureEmbedder(vocab_sizes, embedding_size)
|
692
|
+
#gct_model = GraphConvolutionalTransformer(**gct_params)
|
693
|
+
#
|
694
|
+
# Assume `feature_map` is a dictionary of tensors, and `max_num_codes` is provided
|
695
|
+
#embeddings, masks = feature_embedder(feature_map, max_num_codes)
|
696
|
+
#logits, attentions = gct_model(embeddings, masks)
|
697
|
+
|
698
|
+
import torch
|
699
|
+
import torchvision.transforms as transforms
|
700
|
+
from torchvision.models import resnet50
|
701
|
+
from PIL import Image
|
702
|
+
import numpy as np
|
703
|
+
import umap
|
704
|
+
import pandas as pd
|
705
|
+
from sklearn.ensemble import RandomForestClassifier
|
706
|
+
from sklearn.preprocessing import StandardScaler
|
707
|
+
from scipy.stats import f_oneway, kruskal
|
708
|
+
from sklearn.cluster import KMeans
|
709
|
+
from scipy import stats
|
710
|
+
|
711
|
+
def load_image(image_path):
|
712
|
+
"""Load and preprocess an image."""
|
713
|
+
transform = transforms.Compose([
|
714
|
+
transforms.Resize((224, 224)),
|
715
|
+
transforms.ToTensor(),
|
716
|
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
|
717
|
+
])
|
718
|
+
image = Image.open(image_path).convert('RGB')
|
719
|
+
image = transform(image).unsqueeze(0)
|
720
|
+
return image
|
721
|
+
|
722
|
+
def extract_features(image_paths, resnet=resnet50):
|
723
|
+
"""Extract features from images using a pre-trained ResNet model."""
|
724
|
+
model = resnet(pretrained=True)
|
725
|
+
model = model.eval()
|
726
|
+
model = torch.nn.Sequential(*list(model.children())[:-1]) # Remove the last classification layer
|
727
|
+
|
728
|
+
features = []
|
729
|
+
for image_path in image_paths:
|
730
|
+
image = load_image(image_path)
|
731
|
+
with torch.no_grad():
|
732
|
+
feature = model(image).squeeze().numpy()
|
733
|
+
features.append(feature)
|
734
|
+
|
735
|
+
return np.array(features)
|
736
|
+
|
737
|
+
def check_normality(series):
|
738
|
+
"""Helper function to check if a feature is normally distributed."""
|
739
|
+
k2, p = stats.normaltest(series)
|
740
|
+
alpha = 0.05
|
741
|
+
if p < alpha: # null hypothesis: x comes from a normal distribution
|
742
|
+
return False
|
743
|
+
return True
|
744
|
+
|
745
|
+
def random_forest_feature_importance(all_df, cluster_col='cluster'):
|
746
|
+
"""Random Forest feature importance."""
|
747
|
+
numeric_features = all_df.select_dtypes(include=[np.number]).columns.tolist()
|
748
|
+
if cluster_col in numeric_features:
|
749
|
+
numeric_features.remove(cluster_col)
|
750
|
+
|
751
|
+
X = all_df[numeric_features]
|
752
|
+
y = all_df[cluster_col]
|
753
|
+
|
754
|
+
scaler = StandardScaler()
|
755
|
+
X_scaled = scaler.fit_transform(X)
|
756
|
+
|
757
|
+
model = RandomForestClassifier(n_estimators=100, random_state=42)
|
758
|
+
model.fit(X_scaled, y)
|
759
|
+
|
760
|
+
feature_importances = model.feature_importances_
|
761
|
+
|
762
|
+
importance_df = pd.DataFrame({
|
763
|
+
'Feature': numeric_features,
|
764
|
+
'Importance': feature_importances
|
765
|
+
}).sort_values(by='Importance', ascending=False)
|
766
|
+
|
767
|
+
return importance_df
|
768
|
+
|
769
|
+
def perform_statistical_tests(all_df, cluster_col='cluster'):
|
770
|
+
"""Perform ANOVA or Kruskal-Wallis tests depending on normality of features."""
|
771
|
+
numeric_features = all_df.select_dtypes(include=[np.number]).columns.tolist()
|
772
|
+
if cluster_col in numeric_features:
|
773
|
+
numeric_features.remove(cluster_col)
|
774
|
+
|
775
|
+
anova_results = []
|
776
|
+
kruskal_results = []
|
777
|
+
|
778
|
+
for feature in numeric_features:
|
779
|
+
groups = [all_df[all_df[cluster_col] == label][feature] for label in np.unique(all_df[cluster_col])]
|
780
|
+
|
781
|
+
if check_normality(all_df[feature]):
|
782
|
+
stat, p = f_oneway(*groups)
|
783
|
+
anova_results.append((feature, stat, p))
|
784
|
+
else:
|
785
|
+
stat, p = kruskal(*groups)
|
786
|
+
kruskal_results.append((feature, stat, p))
|
787
|
+
|
788
|
+
anova_df = pd.DataFrame(anova_results, columns=['Feature', 'ANOVA_Statistic', 'ANOVA_pValue'])
|
789
|
+
kruskal_df = pd.DataFrame(kruskal_results, columns=['Feature', 'Kruskal_Statistic', 'Kruskal_pValue'])
|
790
|
+
|
791
|
+
return anova_df, kruskal_df
|
792
|
+
|
793
|
+
def combine_results(rf_df, anova_df, kruskal_df):
|
794
|
+
"""Combine the results into a single DataFrame."""
|
795
|
+
combined_df = rf_df.merge(anova_df, on='Feature', how='left')
|
796
|
+
combined_df = combined_df.merge(kruskal_df, on='Feature', how='left')
|
797
|
+
return combined_df
|
798
|
+
|
799
|
+
def cluster_feature_analysis(all_df, cluster_col='cluster'):
|
800
|
+
"""
|
801
|
+
Perform Random Forest feature importance, ANOVA for normally distributed features,
|
802
|
+
and Kruskal-Wallis for non-normally distributed features. Combine results into a single DataFrame.
|
803
|
+
"""
|
804
|
+
rf_df = random_forest_feature_importance(all_df, cluster_col)
|
805
|
+
anova_df, kruskal_df = perform_statistical_tests(all_df, cluster_col)
|
806
|
+
combined_df = combine_results(rf_df, anova_df, kruskal_df)
|
807
|
+
return combined_df
|