embkit 0.1.0__tar.gz → 0.3__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 (96) hide show
  1. embkit-0.3/PKG-INFO +71 -0
  2. embkit-0.3/README.md +49 -0
  3. {embkit-0.1.0 → embkit-0.3}/pyproject.toml +13 -3
  4. embkit-0.3/src/embkit/__init__.py +77 -0
  5. embkit-0.3/src/embkit/__main__.py +91 -0
  6. embkit-0.3/src/embkit/align.py +110 -0
  7. {embkit-0.1.0 → embkit-0.3}/src/embkit/bmeg.py +7 -0
  8. embkit-0.3/src/embkit/c_bio/__init__.py +1 -0
  9. embkit-0.3/src/embkit/c_bio/api.py +13 -0
  10. embkit-0.3/src/embkit/commands/__init__.py +20 -0
  11. embkit-0.3/src/embkit/commands/align.py +30 -0
  12. embkit-0.3/src/embkit/commands/cbio.py +63 -0
  13. embkit-0.3/src/embkit/commands/matrix.py +36 -0
  14. embkit-0.3/src/embkit/commands/model.py +233 -0
  15. embkit-0.3/src/embkit/commands/protein.py +71 -0
  16. embkit-0.3/src/embkit/commands/resources.py +61 -0
  17. {embkit-0.1.0 → embkit-0.3}/src/embkit/constraints/network_constraint.py +19 -1
  18. embkit-0.3/src/embkit/datasets/__init__.py +51 -0
  19. embkit-0.3/src/embkit/encoding/__init__.py +155 -0
  20. embkit-0.3/src/embkit/encoding/protein.py +98 -0
  21. {embkit-0.1.0 → embkit-0.3}/src/embkit/estimator/vae_estimator.py +16 -5
  22. embkit-0.3/src/embkit/factory/__init__.py +17 -0
  23. embkit-0.3/src/embkit/factory/core.py +46 -0
  24. embkit-0.3/src/embkit/factory/layers.py +253 -0
  25. embkit-0.3/src/embkit/factory/mapping.py +117 -0
  26. embkit-0.3/src/embkit/factory/registry.py +71 -0
  27. embkit-0.3/src/embkit/files/__init__.py +3 -0
  28. embkit-0.3/src/embkit/files/h5.py +131 -0
  29. embkit-0.3/src/embkit/files/json.py +20 -0
  30. embkit-0.3/src/embkit/files/loaders.py +40 -0
  31. embkit-0.3/src/embkit/files/read_csv.py +262 -0
  32. embkit-0.3/src/embkit/losses/__init__.py +1 -0
  33. embkit-0.3/src/embkit/losses/vae_loss.py +109 -0
  34. embkit-0.3/src/embkit/metrics/distance/__init__.py +1 -0
  35. embkit-0.3/src/embkit/metrics/distance/metrics.py +36 -0
  36. embkit-0.3/src/embkit/models/__init__.py +21 -0
  37. embkit-0.3/src/embkit/models/ffnn.py +50 -0
  38. embkit-0.3/src/embkit/models/vae/__init__.py +10 -0
  39. embkit-0.3/src/embkit/models/vae/base_vae.py +112 -0
  40. embkit-0.3/src/embkit/models/vae/decoder.py +84 -0
  41. embkit-0.3/src/embkit/models/vae/encoder.py +165 -0
  42. embkit-0.3/src/embkit/models/vae/net_vae.py +115 -0
  43. embkit-0.3/src/embkit/models/vae/rna_vae.py +282 -0
  44. embkit-0.3/src/embkit/models/vae/vae.py +102 -0
  45. embkit-0.3/src/embkit/modules/__init__.py +18 -0
  46. embkit-0.3/src/embkit/modules/masked_linear.py +88 -0
  47. embkit-0.3/src/embkit/modules/pairwise_comparison_layer.py +91 -0
  48. embkit-0.3/src/embkit/modules/tsp.py +103 -0
  49. embkit-0.3/src/embkit/optimize/__init__.py +504 -0
  50. embkit-0.3/src/embkit/pathway.py +227 -0
  51. embkit-0.3/src/embkit/preprocessing/__init__.py +8 -0
  52. embkit-0.3/src/embkit/preprocessing/dataset.py +35 -0
  53. {embkit-0.1.0/src/embkit → embkit-0.3/src/embkit/preprocessing}/normalize.py +35 -4
  54. embkit-0.3/src/embkit/resources/__init__.py +4 -0
  55. embkit-0.3/src/embkit/resources/c_bio_portal.py +135 -0
  56. embkit-0.3/src/embkit/resources/gtex.py +109 -0
  57. embkit-0.3/src/embkit/resources/hugo.py +17 -0
  58. embkit-0.3/src/embkit/resources/resource.py +142 -0
  59. embkit-0.3/src/embkit/resources/sif.py +17 -0
  60. embkit-0.3/src/embkit/resources/util.py +49 -0
  61. embkit-0.3/src/embkit/utilities/__init__.py +2 -0
  62. embkit-0.3/src/embkit/utilities/kmeans.py +46 -0
  63. embkit-0.3/src/embkit/utilities/pca.py +38 -0
  64. embkit-0.3/src/embkit/version.py +62 -0
  65. embkit-0.3/src/embkit.egg-info/PKG-INFO +71 -0
  66. embkit-0.3/src/embkit.egg-info/SOURCES.txt +74 -0
  67. embkit-0.3/src/embkit.egg-info/entry_points.txt +2 -0
  68. embkit-0.3/src/embkit.egg-info/requires.txt +12 -0
  69. embkit-0.3/tests/test_main.py +94 -0
  70. embkit-0.1.0/PKG-INFO +0 -42
  71. embkit-0.1.0/README.md +0 -27
  72. embkit-0.1.0/src/embkit/__main__.py +0 -14
  73. embkit-0.1.0/src/embkit/align.py +0 -59
  74. embkit-0.1.0/src/embkit/commands.py +0 -27
  75. embkit-0.1.0/src/embkit/layers/__init__.py +0 -1
  76. embkit-0.1.0/src/embkit/layers/masked_linear.py +0 -28
  77. embkit-0.1.0/src/embkit/losses/__init__.py +0 -1
  78. embkit-0.1.0/src/embkit/losses/vae_loss.py +0 -16
  79. embkit-0.1.0/src/embkit/models/__init__.py +0 -1
  80. embkit-0.1.0/src/embkit/models/vae_model/__init__.py +0 -3
  81. embkit-0.1.0/src/embkit/models/vae_model/base_vae.py +0 -226
  82. embkit-0.1.0/src/embkit/models/vae_model/decoder.py +0 -17
  83. embkit-0.1.0/src/embkit/models/vae_model/encoder.py +0 -99
  84. embkit-0.1.0/src/embkit/models/vae_model/net_vae.py +0 -186
  85. embkit-0.1.0/src/embkit/pathway.py +0 -8
  86. embkit-0.1.0/src/embkit/vae.py +0 -97
  87. embkit-0.1.0/src/embkit.egg-info/PKG-INFO +0 -42
  88. embkit-0.1.0/src/embkit.egg-info/SOURCES.txt +0 -30
  89. embkit-0.1.0/src/embkit.egg-info/requires.txt +0 -5
  90. {embkit-0.1.0 → embkit-0.3}/setup.cfg +0 -0
  91. {embkit-0.1.0 → embkit-0.3}/setup.py +0 -0
  92. {embkit-0.1.0 → embkit-0.3}/src/embkit/constraints/__init__.py +0 -0
  93. {embkit-0.1.0/src/embkit → embkit-0.3/src/embkit/estimator}/__init__.py +0 -0
  94. {embkit-0.1.0/src/embkit/estimator → embkit-0.3/src/embkit/metrics}/__init__.py +0 -0
  95. {embkit-0.1.0 → embkit-0.3}/src/embkit.egg-info/dependency_links.txt +0 -0
  96. {embkit-0.1.0 → embkit-0.3}/src/embkit.egg-info/top_level.txt +0 -0
embkit-0.3/PKG-INFO ADDED
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: embkit
3
+ Version: 0.3
4
+ Summary: Embedding Kit for embedding models
5
+ Author-email: Kyle Ellrott <ellrott@ohsu.edu>, Raphael Kirchgaessner <kirchgae@ohsu.edu>
6
+ License: MIT
7
+ Keywords: embeddings,machine learning,deep learning
8
+ Requires-Python: >=3.8
9
+ Description-Content-Type: text/markdown
10
+ Requires-Dist: torch>=2.0
11
+ Requires-Dist: pandas
12
+ Requires-Dist: numpy
13
+ Requires-Dist: click
14
+ Requires-Dist: scikit-learn
15
+ Requires-Dist: scipy
16
+ Requires-Dist: gripql
17
+ Requires-Dist: tqdm
18
+ Requires-Dist: biopython
19
+ Requires-Dist: fair-esm
20
+ Requires-Dist: faiss-cpu
21
+ Requires-Dist: h5py
22
+
23
+
24
+ # Embedding Kit
25
+
26
+ Methods for data normalization, embedding, synthesis and transformation
27
+
28
+
29
+ ## Installation
30
+ ```
31
+ pip install embkit
32
+ ```
33
+
34
+ # Training a model
35
+ ```
36
+ embkit model train-vae ./experiments/tcga/tumor.normalized.tsv --epochs 120
37
+ ```
38
+
39
+ ## Development
40
+
41
+ To install the library locally use:
42
+ ```pip install -e .```
43
+ ```python setup.py build```
44
+ ```python setup.py install```
45
+
46
+ ### To run tests use:
47
+ ```bash
48
+ coverage run --source=embkit -m unittest discover -s tests
49
+ ```
50
+
51
+ To generate a coverage report use:
52
+ ```bash
53
+ coverage html
54
+ ```
55
+
56
+ To open the coverage report in a browser, run:
57
+ #### MacOS:
58
+ ```bash
59
+ open htmlcov/index.html
60
+ ```
61
+
62
+ #### Linux:
63
+ ```bash
64
+ xdg-open htmlcov/index.html
65
+ ```
66
+
67
+ #### Windows:
68
+ ```bash
69
+ start htmlcov\index.html
70
+ ```
71
+
embkit-0.3/README.md ADDED
@@ -0,0 +1,49 @@
1
+
2
+ # Embedding Kit
3
+
4
+ Methods for data normalization, embedding, synthesis and transformation
5
+
6
+
7
+ ## Installation
8
+ ```
9
+ pip install embkit
10
+ ```
11
+
12
+ # Training a model
13
+ ```
14
+ embkit model train-vae ./experiments/tcga/tumor.normalized.tsv --epochs 120
15
+ ```
16
+
17
+ ## Development
18
+
19
+ To install the library locally use:
20
+ ```pip install -e .```
21
+ ```python setup.py build```
22
+ ```python setup.py install```
23
+
24
+ ### To run tests use:
25
+ ```bash
26
+ coverage run --source=embkit -m unittest discover -s tests
27
+ ```
28
+
29
+ To generate a coverage report use:
30
+ ```bash
31
+ coverage html
32
+ ```
33
+
34
+ To open the coverage report in a browser, run:
35
+ #### MacOS:
36
+ ```bash
37
+ open htmlcov/index.html
38
+ ```
39
+
40
+ #### Linux:
41
+ ```bash
42
+ xdg-open htmlcov/index.html
43
+ ```
44
+
45
+ #### Windows:
46
+ ```bash
47
+ start htmlcov\index.html
48
+ ```
49
+
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "embkit"
7
- version = "0.1.0"
7
+ version = "0.3"
8
8
  description = "Embedding Kit for embedding models"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.8"
@@ -19,11 +19,21 @@ dependencies = [
19
19
  "pandas",
20
20
  "numpy",
21
21
  "click",
22
- "scikit-learn"
22
+ "scikit-learn",
23
+ "scipy",
24
+ "gripql",
25
+ "tqdm",
26
+ "biopython",
27
+ "fair-esm",
28
+ "faiss-cpu",
29
+ "h5py"
23
30
  ]
24
31
 
25
32
  [tool.setuptools]
26
33
  package-dir = { "" = "src" }
27
34
 
28
35
  [tool.setuptools.packages.find]
29
- where = ["src"]
36
+ where = ["src"]
37
+
38
+ [project.scripts]
39
+ embkit = "embkit.__main__:cli"
@@ -0,0 +1,77 @@
1
+ """
2
+ Embedding Kit
3
+
4
+ The base module contains frequently used methods and functions
5
+ """
6
+ import logging
7
+ import torch
8
+ import pandas as pd
9
+ import numpy as np
10
+ from torch.utils.data import TensorDataset, DataLoader
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ def get_device() -> torch.device:
15
+ """
16
+ get_device - scan system and return default device
17
+ """
18
+ if torch.cuda.is_available():
19
+ logger.info("Using CUDA GPU")
20
+ return torch.device("cuda")
21
+ if torch.backends.mps.is_available():
22
+ logger.info("Using Metal GPU")
23
+ return torch.device("mps")
24
+ logger.info("Using CPU")
25
+ return torch.device("cpu")
26
+
27
+ def dataframe_tensor(df: pd.DataFrame, device=None, dtype=torch.float32) -> torch.Tensor:
28
+ """
29
+ dataframe_tensor
30
+
31
+ take a pandas dataframe, create a tensor
32
+ """
33
+ if device is None:
34
+ device = get_device()
35
+ return torch.from_numpy(df.to_numpy(copy=True)).to(device=device, dtype=dtype)
36
+
37
+ def tensor_dataframe(tn: torch.Tensor, index=None, columns=None) -> pd.DataFrame:
38
+ """
39
+ dataframe_tensor
40
+
41
+ take a torch tensor, create a pandas dataframe
42
+ """
43
+ return pd.DataFrame(tn.to(device="cpu", dtype=torch.float32).detach().numpy(), index=index, columns=columns)
44
+
45
+ def dataframe_dataset(df: pd.DataFrame, device=None, dtype=torch.float32) -> torch.utils.data.Dataset:
46
+ """
47
+ dataframe_dataset
48
+
49
+ take a pandas dataframe and return a pytorch dataset
50
+
51
+ :param df: Input pandas Dataframe
52
+ :type df: pd.DataFrame
53
+ :param device: Device to put torch tensors on
54
+ :return: Description
55
+ :rtype: Dataset
56
+ """
57
+ if device is None:
58
+ device = get_device()
59
+ x = torch.from_numpy(df.to_numpy(copy=True)).to(device=device, dtype=dtype)
60
+ dataset = TensorDataset(x)
61
+ return dataset
62
+
63
+ def dataframe_loader(df: pd.DataFrame,
64
+ batch_size = 256, shuffle=True,
65
+ device=None, dtype=torch.float32) -> torch.utils.data.DataLoader:
66
+ """
67
+ dataframe_loader
68
+
69
+ :param df: Pandas Dataframe to be converted into passed to DataLoader
70
+ :param batch_size: value to be passed to DataLoader batch_size
71
+ :param shuffle: value to be passed to DataLoader shuffle
72
+ :param device: Device the where tensor should be moved. If None, use get_device
73
+ """
74
+
75
+ dataset = dataframe_dataset(df, device=device, dtype=dtype)
76
+ data_loader = DataLoader(dataset, batch_size=batch_size, shuffle=shuffle)
77
+ return data_loader
@@ -0,0 +1,91 @@
1
+ import click
2
+ import logging
3
+
4
+ from embkit.version import get_version
5
+
6
+ from .commands import model, matrix, cbio_cmd, protein, resources, align
7
+
8
+ @click.group(invoke_without_command=True)
9
+ @click.option('--verbose', is_flag=True, help="Enable verbose logging")
10
+ @click.option('--version', is_flag=True, help="Show version information")
11
+ @click.pass_context
12
+ def cli(ctx, verbose, version):
13
+ """Embedding Kit CLI.
14
+
15
+ Use 'embkit help [COMMAND]' for details on a specific command.
16
+ """
17
+ # Set up logging based on the verbose flag
18
+ logging.basicConfig(
19
+ level=logging.DEBUG if verbose else logging.INFO,
20
+ format="%(asctime)s [%(levelname)s] %(message)s"
21
+ )
22
+
23
+ ctx.ensure_object(dict)
24
+ ctx.obj["VERBOSE"] = verbose
25
+
26
+ if version:
27
+ click.echo(get_version())
28
+ ctx.exit()
29
+
30
+ if ctx.invoked_subcommand is None:
31
+ click.echo(ctx.get_help())
32
+
33
+
34
+ # Register our commands here
35
+ cli.add_command(model)
36
+ cli.add_command(matrix)
37
+ cli.add_command(cbio_cmd)
38
+ cli.add_command(protein)
39
+ cli.add_command(resources)
40
+ cli.add_command(align)
41
+
42
+
43
+ # ---- 'help' command ----
44
+ @cli.command("help", context_settings=dict(ignore_unknown_options=True))
45
+ @click.argument("path", nargs=-1)
46
+ @click.pass_context
47
+ def help_cmd(ctx, path):
48
+ """
49
+ Show help for the CLI or a specific command.
50
+
51
+ Examples:
52
+ embkit help
53
+ embkit help model
54
+ embkit help model train
55
+ """
56
+ # No args -> show top-level help plus a neat command list summary
57
+ if not path:
58
+ click.echo(ctx.parent.get_help())
59
+ click.echo("\nCommands:")
60
+ # Sorted, with 1-line summaries
61
+ for name in sorted(cli.commands):
62
+ cmd = cli.commands[name]
63
+ summary = (cmd.help or cmd.short_help or "").strip().splitlines()[0]
64
+ click.echo(f" {name:15s} {summary}")
65
+ return
66
+
67
+ # Resolve dotted/space-separated path to a nested command
68
+ cmd = cli
69
+ info_name = []
70
+ parent = ctx.parent # start from top-level context
71
+ for part in path:
72
+ if not isinstance(cmd, click.Group):
73
+ click.echo(cli.get_help(ctx)) # pragma: no cover
74
+ return
75
+
76
+ nxt_cmd = cmd.get_command(parent, part)
77
+ if nxt_cmd is None:
78
+ raise click.UsageError(f"Unknown command: {' '.join(path)}")
79
+
80
+ info_name.append(part)
81
+ cmd = nxt_cmd
82
+ parent = click.Context(cmd, info_name=part, parent=parent)
83
+
84
+ # Print help for the resolved command
85
+ click.echo(cmd.get_help(parent))
86
+
87
+
88
+ cli_main = cli
89
+
90
+ if __name__ == "__main__": # pragma: no cover
91
+ cli()
@@ -0,0 +1,110 @@
1
+ import numpy as np
2
+ import pandas as pd
3
+ from scipy.stats import spearmanr
4
+ from scipy.optimize import linear_sum_assignment
5
+
6
+ def calc_rmsd(array1, array2):
7
+ """
8
+ Calculates the Root Mean Square Deviation (RMSD) between two arrays.
9
+ Parameters:
10
+ array1 (numpy.ndarray): The first array.
11
+ array2 (numpy.ndarray): The second array, must be of the same length as array1.
12
+
13
+ Returns:
14
+ float: The RMSD between the two arrays.
15
+ """
16
+ if len(array1) != len(array2):
17
+ raise ValueError("Arrays must be of the same length")
18
+ diff = array1 - array2
19
+ squared_diff = diff ** 2
20
+ mean_squared_diff = np.mean(squared_diff)
21
+ rmsd = np.sqrt(mean_squared_diff)
22
+
23
+ return rmsd
24
+
25
+
26
+ def matrix_spearman_alignment_linear(a, b, cutoff=0.0):
27
+ """
28
+ matrix_spearman_alignment_linear
29
+
30
+ Uses the linear_sum_assignment algorithm to create an optimal
31
+ mapping between two matrices by maximizing the total Spearman
32
+ correlation score.
33
+ """
34
+ # Identify overlapping columns
35
+ isect = a.columns.intersection(b.columns)
36
+
37
+ combined_df = pd.concat([a[isect], b[isect]], axis=0)
38
+ o = spearmanr(combined_df, axis=1)
39
+
40
+ a_count = a.shape[0]
41
+ sdf = pd.DataFrame(o.correlation[a_count:, :a_count], index=b.index, columns=a.index)
42
+
43
+ rows, cols = linear_sum_assignment(-sdf)
44
+
45
+ out_a = []
46
+ out_b = []
47
+ out_score = []
48
+
49
+ for r, c in zip(rows, cols):
50
+ score = sdf.iloc[r, c]
51
+ if score >= cutoff:
52
+ out_a.append(a.index[c])
53
+ out_b.append(b.index[r])
54
+ out_score.append(score)
55
+
56
+ return out_a, out_b, out_score
57
+
58
+
59
+ def procrustes(X, Y):
60
+ """
61
+ Computes the Procrustes transformation (optimal PURE rotation)
62
+ to align X to Y, correcting for reflections.
63
+
64
+ Args:
65
+ X: The first matrix (N_points, N_dims).
66
+ Y: The second matrix (N_points, N_dims).
67
+
68
+ Returns:
69
+ R: The optimal rotation matrix (guaranteed det(R) = +1).
70
+ """
71
+ assert X.shape == Y.shape
72
+
73
+ M = np.dot(X.T, Y)
74
+
75
+ U, S, Vt = np.linalg.svd(M)
76
+
77
+ R = np.dot(U, Vt)
78
+
79
+ if np.linalg.det(R) < 0:
80
+ Vt_corrected = Vt.copy()
81
+ Vt_corrected[-1, :] *= -1
82
+ R = np.dot(U, Vt_corrected)
83
+
84
+ return R
85
+
86
+
87
+ def procrustes_scale(X, Y):
88
+ """
89
+ Compute the procrustes transformation (R), then compute a factor (k) to rescale the src matrix.
90
+
91
+ To apply transformtion:
92
+ src.dot(R) * k
93
+
94
+
95
+ Args:
96
+ X: The first matrix (N_points, N_dims).
97
+ Y: The second matrix (N_points, N_dims).
98
+
99
+ Returns:
100
+ R: The optimal rotation matrix (guaranteed det(R) = +1).
101
+ k: Scaling factor
102
+
103
+ """
104
+ R = procrustes(X,Y)
105
+ A = np.array(X.dot(R))
106
+ B = np.array(Y)
107
+ numerators = np.sum(A * B, axis=0)
108
+ denominators = np.sum(A * A, axis=0)
109
+ k = np.divide(numerators, denominators, out=np.zeros_like(numerators), where=denominators!=0)
110
+ return R, k
@@ -1,3 +1,10 @@
1
+
2
+ """
3
+ BMEG
4
+
5
+ Data retrieval from BMEG instance
6
+ """
7
+
1
8
  import gripql
2
9
 
3
10
  def connect(url="https://bmeg.io/grip", graph="rc6", cred_file="./bmeg_credentials.json"):
@@ -0,0 +1 @@
1
+ from .api import CBIOAPI
@@ -0,0 +1,13 @@
1
+ import requests
2
+
3
+
4
+ class CBIOAPI:
5
+
6
+ @staticmethod
7
+ def list_studies():
8
+ try:
9
+ studies = requests.get("https://www.cbioportal.org/api/studies").json()
10
+ return studies
11
+ except requests.RequestException as e:
12
+ print(f"Error fetching studies: {e}")
13
+ return None
@@ -0,0 +1,20 @@
1
+
2
+ """
3
+ Command Line Methods
4
+
5
+ embkit matrix <> : Matrix methods for normalization and transformation
6
+
7
+ embkit model <> : Methods of model training and application
8
+
9
+ embkit cbio <> : cBIO methods for data querying and download
10
+
11
+ """
12
+
13
+ from .model import model
14
+ from .matrix import matrix
15
+ from .cbio import cbio_cmd
16
+ from .resources import resources
17
+ from .protein import protein
18
+ from .align import align
19
+
20
+ __all__ = ["model", "matrix", "resources", "protein"]
@@ -0,0 +1,30 @@
1
+ """
2
+
3
+ Command line tools for aligning embedding spaces
4
+
5
+ """
6
+
7
+ import click
8
+ import pandas as pd
9
+ from ..align import matrix_spearman_alignment_linear
10
+
11
+ align = click.Group(name="align", help="Embedding Alignment methods")
12
+
13
+ @align.command(name="pair")
14
+ @click.argument("matrix1")
15
+ @click.argument("matrix2")
16
+ @click.option("--method", "-m", required=False, type=str, default="linear")
17
+ @click.option("--cutoff", "-c", required=False, type=float, default=0.5)
18
+ def pair(matrix1, matrix2, method, cutoff):
19
+ """
20
+ Given two matrices, use feature rank correlation to
21
+ create list of pairs
22
+ """
23
+
24
+ m1 = pd.read_csv(matrix1, sep="\t", index_col=0)
25
+ m2 = pd.read_csv(matrix2, sep="\t", index_col=0)
26
+
27
+ if method == "linear":
28
+ out = matrix_spearman_alignment_linear(m1, m2, cutoff)
29
+ for k, v in out.items():
30
+ print(f"{k}\t{v[0]}\t{v[1]}")
@@ -0,0 +1,63 @@
1
+ import click
2
+ from ..resources import CBIOPortal
3
+ from ..c_bio import CBIOAPI
4
+ import logging
5
+
6
+ logger = logging.getLogger(__name__)
7
+
8
+ cbio_cmd = click.Group(name="cbio", help="cBIO commands.")
9
+
10
+
11
+ @cbio_cmd.command(name="studies", help="List cbio studies.")
12
+ @click.pass_context
13
+ def list_studies(ctx):
14
+ """
15
+ Command to list available cBIO studies.
16
+
17
+ Parameters:
18
+ ctx: Click context object.
19
+
20
+ Returns:
21
+ None
22
+ """
23
+ api = CBIOAPI()
24
+ studies = api.list_studies()
25
+
26
+ if studies:
27
+ for study in studies:
28
+ click.echo(f"Study ID: {study['studyId']}, Name: {study['name']}")
29
+ else:
30
+ click.echo("No studies found or an error occurred while fetching studies.")
31
+
32
+
33
+ @cbio_cmd.command(name="download", help="Download cbio dataset.")
34
+ @click.option("--save_path", "-s", type=click.Path(exists=False, writable=True, path_type=str),
35
+ help="Path to save the dataset.")
36
+ @click.option("--study_id", "-si", type=str, show_default=True, help="Id of the study to download.")
37
+ @click.pass_context
38
+ def download_tmp(ctx, save_path: str | None, study_id: str):
39
+ """
40
+ Command to download a cBIO dataset by specifying the study ID.
41
+
42
+
43
+ Parameters:
44
+ ctx: Click context object.
45
+ save_path: Path to save the dataset.
46
+ study_id: ID of the study to download.
47
+
48
+ Returns:
49
+ None
50
+ """
51
+
52
+ if study_id is None:
53
+ click.echo("Study Id not specified. Please use -si option to specify the study id.")
54
+ return
55
+
56
+ cbio_portal: CBIOPortal = CBIOPortal(save_path=save_path, study_id=study_id, download=True)
57
+ cbio_portal.download()
58
+ cbio_portal.unpack()
59
+
60
+
61
+ # needed for testing
62
+ if __name__ == "__main__":
63
+ cbio_cmd() # pragma: no cover
@@ -0,0 +1,36 @@
1
+ import click
2
+ import pandas as pd
3
+
4
+ matrix = click.Group(name="matrix", help="Model commands.")
5
+
6
+ @matrix.command()
7
+ @click.argument("srcs", nargs=-1)
8
+ @click.option("--out", "-o", required=True)
9
+ @click.option("--features", default=None, type=click.Path(exists=True, dir_okay=False, readable=True, path_type=str))
10
+ @click.option("--col-quantile", "col_quantile", default=False, is_flag=True)
11
+ @click.option("--quantile-max", "quantile_max", default=0.9, type=float)
12
+ @click.option("--precision", "-p", type=int, default=5)
13
+ def normalize(srcs, out, features, col_quantile, quantile_max, precision):
14
+
15
+ features_list = None
16
+ if features is not None:
17
+ features = []
18
+ with open(features, encoding="ascii") as handle:
19
+ features_list = list(line.rstrip() for line in handle)
20
+
21
+ dfs = []
22
+ for i in srcs:
23
+ df = pd.read_csv(i, sep="\t", index_col=0)
24
+ if features is not None:
25
+ df = df[features]
26
+ dfs.append(df)
27
+ if len(dfs) == 0:
28
+ click.echo("No matrices defined")
29
+ return
30
+ df = pd.concat( dfs )
31
+
32
+ if not col_quantile:
33
+ normDF = (df.transpose() / df.quantile(quantile_max, axis=1)).transpose().clip(upper=1.0, lower=0.0).fillna(0.0)
34
+ else:
35
+ normDF = (df / df.quantile(quantile_max)).clip(upper=1.0, lower=0.0).fillna(0.0)
36
+ normDF.round(decimals=precision).to_csv(out, sep="\t")