├── cobra ├── __init__.py ├── model │ ├── __init__.py │ └── cobra.py ├── ssl │ ├── __init__.py │ ├── data.py │ ├── model.py │ └── pretrain.py ├── utils │ ├── __init__.py │ ├── abmil.py │ ├── mamba2.py │ ├── get_mpp.py │ └── load_cobra.py ├── inference │ ├── __init__.py │ ├── heatmaps.py │ └── extract_feats.py ├── configs │ └── example.yml └── crossval │ ├── deploy.py │ └── train.py ├── assets ├── cobra.png └── fig1.png ├── pyproject.toml ├── .gitignore ├── README.md └── LICENSE /cobra/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cobra/model/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cobra/ssl/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cobra/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /cobra/inference/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /assets/cobra.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KatherLab/COBRA/HEAD/assets/cobra.png -------------------------------------------------------------------------------- /assets/fig1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KatherLab/COBRA/HEAD/assets/fig1.png -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "cobra" 3 | version = "0.1.0" 4 | description = "Slide Encoder for Computational Pathology" 5 | readme = "README.md" 6 | license = {text = "GPLv3"} 7 | authors = [ 8 | {name = "Tim Lenz", email = "tim.lenz@tu-dresden.de"}, 9 | {name = "Peter Neidlinger", email = "peter.neidlinger@fau.de"} 10 | ] 11 | requires-python = ">=3.10.0" 12 | classifiers = [ 13 | "Programming Language :: Python :: 3", 14 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 15 | "Operating System :: OS Independent", 16 | ] 17 | dependencies = [ 18 | "torch>=2.6.0", 19 | "h5py>=3.12.1", 20 | "jinja2>=3.1.4", 21 | "numpy>=2.0.2", 22 | "pandas>=2.2.3", 23 | "pyyaml>=6.0.2", 24 | "tqdm>=4.67.1", 25 | #"mamba-ssm @ git+https://github.com/KatherLab/mamba.git@d0d4192621889b26f9669ea4a8e6fe79cc84e8d9", 26 | #"causal-conv1d @ git+https://github.com/KatherLab/causal-conv1d.git@b73d1ca0e0726ba6520c38d342bd411bb5850064", 27 | "mamba-ssm", 28 | "causal-conv1d", 29 | "torchvision>=0.19.1", 30 | "einops>=0.8.0", 31 | "huggingface-hub>=0.26.5", 32 | "torchmetrics>=1.6.1", 33 | "pytorch-lightning>=2.5.0.post0", 34 | "scikit-learn>=1.6.1", 35 | "openpyxl>=3.1.5", 36 | "matplotlib>=3.10.1", 37 | "openslide-python>=1.4.1", 38 | "openslide-bin>=4.0.0.6", 39 | ] 40 | 41 | [build-system] 42 | requires = ["hatchling", "torch"] 43 | build-backend = "hatchling.build" 44 | 45 | [tool.hatch.metadata] 46 | # To allow referencing git repos in dependencies 47 | allow-direct-references = true 48 | 49 | [tool.pytest.ini_options] 50 | markers = [ 51 | "slow: marks tests as slow (deselect with '-m \"not slow\"')", 52 | ] 53 | 54 | [tool.uv.extra-build-dependencies] 55 | mamba-ssm = [{ requirement = "torch", match-runtime = true }] 56 | causal-conv1d = [{ requirement = "torch", match-runtime = true }] 57 | -------------------------------------------------------------------------------- /cobra/configs/example.yml: -------------------------------------------------------------------------------- 1 | extract_feats: 2 | download_model: false 3 | checkpoint_path: "/path/to/checkpoint.pth.tar" 4 | top_k: null 5 | output_dir: "/path/to/slide_embeddings" 6 | feat_dir: "/path/to/tile_embeddings" 7 | feat_dir_a: null # Optional: for aggregation features 8 | model_name: "COBRAII" 9 | patch_encoder: "Virchow2" 10 | patch_encoder_a: "Virchow2" 11 | h5_name: "cobraII_feats.h5" 12 | microns: 224 13 | use_cobraI: false 14 | slide_table: null # Provide for patient-level extraction; omit for slide-level 15 | 16 | train: 17 | csv_path: "/path/to/metadata.csv" 18 | target_column: "TARGET" 19 | patient_id_column: "PATIENT_ID" 20 | h5_path: "/path/to/extracted_features.h5" 21 | output_folder: "/path/to/crossval" 22 | hps: 23 | lr: 0.0005 24 | hidden_dim: 512 25 | max_epochs: 64 26 | patience: 16 27 | batch_size: 32 28 | num_workers: 8 29 | n_folds: 5 30 | dropout: 0.3 31 | 32 | deploy: 33 | csv_path: "/path/to/test_metadata.csv" 34 | target_column: "TARGET" 35 | patient_id_column: "PATIENT_ID" 36 | h5_path: "/path/to/extracted_features.h5" 37 | output_folder: "/path/to/deploy" 38 | label_encoder_path: "/path/to/label_encoder.pkl" 39 | hps: 40 | hidden_dim: 512 41 | n_folds: 5 42 | 43 | heatmap: 44 | feat_dir: "/path/to/tile_embeddings" 45 | wsi_dir: "/path/to/wsi_files" 46 | checkpoint_path: "/path/to/heatmap_checkpoint.pth.tar" 47 | microns: 112 48 | patch_size: 224 49 | output_dir: "/path/to/heatmap_output" 50 | stamp_version: 2 51 | 52 | model: 53 | nr_heads: 4 54 | nr_mamba_layers: 1 55 | dim: 768 56 | input_dims: 57 | - 512 58 | - 1024 59 | - 1280 60 | - 1536 61 | l_dim: 256 62 | att_dim: 256 63 | dropout: 0.2 64 | d_state: 128 65 | model_name: "cobraII" 66 | 67 | ssl: 68 | moco_m: 0.99 69 | moco_t: 0.2 70 | lr: 5e-4 71 | warmup_epochs: 50 72 | weight_decay: 0.1 73 | epochs: 2000 74 | workers: 56 75 | batch_size: 1024 76 | 77 | general: 78 | nr_feats: 768 79 | fms: 80 | - "fm1" 81 | - "fm2" 82 | - "fm3" 83 | - "fm4" 84 | feat_base_paths: 85 | - "/path/to/features_set1" 86 | - "/path/to/features_set2" 87 | paths: 88 | out_dir: "/path/to/pretrain_output" -------------------------------------------------------------------------------- /cobra/utils/abmil.py: -------------------------------------------------------------------------------- 1 | """ adapted from: https://github.com/mahmoodlab/MADELEINE/blob/main/core/models/abmil.py 2 | Guillaume Jaume, Anurag Jayant Vaidya, Andrew Zhang, 3 | Andrew H Song, Richard J. Chen, Sharifa Sahai, Dandan 4 | Mo, Emilio Madrigal, Long Phi Le, and Mahmood Faisal. 5 | Multistain pretraining for slide representation learning in 6 | pathology. In European Conference on Computer Vision. 7 | Springer, 2024. 8 | """ 9 | import torch 10 | from torch import nn 11 | import torch.nn.functional as F 12 | 13 | class BatchedABMIL(nn.Module): 14 | 15 | def __init__(self, input_dim=1024, hidden_dim=256, dropout=False, n_classes=1, n_heads = 1, activation='softmax'): 16 | super(BatchedABMIL, self).__init__() 17 | 18 | self.activation = activation 19 | self.device = 'cuda' if torch.cuda.is_available() else 'cpu' 20 | self.attention_a = nn.ModuleList([ 21 | nn.Linear(input_dim, hidden_dim), 22 | nn.Tanh() 23 | ]) 24 | 25 | self.attention_b = nn.ModuleList([ 26 | nn.Linear(input_dim, hidden_dim), 27 | nn.Sigmoid() 28 | ]) 29 | 30 | if dropout: 31 | self.attention_a.append(nn.Dropout(0.25)) 32 | self.attention_b.append(nn.Dropout(0.25)) 33 | 34 | self.attention_a = nn.Sequential(*self.attention_a) 35 | self.attention_b = nn.Sequential(*self.attention_b) 36 | self.attention_c = nn.Linear(hidden_dim, n_classes) 37 | 38 | def forward(self, x, return_raw_attention=False): 39 | assert len(x.shape)==3, x.shape 40 | a = self.attention_a(x) 41 | b = self.attention_b(x) 42 | A = a.mul(b) 43 | A = self.attention_c(A) 44 | if self.activation == 'softmax': 45 | activated_A = F.softmax(A, dim=1) 46 | elif self.activation == 'leaky_relu': 47 | activated_A = F.leaky_relu(A) 48 | elif self.activation == 'relu': 49 | activated_A = F.relu(A) 50 | elif self.activation == 'sigmoid': 51 | activated_A = torch.sigmoid(A) 52 | else: 53 | raise NotImplementedError('Activation not implemented.') 54 | 55 | if return_raw_attention: 56 | return activated_A, A 57 | 58 | return activated_A -------------------------------------------------------------------------------- /cobra/utils/mamba2.py: -------------------------------------------------------------------------------- 1 | """ 2 | Adapted from: https://github.com/isyangshu/MambaMIL/blob/main/models/MambaMIL.py 3 | Shu Yang, Yihui Wang, and Hao Chen. MambaMIL: En- 4 | hancing Long Sequence Modeling with Sequence Reorder- 5 | ing in Computational Pathology. In proceedings of Medi- 6 | cal Image Computing and Computer Assisted Intervention – 7 | MICCAI 2024. Springer Nature Switzerland, 2024 8 | """ 9 | 10 | import torch 11 | import torch.nn as nn 12 | import warnings 13 | 14 | warnings.simplefilter(action="ignore", category=FutureWarning) 15 | from mamba_ssm import Mamba2 16 | 17 | 18 | def initialize_weights(module): 19 | for m in module.modules(): 20 | if isinstance(m, nn.Linear): 21 | nn.init.xavier_normal_(m.weight) 22 | if m.bias is not None: 23 | m.bias.data.zero_() 24 | if isinstance(m, nn.LayerNorm): 25 | nn.init.constant_(m.bias, 0) 26 | nn.init.constant_(m.weight, 1.0) 27 | 28 | 29 | class Mamba2Enc(nn.Module): 30 | def __init__( 31 | self, 32 | in_dim, 33 | dim, 34 | n_classes, 35 | dropout=0.25, 36 | act="gelu", 37 | layer=2, 38 | rate=10, 39 | d_state=64, 40 | ): 41 | super(Mamba2Enc, self).__init__() 42 | self._fc1 = [nn.Linear(in_dim, dim)] 43 | if act.lower() == "relu": 44 | self._fc1 += [nn.ReLU()] 45 | elif act.lower() == "gelu": 46 | self._fc1 += [nn.GELU()] 47 | if dropout: 48 | self._fc1 += [nn.Dropout(dropout)] 49 | 50 | self._fc1 = nn.Sequential(*self._fc1) 51 | self.norm = nn.LayerNorm(dim) 52 | self.layers = nn.ModuleList() 53 | 54 | for _ in range(layer): 55 | self.layers.append( 56 | nn.Sequential( 57 | nn.LayerNorm(dim), 58 | Mamba2( 59 | d_model=dim, 60 | d_state=d_state, 61 | d_conv=4, 62 | expand=2, 63 | ), 64 | ) 65 | ) 66 | 67 | self.n_classes = n_classes 68 | self.classifier = nn.Linear(dim, self.n_classes) 69 | self.rate = rate 70 | self.type = type 71 | 72 | self.apply(initialize_weights) 73 | 74 | def forward(self, x): 75 | if len(x.shape) == 2: 76 | x = x.expand(1, -1, -1) 77 | h = x # .float() 78 | 79 | h = self._fc1(h) 80 | 81 | for layer in self.layers: 82 | h_ = h 83 | h = layer[0](h) 84 | h = layer[1](h) 85 | h = h + h_ 86 | 87 | logits = self.classifier(h) 88 | return logits 89 | 90 | def relocate(self): 91 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 92 | self._fc1 = self._fc1.to(device) 93 | self.layers = self.layers.to(device) 94 | 95 | self.attention = self.attention.to(device) 96 | self.norm = self.norm.to(device) 97 | self.classifier = self.classifier.to(device) 98 | -------------------------------------------------------------------------------- /cobra/utils/get_mpp.py: -------------------------------------------------------------------------------- 1 | import openslide 2 | from pathlib import Path 3 | import re 4 | 5 | import xml.dom.minidom as minidom 6 | # 7 | # adapted from: https://github.com/KatherLab/STAMP/blob/main/src/stamp/preprocessing/tiling.py#L379 8 | def get_slide_mpp_( 9 | slide: openslide.AbstractSlide | Path, *, default_mpp: float | None 10 | ) -> float | None: 11 | """ 12 | Retrieve the microns per pixel (MPP) value from a slide. 13 | This function attempts to extract the MPP value from the given slide. If the slide 14 | is provided as a file path, it will be opened using OpenSlide. The function first 15 | checks for the MPP value in the slide's properties. If not found, it attempts to 16 | extract the MPP value from the slide's comments and metadata. If all attempts fail 17 | and a default MPP value is provided, it will use the default value. If no MPP value 18 | can be determined and no default is provided, an MPPExtractionError is raised. 19 | Args: 20 | slide: The slide object or file path to the slide. 21 | default_mpp: The default MPP value to use if extraction fails. 22 | Returns: 23 | The extracted or default MPP value, or None if extraction fails and no default is provided. 24 | Raises: 25 | MPPExtractionError: If the MPP value cannot be determined and no default is provided. 26 | """ 27 | 28 | if isinstance(slide, Path): 29 | slide = openslide.open_slide(slide) 30 | 31 | if openslide.PROPERTY_NAME_MPP_X in slide.properties: 32 | slide_mpp = float(slide.properties[openslide.PROPERTY_NAME_MPP_X]) 33 | elif slide_mpp := _extract_mpp_from_comments(slide): 34 | pass 35 | elif slide_mpp := _extract_mpp_from_metadata(slide): 36 | pass 37 | 38 | if slide_mpp is None and default_mpp: 39 | print( 40 | f"could not infer slide MPP from metadata, using {default_mpp} instead." 41 | ) 42 | elif slide_mpp is None and default_mpp is None: 43 | raise MPPExtractionError() 44 | 45 | return slide_mpp or default_mpp 46 | 47 | def _extract_mpp_from_comments(slide: openslide.AbstractSlide) -> float | None: 48 | slide_properties = slide.properties.get("openslide.comment", "") 49 | pattern = r"(.*?)" 50 | match = re.search(pattern, slide_properties) 51 | if match is not None and (mpp := match.group(1)) is not None: 52 | return float(mpp) 53 | else: 54 | return None 55 | 56 | 57 | def _extract_mpp_from_metadata(slide: openslide.AbstractSlide) -> float | None: 58 | try: 59 | xml_path = slide.properties.get("tiff.ImageDescription") or None 60 | if xml_path is None: 61 | return None 62 | doc = minidom.parseString(xml_path) 63 | collection = doc.documentElement 64 | images = collection.getElementsByTagName("Image") 65 | pixels = images[0].getElementsByTagName("Pixels") 66 | mpp = float(pixels[0].getAttribute("PhysicalSizeX")) 67 | except Exception: 68 | print("failed to extract MPP from image description") 69 | return None 70 | return mpp 71 | 72 | class MPPExtractionError(Exception): 73 | """Raised when the Microns Per Pixel (MPP) extraction from the slide's metadata fails""" 74 | 75 | pass -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /cobra/utils/load_cobra.py: -------------------------------------------------------------------------------- 1 | # %% 2 | from huggingface_hub import login, hf_hub_download 3 | from cobra.model.cobra import Cobra 4 | import torch 5 | import warnings 6 | import os 7 | import requests 8 | warnings.simplefilter(action='ignore', category=FutureWarning) 9 | 10 | def get_cobra(download_weights=False, checkpoint_path="weights/pytorch_model.bin"): 11 | """ 12 | Load the COBRA model. 13 | 14 | Parameters: 15 | - download_weights (bool): If True, download the model weights from Hugging Face Hub. 16 | - checkpoint_path (str): Path to the model checkpoint file. 17 | 18 | Returns: 19 | - Cobra: The loaded COBRA model. 20 | 21 | Raises: 22 | - FileNotFoundError: If the checkpoint file is not found and download_weights is False. 23 | """ 24 | if download_weights: 25 | if not os.path.exists(os.path.dirname(checkpoint_path)): 26 | os.makedirs(os.path.dirname(checkpoint_path)) 27 | download_path = hf_hub_download("KatherLab/COBRA", filename="pytorch_model.bin", 28 | local_dir=os.path.dirname(checkpoint_path), 29 | force_download=True) 30 | os.rename(download_path, checkpoint_path) 31 | print(f"Saving model to {checkpoint_path}") 32 | else: 33 | if not os.path.exists(checkpoint_path): 34 | raise FileNotFoundError(f"Checkpoint file {checkpoint_path} not found") 35 | state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=False) 36 | model = Cobra(input_dims=[768,1024,1280,1536],) 37 | if "state_dict" in list(state_dict.keys()): 38 | chkpt = state_dict["state_dict"] 39 | cobra_weights = {k.split("momentum_enc.")[-1]:v for k,v in chkpt.items() if "momentum_enc" in k and "momentum_enc.proj" not in k} 40 | if len(list(cobra_weights.keys())) == 0: 41 | # from stamp finetuning 42 | print("Loading STAMP model..") 43 | cobra_weights = {k.split("cobra.")[-1]:v for k,v in chkpt.items() if "cobra" in k} 44 | else: 45 | cobra_weights = state_dict 46 | model.load_state_dict(cobra_weights) 47 | print("COBRA model loaded successfully") 48 | return model 49 | 50 | 51 | def get_cobraII(download_weights=False, checkpoint_path="weights/cobraII.pth.tar"): 52 | """ 53 | Load the COBRAII model. 54 | 55 | Parameters: 56 | - download_weights (bool): If True, download the model weights from Hugging Face Hub. 57 | - checkpoint_path (str): Path to the model checkpoint file. 58 | 59 | Returns: 60 | - Cobra: The loaded COBRAII model. 61 | 62 | Raises: 63 | - FileNotFoundError: If the checkpoint file is not found and download_weights is False. 64 | """ 65 | if download_weights: 66 | if not os.path.exists(os.path.dirname(checkpoint_path)): 67 | os.makedirs(os.path.dirname(checkpoint_path)) 68 | download_path = hf_hub_download("KatherLab/COBRA", filename="cobraII.pth.tar", 69 | local_dir=os.path.dirname(checkpoint_path), 70 | force_download=True) 71 | os.rename(download_path, checkpoint_path) 72 | print(f"Saving model to {checkpoint_path}") 73 | else: 74 | if not os.path.exists(checkpoint_path): 75 | raise FileNotFoundError(f"Checkpoint file {checkpoint_path} not found") 76 | state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=False) 77 | model = Cobra(layers=1, input_dims=[512,1024,1280,1536], 78 | num_heads=4, dropout=0.2, att_dim=256, d_state=128) 79 | if "state_dict" in list(state_dict.keys()): 80 | chkpt = state_dict["state_dict"] 81 | cobra_weights = {k.split("momentum_enc.")[-1]:v for k,v in chkpt.items() if "momentum_enc" in k and "momentum_enc.proj" not in k} 82 | if len(list(cobra_weights.keys())) == 0: 83 | # from stamp finetuning 84 | print("Loading STAMP model..") 85 | cobra_weights = {k.split("cobra.")[-1]:v for k,v in chkpt.items() if "cobra" in k} 86 | else: 87 | cobra_weights = state_dict 88 | model.load_state_dict(cobra_weights) 89 | print("COBRAII model loaded successfully") 90 | return model 91 | -------------------------------------------------------------------------------- /cobra/ssl/data.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import torch 3 | from torch.utils.data import Dataset 4 | import h5py 5 | import os 6 | from glob import glob 7 | from tqdm import tqdm 8 | import pathlib 9 | from concurrent.futures import ThreadPoolExecutor 10 | 11 | 12 | class FeatDataset(Dataset): 13 | def __init__(self, pat_dict, num_feats=600, feat_len=1536): 14 | self.pat_dict = pat_dict 15 | self.pat_list = list(self.pat_dict.keys()) 16 | 17 | print(f"Found {len(self.pat_list)} patient ids.") 18 | self.num_feats = num_feats 19 | self.feat_len = feat_len 20 | 21 | def __len__(self): 22 | return len(self.pat_list) 23 | 24 | def __getitem__(self, idx): 25 | pat = self.pat_list[idx] 26 | 27 | idx1 = np.random.randint(0, len(self.pat_dict[pat])) 28 | idx2 = np.random.randint(0, len(self.pat_dict[pat])) 29 | 30 | with h5py.File(self.pat_dict[pat][idx1], "r") as f: 31 | feats1 = f["feats"][:] 32 | 33 | with h5py.File(self.pat_dict[pat][idx2], "r") as f: 34 | feats2 = f["feats"][:] 35 | 36 | assert len(feats1.shape) == 2, f"{feats1.shape=}!" 37 | assert len(feats2.shape) == 2, f"{feats2.shape=}!" 38 | 39 | orig_size_1 = feats1.shape[-1] 40 | orig_size_2 = feats2.shape[-1] 41 | 42 | with torch.no_grad(): 43 | feats1 = self.pad_or_sample( 44 | torch.tensor(feats1), self.num_feats, self.feat_len 45 | ) 46 | feats2 = self.pad_or_sample( 47 | torch.tensor(feats2), self.num_feats, self.feat_len 48 | ) 49 | 50 | assert ( 51 | len(feats1.shape) == 2 52 | and feats1.shape[0] == self.num_feats 53 | and feats1.shape[1] == self.feat_len 54 | ), f"{feats1.shape=}" 55 | assert ( 56 | len(feats2.shape) == 2 57 | and feats2.shape[0] == self.num_feats 58 | and feats2.shape[1] == self.feat_len 59 | ), f"{feats2.shape=}" 60 | 61 | return feats1, torch.tensor(orig_size_1), feats2, torch.tensor(orig_size_2) 62 | 63 | def pad_or_sample(self, x: torch.Tensor, n=1024, k=1536) -> torch.Tensor: 64 | length = x.shape[0] 65 | x = x[torch.randperm(len(x))][:n] 66 | if length < n: 67 | repeats = (n - length) // length 68 | tmp = x 69 | for _ in range(repeats): 70 | x = torch.cat([x, tmp[torch.randperm(length)]]) 71 | resample_size = (n - length) % length 72 | if resample_size > 0: 73 | x = torch.cat([x, x[torch.randperm(len(x))][:resample_size]]) 74 | feat_len = x.shape[1] 75 | if k - feat_len > 0: 76 | pad_size = k - feat_len 77 | x = torch.cat([x, torch.zeros(n, pad_size)], dim=1) 78 | return x 79 | 80 | 81 | def check_file(f): 82 | # try: 83 | # with h5py.File(f, "r") as h5f: 84 | # if "feats" not in h5f: 85 | # raise KeyError(f"'feats' not found in {f}") 86 | # # feats = f["feats"][:] 87 | # except Exception as e: 88 | # print(f"Error reading {f}") 89 | # raise e 90 | # assert len(feats.shape)==2, f"{feats.shape=}!" 91 | assert os.path.getsize(f) > 800, f"{f} is broken!" 92 | 93 | 94 | def get_pat_dict(cfg, num_cores=8): 95 | pat_dict = {} 96 | print(f'FMs: {cfg["general"]["fms"]}') 97 | # for c in tqdm(cfg["general"]["feat_cohorts"]): 98 | for c in tqdm( 99 | os.listdir( 100 | os.path.join(cfg["general"]["feat_base_paths"][0], cfg["general"]["fms"][0]) 101 | ), 102 | leave=False, 103 | ): 104 | for fm in tqdm(cfg["general"]["fms"], leave=False): 105 | for feat_base_path in cfg["general"]["feat_base_paths"]: 106 | feat_path = os.path.join(feat_base_path, fm, c) 107 | feat_path = os.path.join( 108 | feat_path, 109 | [ 110 | f 111 | for f in os.listdir(feat_path) 112 | if "stamp" in f and os.path.isdir(os.path.join(feat_path, f)) 113 | ][0], 114 | ) 115 | feat_files = glob(os.path.join(feat_path, "*.h5")) 116 | assert ( 117 | len(feat_files) > 0 118 | ), f"couldnt find any feat files in path {feat_path}" 119 | 120 | def process_file(f): 121 | pat_id = pathlib.Path(f).stem[:12] 122 | check_file(f) 123 | return pat_id, f 124 | 125 | # num_cores = cfg.get("num_cores", None) 126 | with ThreadPoolExecutor(max_workers=num_cores) as executor: 127 | results = list( 128 | tqdm( 129 | executor.map(process_file, feat_files), 130 | total=len(feat_files), 131 | leave=False, 132 | ) 133 | ) 134 | 135 | for pat_id, f in results: 136 | if pat_id in pat_dict: 137 | pat_dict[pat_id].append(f) 138 | else: 139 | pat_dict[pat_id] = [f] 140 | print(f"Found {sum([len(list(v)) for _,v in pat_dict.items()])} feature paths") 141 | return pat_dict 142 | -------------------------------------------------------------------------------- /cobra/ssl/model.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | warnings.simplefilter(action='ignore', category=FutureWarning) 3 | 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | from cobra.utils.mamba2 import Mamba2Enc 8 | from cobra.utils.abmil import BatchedABMIL 9 | from einops import rearrange 10 | 11 | 12 | class Embed(nn.Module): 13 | def __init__(self, dim, embed_dim=1024,dropout=0.25): 14 | super(Embed, self).__init__() 15 | 16 | self.head = nn.Sequential( 17 | nn.LayerNorm(dim), 18 | nn.Linear(dim, embed_dim), 19 | nn.Dropout(dropout) if dropout else nn.Identity(), 20 | nn.SiLU(), 21 | nn.Linear(embed_dim, embed_dim), 22 | ) 23 | 24 | def forward(self, x): 25 | return self.head(x) 26 | 27 | 28 | class Cobra(nn.Module): 29 | def __init__(self,embed_dim, c_dim, input_dims=[384,512,1024,1280,1536], num_heads=8,layer=2,dropout=0.25,att_dim=256,d_state=64): 30 | super().__init__() 31 | 32 | self.embed = nn.ModuleDict({str(d):Embed(d,embed_dim) for d in input_dims}) 33 | 34 | self.norm = nn.LayerNorm(embed_dim) 35 | 36 | self.mamba_enc = Mamba2Enc(embed_dim,embed_dim,n_classes=embed_dim,layer=layer,dropout=dropout,d_state=d_state) 37 | self.proj = nn.Sequential( 38 | nn.LayerNorm(embed_dim), 39 | nn.Linear(embed_dim,4*embed_dim), 40 | nn.SiLU(), 41 | nn.Dropout(dropout) if dropout else nn.Identity(), 42 | nn.Linear(4*embed_dim,c_dim), 43 | nn.BatchNorm1d(c_dim), 44 | ) 45 | 46 | self.num_heads = num_heads 47 | self.attn = nn.ModuleList([BatchedABMIL(input_dim=int(embed_dim/num_heads),hidden_dim=att_dim, 48 | dropout=dropout,n_classes=1) for _ in range(self.num_heads)]) #,hidden_dim=int(embed_dim/num_heads) 49 | 50 | def forward(self, x, lens=None): 51 | 52 | if lens is not None: 53 | assert len(x)==len(lens) 54 | logits = torch.concat([self.embed[str(lens[i].item())](x[i,:,:lens[i].item()]).unsqueeze(0) for i in range(len(x))],dim=0) 55 | else: 56 | logits = x 57 | 58 | h = self.norm(self.mamba_enc(logits)) 59 | 60 | if self.num_heads > 1: 61 | h_ = rearrange(h, 'b t (e c) -> b t e c',c=self.num_heads) 62 | 63 | attention = [] 64 | for i, attn_net in enumerate(self.attn): 65 | _, processed_attention = attn_net(h_[:, :, :, i], return_raw_attention = True) 66 | attention.append(processed_attention) 67 | A = torch.stack(attention, dim=-1) 68 | A = rearrange(A, 'b t e c -> b t (e c)',c=self.num_heads).mean(-1).unsqueeze(-1) 69 | A = torch.transpose(A,2,1) 70 | A = F.softmax(A, dim=-1) 71 | else: 72 | A = self.attn[0](h) 73 | 74 | h = torch.bmm(A,h).squeeze(1) 75 | feats = self.proj(h) 76 | 77 | assert len(feats.shape)==2, feats.shape 78 | return feats 79 | 80 | class MoCo(nn.Module): # adapted from https://github.com/facebookresearch/moco-v3 81 | def __init__(self,embed_dim, c_dim, input_dims=[384,512,1024,1280,1536], num_heads=8, nr_mamba_layers=2, gpu_id=0, T=0.2,dropout=0.25, 82 | att_dim=256,d_state=64): 83 | super().__init__() 84 | 85 | self.T = T 86 | self.base_enc = Cobra(embed_dim,c_dim,input_dims,num_heads,layer=nr_mamba_layers,dropout=dropout, 87 | att_dim=att_dim,d_state=d_state) 88 | self.momentum_enc = Cobra(embed_dim,c_dim,input_dims,num_heads,layer=nr_mamba_layers,dropout=None, 89 | att_dim=att_dim,d_state=d_state) 90 | self.predictor = nn.Sequential( 91 | nn.LayerNorm(c_dim), 92 | nn.Linear(c_dim,2*c_dim), 93 | nn.SiLU(), 94 | nn.Dropout(dropout) if dropout else nn.Identity(), 95 | nn.Linear(2*c_dim,c_dim), 96 | nn.BatchNorm1d(c_dim), 97 | ).cuda(gpu_id) 98 | 99 | for param_b, param_m in zip(self.base_enc.parameters(), self.momentum_enc.parameters()): 100 | param_m.data.copy_(param_b.data) 101 | param_m.requires_grad = False 102 | 103 | @torch.no_grad() 104 | def _update_momentum_encoder(self, m=0.99): 105 | """Momentum update of the momentum encoder""" 106 | for param_b, param_m in zip(self.base_enc.parameters(), self.momentum_enc.parameters()): 107 | param_m.data = param_m.data * m + param_b.data * (1. - m) 108 | 109 | 110 | def forward(self, x1, x2, sizes_1=None, sizes_2=None,m=0.99): 111 | 112 | x1_enc = self.base_enc(x1,sizes_1) 113 | x2_enc = self.base_enc(x2,sizes_2) 114 | q1 = self.predictor(x1_enc) 115 | q2 = self.predictor(x2_enc) 116 | 117 | with torch.no_grad(): # no gradient 118 | self._update_momentum_encoder(m=m) 119 | 120 | k1 = self.momentum_enc(x1,sizes_1) 121 | k2 = self.momentum_enc(x2,sizes_2) 122 | 123 | return self.contrastive_loss(q1, k2) + self.contrastive_loss(q2, k1) 124 | def contrastive_loss(self, q, k): 125 | # normalize 126 | q = F.normalize(q, dim=1) 127 | k = F.normalize(k, dim=1) 128 | # gather all targets 129 | k = concat_all_gather(k) 130 | # Einstein sum is more intuitive 131 | logits = torch.einsum('nc,mc->nm', [q, k]) / self.T 132 | N = logits.shape[0] # batch size per GPU 133 | labels = torch.arange(N, dtype=torch.long).cuda() 134 | return nn.CrossEntropyLoss()(logits, labels) * (2 * self.T) 135 | 136 | # utils 137 | @torch.no_grad() 138 | def concat_all_gather(tensor): 139 | tensors_gather = [torch.ones_like(tensor) 140 | for _ in range(torch.distributed.get_world_size())] 141 | torch.distributed.all_gather(tensors_gather, tensor, async_op=False) 142 | 143 | output = torch.cat(tensors_gather, dim=0) 144 | return output -------------------------------------------------------------------------------- /cobra/model/cobra.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import torch.nn as nn 3 | import sys 4 | 5 | from cobra.utils.mamba2 import Mamba2Enc 6 | from cobra.utils.abmil import BatchedABMIL 7 | import torch.nn.functional as F 8 | from einops import rearrange 9 | import warnings 10 | warnings.simplefilter(action='ignore', category=FutureWarning) 11 | 12 | class Embed(nn.Module): 13 | def __init__(self, dim, embed_dim=1024,dropout=0.25): 14 | super(Embed, self).__init__() 15 | 16 | self.head = nn.Sequential( 17 | nn.LayerNorm(dim), 18 | nn.Linear(dim, embed_dim), 19 | nn.Dropout(dropout) if dropout else nn.Identity(), 20 | nn.SiLU(), 21 | nn.Linear(embed_dim, embed_dim), 22 | ) 23 | 24 | def forward(self, x): 25 | return self.head(x) 26 | 27 | class Cobra(nn.Module): 28 | """ 29 | Cobra model for processing and aggregating embeddings with attention. 30 | This model utilizes separate embedding layers for different input dimensions, followed by a 31 | normalization layer and a mamba-based encoder (Mamba2Enc). It then applies multi-head 32 | attention using BatchedABMIL modules to compute attention maps and aggregate the input features. 33 | Parameters: 34 | embed_dim (int, optional): 35 | Dimensionality of the embedding vectors. Default is 768. 36 | input_dims (list of int, optional): 37 | A list of input feature dimensions. Each feature dimension corresponds to a key in the 38 | embedding module dictionary. Default is [384, 512, 1024, 1280, 1536]. 39 | num_heads (int, optional): 40 | Number of attention heads. Each head processes a slice of the embedded features. 41 | Default is 8. 42 | layers (int, optional): 43 | Number of layers in the Mamba2Enc encoder. Default is 2. 44 | dropout (float, optional): 45 | Dropout rate used throughout the model to prevent overfitting. Default is 0.25. 46 | att_dim (int, optional): 47 | The hidden dimensionality for the attention branch (BatchedABMIL) per attention head. 48 | Default is 96. 49 | d_state (int, optional): 50 | Dimensionality of the internal state in the Mamba2Enc encoder. Default is 128. 51 | Methods: 52 | forward(x, multi_fm_mode=False, fm_idx=None, get_attention=False): 53 | Forward pass through the Cobra network. 54 | Args: 55 | x (Tensor or list of Tensors): 56 | Input tensor if single feature map; list of tensors if multi_fm_mode is True. 57 | Each tensor should have a shape corresponding to the respective key in the embedding module. 58 | multi_fm_mode (bool, optional): 59 | Flag to indicate that multiple feature maps (different modalities) are provided. 60 | Default is False. 61 | fm_idx (int, optional): 62 | In multi_fm_mode, if provided, selects a specific feature map index for feature aggregation. 63 | Default is None. 64 | get_attention (bool, optional): 65 | If True, the method returns the computed attention matrix rather than the aggregated features. 66 | Default is False. 67 | Returns: 68 | Tensor: 69 | If get_attention is True, returns the attention matrix computed from the input. 70 | Otherwise, returns the aggregated feature representation obtained after applying the attention mechanism. 71 | For multi_fm_mode with a provided fm_idx, returns the features corresponding to the selected modality. 72 | Raises: 73 | AssertionError: 74 | If the dimensions of the embedded features do not match the expected sizes during 75 | concatenation or aggregation, assertions will be raised to signal the discrepancy. 76 | Example: 77 | >>> model = Cobra() 78 | >>> # Processing random input 79 | >>> x = torch.randn(1, 100, 768) # batch size: 1, sequence length: 100, feature dimension: 768 80 | >>> features = model(x) 81 | """ 82 | 83 | def __init__(self,embed_dim=768,input_dims=[384,512,1024,1280,1536], num_heads=8,layers=2,dropout=0.25,att_dim=96,d_state=128): 84 | super().__init__() 85 | 86 | self.embed = nn.ModuleDict({str(d):Embed(d,embed_dim) for d in input_dims}) 87 | 88 | self.norm = nn.LayerNorm(embed_dim) 89 | 90 | self.mamba_enc = Mamba2Enc(embed_dim,embed_dim,n_classes=embed_dim,layer=layers,dropout=dropout,d_state=d_state) 91 | 92 | self.num_heads = num_heads 93 | self.attn = nn.ModuleList([BatchedABMIL(input_dim=int(embed_dim/num_heads),hidden_dim=att_dim, 94 | dropout=dropout,n_classes=1) for _ in range(self.num_heads)]) 95 | 96 | def forward(self, x, multi_fm_mode=False, fm_idx=None, get_attention=False): 97 | if multi_fm_mode: 98 | fm_embs = torch.concat([self.embed[str(xi.shape[-1])](xi) for xi in x],dim=0) 99 | assert fm_embs.shape[-1]==self.embed_dim, fm_embs.shape 100 | assert len(fm_embs.shape)==3, fm_embs.shape 101 | assert fm_embs.shape[0]==len(x), fm_embs.shape 102 | logits = torch.mean(fm_embs,dim=0) 103 | else: 104 | logits = self.embed[str(x.shape[-1])](x) 105 | 106 | h = self.norm(self.mamba_enc(logits)) 107 | 108 | if self.num_heads > 1: 109 | h_ = rearrange(h, 'b t (e c) -> b t e c',c=self.num_heads) 110 | 111 | attention = [] 112 | for i, attn_net in enumerate(self.attn): 113 | _, processed_attention = attn_net(h_[:, :, :, i], return_raw_attention = True) 114 | attention.append(processed_attention) 115 | 116 | A = torch.stack(attention, dim=-1) 117 | 118 | A = rearrange(A, 'b t e c -> b t (e c)',c=self.num_heads).mean(-1).unsqueeze(-1) 119 | A = torch.transpose(A,2,1) 120 | A = F.softmax(A, dim=-1) 121 | else: 122 | A = self.attn[0](h) 123 | 124 | if get_attention: 125 | return A 126 | 127 | if multi_fm_mode: 128 | if fm_idx: 129 | feats = torch.bmm(A,x[fm_idx]).squeeze(0).squeeze(0) 130 | else: 131 | feats=[] 132 | for i,xi in enumerate(x): 133 | feats.append(torch.bmm(A,xi).squeeze(0).squeeze(0)) 134 | assert len(feats[i].shape)==1 and feats[i].shape[0]==xi.shape[-1], feats[i].shape 135 | else: 136 | feats = torch.bmm(A,x).squeeze(1) 137 | 138 | return feats 139 | -------------------------------------------------------------------------------- /cobra/crossval/deploy.py: -------------------------------------------------------------------------------- 1 | import os 2 | import yaml 3 | import pandas as pd 4 | import h5py 5 | import torch 6 | import torch.nn.functional as F 7 | import numpy as np 8 | from torch.utils.data import DataLoader, Dataset 9 | import argparse 10 | from sklearn.preprocessing import LabelEncoder 11 | from sklearn.metrics import roc_auc_score 12 | import pickle 13 | from cobra.crossval.train import MLP, PatientDataset 14 | from tqdm import tqdm 15 | 16 | 17 | def load_config(config_path): 18 | """ 19 | Load configuration from a YAML file. 20 | This function opens the file at the given path, reads its contents, and loads the configuration 21 | using yaml.safe_load. The configuration is returned as a Python dictionary. 22 | Parameters: 23 | config_path (str): The file path to the YAML configuration file. 24 | Returns: 25 | dict: A dictionary representing the configuration settings loaded from the YAML file. 26 | Raises: 27 | FileNotFoundError: If the file at config_path does not exist. 28 | yaml.YAMLError: If there is an error parsing the YAML file. 29 | """ 30 | 31 | with open(config_path, "r") as file: 32 | cfg = yaml.safe_load(file) 33 | return cfg 34 | 35 | 36 | def main(config_path): 37 | """ 38 | Main function for deploying evaluation of the pre-trained models on test data. 39 | This function performs the following steps: 40 | 1. Loads the deployment configuration from the specified config file. 41 | 2. Reads patient data from a CSV file and extracts target labels and patient identifiers. 42 | 3. Loads the label encoder from the training phase and transforms target labels. 43 | 4. Retrieves patient IDs from an H5 file and identifies common patients present in both CSV and H5 files. 44 | 5. Initializes a dataset and dataloader for test data. 45 | 6. Iterates over each cross-validation fold: 46 | - Checks if a model checkpoint exists for the fold. 47 | - Loads the trained model and sets it to evaluation mode. 48 | - Processes the test dataset to compute predictions, losses, and transforms predicted labels back to the original label space. 49 | - Aggregates predictions and computes the AUROC for the fold. 50 | 7. Calculates the average AUROC over all folds. 51 | 8. Saves the detailed per-patient predictions and AUROC scores for each fold (and average) as CSV files in the specified output folder. 52 | Parameters: 53 | config_path (str): The file path to the configuration file containing deployment settings, including paths to CSV, H5, label encoder, 54 | output folder, and hyperparameters for the model. 55 | Returns: 56 | None 57 | Notes: 58 | - The function assumes that the CSV file contains columns for patient IDs, target labels, and that the H5 file keys correspond to patient IDs. 59 | - The models are loaded from checkpoints for each cross-validation fold as specified in the configuration. 60 | - The function uses torch.inference_mode for inference and computes softmax probabilities on the model outputs. 61 | """ 62 | 63 | cfg = load_config(config_path)["deploy"] 64 | data = pd.read_csv(cfg["csv_path"]) 65 | targets = data[cfg["target_column"]].values 66 | # Load the label encoder from the training phase 67 | with open(cfg["label_encoder_path"], "rb") as file: 68 | label_encoder = pickle.load(file) 69 | targets = label_encoder.transform(targets) 70 | patient_ids = data[cfg["patient_id_column"]].values 71 | 72 | with h5py.File(cfg["h5_path"], "r") as f: 73 | h5_patient_ids = list(f.keys()) 74 | 75 | csv_patient_ids_set = set(patient_ids) 76 | h5_patient_ids_set = set(h5_patient_ids) 77 | 78 | common_patient_ids = list(csv_patient_ids_set & h5_patient_ids_set) 79 | common_indices = [ 80 | i for i, pid in enumerate(patient_ids) if pid in common_patient_ids 81 | ] 82 | print(f"Found {len(common_indices)} patients") 83 | patient_ids = patient_ids[common_indices] 84 | targets = targets[common_indices] 85 | 86 | torch.set_float32_matmul_precision("high") 87 | 88 | test_dataset = PatientDataset(cfg["h5_path"], patient_ids, targets) 89 | test_loader = DataLoader(test_dataset, batch_size=1, drop_last=False, shuffle=False) 90 | 91 | input_dim = test_dataset[0][0].shape[0] 92 | output_dim = len(np.unique(targets)) 93 | 94 | all_test_results = [] 95 | auroc_scores = [] 96 | 97 | for fold in range(cfg["hps"]["n_folds"]): 98 | fold_output_folder = os.path.join(cfg["output_folder"], f"fold_{fold}") 99 | model_path = os.path.join(fold_output_folder, "best_model.ckpt") 100 | if not os.path.exists(model_path): 101 | print(f"Model for fold {fold} does not exist. Skipping this fold.") 102 | continue 103 | 104 | model = MLP.load_from_checkpoint( 105 | model_path, input_dim=input_dim, output_dim=output_dim, hidden_dim=cfg["hps"]["hidden_dim"], 106 | ) 107 | 108 | device = torch.device("cuda" if torch.cuda.is_available() else "cpu") 109 | model.to(device) 110 | model.eval() 111 | y_true = [] 112 | y_pred = [] 113 | 114 | with torch.inference_mode(): 115 | fold_test_results = [] 116 | for i, (x, y) in enumerate(tqdm(test_loader)): 117 | x, y = x.to(device), y.to(device) 118 | y_hat = model(x) 119 | loss = model.criterion(y_hat, y).item() 120 | y_true.extend(y.cpu().numpy()) 121 | y_pred.append(F.softmax(y_hat,dim=-1)[0][-1].item()) 122 | fold_test_results.append( 123 | { 124 | "patient_id": patient_ids[i], 125 | "ground_truth": label_encoder.inverse_transform( 126 | y.cpu().numpy() 127 | )[0], 128 | "pred_label": label_encoder.inverse_transform( 129 | y_hat.argmax(dim=-1).cpu().numpy() 130 | )[0], 131 | "pred_prob": F.softmax(y_hat,dim=1)[0][-1].item(), 132 | "loss": loss, 133 | "fold": fold, 134 | } 135 | ) 136 | all_test_results.extend(fold_test_results) 137 | 138 | auroc = roc_auc_score(y_true, y_pred) 139 | auroc_scores.append({"fold": fold, "auroc": auroc}) 140 | print(f"Fold {fold} AUROC: {auroc}") 141 | avg_auroc = np.mean([score["auroc"] for score in auroc_scores]) 142 | print(f"Average AUROC over all folds: {avg_auroc}") 143 | auroc_scores.append({"fold": "average", "auroc": avg_auroc}) 144 | 145 | deploy_output_folder = os.path.join(cfg["output_folder"], "deploy") 146 | os.makedirs(deploy_output_folder, exist_ok=True) 147 | all_test_results_df = pd.DataFrame(all_test_results) 148 | all_test_results_df.to_csv( 149 | os.path.join(deploy_output_folder, "all_folds_test_results.csv"), index=False 150 | ) 151 | 152 | auroc_scores_df = pd.DataFrame(auroc_scores) 153 | auroc_scores_df.to_csv( 154 | os.path.join(deploy_output_folder, "auroc_scores.csv"), index=False 155 | ) 156 | 157 | 158 | if __name__ == "__main__": 159 | parser = argparse.ArgumentParser( 160 | description="Deploy MLP models on the total test set" 161 | ) 162 | parser.add_argument("-c", "--config", type=str, help="Path to the config file") 163 | args = parser.parse_args() 164 | main(args.config) 165 | -------------------------------------------------------------------------------- /cobra/inference/heatmaps.py: -------------------------------------------------------------------------------- 1 | import torch 2 | import pandas as pd 3 | import os 4 | from os.path import exists 5 | from tqdm import tqdm 6 | import argparse 7 | import h5py 8 | import numpy as np 9 | import h5py 10 | import numpy as np 11 | import matplotlib.pyplot as plt 12 | from PIL import Image 13 | import openslide 14 | import yaml 15 | 16 | from cobra.utils.load_cobra import get_cobraII, get_cobra 17 | from cobra.utils.get_mpp import get_slide_mpp_ 18 | #from cobra.utils.load_cobra import get_cobraI 19 | 20 | def get_slide_thumbnail(slide, heatmap_shape, heat_map_scale_factor=8): 21 | """ 22 | Generate a thumbnail of the slide with the specified heatmap shape and scale factor. 23 | 24 | Args: 25 | slide (OpenSlide object): The whole slide image object. 26 | heatmap_shape (tuple): Shape of the heatmap. 27 | heat_map_scale_factor (int): Scale factor for the thumbnail. 28 | 29 | Returns: 30 | np.ndarray: Thumbnail image as a NumPy array. 31 | """ 32 | thumb = slide.get_thumbnail(heatmap_shape * heat_map_scale_factor) 33 | thumb = np.array(thumb).transpose(1, 0, 2) 34 | return thumb 35 | 36 | 37 | def load_patch_features(feat_path, device="cuda"): 38 | """ 39 | Load patch features and coordinates from the specified HDF5 file. 40 | 41 | Args: 42 | feat_path (str): Path to the HDF5 file containing patch features. 43 | device (str): Device to load the features onto (e.g., "cuda" or "cpu"). 44 | 45 | Returns: 46 | tuple: A tuple containing patch features (torch.Tensor) and coordinates (torch.Tensor). 47 | """ 48 | with h5py.File(feat_path, "r") as f: 49 | feats = torch.tensor(f["feats"][:]).to(device) 50 | coords = torch.tensor(f["coords"][:]).to(device) 51 | return feats, coords 52 | 53 | 54 | def create_heatmap(model, slide_name, wsi_path, feat_path, output_dir, microns_per_patch=112, 55 | patch_size=224, scale_factor=8, device="cuda" , stamp_v=1,default_mpp=None): 56 | """ 57 | Create a heatmap for the given slide using the specified model and save it to the output directory. 58 | 59 | Args: 60 | model (torch.nn.Module): The trained COBRA model. 61 | slide_name (str): Name of the slide. 62 | wsi_path (str): Path to the whole slide image (WSI) file. 63 | feat_path (str): Path to the HDF5 file containing patch features. 64 | output_dir (str): Directory to save the generated heatmap. 65 | microns_per_patch (int): Microns per patch used for extraction. 66 | patch_size (int): Size of each patch in pixels. 67 | scale_factor (int): Scale factor for resizing the heatmap. 68 | device (str): Device to perform computations on (e.g., "cuda" or "cpu"). 69 | """ 70 | # Load patch features 71 | feats, coords = load_patch_features(feat_path, device=device) 72 | patch_feat_mpp = (microns_per_patch / patch_size) 73 | with torch.inference_mode(): 74 | attention = model(feats.to(torch.float32), get_attention=True).squeeze().cpu().numpy() 75 | if stamp_v==2: 76 | coords = np.floor(coords.cpu().numpy() / patch_feat_mpp).astype(np.int32) 77 | else: 78 | coords = coords.cpu().numpy().astype(np.int32) 79 | xs = np.unique(sorted(coords[:, 0])) 80 | stride = min(xs[1:] - xs[:-1]) 81 | 82 | coords_norm = coords // stride 83 | 84 | slide = openslide.open_slide(wsi_path) 85 | if default_mpp: 86 | default_mpp = float(default_mpp) 87 | mpp = get_slide_mpp_(slide, default_mpp=default_mpp) 88 | #except MPPExtractionError: 89 | #mpp = cfg[""] 90 | dims_um = np.ceil(np.array(slide.dimensions) * mpp / (patch_feat_mpp * patch_size)).astype(np.int32) 91 | if not np.all(coords_norm.max(0) <= dims_um): 92 | tqdm.write(f"Warning: Coordinates exceed slide dimensions. Trying to flip axes...") 93 | coords_norm = coords_norm[:, ::-1] 94 | im = np.zeros((dims_um[0], dims_um[1]), dtype=np.float32) 95 | 96 | for att, pos in zip(attention / attention.max(), coords_norm, strict=True): 97 | im[*pos] = att 98 | foreground = im > 0 99 | im = plt.get_cmap("viridis")(im) 100 | im[..., -1] = foreground 101 | 102 | heatmap_im = Image.fromarray(np.uint8(im * 255)).resize( 103 | np.array(im.shape[:2][::-1]) * 8, Image.Resampling.NEAREST 104 | ) 105 | slide_im = Image.fromarray(get_slide_thumbnail(slide, np.array(im.shape[:2]), heat_map_scale_factor=scale_factor)) 106 | 107 | # Convert heatmap and slide images to NumPy arrays 108 | heatmap_array = np.array(heatmap_im) 109 | slide_array = np.array(slide_im) 110 | 111 | # Dynamically adjust figure size based on aspect ratios 112 | slide_aspect_ratio = slide_array.shape[1] / slide_array.shape[0] 113 | heatmap_aspect_ratio = heatmap_array.shape[1] / heatmap_array.shape[0] 114 | width_ratios = [slide_aspect_ratio, heatmap_aspect_ratio] 115 | fig_width = 10 116 | fig_height = fig_width / (sum(width_ratios) / len(width_ratios)) / 2 117 | fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(fig_width, fig_height), gridspec_kw={'width_ratios': width_ratios}) 118 | 119 | # Display slide image 120 | ax1.imshow(slide_array) 121 | ax1.axis('off') 122 | 123 | # Add scale bar annotation 124 | scale_bar_length = 2000 / microns_per_patch * scale_factor # 2000 microns = 2 mm 125 | scale_bar_text = '2 mm' 126 | ax1.annotate('', xy=(10, slide_array.shape[0] - 20), xytext=(10 + scale_bar_length, slide_array.shape[0] - 20), 127 | arrowprops=dict(arrowstyle='-', color='black', lw=2)) 128 | ax1.text(10 + scale_bar_length / 2, slide_array.shape[0] - 30, scale_bar_text, color='black', ha='center') 129 | 130 | # Display heatmap image with colorbar 131 | cax = ax2.imshow(heatmap_array, cmap='viridis') 132 | ax2.axis('off') 133 | cbar_ax = fig.add_axes([0.92, 0.15, 0.02, 0.7]) 134 | fig.colorbar(cax, cax=cbar_ax, orientation='vertical') 135 | 136 | # Save the combined figure as a PDF 137 | print(f"Saving heatmap and slide images for {slide_name}...") 138 | plt.savefig(os.path.join(output_dir, f"{slide_name}.pdf"), dpi=300) 139 | 140 | 141 | 142 | def main(device="cuda"): 143 | """ 144 | Main function to generate heatmaps for whole slide images using the COBRA model. 145 | 146 | Args: 147 | device (str): Device to perform computations on (e.g., "cuda" or "cpu"). 148 | """ 149 | parser = argparse.ArgumentParser( 150 | description="Generate heatmaps for whole slide images using the COBRA model." 151 | ) 152 | parser.add_argument("-c", "--config", type=str, help="Path to configuration YAML file", default=None) 153 | # Commandline arguments (will be overridden if --config is provided) 154 | parser.add_argument("-f", "--feat_dir", type=str, default="/path/to/features", 155 | help="Directory containing tile feature files.") 156 | parser.add_argument("-s", "--wsi_dir", type=str, default="/path/to/wsi", 157 | help="Directory containing WSI files.") 158 | parser.add_argument("-w", "--checkpoint_path", type=str, default="/path/to/checkpoint.pth.tar", 159 | help="Path to the model checkpoint.") 160 | parser.add_argument("-r", "--microns", type=int, default=112, 161 | help="Microns per patch used for extraction.") 162 | parser.add_argument("-p", "--patch_size", type=int, default=224, 163 | help="Patch size used for extraction.") 164 | parser.add_argument("-o", "--output_dir", type=str, default="/path/to/output", 165 | help="Directory to save the generated heatmaps.") 166 | parser.add_argument("-v", "--stamp_version", type=int, default=2, 167 | help="Stamp version that was used for extraction.") 168 | parser.add_argument('-u',"--use_cobraI", type=bool, default=False, help="Use the COBRA I model instead of COBRA II") 169 | args = parser.parse_args() 170 | 171 | # If a config file is provided, load and override the defaults 172 | if args.config is not None: 173 | with open(args.config, "r") as f: 174 | config = yaml.safe_load(f) 175 | config = config.get("heatmap", {}) 176 | args.feat_dir = config.get("feat_dir", args.feat_dir) 177 | args.wsi_dir = config.get("wsi_dir", args.wsi_dir) 178 | args.checkpoint_path = config.get("checkpoint_path", args.checkpoint_path) 179 | args.microns = config.get("microns", args.microns) 180 | args.patch_size = config.get("patch_size", args.patch_size) 181 | args.output_dir = config.get("output_dir", args.output_dir) 182 | args.stamp_version = config.get("stamp_version", args.stamp_version) 183 | args.use_cobraI = config.get("use_cobraI", args.use_cobraI) 184 | 185 | print(f"Using configuration: {args}") 186 | device = "cuda" if torch.cuda.is_available() else "cpu" 187 | 188 | if args.use_cobraI: 189 | model = get_cobra(download_weights=(not exists(args.checkpoint_path)), checkpoint_path=args.checkpoint_path) 190 | else: 191 | model = get_cobraII(download_weights=(not exists(args.checkpoint_path)), checkpoint_path=args.checkpoint_path) 192 | model.eval() 193 | model.to(device) 194 | for wsi in tqdm([f for f in os.listdir(args.wsi_dir) if os.path.isfile(os.path.join(args.wsi_dir, f))]): 195 | wsi_path = os.path.join(args.wsi_dir, wsi) 196 | slide_name = os.path.splitext(wsi)[0] 197 | feat_path = os.path.join(args.feat_dir, slide_name + ".h5") 198 | if not exists(feat_path): 199 | tqdm.write(f"Feature file {feat_path} does not exist. Skipping...") 200 | continue 201 | if not exists(args.output_dir): 202 | os.makedirs(args.output_dir, exist_ok=True) 203 | create_heatmap(model, slide_name, wsi_path, feat_path, args.output_dir, 204 | microns_per_patch=args.microns, 205 | patch_size=args.patch_size, 206 | scale_factor=8, 207 | device=device, 208 | default_mpp=config.get("default_mpp",None), 209 | stamp_v=args.stamp_version) 210 | 211 | if __name__ == "__main__": 212 | main() 213 | -------------------------------------------------------------------------------- /cobra/ssl/pretrain.py: -------------------------------------------------------------------------------- 1 | """ 2 | Adapted from the official MoCoV3 implementation: https://github.com/facebookresearch/moco-v3 3 | @Article{chen2021mocov3, 4 | author = {Xinlei Chen* and Saining Xie* and Kaiming He}, 5 | title = {An Empirical Study of Training Self-Supervised Vision Transformers}, 6 | journal = {arXiv preprint arXiv:2104.02057}, 7 | year = {2021}, 8 | } 9 | """ 10 | 11 | import warnings 12 | 13 | warnings.simplefilter(action="ignore", category=FutureWarning) 14 | import torch 15 | from tqdm import tqdm 16 | from pathlib import Path 17 | import os 18 | import builtins 19 | from torch.utils.data import DataLoader 20 | #import torch.multiprocessing as mp 21 | import torch.nn.parallel 22 | import torch.backends.cudnn as cudnn 23 | import torch.distributed as dist 24 | import torch.utils.data.distributed 25 | import argparse 26 | import yaml 27 | from jinja2 import Environment, FileSystemLoader 28 | from pprint import pprint 29 | from datetime import datetime 30 | import math 31 | 32 | from cobra.ssl.model import MoCo 33 | from cobra.ssl.data import FeatDataset, get_pat_dict 34 | 35 | 36 | def main(args, cfg): 37 | 38 | ngpus_per_node = torch.cuda.device_count() 39 | 40 | main_worker(args.gpu, ngpus_per_node, args, cfg) 41 | 42 | def main_worker(gpu, ngpus_per_node, args, cfg): 43 | 44 | if args.rank != 0: 45 | 46 | def print_pass(*args): 47 | pass 48 | 49 | builtins.print = print_pass 50 | 51 | pprint(cfg) 52 | 53 | print(f"Initializing process group with {args.rank=}, {args.world_size=}, {args.gpu=}") 54 | 55 | dist.init_process_group( 56 | backend=args.dist_backend, 57 | init_method=args.dist_url, 58 | world_size=args.world_size, 59 | rank=args.rank, 60 | ) 61 | 62 | 63 | print("=> creating model...") 64 | 65 | model = MoCo( 66 | embed_dim=cfg["model"]["dim"], 67 | c_dim=cfg["model"]["l_dim"], 68 | input_dims = cfg["model"].get("input_dims",[512,1024,1280,1536]), 69 | num_heads=cfg["model"]["nr_heads"], 70 | gpu_id=args.gpu, 71 | T=cfg["ssl"]["moco_t"], 72 | nr_mamba_layers=cfg["model"]["nr_mamba_layers"], 73 | dropout=cfg["model"]["dropout"], 74 | att_dim=cfg["model"]["att_dim"], 75 | d_state=cfg["model"]["d_state"], 76 | ) 77 | 78 | model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model) 79 | 80 | torch.cuda.set_device(args.gpu) 81 | model.cuda(args.gpu) 82 | 83 | # infer learning rate before changing batch size 84 | args.lr = float(cfg["ssl"]["lr"]) * cfg["ssl"]["batch_size"] / 256 85 | 86 | args.batch_size = int(cfg["ssl"]["batch_size"] / args.world_size) 87 | print(f"{args.batch_size=}") 88 | #args.workers = int((cfg["ssl"]["workers"] + ngpus_per_node - 1) / ngpus_per_node) # ? round up or something 89 | args.workers = int(cfg["ssl"]["workers"]/args.world_size) 90 | args.warmup = cfg["ssl"]["warmup_epochs"] 91 | model_params = sum(p.numel() for p in model.base_enc.parameters()) 92 | model = torch.nn.parallel.DistributedDataParallel( 93 | model, device_ids=[args.gpu], find_unused_parameters=True 94 | ) 95 | 96 | optimizer = torch.optim.AdamW( 97 | model.parameters(), args.lr, weight_decay=cfg["ssl"]["weight_decay"] 98 | ) 99 | scaler = torch.amp.GradScaler("cuda") 100 | 101 | dataset = FeatDataset( 102 | pat_dict=get_pat_dict(cfg), num_feats=cfg["general"]["nr_feats"], feat_len=1536 103 | ) 104 | 105 | print(f"number of training samples = {len(dataset)}") 106 | print(f"# base_enc model params: {model_params}") 107 | train_sampler = torch.utils.data.distributed.DistributedSampler(dataset) 108 | 109 | loader = DataLoader( 110 | dataset, 111 | batch_size=args.batch_size, 112 | shuffle=False, 113 | sampler=train_sampler, 114 | num_workers=args.workers, 115 | drop_last=True, 116 | pin_memory=True, 117 | ) 118 | args.start_epoch = 0 119 | if args.resume: 120 | if os.path.isfile(args.resume): 121 | print("=> loading checkpoint '{}'".format(args.resume)) 122 | if args.gpu is None: 123 | checkpoint = torch.load(args.resume) 124 | else: 125 | # Map model to be loaded to specified single gpu. 126 | loc = "cuda:{}".format(args.gpu) 127 | checkpoint = torch.load(args.resume, map_location=loc) 128 | args.start_epoch = checkpoint["epoch"] 129 | model.load_state_dict(checkpoint["state_dict"]) 130 | optimizer.load_state_dict(checkpoint["optimizer"]) 131 | scaler.load_state_dict(checkpoint["scaler"]) 132 | print( 133 | "=> loaded checkpoint '{}' (epoch {})".format( 134 | args.resume, checkpoint["epoch"] 135 | ) 136 | ) 137 | else: 138 | print("=> no checkpoint found at '{}'".format(args.resume)) 139 | 140 | cudnn.benchmark = True 141 | 142 | model.train() 143 | 144 | iters_per_epoch = len(loader) 145 | 146 | # print_freq = 10 147 | 148 | for e in tqdm( 149 | range(args.start_epoch, cfg["ssl"]["epochs"]), disable=args.rank != 0 150 | ): 151 | t_loss = 0.0 152 | 153 | for i, (x1, sizes1, x2, sizes2) in enumerate( 154 | tqdm(loader, leave=False, disable=args.rank != 0) 155 | ): 156 | lr = adjust_learning_rate(optimizer, e + i / iters_per_epoch, args, cfg) 157 | moco_m = adjust_moco_momentum(e + i / iters_per_epoch, cfg) 158 | 159 | x1 = x1.to(torch.float32).cuda() 160 | x2 = x2.to(torch.float32).cuda() 161 | 162 | sizes1 = sizes1.cuda() 163 | sizes2 = sizes2.cuda() 164 | loss = model(x1, x2, sizes_1=sizes1, sizes_2=sizes2, m=moco_m) 165 | t_loss += loss.item() 166 | 167 | optimizer.zero_grad() 168 | scaler.scale(loss).backward() 169 | scaler.step(optimizer) 170 | scaler.update() 171 | 172 | if args.rank == 0: 173 | print(f"Epoch {e+1}; loss: {t_loss/len(loader):.4f}; lr: {lr:.5f}") 174 | with open(os.path.join(cfg["general"]["paths"]["out_dir"], f"training_log_{cfg['general']['job_id']}.csv"), "a") as f: 175 | timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") 176 | f.write(f"{timestamp},{e+1},{t_loss/len(loader):.4f},{lr:.5f}\n") 177 | if (e + 1) % 50 == 0: 178 | state = { 179 | "epoch": e + 1, 180 | "state_dict": model.state_dict(), 181 | "optimizer": optimizer.state_dict(), 182 | "scaler": scaler.state_dict(), 183 | } 184 | torch.save( 185 | state, 186 | os.path.join( 187 | cfg["general"]["paths"]["chkpt_dir"], 188 | f'{cfg["model"]["model_name"]}-{e+1}.pth.tar', 189 | ), 190 | ) 191 | 192 | 193 | def adjust_learning_rate(optimizer, epoch, args, cfg): 194 | """Decays the learning rate with half-cycle cosine after warmup""" 195 | if epoch < cfg["ssl"]["warmup_epochs"]: 196 | lr = args.lr * epoch / cfg["ssl"]["warmup_epochs"] 197 | else: 198 | lr = ( 199 | args.lr 200 | * 0.5 201 | * ( 202 | 1.0 203 | + math.cos( 204 | math.pi 205 | * (epoch - cfg["ssl"]["warmup_epochs"]) 206 | / (cfg["ssl"]["epochs"] - cfg["ssl"]["warmup_epochs"]) 207 | ) 208 | ) 209 | ) 210 | for param_group in optimizer.param_groups: 211 | param_group["lr"] = lr 212 | return lr 213 | 214 | 215 | def adjust_moco_momentum(epoch, cfg): 216 | """Adjust moco momentum based on current epoch""" 217 | m = 1.0 - 0.5 * (1.0 + math.cos(math.pi * epoch / cfg["ssl"]["epochs"])) * ( 218 | 1.0 - cfg["ssl"]["moco_m"] 219 | ) 220 | return m 221 | 222 | 223 | if __name__ == "__main__": 224 | parser = argparse.ArgumentParser(description="Cobra-training.") 225 | 226 | # Add the command-line argument for the config path 227 | parser.add_argument( 228 | "-c", "--config", type=str, default="config.yml", help="Path to the config file" 229 | ) 230 | parser.add_argument( 231 | "--world-size", 232 | default=1, 233 | type=int, 234 | help="number of nodes for distributed training", 235 | ) 236 | parser.add_argument( 237 | "--rank", default=0, type=int, help="node rank for distributed training" 238 | ) 239 | parser.add_argument( 240 | "--dist-url", 241 | default="env://", #"tcp://localhost:23459", 242 | type=str, 243 | help="url used to set up distributed training", 244 | ) 245 | parser.add_argument( 246 | "--dist-backend", default="nccl", type=str, help="distributed backend" 247 | ) 248 | parser.add_argument( 249 | "--seed", default=None, type=int, help="seed for initializing training. " 250 | ) 251 | parser.add_argument("--gpu", default=None, type=int, help="GPU id to use.") 252 | parser.add_argument( 253 | "--resume", 254 | default="", 255 | type=str, 256 | metavar="PATH", 257 | help="path to latest checkpoint (default: none)", 258 | ) 259 | parser.add_argument( 260 | "--job_id", 261 | default="", 262 | type=str, 263 | help="Job ID for the training run", 264 | ) 265 | args = parser.parse_args() 266 | 267 | with open(args.config, "r") as f: 268 | cfg_data = yaml.safe_load(f) 269 | 270 | template_env = Environment(loader=FileSystemLoader(searchpath="./")) 271 | template = template_env.from_string(str(cfg_data)) 272 | # Render the template with the values from the config_data 273 | cfg = yaml.safe_load(template.render(**cfg_data)) 274 | cfg["general"]["job_id"] = args.job_id 275 | exp_str = datetime.now().strftime("%Y-%m-%d-%H:%M") 276 | cfg["general"]["paths"]["out_dir"] = os.path.join( 277 | cfg["general"]["paths"]["out_dir"], exp_str, cfg["general"]["job_id"] 278 | ) 279 | cfg["general"]["paths"]["chkpt_dir"] = os.path.join( 280 | cfg["general"]["paths"]["out_dir"], "checkpoints" 281 | ) 282 | 283 | # for k in cfg.keys(): 284 | for path in cfg["general"]["paths"].values(): 285 | Path(path).mkdir(parents=True, exist_ok=True) 286 | 287 | if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: 288 | args.rank = int(os.environ["RANK"]) 289 | args.world_size = int(os.environ['WORLD_SIZE']) 290 | args.gpu = int(os.environ['LOCAL_RANK']) 291 | 292 | cfg["general"]["world_size"] = args.world_size 293 | 294 | with open(os.path.join(cfg["general"]["paths"]["out_dir"], f"config-{args.job_id}.yml"), "w") as f: 295 | yaml.dump(cfg, f, sort_keys=False, default_flow_style=False) 296 | 297 | main(args, cfg) 298 | -------------------------------------------------------------------------------- /cobra/crossval/train.py: -------------------------------------------------------------------------------- 1 | import os 2 | import yaml 3 | import pandas as pd 4 | import numpy as np 5 | import h5py 6 | import torch 7 | import torchmetrics 8 | from torchmetrics.classification import MulticlassAUROC 9 | import pytorch_lightning as pl 10 | from pytorch_lightning.callbacks import EarlyStopping, ModelCheckpoint 11 | from sklearn.model_selection import StratifiedKFold 12 | from torch.utils.data import DataLoader, Dataset, random_split 13 | import argparse 14 | from sklearn.preprocessing import LabelEncoder 15 | import torch.nn as nn 16 | import torch.optim as optim 17 | import warnings 18 | import pickle 19 | 20 | 21 | class PatientDataset(Dataset): 22 | def __init__(self, h5_file, patient_ids, target_ids): 23 | self.h5_file = h5_file 24 | 25 | self.target_ids = target_ids 26 | self.patient_ids = patient_ids 27 | 28 | def __len__(self): 29 | return len(self.patient_ids) 30 | 31 | def __getitem__(self, idx): 32 | patient_id = self.patient_ids[idx] 33 | target = self.target_ids[idx] 34 | with h5py.File(self.h5_file, 'r') as f: 35 | features = f[patient_id][:] 36 | return torch.tensor(features, dtype=torch.float32), torch.tensor( 37 | target, dtype=torch.long 38 | ) 39 | 40 | 41 | class MLP(pl.LightningModule): 42 | def __init__(self, input_dim, output_dim, hidden_dim=512, lr=1e-4,dropout=0.5): 43 | super(MLP, self).__init__() 44 | self.model = nn.Sequential( 45 | nn.LayerNorm(input_dim), 46 | nn.Linear(input_dim, hidden_dim), 47 | nn.SiLU(), 48 | nn.Dropout(dropout), 49 | nn.Linear(hidden_dim, output_dim), 50 | ) 51 | self.criterion = nn.CrossEntropyLoss() 52 | self.accuracy = torchmetrics.Accuracy(task="multiclass", num_classes=output_dim) 53 | self.valid_auroc = MulticlassAUROC(output_dim) 54 | self.test_auroc = MulticlassAUROC(output_dim) 55 | self.lr = lr 56 | 57 | def forward(self, x): 58 | return self.model(x) 59 | 60 | def training_step(self, batch, batch_idx): 61 | x, y = batch 62 | y_hat = self(x) 63 | loss = self.criterion(y_hat, y) 64 | acc = self.accuracy(y_hat, y) 65 | # auroc = self.auroc(y_hat, y) 66 | self.log("train_loss", loss, on_step=False, on_epoch=True, prog_bar=True) 67 | self.log("train_acc", acc, on_step=False, on_epoch=True, prog_bar=True) 68 | return loss 69 | 70 | def validation_step(self, batch, batch_idx): 71 | x, y = batch 72 | y_hat = self(x) 73 | loss = self.criterion(y_hat, y) 74 | acc = self.accuracy(y_hat, y) 75 | self.valid_auroc.update(y_hat, y) 76 | self.log("val_loss", loss, on_step=False, on_epoch=True, prog_bar=True) 77 | self.log("val_acc", acc, on_step=False, on_epoch=True, prog_bar=True) 78 | self.log( 79 | "val_auroc", self.valid_auroc, on_step=False, on_epoch=True, prog_bar=True 80 | ) 81 | return loss 82 | 83 | def test_step(self, batch, batch_idx): 84 | x, y = batch 85 | y_hat = self(x) 86 | loss = self.criterion(y_hat, y) 87 | acc = self.accuracy(y_hat, y) 88 | self.test_auroc.update(y_hat, y) 89 | self.log("test_loss", loss) 90 | self.log("test_acc", acc) 91 | self.log("test_auroc", self.test_auroc) 92 | return loss 93 | 94 | def configure_optimizers(self): 95 | optimizer = optim.Adam(self.parameters(), lr=self.lr) 96 | return optimizer 97 | 98 | 99 | def load_config(config_path): 100 | with open(config_path, "r") as file: 101 | cfg = yaml.safe_load(file) 102 | return cfg 103 | 104 | 105 | def main(config_path): 106 | """ 107 | Main function to orchestrate the training and cross-validation process for the MLP model. 108 | 109 | This function performs the following operations: 110 | - Loads the training configuration from a provided YAML file. 111 | - Ensures that the output folder exists and saves a copy of the configuration. 112 | - Reads input data from a CSV or Excel file, while verifying that the file format is supported. 113 | - Cleans the data by removing rows with missing target values. 114 | - Encodes target labels using a LabelEncoder and saves the encoder for later use. 115 | - Loads patient IDs from an H5 file and compares them with those in the CSV, issuing warnings if there are any mismatches. 116 | - Filters the dataset to include only common patient IDs present in both files. 117 | - Sets up stratified K-fold cross-validation, ensuring balanced splits based on the target labels. 118 | - For each fold: 119 | - Splits the data into training/validation and test sets. 120 | - Constructs PyTorch DataLoaders for training, validation, and testing. 121 | - Instantiates an MLP model with parameters specified in the configuration. 122 | - Trains the model using PyTorch Lightning, with callbacks for model checkpointing and early stopping. 123 | - Evaluates the model on the test set and logs the test AUROC metric. 124 | - Stores detailed test results (including patient IDs, predictions, ground truth, and loss) as CSV files. 125 | - Aggregates the AUROC scores across all folds and saves the summary to disk. 126 | 127 | Parameters: 128 | config_path (str): The file path to the YAML configuration file containing training settings, data paths, and hyperparameters. 129 | 130 | Raises: 131 | ValueError: If the input data file format is unsupported (i.e., not a CSV or XLSX file). 132 | 133 | Returns: 134 | None 135 | 136 | Side Effects: 137 | - Creates directories and files (config.yaml, label_encoder.pkl, best_model.ckpt, test results CSVs, and fold AUROC CSV) in the specified output folder. 138 | - Logs progress and warnings via printed messages and the warnings module. 139 | """ 140 | cfg = load_config(config_path)["train"] 141 | if not os.path.exists(cfg["output_folder"]): 142 | os.makedirs(cfg["output_folder"]) 143 | config_output_path = os.path.join(cfg["output_folder"], "config.yaml") 144 | with open(config_output_path, "w") as file: 145 | yaml.dump(cfg, file) 146 | hps = cfg["hps"] 147 | if cfg["csv_path"].endswith(".csv"): 148 | data = pd.read_csv(cfg["csv_path"]) 149 | elif cfg["csv_path"].endswith(".xlsx"): 150 | data = pd.read_excel(cfg["csv_path"]) 151 | else: 152 | raise ValueError(f"Unsupported file format: only .csv and .xlsx are supported found {os.path.splitext(cfg['csv_path'])[1]}") 153 | data = data.dropna(subset=[cfg["target_column"]], axis=0) 154 | targets = data[cfg["target_column"]].values 155 | label_encoder = LabelEncoder() 156 | targets = label_encoder.fit_transform(targets) 157 | patient_ids = data[cfg["patient_id_column"]].values 158 | 159 | torch.set_float32_matmul_precision("high") 160 | 161 | label_encoder_path = os.path.join(cfg["output_folder"], "label_encoder.pkl") 162 | with open(label_encoder_path, "wb") as f: 163 | pickle.dump(label_encoder, f) 164 | with h5py.File(cfg["h5_path"], "r") as f: 165 | h5_patient_ids = list(f.keys()) 166 | 167 | csv_patient_ids_set = set(patient_ids) 168 | h5_patient_ids_set = set(h5_patient_ids) 169 | 170 | missing_in_h5 = csv_patient_ids_set - h5_patient_ids_set 171 | missing_in_csv = h5_patient_ids_set - csv_patient_ids_set 172 | 173 | if missing_in_h5: 174 | warnings.warn(f"Patient IDs missing in H5 file: {missing_in_h5}") 175 | if missing_in_csv: 176 | warnings.warn(f"Patient IDs missing in CSV file: {missing_in_csv}") 177 | 178 | common_patient_ids = list(csv_patient_ids_set & h5_patient_ids_set) 179 | common_indices = [ 180 | i for i, pid in enumerate(patient_ids) if pid in common_patient_ids 181 | ] 182 | 183 | patient_ids = patient_ids[common_indices] 184 | targets = targets[common_indices] 185 | 186 | skf = StratifiedKFold(n_splits=hps["n_folds"], shuffle=True, random_state=42) 187 | all_fold_aurocs = [] 188 | for fold, (train_val_idx, test_idx) in enumerate(skf.split(patient_ids, targets)): 189 | fold_output_folder = os.path.join(cfg["output_folder"], f"fold_{fold}") 190 | if os.path.exists(os.path.join(fold_output_folder, "best_model.ckpt")): 191 | print(f"Model for fold {fold} already exists. Skipping this fold.") 192 | continue 193 | train_val_ids = patient_ids[train_val_idx] 194 | train_val_targets = targets[train_val_idx] 195 | test_ids = patient_ids[test_idx] 196 | test_targets = targets[test_idx] 197 | 198 | train_val_dataset = PatientDataset( 199 | cfg["h5_path"], 200 | train_val_ids, 201 | train_val_targets, 202 | ) 203 | test_dataset = PatientDataset( 204 | cfg["h5_path"], 205 | test_ids, 206 | test_targets, 207 | ) 208 | 209 | train_size = int(0.8 * len(train_val_dataset)) 210 | val_size = len(train_val_dataset) - train_size 211 | train_dataset, val_dataset = random_split( 212 | train_val_dataset, [train_size, val_size] 213 | ) 214 | 215 | train_loader = DataLoader( 216 | train_dataset, 217 | batch_size=hps["batch_size"], 218 | shuffle=True, 219 | num_workers=hps["num_workers"], 220 | ) 221 | val_loader = DataLoader(val_dataset, batch_size=1, drop_last=False) 222 | test_loader = DataLoader(test_dataset, batch_size=1, drop_last=False) 223 | 224 | input_dim = train_dataset[0][0].shape[0] 225 | output_dim = len(np.unique(targets)) 226 | print(f"Input dim: {input_dim}, Output dim: {output_dim}") 227 | 228 | model = MLP(input_dim, output_dim, hidden_dim=hps["hidden_dim"], lr=hps["lr"],dropout=hps["dropout"]) 229 | 230 | if not os.path.exists(cfg["output_folder"]): 231 | os.makedirs(cfg["output_folder"]) 232 | 233 | checkpoint_callback = ModelCheckpoint( 234 | dirpath=fold_output_folder, 235 | filename="best_model", 236 | save_top_k=1, 237 | monitor="val_loss", 238 | mode="min", 239 | ) 240 | early_stopping_callback = EarlyStopping( 241 | monitor="val_loss", patience=hps["patience"], mode="min" 242 | ) 243 | 244 | trainer = pl.Trainer( 245 | max_epochs=hps["max_epochs"], 246 | callbacks=[checkpoint_callback, early_stopping_callback], 247 | devices=1, # Use only one GPU 248 | accelerator="gpu", 249 | ) 250 | 251 | trainer.fit(model, train_loader, val_loader) 252 | 253 | model = MLP.load_from_checkpoint( 254 | checkpoint_callback.best_model_path, 255 | input_dim=input_dim, 256 | output_dim=output_dim, 257 | hidden_dim=hps["hidden_dim"], 258 | ) 259 | trainer.test(model, test_loader) 260 | 261 | with torch.inference_mode(): 262 | test_results = [] 263 | for i, (x, y) in enumerate(test_loader): 264 | y_hat = model(x) 265 | loss = model.criterion(y_hat, y).item() 266 | test_results.append( 267 | { 268 | "patient_id": test_ids[i], 269 | "ground_truth": label_encoder.inverse_transform(y.numpy())[0], 270 | "prediction": label_encoder.inverse_transform( 271 | y_hat.argmax(dim=1).numpy() 272 | )[0], 273 | "loss": loss, 274 | } 275 | ) 276 | 277 | test_results_df = pd.DataFrame(test_results) 278 | test_results_df.to_csv( 279 | os.path.join(cfg["output_folder"], f"fold_{fold}_test_results.csv"), 280 | index=False, 281 | ) 282 | avg_auroc = trainer.callback_metrics["test_auroc"].item() 283 | print(f"Fold {fold} Test AUROC: {avg_auroc}") 284 | 285 | all_fold_aurocs.append(avg_auroc) 286 | auroc_df = pd.DataFrame({"fold": list(range(len(all_fold_aurocs))), "auroc": all_fold_aurocs}) 287 | auroc_df.to_csv(os.path.join(cfg["output_folder"], "fold_aurocs.csv"), index=False) 288 | avg_auroc_over_folds = np.mean(all_fold_aurocs) 289 | print(f"Average Test AUROC over all folds: {avg_auroc_over_folds}") 290 | 291 | 292 | if __name__ == "__main__": 293 | parser = argparse.ArgumentParser(description="Train MLP with cross-validation") 294 | parser.add_argument("-c", "--config", type=str, help="Path to the config file") 295 | args = parser.parse_args() 296 | main(args.config) 297 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # COntrastive Biomarker Representation Alignment (COBRA) 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | ## Table of Contents 13 | 14 | - [Abstract](#abstract) 15 | - [News](#news) 16 | - [Installation](#installation) 17 | - [Feature Extraction](#feature-extraction) 18 | - [Crossvalidation](#crossvalidation) 19 | - [Heatmaps](#generating-heatmaps) 20 | - [Pretraining](#pretraining) 21 | - [References](#references) 22 | - [Citation](#citation) 23 | 24 | ## Abstract 25 | 26 | 27 | > Representation learning of pathology whole-slide images (WSIs) has primarily relied on weak supervision with Multiple Instance Learning (MIL). This approach leads to slide representations highly tailored to a specific clinical task. Self-supervised learning (SSL) has been successfully applied to train histopathology foundation models (FMs) for patch embedding generation. However, generating patient or slide level embeddings remains challenging. Existing approaches for slide representation learning extend the principles of SSL from patch level learning to entire slides by aligning different augmentations of the slide or by utilizing multimodal data. By integrating tile embeddings from multiple FMs, we propose a new single modality SSL method in feature space that generates useful slide representations. Our contrastive pretraining strategy, called COBRA, employs multiple FMs and an architecture based on Mamba-2. COBRA exceeds performance of state-of-the-art slide encoders on several public cohorts by at least +4.4% AUC, despite only being pretrained on a limited set of WSIs. Additionally, COBRA is readily compatible at inference time with previously unseen feature extractors. 28 | 29 |

30 | COBRA overview 31 |

32 | 33 | ## News 34 | - **[Feb 27th 2025]** Our [paper](https://arxiv.org/abs/2411.13623) has been accepted to [CVPR 2025](https://cvpr.thecvf.com/Conferences/2025/AcceptedPapers)! 🎉 35 | - **[Feb 7th 2025]**: [COBRA II](https://huggingface.co/KatherLab/COBRA) trained on all TCGA cohorts, is now live and ready to use!! 36 | 37 | ## Installation 38 | 39 | To install the necessary dependencies, run the following commands: 40 | 41 | ```bash 42 | git clone https://github.com/KatherLab/COBRA.git && cd COBRA 43 | pip install uv 44 | uv venv --python=3.11 45 | source .venv/bin/activate 46 | uv pip install torch==2.4.1 setuptools packaging wheel numpy==2.0.0 47 | uv sync --no-build-isolation 48 | ``` 49 | 50 | If there are any **issues**, consider also installing hatchling and editables: 51 | 52 | 53 | ```bash 54 | uv pip install hatchling editables 55 | ``` 56 | 57 | And make sure python3.11-devel (or python3.11-dev) is installed. For Fedora or derivatives: 58 | 59 | ```bash 60 | dnf install python3.11-devel 61 | ``` 62 | 63 | For Debian or derivatives: 64 | 65 | ```bash 66 | apt install python3.11-dev 67 | ``` 68 | 69 | ## Feature extraction 70 | 71 | To deploy the COBRA model to extract WSI-level or even patient-level embeddings, follow these steps: 72 | 73 | 1. **Prepare your data**: Extract tile embeddings with one or more patch encoders of your choice using [STAMP](https://github.com/KatherLab/STAMP). 74 | - **COBRA I:** 75 | - Supported tissue types: LUAD, LUSC, STAD, CRC, BRCA 76 | - Supported patch encoders to generate weighting: CTransPath, UNI, Virchow2, H_optimus_0 77 | - Supported patch encoders for patch feature aggregation: all existing patch encoders 78 | - **COBRA II:** 79 | - Supported tissue types: all tissue types included in TCGA 80 | - Supported patch encoders to generate COBRAII weighting: CONCH, UNI, Virchow2, H_optimus_0 81 | - Supported patch encoders for patch feature aggregation: all existing patch encoders 82 | 83 | 2. **Request Access** on [Huggingface](https://huggingface.co/KatherLab/COBRA). 84 | 85 | 3. **Extract COBRA Features**: 86 | The extraction scripts allow you to obtain slide‑ or patient‑level embeddings. In addition to standard command‑line arguments, you can now supply a YAML configuration file (using the `--config` flag) which overrides or specifies all extraction parameters (such as input directories, checkpoint paths, top‑k selection, etc.). 87 | 88 | **Example configuration (extract_feats_config.yml):** 89 | 90 | ```yaml 91 | extract_feats: 92 | download_model: false 93 | checkpoint_path: "/path/to/checkpoint.pth.tar" 94 | top_k: null 95 | output_dir: "/path/to/extracted/output" 96 | feat_dir: "/path/to/tile_embeddings" 97 | feat_dir_a: "/path/to/tile_embeddings_aux" # Optional, for aggregation features 98 | model_name: "COBRAII" 99 | patch_encoder: "Virchow2" 100 | patch_encoder_a: "Virchow2" 101 | h5_name: "cobra_feats.h5" 102 | microns: 224 103 | use_cobraI: false # wheter to use cobraI or cobraII 104 | slide_table: "/path/to/slide_table.csv" # Provide for patient-level extraction, omit for slide-level 105 | ``` 106 | 107 | **Usage:** 108 | 109 | - **Slide-level extraction** (without a slide table): 110 | 111 | ```bash 112 | python -m cobra.inference.extract_feats --feat_dir "/path/to/tile_embeddings" --output_dir "/path/to/slide_embeddings" --checkpoint_path "/path/to/checkpoint.pth.tar" 113 | ``` 114 | 115 | Or by providing a configuration file: 116 | 117 | ```bash 118 | python -m cobra.inference.extract_feats --config /path/to/extract_feats_config.yml 119 | ``` 120 | 121 | - **Patient-level extraction** (using a slide table): 122 | 123 | ```bash 124 | python -m cobra.inference.extract_feats --feat_dir "/path/to/tile_embeddings" --output_dir "/path/to/patient_embeddings" --slide_table "/path/to/slide_table.csv" --checkpoint_path "/path/to/checkpoint.pth.tar" 125 | ``` 126 | 127 | Or with configuration: 128 | 129 | ```bash 130 | python -m cobra.inference.extract_feats --config /path/to/extract_feats_config.yml 131 | ``` 132 | 133 | > *Note:* You have the option of providing different directories for weighting and aggregation steps. The script will load primary features from `--feat_dir` and, if provided, additional features from `--feat_dir_a`. Features are matched by their coordinates before aggregation. 134 | 135 | ## Crossvalidation 136 | 137 | After extracting the COBRA features (either at the slide or patient level), you can run crossvalidation to train and evaluate a downstream MLP classifier. The crossvalidation workflow is managed by two main scripts. 138 | 139 | ### 1. Training with Crossvalidation 140 | 141 | The `cobra/crossval/train.py` script performs stratified K-fold crossvalidation and saves test predictions, AUROC scores, and the best model checkpoints per fold. 142 | You need to supply a configuration file that specifies the following: 143 | - **CSV/Excel metadata file** with patient IDs and target values. 144 | - **H5 file** with extracted features. 145 | - **Output folder** for saving checkpoints and results. 146 | - **Hyperparameters** for training (learning rate, hidden dimension, batch size, number of folds, etc.). 147 | 148 | **Example configuration (crossval.yml):** 149 | 150 | ```yaml 151 | train: 152 | csv_path: "/path/to/metadata.csv" 153 | target_column: "TARGET" 154 | patient_id_column: "PATIENT_ID" 155 | h5_path: "/path/to/extracted_features.h5" 156 | output_folder: "/path/to/crossval/results" 157 | hps: 158 | lr: 0.0005 159 | hidden_dim: 512 160 | max_epochs: 64 161 | patience: 16 162 | batch_size: 32 163 | num_workers: 8 164 | n_folds: 5 165 | dropout: 0.3 166 | 167 | deploy: 168 | csv_path: "/path/to/test_metadata.csv" 169 | target_column: "TARGET" 170 | patient_id_column: "PATIENT_ID" 171 | h5_path: "/path/to/extracted_features.h5" 172 | output_folder: "/path/to/deploy/results" 173 | label_encoder_path: "/path/to/label_encoder.pkl" 174 | hps: 175 | hidden_dim: 512 176 | n_folds: 5 177 | ``` 178 | 179 | **Usage:** 180 | 181 | Train with: 182 | 183 | ```bash 184 | python -m cobra.crossval.train -c /path/to/crossval.yml 185 | ``` 186 | 187 | During training, the script: 188 | - Loads the CSV metadata and matches patient IDs with those in the H5 file. 189 | - Encodes the target labels and saves the encoder. 190 | - Splits data using Stratified K-Fold. 191 | - Trains the MLP with PyTorch Lightning (using early stopping and checkpoint callbacks). 192 | - Evaluates each fold and saves detailed results (including per-patient predictions and AUROC scores). 193 | 194 | ### 2. Deployment and Evaluation 195 | 196 | The corresponding deployment script (`cobra/crossval/deploy.py`) lets you evaluate a trained model on unseen data. Its configuration file should include: 197 | - CSV metadata file with test targets. 198 | - H5 file with features used during inference. 199 | - Path to the saved label encoder from training. 200 | - Output folder for saving summaries and predictions. 201 | 202 | **Usage:** 203 | 204 | ```bash 205 | python -m cobra.crossval.deploy -c /path/to/crossval.yml 206 | ``` 207 | 208 | This script loads the best checkpoints from training, matches test patient IDs with the H5 file, computes evaluation metrics (e.g., AUROC), and saves both per-fold and aggregated results. 209 | 210 | > *Note:* Use your crossvalidation configuration file to supply all necessary file paths and hyperparameters. 211 | 212 | ## Generating Heatmaps 213 | 214 | The `cobra/inference/heatmaps.py` script generates visual heatmaps of WSIs by overlaying model attention maps. 215 | 216 | ### How It Works 217 | - Reads tile feature files (HDF5) and corresponding WSIs. 218 | - Computes attention values from the COBRA model. 219 | - Creates a composite image combining the slide thumbnail and a heatmap. 220 | - Adds a 2 mm scale bar for reference. 221 | - Saves the final composite as a PDF. 222 | 223 | ### Example Configuration (heatmap_config.yml) 224 | 225 | ```yaml 226 | heatmap: 227 | feat_dir: "/path/to/tile_embeddings" # Directory for tile feature files (HDF5) 228 | wsi_dir: "/path/to/wsi_files" # Directory for whole slide images 229 | checkpoint_path: "/path/to/checkpoint.pth.tar" # Model checkpoint path 230 | microns: 112 # Microns per patch used for extraction 231 | patch_size: 224 # Size of each patch in pixels 232 | output_dir: "/path/to/heatmap/output" # Where to save generated heatmaps 233 | stamp_version: 2 # Stamp version used during extraction 234 | ``` 235 | 236 | ### Usage 237 | 238 | - With a configuration file: 239 | 240 | ```bash 241 | python -m cobra.inference.heatmaps -c /path/to/heatmap_config.yml 242 | ``` 243 | 244 | - Or via command-line arguments: 245 | 246 | ```bash 247 | python -m cobra.inference.heatmaps \ 248 | -f "/path/to/tile_embeddings" \ 249 | -s "/path/to/wsi_files" \ 250 | -w "/path/to/checkpoint.pth.tar" \ 251 | -r 112 \ 252 | -p 224 \ 253 | -o "/path/to/heatmap/output" \ 254 | -v 2 255 | ``` 256 | 257 | ## Pretraining 258 | 259 | COBRA is pretrained with constrastive self-supervised learning based on [MoCo-v3](https://github.com/facebookresearch/moco-v3). 260 | The code to pretrain COBRA is explained in the following. 261 | 262 | ### What It Does 263 | - Pretrains a COBRA-based model using tile-level features. 264 | - Uses a YAML configuration to specify model parameters, data paths, and training hyperparameters. 265 | - Saves pretrained weights for later use in feature extraction and downstream tasks. 266 | 267 | ### Example Configuration (cobraII.yml) 268 | 269 | ```yaml 270 | model: 271 | nr_heads: 4 272 | nr_mamba_layers: 1 273 | dim: 768 274 | input_dims: 275 | - 512 276 | - 1024 277 | - 1280 278 | - 1536 279 | l_dim: 256 280 | att_dim: 256 281 | dropout: 0.2 282 | d_state: 128 283 | model_name: "cobraII" 284 | 285 | ssl: 286 | moco_m: 0.99 287 | moco_t: 0.2 288 | lr: 5e-4 289 | warmup_epochs: 50 290 | weight_decay: 0.1 291 | epochs: 2000 292 | workers: 56 293 | batch_size: 1024 294 | 295 | general: 296 | nr_feats: 768 297 | fms: 298 | - "fm1" 299 | - "fm2" 300 | - "fm3" 301 | - "fm4" 302 | feat_base_paths: 303 | - "/path/to/features_set1" 304 | - "/path/to/features_set2" 305 | paths: 306 | out_dir: "/path/to/pretrain/output" 307 | ``` 308 | 309 | ### Usage 310 | 311 | ```bash 312 | python -m cobra.ssl.pretrain -c /path/to/config.yml 313 | ``` 314 | 315 | This script sets up the SSL pretraining using your specified configuration and trains the model on tile features. 316 | 317 | ## References 318 | 319 | - [CTransPath](https://github.com/Xiyue-Wang/TransPath) 320 | - [UNI](https://github.com/mahmoodlab/uni) 321 | - [Virchow2](https://huggingface.co/paige-ai/Virchow2) 322 | - [H-Optimus-0](https://github.com/bioptimus/releases/tree/main/models/h-optimus/v0) 323 | - [CONCH](https://github.com/mahmoodlab/CONCH) 324 | - [STAMP](https://github.com/KatherLab/STAMP) 325 | - [MoCo-v3](https://github.com/facebookresearch/moco-v3) 326 | 327 | ## Citation 328 | 329 | If you find our work useful in your research or if you use parts of this code please consider citing our paper: 330 | 331 | ```bibtex 332 | @InProceedings{COBRA_2025_CVPR, 333 | author = {Lenz, Tim* and Neidlinger, Peter* and Ligero, Marta and W\"olflein, Georg and van Treeck, Marko and Kather, Jakob N.}, 334 | title = {Unsupervised Foundation Model-Agnostic Slide-Level Representation Learning}, 335 | booktitle = {Proceedings of the Computer Vision and Pattern Recognition Conference (CVPR)}, 336 | month = {June}, 337 | year = {2025}, 338 | pages = {30807-30817} 339 | } 340 | ``` 341 | -------------------------------------------------------------------------------- /cobra/inference/extract_feats.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import torch.nn.functional as F 4 | import h5py 5 | from tqdm import tqdm 6 | from glob import glob 7 | import warnings 8 | warnings.simplefilter(action="ignore", category=FutureWarning) 9 | from cobra.utils.load_cobra import get_cobra, get_cobraII 10 | import argparse 11 | 12 | from pathlib import Path 13 | import pandas as pd 14 | import numpy as np 15 | import json 16 | import yaml 17 | 18 | def load_patch_feats(h5_path,device): 19 | """ 20 | Load patch features from an HDF5 file. 21 | Args: 22 | h5_path (str): Path to the HDF5 file containing patch features. 23 | device (str): Device to load the features onto (e.g., "cuda" or "cpu"). 24 | Returns: 25 | feats (torch.Tensor): Loaded patch features as a PyTorch tensor. 26 | coords (np.ndarray): Coordinates associated with the patch features. 27 | """ 28 | if not os.path.exists(h5_path): 29 | tqdm.write(f"File {h5_path} does not exist, skipping") 30 | return None 31 | with h5py.File(h5_path, "r") as f: 32 | feats = f["feats"][:] 33 | feats = torch.tensor(feats).to(device) 34 | coords = np.array(f["coords"][:]) 35 | return feats, coords 36 | 37 | def match_coords(feats_w,feats_a,coords_w,coords_a): 38 | """ 39 | Match and extract features whose corresponding coordinates are identical in two sets. 40 | 41 | It uses np.intersect1d to compute the intersection (in sorted order) 42 | of the coordinate arrays, and returns the features accordingly. 43 | 44 | Parameters: 45 | feats_w (np.ndarray): Feature array for weighted patches. 46 | feats_a (np.ndarray): Feature array for auxiliary patches. 47 | coords_w (np.ndarray): Coordinates for feats_w with shape (N, D). 48 | coords_a (np.ndarray): Coordinates for feats_a with shape (M, D). 49 | 50 | Returns: 51 | tuple: (matched_feats_w, matched_feats_a) where the i-th entry in both arrays corresponds 52 | to the same common coordinate. 53 | 54 | Raises: 55 | ValueError: If no common coordinates are found. 56 | """ 57 | # Create structured views so entire rows can be compared as single elements. 58 | dt = np.dtype((np.void, coords_w.dtype.itemsize * coords_w.shape[1])) 59 | coords_w_view = np.ascontiguousarray(coords_w).view(dt).ravel() 60 | coords_a_view = np.ascontiguousarray(coords_a).view(dt).ravel() 61 | 62 | common, idx_w, idx_a = np.intersect1d(coords_w_view, coords_a_view, return_indices=True) 63 | if len(common) == 0: 64 | raise ValueError("No matching coordinates found") 65 | 66 | return feats_w[idx_w], feats_a[idx_a] 67 | 68 | def get_cobra_feats(model,patch_feats_w,patch_feats_a,top_k=None): 69 | """ 70 | Compute COBRA features by aggregating patch features using attention scores from the model. 71 | This function takes patch features and processes them with the given model to extract 72 | attention scores. If a top_k value is provided, it selects the top_k patches based on 73 | the attention scores, applies a softmax weighting over these scores, and computes a weighted 74 | sum of the corresponding patch features. Otherwise, it directly aggregates all patch 75 | features with the raw attention scores. 76 | Parameters: 77 | model (torch.nn.Module): The neural network model used to compute attention scores. 78 | It should accept patch_feats_w as input and support a "get_attention" 79 | keyword argument. 80 | patch_feats_w (torch.Tensor): The input patch features that are processed by the model to obtain 81 | attention scores. 82 | patch_feats_a (torch.Tensor): The patch features used for the final feature aggregation. 83 | top_k (int, optional): The number of top patches (based on attention score) to use for feature 84 | aggregation. If specified, only the top_k patches are aggregated; if not, 85 | all patches are used. 86 | Returns: 87 | torch.Tensor: The aggregated COBRA features as a 1D tensor (after squeezing the unnecessary dimensions). 88 | Notes: 89 | - The function runs within torch.inference_mode() to disable gradient calculations. 90 | - When top_k is used, the function ensures that top_k does not exceed the total number of patches. 91 | - The attention weights are normalized using softmax before being used for aggregation. 92 | """ 93 | with torch.inference_mode(): 94 | A = model(patch_feats_w,get_attention=True) 95 | # A.shape: (1,1,num_patches) 96 | if top_k: 97 | if A.size(-1) < top_k: 98 | top_k = A.size(-1) 99 | top_k_indices = torch.topk(A, top_k, dim=-1).indices # (1,1,top_k) 100 | top_k_A = A.gather(-1, top_k_indices) # (1,1,top_k) 101 | top_k_x = patch_feats_a.gather(1, top_k_indices.squeeze(0).unsqueeze(-1).expand(-1, -1, patch_feats_a.size(-1))) 102 | # top_k_x.shape: (1,top_k,feat_dim) 103 | cobra_feats = torch.bmm(F.softmax(top_k_A,dim=-1), top_k_x).squeeze(1) 104 | # cobra_feats.shape: (1,feat_dim) 105 | else: 106 | cobra_feats = torch.bmm(A, patch_feats_a).squeeze(1) 107 | return cobra_feats.squeeze(0) 108 | 109 | def get_pat_embs( 110 | model, 111 | output_dir, 112 | feat_dir_w, 113 | feat_dir_a=None, 114 | output_file="cobra-feats.h5", 115 | model_name="COBRAII", 116 | slide_table_path=None, 117 | device="cuda", 118 | dtype=torch.float32, 119 | top_k=None, 120 | weighting_fm="Virchow2", 121 | aggregation_fm="Virchow2", 122 | microns=224, 123 | ): 124 | """ 125 | Extract patient-level features from slide-level feature files and save them into an HDF5 file. 126 | Loads a slide table CSV file grouping slides by patient, then for each patient loads features from 127 | the provided directories and aggregates them. Optionally, match_coords is applied only if an alternative 128 | feature directory is provided and weighting_fm != aggregation_fm. 129 | """ 130 | slide_table = pd.read_csv(slide_table_path) 131 | patient_groups = slide_table.groupby("PATIENT") 132 | pat_dict = {} 133 | 134 | output_file = os.path.join(output_dir, output_file) 135 | if os.path.exists(output_file) and os.path.getsize(output_file) > 800: 136 | tqdm.write(f"Output file {output_file} already exists, skipping") 137 | return 138 | 139 | # Determine if we need to run match_coords. 140 | do_match = (feat_dir_a is not None) and (weighting_fm != aggregation_fm) 141 | if do_match: 142 | print("Using match_coords for patient-level extraction (weighting_fm != aggregation_fm).") 143 | else: 144 | print("Skipping match_coords for patient-level extraction (using identical features or no auxiliary features).") 145 | 146 | for patient_id, group in tqdm(patient_groups, leave=False): 147 | all_feats_list_w = [] 148 | all_feats_list_a = [] 149 | 150 | for _, row in group.iterrows(): 151 | slide_filename = row["FILENAME"] 152 | h5_path_w = os.path.join(feat_dir_w, str(slide_filename)) 153 | if not h5_path_w.endswith(".h5"): 154 | h5_path_w+=".h5" 155 | feats_w, coords_w = load_patch_feats(h5_path_w, device) 156 | if feats_w is None: 157 | continue 158 | 159 | # Load auxiliary features if available; otherwise, use weighted features. 160 | if feat_dir_a: 161 | h5_path_a = os.path.join(feat_dir_a, str(slide_filename)) 162 | if not h5_path_a.endswith(".h5"): 163 | h5_path_a+=".h5" 164 | feats_a, coords_a = load_patch_feats(h5_path_a, device) 165 | else: 166 | feats_a, coords_a = feats_w, coords_w 167 | 168 | if feats_a is None: 169 | continue 170 | 171 | # Perform coordinate matching only if required. 172 | if do_match: 173 | feats_w, feats_a = match_coords(feats_w, feats_a, coords_w, coords_a) 174 | # Else, assume features are already aligned. 175 | 176 | all_feats_list_w.append(feats_w) 177 | all_feats_list_a.append(feats_a) 178 | 179 | if all_feats_list_w: 180 | all_feats_cat_w = torch.cat(all_feats_list_w, dim=0).unsqueeze(0) 181 | all_feats_cat_a = torch.cat(all_feats_list_a, dim=0).unsqueeze(0) 182 | assert all_feats_cat_w.ndim == 3, f"Expected 3D tensor, got {all_feats_cat_w.ndim}" 183 | assert all_feats_cat_a.ndim == 3, f"Expected 3D tensor, got {all_feats_cat_a.ndim}" 184 | assert ( 185 | all_feats_cat_w.shape[1] == all_feats_cat_a.shape[1] 186 | ), f"Expected same number of tiles, got {all_feats_cat_w.shape[1]} and {all_feats_cat_a.shape[1]}" 187 | patient_feats = get_cobra_feats(model, all_feats_cat_w.to(dtype), all_feats_cat_a.to(dtype), top_k=top_k) 188 | pat_dict[patient_id] = { 189 | "feats": patient_feats.to(torch.float32).detach().squeeze().cpu().numpy(), 190 | } 191 | else: 192 | tqdm.write(f"No features found for patient {patient_id}, skipping") 193 | 194 | os.makedirs(os.path.dirname(output_file), exist_ok=True) 195 | with h5py.File(output_file, "w") as f: 196 | for patient_id, data in pat_dict.items(): 197 | f.create_dataset(f"{patient_id}", data=data["feats"]) 198 | f.attrs["extractor"] = model_name 199 | f.attrs["top_k"] = top_k if top_k else "None" 200 | f.attrs["dtype"] = str(dtype) 201 | f.attrs["weighting_FM"] = weighting_fm 202 | f.attrs["aggregation_FM"] = aggregation_fm 203 | f.attrs["microns"] = microns 204 | 205 | tqdm.write(f"Finished extraction, saved to {output_file}") 206 | metadata = { 207 | "extractor": model_name, 208 | "top_k": top_k if top_k else "None", 209 | "dtype": str(dtype), 210 | "weighting_FM": weighting_fm, 211 | "aggregation_FM": aggregation_fm, 212 | "microns": microns, 213 | } 214 | with open(os.path.join(output_dir, "metadata.json"), "w") as json_file: 215 | json.dump(metadata, json_file, indent=4) 216 | 217 | def get_slide_embs( 218 | model, 219 | output_dir, 220 | feat_dir_w, 221 | feat_dir_a=None, 222 | output_file="cobra-feats.h5", 223 | model_name="COBRAII", 224 | device="cuda", 225 | dtype=torch.float32, 226 | top_k=None, 227 | weighting_fm="Virchow2", 228 | aggregation_fm="Virchow2", 229 | microns=224, 230 | ): 231 | """ 232 | Generates slide-level features from tile embeddings and saves them to an HDF5 file along with metadata. 233 | Loads tile embeddings from the provided directories, optionally applies match_coords (only when feat_dir_a is provided and 234 | weighting_fm != aggregation_fm), and computes slide features via model aggregation. 235 | """ 236 | slide_dict = {} 237 | 238 | tile_emb_paths_w = glob(f"{feat_dir_w}/**/*.h5", recursive=True) 239 | if feat_dir_a is not None: 240 | tile_emb_paths_a = glob(f"{feat_dir_a}/**/*.h5", recursive=True) 241 | else: 242 | tile_emb_paths_a = tile_emb_paths_w 243 | 244 | assert len(tile_emb_paths_w) == len(tile_emb_paths_a), ( 245 | f"Expected same number of files, got {len(tile_emb_paths_w)} and {len(tile_emb_paths_a)}" 246 | ) 247 | 248 | # Determine if we need to run match_coords. 249 | do_match = (feat_dir_a is not None) and (weighting_fm != aggregation_fm) 250 | if do_match: 251 | print("Using match_coords for slide-level extraction (weighting_fm != aggregation_fm).") 252 | else: 253 | print("Skipping match_coords for slide-level extraction (using identical features or no auxiliary features).") 254 | 255 | for tile_emb_path_w, tile_emb_path_a in zip(tqdm(tile_emb_paths_w), tile_emb_paths_a): 256 | slide_name = Path(tile_emb_path_w).stem 257 | feats_w, coords_w = load_patch_feats(tile_emb_path_w, device) 258 | if feats_w is None: 259 | continue 260 | if feat_dir_a: 261 | tile_emb_path_a = os.path.join(feat_dir_a, f"{slide_name}.h5") 262 | feats_a, coords_a = load_patch_feats(tile_emb_path_a, device) 263 | else: 264 | feats_a, coords_a = feats_w, coords_w 265 | if feats_a is None: 266 | continue 267 | 268 | if do_match: 269 | feats_w, feats_a = match_coords(feats_w, feats_a, coords_w, coords_a) 270 | 271 | tile_embs_w = feats_w.unsqueeze(0) 272 | tile_embs_a = feats_a.unsqueeze(0) 273 | assert tile_embs_w.ndim == 3, f"Expected 3D tensor, got {tile_embs_w.ndim}" 274 | assert tile_embs_a.ndim == 3, f"Expected 3D tensor, got {tile_embs_a.ndim}" 275 | assert tile_embs_w.shape[1] == tile_embs_a.shape[1], ( 276 | f"Expected same number of tiles, got {tile_embs_w.shape[1]} and {tile_embs_a.shape[1]}" 277 | ) 278 | 279 | slide_feats = get_cobra_feats(model, tile_embs_w.to(dtype), tile_embs_a.to(dtype), top_k=top_k) 280 | slide_dict[slide_name] = { 281 | "feats": slide_feats.to(torch.float32).detach().cpu().numpy(), 282 | "extractor": model_name, 283 | } 284 | 285 | output_path = os.path.join(output_dir, output_file) 286 | os.makedirs(os.path.dirname(output_path), exist_ok=True) 287 | with h5py.File(output_path, "w") as f: 288 | for slide_name, data in slide_dict.items(): 289 | f.create_dataset(f"{slide_name}", data=data["feats"]) 290 | f.attrs["extractor"] = model_name 291 | f.attrs["top_k"] = top_k if top_k else "None" 292 | f.attrs["dtype"] = str(dtype) 293 | f.attrs["weighting_FM"] = weighting_fm 294 | f.attrs["aggregation_FM"] = aggregation_fm 295 | f.attrs["microns"] = microns 296 | 297 | tqdm.write(f"Finished extraction, saved to {output_path}") 298 | metadata = { 299 | "extractor": model_name, 300 | "top_k": top_k if top_k else "None", 301 | "dtype": str(dtype), 302 | "weighting_FM": weighting_fm, 303 | "aggregation_FM": aggregation_fm, 304 | "microns": microns, 305 | } 306 | with open(os.path.join(output_dir, "metadata.json"), "w") as json_file: 307 | json.dump(metadata, json_file, indent=4) 308 | 309 | 310 | def main(): 311 | """ 312 | Main function for extracting slide or patient embeddings using the COBRA model. 313 | This function parses command-line arguments, optionally loads configuration parameters 314 | from a YAML file, and sets up the model based on the provided arguments. It supports 315 | two modes of embedding extraction: 316 | - Patient-level embeddings: If a slide table is provided via the '--slide_table' argument. 317 | - Slide-level embeddings: If no slide table is provided. 318 | The function determines whether to download model weights or load a checkpoint based on 319 | the provided flags, selects the appropriate COBRA model function (COBRA I or COBRAII), 320 | and configures the model's device and data type (adjusting to mixed FP16 precision if the 321 | GPU's compute capability is less than 8.0). 322 | Arguments: 323 | -c, --config (str): Optional path to a YAML configuration file to override command-line arguments. 324 | -d, --download_model: Flag indicating whether to download model weights. 325 | -w, --checkpoint_path (str): Path to the model checkpoint file. 326 | -k, --top_k (int): Optional top k tiles to use for slide/patient embedding. 327 | -o, --output_dir (str): Directory to save the extracted features (required). 328 | -f, --feat_dir (str): Directory containing tile feature files (required). 329 | -g, --feat_dir_a (str): Optional directory containing tile feature files for aggregation. 330 | -m, --model_name (str): Model name (default: "COBRAII"). 331 | -p, --patch_encoder (str): Patch encoder name (default: "Virchow2"). 332 | -a, --patch_encoder_a (str): Patch encoder name used for aggregation (default: "Virchow2"). 333 | -e, --h5_name (str): Output HDF5 file name (default: "cobra_feats.h5"). 334 | -r, --microns (int): Microns per patch used for extraction (default: 224). 335 | -s, --slide_table (str): Optional slide table path for patient-level extraction. 336 | -u, --use_cobraI: Flag to use the COBRA I model; if not set, COBRAII is used. 337 | Raises: 338 | FileNotFoundError: If a checkpoint path is provided but the file does not exist. 339 | ValueError: If neither a checkpoint path is provided nor the download_model flag is set. 340 | Returns: 341 | None 342 | """ 343 | 344 | parser = argparse.ArgumentParser( 345 | description="Extract slide/patient embeddings using COBRA model" 346 | ) 347 | parser.add_argument("-c", "--config", type=str, 348 | help="Path to a YAML configuration file", default=None) 349 | parser.add_argument("-d", "--download_model", action="store_true", 350 | help="Flag to download model weights") 351 | parser.add_argument("-w", "--checkpoint_path", type=str, default=None, 352 | help="Path to model checkpoint") 353 | parser.add_argument("-k", "--top_k", type=int, required=False, default=None, 354 | help="Top k tiles to use for slide/patient embedding") 355 | parser.add_argument("-o", "--output_dir", type=str, required=False, 356 | help="Directory to save extracted features") 357 | parser.add_argument("-f", "--feat_dir", type=str, required=False, 358 | help="Directory containing tile feature files") 359 | parser.add_argument("-g", "--feat_dir_a", type=str, required=False, default=None, 360 | help="Directory containing tile feature files for aggregation") 361 | parser.add_argument("-m", "--model_name", type=str, required=False, default="COBRAII", 362 | help="Model name") 363 | parser.add_argument("-p", "--patch_encoder", type=str, required=False, default="Virchow2", 364 | help="Patch encoder name") 365 | parser.add_argument("-a", "--patch_encoder_a", type=str, required=False, default="Virchow2", 366 | help="Patch encoder name used for aggregation") 367 | parser.add_argument("-e", "--h5_name", type=str, required=False, default="cobra_feats.h5", 368 | help="Output HDF5 file name") 369 | parser.add_argument("-r", "--microns", type=int, required=False, default=224, 370 | help="Microns per patch used for extraction") 371 | parser.add_argument("-s", "--slide_table", type=str, required=False, 372 | help="Slide table path (for patient-level extraction)") 373 | parser.add_argument("-u", "--use_cobraI", action="store_true", 374 | help="Whether to use COBRA I (if not set, use COBRAII)") 375 | 376 | args = parser.parse_args() 377 | 378 | # If a config file is provided, load parameters from the config file 379 | if args.config is not None: 380 | with open(args.config, "r") as f: 381 | config = yaml.safe_load(f) 382 | config = config.get("extract_feats", {}) 383 | args.download_model = config.get("download_model", args.download_model) 384 | args.checkpoint_path = config.get("checkpoint_path", args.checkpoint_path) 385 | args.top_k = config.get("top_k", args.top_k) 386 | args.output_dir = config.get("output_dir", args.output_dir) 387 | args.feat_dir = config.get("feat_dir", args.feat_dir) 388 | args.feat_dir_a = config.get("feat_dir_a", args.feat_dir_a) 389 | args.model_name = config.get("model_name", args.model_name) 390 | args.patch_encoder = config.get("patch_encoder", args.patch_encoder) 391 | args.patch_encoder_a = config.get("patch_encoder_a", args.patch_encoder_a) 392 | args.h5_name = config.get("h5_name", args.h5_name) 393 | args.microns = config.get("microns", args.microns) 394 | args.slide_table = config.get("slide_table", args.slide_table) 395 | args.use_cobraI = config.get("use_cobraI", args.use_cobraI) 396 | 397 | print(f"Using configuration: {args}") 398 | device = "cuda" if torch.cuda.is_available() else "cpu" 399 | cobra_func = get_cobra if args.use_cobraI else get_cobraII 400 | if args.checkpoint_path: 401 | model = cobra_func( 402 | download_weights=(not os.path.exists(args.checkpoint_path)), 403 | checkpoint_path=args.checkpoint_path, 404 | ) 405 | else: 406 | print("No checkpoint path provided. Downloading model weights...") 407 | model = cobra_func( 408 | download_weights=True, 409 | ) 410 | model = model.to(device) 411 | model.eval() 412 | 413 | if torch.cuda.get_device_capability()[0] < 8: 414 | print( 415 | f"\033[93mCOBRA (Mamba2) is designed to run on GPUs with compute capability 8.0 or higher!! " 416 | f"Your GPU has compute capability {torch.cuda.get_device_capability()[0]}. " 417 | f"We are forced to switch to mixed FP16 precision. This may lead to numerical instability and reduced performance!!\033[0m" 418 | ) 419 | model = model.half() 420 | dtype = torch.float16 421 | else: 422 | dtype = torch.float32 423 | 424 | if args.slide_table: 425 | # patient level embeddings 426 | get_pat_embs( 427 | model, 428 | args.output_dir, 429 | args.feat_dir, 430 | args.feat_dir_a, 431 | args.h5_name, 432 | args.model_name, 433 | args.slide_table, 434 | device, 435 | dtype=dtype, 436 | top_k=args.top_k, 437 | weighting_fm=args.patch_encoder, 438 | aggregation_fm=args.patch_encoder_a, 439 | microns=args.microns, 440 | ) 441 | else: 442 | # slide level embeddings 443 | get_slide_embs( 444 | model, 445 | args.output_dir, 446 | args.feat_dir, 447 | args.feat_dir_a, 448 | args.h5_name, 449 | args.model_name, 450 | device=device, 451 | dtype=dtype, 452 | top_k=args.top_k, 453 | weighting_fm=args.patch_encoder, 454 | aggregation_fm=args.patch_encoder_a, 455 | microns=args.microns, 456 | ) 457 | 458 | if __name__ == "__main__": 459 | main() 460 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------