spacr 0.2.65__tar.gz → 0.2.66__tar.gz

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.
Files changed (121) hide show
  1. {spacr-0.2.65/spacr.egg-info → spacr-0.2.66}/PKG-INFO +3 -1
  2. {spacr-0.2.65 → spacr-0.2.66}/setup.py +3 -21
  3. {spacr-0.2.65 → spacr-0.2.66}/spacr/__init__.py +0 -8
  4. {spacr-0.2.65 → spacr-0.2.66}/spacr/gui.py +9 -0
  5. {spacr-0.2.65 → spacr-0.2.66}/spacr/utils.py +11 -1
  6. {spacr-0.2.65 → spacr-0.2.66/spacr.egg-info}/PKG-INFO +3 -1
  7. {spacr-0.2.65 → spacr-0.2.66}/spacr.egg-info/SOURCES.txt +0 -1
  8. {spacr-0.2.65 → spacr-0.2.66}/spacr.egg-info/requires.txt +2 -0
  9. spacr-0.2.65/spacr/graph_learning.py +0 -340
  10. {spacr-0.2.65 → spacr-0.2.66}/LICENSE +0 -0
  11. {spacr-0.2.65 → spacr-0.2.66}/MANIFEST.in +0 -0
  12. {spacr-0.2.65 → spacr-0.2.66}/README.rst +0 -0
  13. {spacr-0.2.65 → spacr-0.2.66}/setup.cfg +0 -0
  14. {spacr-0.2.65 → spacr-0.2.66}/spacr/__main__.py +0 -0
  15. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_annotate.py +0 -0
  16. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_classify.py +0 -0
  17. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_make_masks.py +0 -0
  18. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_mask.py +0 -0
  19. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_measure.py +0 -0
  20. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_sequencing.py +0 -0
  21. {spacr-0.2.65 → spacr-0.2.66}/spacr/app_umap.py +0 -0
  22. {spacr-0.2.65 → spacr-0.2.66}/spacr/core.py +0 -0
  23. {spacr-0.2.65 → spacr-0.2.66}/spacr/deep_spacr.py +0 -0
  24. {spacr-0.2.65 → spacr-0.2.66}/spacr/gui_core.py +0 -0
  25. {spacr-0.2.65 → spacr-0.2.66}/spacr/gui_elements.py +0 -0
  26. {spacr-0.2.65 → spacr-0.2.66}/spacr/gui_utils.py +0 -0
  27. {spacr-0.2.65 → spacr-0.2.66}/spacr/io.py +0 -0
  28. {spacr-0.2.65 → spacr-0.2.66}/spacr/logger.py +0 -0
  29. {spacr-0.2.65 → spacr-0.2.66}/spacr/measure.py +0 -0
  30. {spacr-0.2.65 → spacr-0.2.66}/spacr/plot.py +0 -0
  31. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/OFL.txt +0 -0
  32. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/OpenSans-Italic-VariableFont_wdth,wght.ttf +0 -0
  33. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/OpenSans-VariableFont_wdth,wght.ttf +0 -0
  34. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/README.txt +0 -0
  35. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-Bold.ttf +0 -0
  36. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-BoldItalic.ttf +0 -0
  37. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-ExtraBold.ttf +0 -0
  38. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-ExtraBoldItalic.ttf +0 -0
  39. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-Italic.ttf +0 -0
  40. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-Light.ttf +0 -0
  41. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-LightItalic.ttf +0 -0
  42. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-Medium.ttf +0 -0
  43. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-MediumItalic.ttf +0 -0
  44. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-Regular.ttf +0 -0
  45. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-SemiBold.ttf +0 -0
  46. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans-SemiBoldItalic.ttf +0 -0
  47. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-Bold.ttf +0 -0
  48. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-BoldItalic.ttf +0 -0
  49. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-ExtraBold.ttf +0 -0
  50. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-ExtraBoldItalic.ttf +0 -0
  51. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-Italic.ttf +0 -0
  52. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-Light.ttf +0 -0
  53. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-LightItalic.ttf +0 -0
  54. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-Medium.ttf +0 -0
  55. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-MediumItalic.ttf +0 -0
  56. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-Regular.ttf +0 -0
  57. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-SemiBold.ttf +0 -0
  58. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_Condensed-SemiBoldItalic.ttf +0 -0
  59. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-Bold.ttf +0 -0
  60. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-BoldItalic.ttf +0 -0
  61. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-ExtraBold.ttf +0 -0
  62. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-ExtraBoldItalic.ttf +0 -0
  63. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-Italic.ttf +0 -0
  64. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-Light.ttf +0 -0
  65. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-LightItalic.ttf +0 -0
  66. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-Medium.ttf +0 -0
  67. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-MediumItalic.ttf +0 -0
  68. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-Regular.ttf +0 -0
  69. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-SemiBold.ttf +0 -0
  70. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/font/open_sans/static/OpenSans_SemiCondensed-SemiBoldItalic.ttf +0 -0
  71. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/abort.png +0 -0
  72. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/annotate.png +0 -0
  73. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/cellpose_all.png +0 -0
  74. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/cellpose_masks.png +0 -0
  75. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/classify.png +0 -0
  76. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/default.png +0 -0
  77. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/download.png +0 -0
  78. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/logo.pdf +0 -0
  79. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/logo_spacr.png +0 -0
  80. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/logo_spacr_1.png +0 -0
  81. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/make_masks.png +0 -0
  82. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/map_barcodes.png +0 -0
  83. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/mask.png +0 -0
  84. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/measure.png +0 -0
  85. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/ml_analyze.png +0 -0
  86. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/recruitment.png +0 -0
  87. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/regression.png +0 -0
  88. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/run.png +0 -0
  89. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/sequencing.png +0 -0
  90. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/settings.png +0 -0
  91. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/spacr_logo_rotation.gif +0 -0
  92. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/train_cellpose.png +0 -0
  93. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/icons/umap.png +0 -0
  94. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/models/cp/toxo_plaque_cyto_e25000_X1120_Y1120.CP_model +0 -0
  95. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/models/cp/toxo_plaque_cyto_e25000_X1120_Y1120.CP_model_settings.csv +0 -0
  96. {spacr-0.2.65 → spacr-0.2.66}/spacr/resources/models/cp/toxo_pv_lumen.CP_model +0 -0
  97. {spacr-0.2.65 → spacr-0.2.66}/spacr/sequencing.py +0 -0
  98. {spacr-0.2.65 → spacr-0.2.66}/spacr/settings.py +0 -0
  99. {spacr-0.2.65 → spacr-0.2.66}/spacr/sim.py +0 -0
  100. {spacr-0.2.65 → spacr-0.2.66}/spacr/sim_app.py +0 -0
  101. {spacr-0.2.65 → spacr-0.2.66}/spacr/timelapse.py +0 -0
  102. {spacr-0.2.65 → spacr-0.2.66}/spacr/version.py +0 -0
  103. {spacr-0.2.65 → spacr-0.2.66}/spacr.egg-info/dependency_links.txt +0 -0
  104. {spacr-0.2.65 → spacr-0.2.66}/spacr.egg-info/entry_points.txt +0 -0
  105. {spacr-0.2.65 → spacr-0.2.66}/spacr.egg-info/top_level.txt +0 -0
  106. {spacr-0.2.65 → spacr-0.2.66}/tests/test_annotate_app.py +0 -0
  107. {spacr-0.2.65 → spacr-0.2.66}/tests/test_core.py +0 -0
  108. {spacr-0.2.65 → spacr-0.2.66}/tests/test_gui_classify_app.py +0 -0
  109. {spacr-0.2.65 → spacr-0.2.66}/tests/test_gui_mask_app.py +0 -0
  110. {spacr-0.2.65 → spacr-0.2.66}/tests/test_gui_measure_app.py +0 -0
  111. {spacr-0.2.65 → spacr-0.2.66}/tests/test_gui_sim_app.py +0 -0
  112. {spacr-0.2.65 → spacr-0.2.66}/tests/test_gui_utils.py +0 -0
  113. {spacr-0.2.65 → spacr-0.2.66}/tests/test_io.py +0 -0
  114. {spacr-0.2.65 → spacr-0.2.66}/tests/test_mask_app.py +0 -0
  115. {spacr-0.2.65 → spacr-0.2.66}/tests/test_measure.py +0 -0
  116. {spacr-0.2.65 → spacr-0.2.66}/tests/test_plot.py +0 -0
  117. {spacr-0.2.65 → spacr-0.2.66}/tests/test_sim.py +0 -0
  118. {spacr-0.2.65 → spacr-0.2.66}/tests/test_timelapse.py +0 -0
  119. {spacr-0.2.65 → spacr-0.2.66}/tests/test_train.py +0 -0
  120. {spacr-0.2.65 → spacr-0.2.66}/tests/test_umap.py +0 -0
  121. {spacr-0.2.65 → spacr-0.2.66}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: spacr
3
- Version: 0.2.65
3
+ Version: 0.2.66
4
4
  Summary: Spatial phenotype analysis of crisp screens (SpaCr)
5
5
  Home-page: https://github.com/EinarOlafsson/spacr
6
6
  Author: Einar Birnir Olafsson
@@ -14,6 +14,8 @@ Requires-Dist: torchvision<1.0,>=0.1
14
14
  Requires-Dist: torch-geometric<3.0,>=2.5
15
15
  Requires-Dist: numpy<2.0,>=1.26.4
16
16
  Requires-Dist: pandas<3.0,>=2.2.1
17
+ Requires-Dist: bottleneck<2.0,>=1.3.6
18
+ Requires-Dist: numexpr<3.0,>=2.8.4
17
19
  Requires-Dist: statsmodels<1.0,>=0.14.1
18
20
  Requires-Dist: scikit-image<1.0,>=0.22.0
19
21
  Requires-Dist: scikit-learn<2.0,>=1.4.1
@@ -1,15 +1,6 @@
1
1
  from setuptools import setup, find_packages
2
2
  import subprocess
3
3
 
4
- # Function to determine the CUDA version
5
- def get_cuda_version():
6
- try:
7
- output = subprocess.check_output(['nvcc', '--version'], stderr=subprocess.STDOUT).decode('utf-8')
8
- if 'release' in output:
9
- return output.split('release ')[1].split(',')[0].replace('.', '')
10
- except (subprocess.CalledProcessError, FileNotFoundError):
11
- return None
12
-
13
4
  # Ensure you have read the README.rst content into a variable, e.g., `long_description`
14
5
  with open("README.rst", "r", encoding="utf-8") as fh:
15
6
  long_description = fh.read()
@@ -20,6 +11,8 @@ dependencies = [
20
11
  'torch-geometric>=2.5,<3.0',
21
12
  'numpy>=1.26.4,<2.0',
22
13
  'pandas>=2.2.1,<3.0',
14
+ 'bottleneck>=1.3.6,<2.0',
15
+ 'numexpr>=2.8.4,<3.0',
23
16
  'statsmodels>=0.14.1,<1.0',
24
17
  'scikit-image>=0.22.0,<1.0',
25
18
  'scikit-learn>=1.4.1,<2.0',
@@ -56,7 +49,7 @@ dependencies = [
56
49
 
57
50
  setup(
58
51
  name="spacr",
59
- version="0.2.65",
52
+ version="0.2.66",
60
53
  author="Einar Birnir Olafsson",
61
54
  author_email="olafsson@med.umich.com",
62
55
  description="Spatial phenotype analysis of crisp screens (SpaCr)",
@@ -89,17 +82,6 @@ setup(
89
82
  ]
90
83
  )
91
84
 
92
- cuda_version = get_cuda_version()
93
-
94
- if cuda_version:
95
- dgl = f'dgl-cu{cuda_version}==0.9.1'
96
- else:
97
- dgl = 'dgl==0.9.1' # Fallback to CPU version if no CUDA is detected
98
- try:
99
- subprocess.run(['pip', 'install', dgl], check=True)
100
- except subprocess.CalledProcessError:
101
- subprocess.run(['pip', 'install', 'dgl'], check=True)
102
-
103
85
  deps = ['pyqtgraph>=0.13.7,<0.14',
104
86
  'pyqt6>=6.7.1,<6.8',
105
87
  'pyqt6.sip',
@@ -51,13 +51,5 @@ __all__ = [
51
51
  "logger"
52
52
  ]
53
53
 
54
- # Check for CUDA GPU availability
55
- if torch.cuda.is_available():
56
- from . import graph_learning
57
- __all__.append("graph_learning")
58
- logging.info("CUDA GPU detected. Graph learning module loaded.")
59
- else:
60
- logging.info("No CUDA GPU detected. Graph learning module not loaded.")
61
-
62
54
  logging.basicConfig(filename='spacr.log', level=logging.INFO,
63
55
  format='%(asctime)s:%(levelname)s:%(message)s')
@@ -7,6 +7,15 @@ from .gui_core import initiate_root
7
7
  class MainApp(tk.Tk):
8
8
  def __init__(self, default_app=None):
9
9
  super().__init__()
10
+
11
+ # Initialize the window
12
+ self.geometry("100x100")
13
+ self.update_idletasks()
14
+
15
+ # Expand the window to fullscreen
16
+ self.attributes('-fullscreen', True)
17
+ self.update_idletasks()
18
+
10
19
  width = self.winfo_screenwidth()
11
20
  height = self.winfo_screenheight()
12
21
  self.geometry(f"{width}x{height}")
@@ -1,4 +1,4 @@
1
- import sys, os, re, sqlite3, torch, torchvision, random, string, shutil, cv2, tarfile, glob, psutil, platform, gzip
1
+ import sys, os, re, sqlite3, torch, torchvision, random, string, shutil, cv2, tarfile, glob, psutil, platform, gzip, subprocess
2
2
 
3
3
  import numpy as np
4
4
  from cellpose import models as cp_models
@@ -4433,3 +4433,13 @@ def count_reads_in_fastq(fastq_file):
4433
4433
  for _ in f:
4434
4434
  count += 1
4435
4435
  return count // 4
4436
+
4437
+
4438
+ # Function to determine the CUDA version
4439
+ def get_cuda_version():
4440
+ try:
4441
+ output = subprocess.check_output(['nvcc', '--version'], stderr=subprocess.STDOUT).decode('utf-8')
4442
+ if 'release' in output:
4443
+ return output.split('release ')[1].split(',')[0].replace('.', '')
4444
+ except (subprocess.CalledProcessError, FileNotFoundError):
4445
+ return None
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: spacr
3
- Version: 0.2.65
3
+ Version: 0.2.66
4
4
  Summary: Spatial phenotype analysis of crisp screens (SpaCr)
5
5
  Home-page: https://github.com/EinarOlafsson/spacr
6
6
  Author: Einar Birnir Olafsson
@@ -14,6 +14,8 @@ Requires-Dist: torchvision<1.0,>=0.1
14
14
  Requires-Dist: torch-geometric<3.0,>=2.5
15
15
  Requires-Dist: numpy<2.0,>=1.26.4
16
16
  Requires-Dist: pandas<3.0,>=2.2.1
17
+ Requires-Dist: bottleneck<2.0,>=1.3.6
18
+ Requires-Dist: numexpr<3.0,>=2.8.4
17
19
  Requires-Dist: statsmodels<1.0,>=0.14.1
18
20
  Requires-Dist: scikit-image<1.0,>=0.22.0
19
21
  Requires-Dist: scikit-learn<2.0,>=1.4.1
@@ -13,7 +13,6 @@ spacr/app_sequencing.py
13
13
  spacr/app_umap.py
14
14
  spacr/core.py
15
15
  spacr/deep_spacr.py
16
- spacr/graph_learning.py
17
16
  spacr/gui.py
18
17
  spacr/gui_core.py
19
18
  spacr/gui_elements.py
@@ -3,6 +3,8 @@ torchvision<1.0,>=0.1
3
3
  torch-geometric<3.0,>=2.5
4
4
  numpy<2.0,>=1.26.4
5
5
  pandas<3.0,>=2.2.1
6
+ bottleneck<2.0,>=1.3.6
7
+ numexpr<3.0,>=2.8.4
6
8
  statsmodels<1.0,>=0.14.1
7
9
  scikit-image<1.0,>=0.22.0
8
10
  scikit-learn<2.0,>=1.4.1
@@ -1,340 +0,0 @@
1
- import os
2
- os.environ['DGLBACKEND'] = 'pytorch'
3
- import torch, dgl
4
- import pandas as pd
5
- import torch.nn as nn
6
- from torchvision import datasets, transforms
7
- from sklearn.preprocessing import StandardScaler
8
- from PIL import Image
9
- import dgl.nn.pytorch as dglnn
10
- from sklearn.datasets import make_classification
11
- from .utils import SelectChannels
12
- from IPython.display import display
13
-
14
- # approach outline
15
- #
16
- # 1. Data Preparation:
17
- # Test Mode: Load MNIST data and generate synthetic gRNA data.
18
- # Real Data: Load image paths and sequencing data as fractions.
19
- #
20
- # 2. Graph Construction:
21
- # Each well is represented as a graph.
22
- # Each graph has cell nodes (with image features) and gRNA nodes (with gRNA fraction features).
23
- # Each cell node is connected to each gRNA node within the same well.
24
- #
25
- # 3. Model Training:
26
- # Use an encoder-decoder architecture with the Graph Transformer model.
27
- # The encoder processes the cell and gRNA nodes.
28
- # The decoder outputs the phenotype score for each cell node.
29
- # The model is trained on all wells (including positive and negative controls).
30
- # The model learns to score the gRNA in column 1 (negative control) as 0 and the gRNA in column 2 (positive control) as 1 based on the cell features.
31
- #
32
- # 4. Model Application:
33
- # Apply the trained model to all wells to get classification probabilities.
34
- #
35
- # 5. Evaluation:
36
- # Evaluate the model's performance using the control wells.
37
- #
38
- # 6. Association Analysis:
39
- # Analyze the association between gRNAs and the classification scores.
40
- #
41
- # The model learns the associations between cell features and phenotype scores based on the controls and then generalizes this learning to the screening wells.
42
-
43
- # Load MNIST data for testing
44
- def load_mnist_data():
45
- transform = transforms.Compose([
46
- transforms.Resize((28, 28)),
47
- transforms.ToTensor(),
48
- transforms.Normalize((0.1307,), (0.3081,))
49
- ])
50
- mnist_train = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
51
- mnist_test = datasets.MNIST(root='./data', train=False, download=True, transform=transform)
52
- return mnist_train, mnist_test
53
-
54
- # Generate synthetic gRNA data
55
- def generate_synthetic_grna_data(n_samples, n_features):
56
- X, y = make_classification(n_samples=n_samples, n_features=n_features, n_informative=5, n_redundant=0, n_classes=2, random_state=42)
57
- synthetic_data = pd.DataFrame(X, columns=[f'feature_{i}' for i in range(n_features)])
58
- synthetic_data['label'] = y
59
- return synthetic_data
60
-
61
- # Preprocess image
62
- def preprocess_image(image_path, image_size=224, channels=[1,2,3], normalize=True):
63
-
64
- if normalize:
65
- preprocess = transforms.Compose([
66
- transforms.ToTensor(),
67
- transforms.CenterCrop(size=(image_size, image_size)),
68
- SelectChannels(channels),
69
- transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))])
70
- else:
71
- preprocess = transforms.Compose([
72
- transforms.ToTensor(),
73
- transforms.CenterCrop(size=(image_size, image_size)),
74
- SelectChannels(channels)])
75
-
76
- image = Image.open(image_path).convert('RGB')
77
- return preprocess(image)
78
-
79
- def extract_metadata_from_path(path):
80
- """
81
- Extract metadata from the image path.
82
- The path format is expected to be plate_well_field_objectnumber.png
83
-
84
- Parameters:
85
- path (str): The path to the image file.
86
-
87
- Returns:
88
- dict: A dictionary with the extracted metadata.
89
- """
90
- filename = os.path.basename(path)
91
- name, ext = os.path.splitext(filename)
92
-
93
- # Ensure the file has the correct extension
94
- if ext.lower() != '.png':
95
- raise ValueError("Expected a .png file")
96
-
97
- # Split the name by underscores
98
- parts = name.split('_')
99
- if len(parts) != 4:
100
- raise ValueError("Expected filename format: plate_well_field_objectnumber.png")
101
-
102
- plate, well, field, object_number = parts
103
-
104
- return {'plate': plate, 'well': well,'field': field, 'object_number': object_number}
105
-
106
- # Load images
107
- def load_images(image_paths, image_size=224, channels=[1,2,3], normalize=True):
108
- images = []
109
- metadata_list = []
110
- for path in image_paths:
111
- image = preprocess_image(path, image_size, channels, normalize)
112
- images.append(image)
113
- metadata = extract_metadata_from_path(path) # Extract metadata from image path or database
114
- metadata_list.append(metadata)
115
- return torch.stack(images), metadata_list
116
-
117
- # Normalize sequencing data
118
- def normalize_sequencing_data(sequencing_data):
119
- scaler = StandardScaler()
120
- sequencing_data.iloc[:, 2:] = scaler.fit_transform(sequencing_data.iloc[:, 2:])
121
- return sequencing_data
122
-
123
- # Construct graph for each well
124
- def construct_well_graph(images, image_metadata, grna_data):
125
- cell_nodes = len(images)
126
- grna_nodes = grna_data.shape[0]
127
-
128
- graph = dgl.DGLGraph()
129
- graph.add_nodes(cell_nodes + grna_nodes)
130
-
131
- cell_features = torch.stack(images)
132
- grna_features = torch.tensor(grna_data).float()
133
-
134
- features = torch.cat([cell_features, grna_features], dim=0)
135
- graph.ndata['features'] = features
136
-
137
- for i in range(cell_nodes):
138
- for j in range(cell_nodes, cell_nodes + grna_nodes):
139
- graph.add_edge(i, j)
140
- graph.add_edge(j, i)
141
-
142
- return graph
143
-
144
- def create_graphs_for_wells(images, metadata_list, sequencing_data):
145
- graphs = []
146
- labels = []
147
-
148
- for well in sequencing_data['well'].unique():
149
- well_images = [img for img, meta in zip(images, metadata_list) if meta['well'] == well]
150
- well_metadata = [meta for meta in metadata_list if meta['well'] == well]
151
- well_grna_data = sequencing_data[sequencing_data['well'] == well].iloc[:, 2:].values
152
-
153
- graph = construct_well_graph(well_images, well_metadata, well_grna_data)
154
- graphs.append(graph)
155
-
156
- if well_metadata[0]['column'] == 1: # Negative control
157
- labels.append(0)
158
- elif well_metadata[0]['column'] == 2: # Positive control
159
- labels.append(1)
160
- else:
161
- labels.append(-1) # Screen wells, will be used for evaluation
162
-
163
- return graphs, labels
164
-
165
- # Define Encoder-Decoder Transformer Model
166
- class Encoder(nn.Module):
167
- def __init__(self, in_feats, hidden_feats):
168
- super(Encoder, self).__init__()
169
- self.conv1 = dglnn.GraphConv(in_feats, hidden_feats)
170
- self.conv2 = dglnn.GraphConv(hidden_feats, hidden_feats)
171
-
172
- def forward(self, g, features):
173
- x = self.conv1(g, features)
174
- x = torch.relu(x)
175
- x = self.conv2(g, x)
176
- x = torch.relu(x)
177
- return x
178
-
179
- class Decoder(nn.Module):
180
- def __init__(self, hidden_feats, out_feats):
181
- super(Decoder, self).__init__()
182
- self.linear = nn.Linear(hidden_feats, out_feats)
183
-
184
- def forward(self, x):
185
- return self.linear(x)
186
-
187
- class GraphTransformer(nn.Module):
188
- def __init__(self, in_feats, hidden_feats, out_feats):
189
- super(GraphTransformer, self).__init__()
190
- self.encoder = Encoder(in_feats, hidden_feats)
191
- self.decoder = Decoder(hidden_feats, out_feats)
192
-
193
- def forward(self, g, features):
194
- x = self.encoder(g, features)
195
- with g.local_scope():
196
- g.ndata['h'] = x
197
- hg = dgl.mean_nodes(g, 'h')
198
- return self.decoder(hg)
199
-
200
- def train(graphs, labels, model, loss_fn, optimizer, epochs=100):
201
- for epoch in range(epochs):
202
- model.train()
203
- total_loss = 0
204
- correct = 0
205
- total = 0
206
-
207
- for graph, label in zip(graphs, labels):
208
- if label == -1:
209
- continue # Skip screen wells for training
210
-
211
- features = graph.ndata['features']
212
- logits = model(graph, features)
213
- loss = loss_fn(logits, torch.tensor([label]))
214
-
215
- optimizer.zero_grad()
216
- loss.backward()
217
- optimizer.step()
218
-
219
- total_loss += loss.item()
220
- _, predicted = torch.max(logits, 1)
221
- correct += (predicted == label).sum().item()
222
- total += 1
223
-
224
- accuracy = correct / total if total > 0 else 0
225
- print(f'Epoch {epoch}, Loss: {total_loss / total:.4f}, Accuracy: {accuracy * 100:.2f}%')
226
-
227
- def apply_model(graphs, model):
228
- model.eval()
229
- results = []
230
-
231
- with torch.no_grad():
232
- for graph in graphs:
233
- features = graph.ndata['features']
234
- logits = model(graph, features)
235
- probabilities = torch.softmax(logits, dim=1)
236
- results.append(probabilities[:, 1].item())
237
-
238
- return results
239
-
240
- def analyze_associations(probabilities, sequencing_data):
241
- # Analyze associations between gRNAs and classification scores
242
- sequencing_data['positive_prob'] = probabilities
243
- return sequencing_data.groupby('gRNA').positive_prob.mean().sort_values(ascending=False)
244
-
245
- def process_sequencing_df(seq):
246
-
247
- if isinstance(seq, pd.DataFrame):
248
- sequencing_df = seq
249
- elif isinstance(seq, str):
250
- sequencing_df = pd.read_csv(seq)
251
-
252
- # Check if 'plate_row' column exists and split into 'plate' and 'row'
253
- if 'plate_row' in sequencing_df.columns:
254
- sequencing_df[['plate', 'row']] = sequencing_df['plate_row'].str.split('_', expand=True)
255
-
256
- # Check if 'plate', 'row' and 'col' or 'plate', 'row' and 'column' exist
257
- if {'plate', 'row', 'col'}.issubset(sequencing_df.columns) or {'plate', 'row', 'column'}.issubset(sequencing_df.columns):
258
- if 'col' in sequencing_df.columns:
259
- sequencing_df['prc'] = sequencing_df[['plate', 'row', 'col']].agg('_'.join, axis=1)
260
- elif 'column' in sequencing_df.columns:
261
- sequencing_df['prc'] = sequencing_df[['plate', 'row', 'column']].agg('_'.join, axis=1)
262
-
263
- # Check if 'count', 'total_reads', 'read_fraction', 'grna' exist and create new dataframe
264
- if {'count', 'total_reads', 'read_fraction', 'grna'}.issubset(sequencing_df.columns):
265
- new_df = sequencing_df[['grna', 'prc', 'count', 'total_reads', 'read_fraction']]
266
- return new_df
267
-
268
- return sequencing_df
269
-
270
- def train_graph_transformer(src, lr=0.01, epochs=100, hidden_feats=128, n_classes=2, row_limit=None, image_size=224, channels=[1,2,3], normalize=True, test_mode=False):
271
- if test_mode:
272
- # Load MNIST data
273
- mnist_train, mnist_test = load_mnist_data()
274
-
275
- # Generate synthetic gRNA data
276
- synthetic_grna_data = generate_synthetic_grna_data(len(mnist_train), 10) # 10 synthetic features
277
- sequencing_data = synthetic_grna_data
278
-
279
- # Load MNIST images and metadata
280
- images = []
281
- metadata_list = []
282
- for idx, (img, label) in enumerate(mnist_train):
283
- images.append(img)
284
- metadata_list.append({'index': idx, 'plate': 'plate1', 'well': idx, 'column': label})
285
- images = torch.stack(images)
286
-
287
- # Normalize synthetic sequencing data
288
- sequencing_data = normalize_sequencing_data(sequencing_data)
289
- else:
290
- from .io import _read_and_join_tables
291
- from .utils import get_db_paths, get_sequencing_paths, correct_paths
292
-
293
- db_paths = get_db_paths(src)
294
- seq_paths = get_sequencing_paths(src)
295
-
296
- if isinstance(src, str):
297
- src = [src]
298
-
299
- sequencing_data = pd.DataFrame()
300
- for seq in seq_paths:
301
- sequencing_df = pd.read_csv(seq)
302
- sequencing_df = process_sequencing_df(sequencing_df)
303
- sequencing_data = pd.concat([sequencing_data, sequencing_df], axis=0)
304
-
305
- all_df = pd.DataFrame()
306
- image_paths = []
307
- for i, db_path in enumerate(db_paths):
308
- df = _read_and_join_tables(db_path, table_names=['png_list'])
309
- df, image_paths_tmp = correct_paths(df, src[i])
310
- all_df = pd.concat([all_df, df], axis=0)
311
- image_paths.extend(image_paths_tmp)
312
-
313
- if row_limit is not None:
314
- all_df = all_df.sample(n=row_limit, random_state=42)
315
-
316
- images, metadata_list = load_images(image_paths, image_size, channels, normalize)
317
- sequencing_data = normalize_sequencing_data(sequencing_data)
318
-
319
- # Step 1: Create graphs for each well
320
- graphs, labels = create_graphs_for_wells(images, metadata_list, sequencing_data)
321
-
322
- # Step 2: Train Graph Transformer Model
323
- in_feats = graphs[0].ndata['features'].shape[1]
324
- model = GraphTransformer(in_feats, hidden_feats, n_classes)
325
- loss_fn = nn.CrossEntropyLoss()
326
- optimizer = torch.optim.Adam(model.parameters(), lr=lr)
327
-
328
- # Train the model
329
- train(graphs, labels, model, loss_fn, optimizer, epochs)
330
-
331
- # Step 3: Apply the model to all wells (including screen wells)
332
- screen_graphs = [graph for graph, label in zip(graphs, labels) if label == -1]
333
- probabilities = apply_model(screen_graphs, model)
334
-
335
- # Step 4: Analyze associations between gRNAs and classification scores
336
- associations = analyze_associations(probabilities, sequencing_data)
337
- print("Top associated gRNAs with positive control phenotype:")
338
- print(associations.head())
339
-
340
- return model, associations
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes