keyword stringclasses 7
values | repo_name stringlengths 8 98 | file_path stringlengths 4 244 | file_extension stringclasses 29
values | file_size int64 0 84.1M | line_count int64 0 1.6M | content stringlengths 1 84.1M ⌀ | language stringclasses 14
values |
|---|---|---|---|---|---|---|---|
3D | chenz53/MIM-Med3D | code/losses/contrastive.py | .py | 3,273 | 93 | import torch
from torch.nn import functional as F
from torch.nn.modules.loss import _Loss
from monai.utils import deprecated_arg
class ContrastiveLoss(_Loss):
"""
Compute the Contrastive loss defined in:
Chen, Ting, et al. "A simple framework for contrastive learning of visual representations." Int... | Python |
3D | chenz53/MIM-Med3D | code/losses/__init__.py | .py | 41 | 2 | from .contrastive import ContrastiveLoss
| Python |
3D | chenz53/MIM-Med3D | code/optimizers/lr_scheduler.py | .py | 6,791 | 209 | import math
import warnings
from typing import List
from torch.optim.lr_scheduler import LambdaLR, _LRScheduler
from torch import nn as nn
from torch.optim import Adam, Optimizer
from torch.optim.lr_scheduler import _LRScheduler
from pytorch_lightning.utilities.cli import LR_SCHEDULER_REGISTRY
__all__ = ["LinearLR",... | Python |
3D | chenz53/MIM-Med3D | code/optimizers/__init__.py | .py | 56 | 2 | from .lr_scheduler import LinearWarmupCosineAnnealingLR
| Python |
3D | chenz53/MIM-Med3D | code/data/btcv_dataset.py | .py | 11,225 | 316 | from typing import Optional, Sequence, Union
import torch
import torch.distributed as ptdist
import pytorch_lightning as pl
from monai.data import (
CacheDataset,
Dataset,
partition_dataset,
PersistentDataset,
load_decathlon_datalist,
list_data_collate,
decollate_batch,
)
from monai.transf... | Python |
3D | chenz53/MIM-Med3D | code/data/__init__.py | .py | 242 | 11 | from .btcv_dataset import BTCVDataset
from .brats_dataset import BratsDataset
from .utils import (
list_splitter,
get_modalities,
StackStuff,
StackStuffM,
ConvertToMultiChannelBasedOnBratsClassesd,
DataAugmentation,
)
| Python |
3D | chenz53/MIM-Med3D | code/data/utils.py | .py | 21,957 | 532 | from typing import Any, Callable, List, Sequence, Tuple, Union
import glob
import numpy as np
import kornia.augmentation as K
from einops import rearrange, repeat
import torch
import torch.nn.functional as F
from monai.data.utils import (
compute_importance_map,
dense_patch_slices,
get_valid_patch_size,
... | Python |
3D | chenz53/MIM-Med3D | code/data/brats_dataset.py | .py | 7,990 | 239 | import logging
from typing import Union, Sequence
import pytorch_lightning as pl
from pytorch_lightning.utilities.cli import DATAMODULE_REGISTRY
import torch.distributed as dist
from monai.data import (
CacheDataset,
Dataset,
partition_dataset,
DataLoader,
PersistentDataset,
load_decathlon_dat... | Python |
3D | flystar233/3d_dna_pipe | generate_site_positions.py | .py | 6,710 | 281 | #!/usr/bin/env python
# Generate site positions in genome from given restriction enzyme
# Juicer 1.5
from __future__ import print_function
import sys
import re
def usage():
print('Usage: {} <restriction enzyme> <genome> [location]'.format(sys.argv[0]), file=sys.stderr)
sys.exit(1)
# ---------------------------... | Python |
3D | flystar233/3d_dna_pipe | getread.sh | .sh | 710 | 18 | #!/bin/sh
(($# == 3)) || { echo -e "\nUsage: $0 rawdata_allValidPairs fq1.gz fq2.gz\n"; exit; }
file=$1
fq1=$2
fq2=$3
sign=`head -1 $file |grep "/"`
sign_fq=`zcat $fq1|head -1|grep "/"`
if [ ! -n "$sign" ]; then
cut -f 1 $file > fastq.name
else
cut -f 1 -d "/" $file > fastq.name
fi
if [ ! -n "$sign_fq" ]; the... | Shell |
3D | flystar233/3d_dna_pipe | getread.py | .py | 1,820 | 47 | import pyfastx
from collections import defaultdict
import gzip
import argparse
import time
def fastq_grep():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument( "--input", action="store", dest="seqname", required=True,help="File of allValid... | Python |
3D | flystar233/3d_dna_pipe | juicer_3d_dna_pipe.py | .py | 4,499 | 89 | #coding=utf8
'''
Created by xutengfei <xutengfei1@genomics.cn> on 2020.12.29.
__author__ = "<xutengfei1@genomics.cn>"
__version__ = "v1.0"
'''
import re,os
import argparse
import textwrap
parser = argparse.ArgumentParser(description=textwrap.dedent('''
==============================================================
... | Python |
3D | flystar233/3d_dna_pipe | fa_length.py | .py | 729 | 24 | import sys
def length_fa(faname,out):
with open(faname,'rt') as IN, open(out,'wt') as OUT:
Dict = {}
result=[]
for line in IN:
if line[0] == '>':
key = line[1:-1]
Dict[key] = []
else:
Dict[key].append(line.strip("\n"))
... | Python |
3D | Hejrati/cDAL | metrics.py | .py | 7,972 | 183 | import math
import os
import random
import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
from PIL import Image
from sklearn.metrics import f1_score, jaccard_score
from torch.utils.data import DataLoader
from tqdm import tqdm
from preprocess_dataset.MoNu import MonuDataset... | Python |
3D | Hejrati/cDAL | train_cDAL_hippo.py | .py | 21,122 | 620 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for Denoising Diffusion GAN. To view a copy of this license, see the LICENSE file.
# -----------------------------------------... | Python |
3D | Hejrati/cDAL | sampling_monu_and_lung.py | .py | 3,120 | 92 | """
Generate a large batch of image samples from a model and save them as a large
numpy array. This can be used to produce samples for FID evaluation.
"""
import argparse
import json
import os
from pathlib import Path
import torch.distributed
from torch import nn
import torch.distributed as dist
from preprocess_data... | Python |
3D | Hejrati/cDAL | train_cDal_monu_and_lung.py | .py | 17,554 | 506 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for Denoising Diffusion GAN. To view a copy of this license, 01see the LICENSE file.
# --------------------------------------... | Python |
3D | Hejrati/cDAL | logger.py | .py | 15,139 | 536 | """
Logger copied from OpenAI baselines to avoid extra RL-based dependencies:
https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py
"""
import argparse
import os
import sys
import shutil
import os.path as osp
import json
import time
import datetime
import tempfile
import ... | Python |
3D | Hejrati/cDAL | metrics_hippo.py | .py | 7,997 | 213 | import math
import os
import numpy as np
import torch
import torch.distributed as dist
import torch.nn.functional as F
from PIL import Image
import random
from monai.data import decollate_batch
from monai.inferers import sliding_window_inference
from monai.metrics import DiceMetric, ConfusionMatrixMetric
from monai.... | Python |
3D | Hejrati/cDAL | utils.py | .py | 1,453 | 60 | import random
from torch import nn
from torch.backends import cudnn
import torch
import shutil
import os
import numpy as np
import torch.distributed as dist
# %%
def mean_flat(tensor):
"""
Take the mean over all non-batch dimensions.
"""
return tensor.mean(dim=list(range(1, len(tensor.shape))))
de... | Python |
3D | Hejrati/cDAL | EMA.py | .py | 3,321 | 91 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for Denoising Diffusion GAN. To view a copy of this license, see the LICENSE file.
# -----------------------------------------... | Python |
3D | Hejrati/cDAL | sampling_hippo.py | .py | 4,538 | 158 | """
Generate a large batch of image samples from a model and save them as a large
numpy array. This can be used to produce samples for FID evaluation.
"""
import argparse
import json
import os
from pathlib import Path
from torch import nn
import torch
import torch.distributed as dist
import logger
from preprocess_d... | Python |
3D | Hejrati/cDAL | preprocess_dataset/Lung.py | .py | 5,533 | 129 | import os
from pathlib import Path
import cv2
import torch
from torch.utils.data import DataLoader
from preprocess_dataset.transforms import \
Compose, ToPILImage, ToTensor, Resize, RandomHorizontalFlip, RandomVerticalFlip, RandomAffine, Normalize
def cv2_loader_lung(path, is_mask):
if is_mask:
img... | Python |
3D | Hejrati/cDAL | preprocess_dataset/dataset.py | .py | 3,517 | 84 | import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from preprocess_dataset.Lung import LungDataset, get_lung_transform
from preprocess_dataset.MoNu import MonuDataset, get_monu_transform
def create_dataset(data_dir: str, mode: str = "train", ... | Python |
3D | Hejrati/cDAL | preprocess_dataset/make_mhd5.py | .py | 1,046 | 25 | import h5py
import os
from glob import glob
import numpy as np
from imageio import imread
from tqdm import tqdm
import argparse
parser = argparse.ArgumentParser(description='Convert Cityscapes to HDF5')
parser.add_argument('--images-path', type=str,
default="/home/share/Data/Cityscapes/leftimg8bit"... | Python |
3D | Hejrati/cDAL | preprocess_dataset/MoNu.py | .py | 2,811 | 80 | import os
from pathlib import Path
import imageio
import tifffile
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from preprocess_dataset.transforms import \
Compose, ToPILImage, ColorJitter, RandomHorizontalFlip, ToTensor, Normalize, RandomVerticalFlip, RandomAffine, \
Resize, Rand... | Python |
3D | Hejrati/cDAL | preprocess_dataset/hippo.py | .py | 8,253 | 192 | import os
import numpy as np
import torch
from matplotlib import pyplot as plt
from monai.data import CacheDataset, DataLoader, Dataset, PersistentDataset,\
load_decathlon_datalist, partition_dataset, decollate_batch
from monai.transforms import (
EnsureChannelFirstd,
Compose,
DeleteItemsd,
FgBgToI... | Python |
3D | Hejrati/cDAL | preprocess_dataset/transforms.py | .py | 21,146 | 564 | from __future__ import division
import math
import random
import sys
import torch
from PIL import Image
try:
import accimage # type:ignore
except ImportError:
accimage = None
import numpy as np
import numbers
import collections
import warnings
from torchvision.transforms import functional as F
if sys.versi... | Python |
3D | Hejrati/cDAL | score_sde/distribution.py | .py | 5,512 | 143 | from torch.distributions import Normal, Independent
import torch
import torch.nn as nn
def truncated_normal_(tensor, mean=0, std=1):
size = tensor.shape
tmp = tensor.new_empty(size + (4,)).normal_()
valid = (tmp < 2) & (tmp > -2)
ind = valid.max(-1, keepdim=True)[1]
tensor.data.copy_(tmp.gather(-... | Python |
3D | Hejrati/cDAL | score_sde/__init__.py | .py | 0 | 0 | null | Python |
3D | Hejrati/cDAL | score_sde/models/nn.py | .py | 15,892 | 412 | """
Various utilities for neural networks.
"""
import abc
import math
import torch as th
import torch.nn as nn
import torch
from typing import Any, Optional, Type
class CrossAttentionEncoder(th.nn.Module, abc.ABC):
"""
An attention encoder that uses cross attention to encode the input image and the condition... | Python |
3D | Hejrati/cDAL | score_sde/models/unet.py | .py | 21,768 | 621 | from abc import abstractmethod
import math
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from matplotlib import pyplot as plt
from .nn import (
SiLU,
conv_nd,
linear,
avg_pool_nd,
zero_module,
normalization,
timestep_embedding,
checkpoint
... | Python |
3D | Hejrati/cDAL | score_sde/models/up_or_down_sampling.py | .py | 9,107 | 263 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# ---------------------------------------------------------------
"""Layers used for up-sampling or down-sampling images.
Many functions are ported from https://github.com/NVlabs/stylegan2... | Python |
3D | Hejrati/cDAL | score_sde/models/ncsnpp_generator_adagn.py | .py | 22,578 | 567 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the Score SDE library
# which was released under the Apache License.
#
# Source:
# https://github.com/yang-song/score_sde_pytorch/blob/main/mode... | Python |
3D | Hejrati/cDAL | score_sde/models/__init__.py | .py | 608 | 16 | # coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | Python |
3D | Hejrati/cDAL | score_sde/models/discriminator.py | .py | 8,192 | 264 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This work is licensed under the NVIDIA Source Code License
# for Denoising Diffusion GAN. To view a copy of this license, see the LICENSE file.
# -----------------------------------------... | Python |
3D | Hejrati/cDAL | score_sde/models/dense_layer.py | .py | 3,234 | 83 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file released under the MIT License.
#
# Source:
# https://github.com/CW-Huang/sdeflow-light/blob/524650bc5ad69522b3e0905672deef0650374512/lib/models/un... | Python |
3D | Hejrati/cDAL | score_sde/models/layers.py | .py | 20,853 | 619 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the Score SDE library
# which was released under the Apache License.
#
# Source:
# https://github.com/yang-song/score_sde_pytorch/blob/main/mode... | Python |
3D | Hejrati/cDAL | score_sde/models/utils.py | .py | 4,342 | 148 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the Score SDE library
# which was released under the Apache License.
#
# Source:
# https://github.com/yang-song/score_sde_pytorch/blob/main/mode... | Python |
3D | Hejrati/cDAL | score_sde/models/layerspp.py | .py | 12,549 | 381 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
#
# This file has been modified from a file in the Score SDE library
# which was released under the Apache License.
#
# Source:
# https://github.com/yang-song/score_sde_pytorch/blob/main/mode... | Python |
3D | Hejrati/cDAL | score_sde/op/fused_act.py | .py | 3,055 | 106 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# ---------------------------------------------------------------
""" Originated from https://github.com/rosinality/stylegan2-pytorch
The license for the original version of this file can be... | Python |
3D | Hejrati/cDAL | score_sde/op/upfirdn2d.cpp | .cpp | 1,333 | 31 | // ---------------------------------------------------------------
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
// ---------------------------------------------------------------
// Originated from https://github.com/rosinality/stylegan2-pytorch
// The license for the original version of this file c... | C++ |
3D | Hejrati/cDAL | score_sde/op/__init__.py | .py | 89 | 3 | from .fused_act import FusedLeakyReLU, fused_leaky_relu
from .upfirdn2d import upfirdn2d
| Python |
3D | Hejrati/cDAL | score_sde/op/fused_bias_act.cpp | .cpp | 1,192 | 28 | // ---------------------------------------------------------------
// Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
// ---------------------------------------------------------------
// Originated from https://github.com/rosinality/stylegan2-pytorch
// The license for the original version of this file c... | C++ |
3D | Hejrati/cDAL | score_sde/op/upfirdn2d.py | .py | 6,516 | 226 | # ---------------------------------------------------------------
# Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
# ---------------------------------------------------------------
""" Originated from https://github.com/rosinality/stylegan2-pytorch
The license for the original version of this file can be... | Python |
3D | viannegao/ChromaFold | ChromaFold - Visualize and Evaluate.ipynb | .ipynb | 4,888,953 | 953 | {
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"ExecuteTime": {
"end_time": "2023-06-11T13:47:54.097143Z",
"start_time": "2023-06-11T13:47:35.484137Z"
}
},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"\n",
"import numpy as np\... | Unknown |
3D | viannegao/ChromaFold | process_input/Process Input - scATAC.ipynb | .ipynb | 11,898 | 434 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Process Input scATAC-seq\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2023-06-13T17:39:24.264881Z",
"start_time": "2023-06-13T17:39:19.010602Z"
... | Unknown |
3D | viannegao/ChromaFold | process_input/Process Input - Hi-C.ipynb | .ipynb | 4,099 | 162 | {
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Scripit to preprocess Hi-C/HiChIP data"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"ExecuteTime": {
"end_time": "2023-06-13T18:02:14.604155Z",
"start_time": "2023-06-13T18:02:14.602... | Unknown |
3D | viannegao/ChromaFold | process_input/ctcf_motif/get_ctcf_motif_mm10.R | .R | 3,108 | 69 | suppressMessages(library(AnnotationHub))
ah <- AnnotationHub()
#> snapshotDate(): 2022-10-31
query_data <- subset(ah, preparerclass == "CTCF")
# Explore the AnnotationHub object
subset(query_data,
genome == "mm10")
CTCF_mm10_all <- query_data[["AH104753"]]
suppressMessages(library(plyranges))
CTCF_mm10_all <-... | R |
3D | viannegao/ChromaFold | process_input/ctcf_motif/get_ctcf_motif_hg38.R | .R | 3,513 | 79 | suppressMessages(library(AnnotationHub))
ah <- AnnotationHub()
#> snapshotDate(): 2022-10-31
query_data <- subset(ah, preparerclass == "CTCF")
# Explore the AnnotationHub object
subset(query_data, species == "Homo sapiens" &
genome == "hg38")
CTCF_hg38_all <- query_data[["AH104727"]]
CTCF_hg38 <- query_data[... | R |
3D | viannegao/ChromaFold | process_input/hic_normalization/without_installation/hicdcplus_pipeline.R | .R | 20,371 | 524 | #library(BSgenome.Hsapiens.UCSC.hg19)
library(BSgenome)
library(dplyr)
library(Rcpp)
library(base)
library(data.table)
library(dplyr)
library(tidyr)
library(GenomeInfoDb)
library(stats)
library(MASS)
options("scipen"=100, "digits"=4)
get_chr_sizes<-function(gen="Hsapiens",gen_ver="hg19",chrs=NULL){
genome <- paste("... | R |
3D | viannegao/ChromaFold | process_input/hic_normalization/without_installation/hicdcplus_run.R | .R | 3,567 | 95 | #!/usr/bin/env Rscript
# Run HiC-DC+ to generate z-score normalized Hi-C library.
#
# Usage
# screen
# bsub -n 2 -W 10:00 -R 'span[hosts=1] rusage[mem=64]' -Is /bin/bash
# source /miniconda3/etc/profile.d/conda.sh
# conda activate chromafold_env
# cd /chromafold/scripts
#
#
# Rscript /chromafold/process input/hic_norm... | R |
3D | viannegao/ChromaFold | process_input/hic_normalization/hicdcplus/step2_python_save.py | .py | 2,408 | 70 | #!/usr/bin/env python
'''Script for processing scATAC fragment files.
Usage example:
screen
bsub -q gpuqueue -gpu - -W 4:00 -n 2 -R 'span[hosts=1] rusage[mem=128]' -Is /bin/bash
python ./hicdcplus/step2_python_save.py \
--assembly 'hg38'
'''
import pandas as pd
import argparse
import pickle
import numpy as np
from ... | Python |
3D | viannegao/ChromaFold | process_input/hic_normalization/hicdcplus/step1_hicdcplus_normalization_run.R | .R | 3,063 | 99 | #hicdc+ for normalization
#
# Usage
# screen
# bsub -n 2 -W 10:00 -R 'span[hosts=1] rusage[mem=128]' -Is /bin/bash
# source /miniconda3/etc/profile.d/conda.sh
# conda activate chromafold_env
# cd ./hic_normalization
#
# Rscript ./hicdcplus/step1_hicdcplus_normalization_run.R \
# imr90.hic \
# 10000 \
# 'hg38'
library(... | R |
3D | viannegao/ChromaFold | process_input/hic_normalization/hicdcplus/hicdcplus_normalization.sh | .sh | 1,283 | 49 | #!/bin/bash
# Usage
# bash ChromaFold/process_input/hicdc_normalization/hicdcplus_normalization.sh \
# hic_file='imr90.hic'
# resolution=10000
# assembly='hg38'
SCRIPT_DIR="/chromafold/process_input/hic_normalization/hicdcplus"
# Ensure required variables are set
if [ -z "$hic_file" ] || [ -z "$resolution" ] || [ -z... | Shell |
3D | viannegao/ChromaFold | preprocessing_pipeline/ArchR_preparation.R | .R | 3,266 | 116 | #!/usr/bin/env Rscript
# Run ArchR to generate metacell information for running ChromaFold
#
# Installation of ArchR
# install.packages("Rcpp", dependencies = TRUE) # nolint
# if (!requireNamespace("devtools", quietly = TRUE)) install.packages("devtools") # nolint
# install.packages("devtools") # nolint
# if (!require... | R |
3D | viannegao/ChromaFold | preprocessing_pipeline/fragment_celltype_merge.py | .py | 3,663 | 94 | #!/usr/bin/env python
'''Script for processing scATAC fragment files.
Usage example:
screen
python /chromafold/scripts/fragment_celltype_merge.py \
--cell_type selected_cell_type \
--fragment_list /data/fragments_1.tsv.gz /data/fragments_2.tsv.gz \
--data_prefix_list "data_prefix" \
--save_name /data/merged_fragmen... | Python |
3D | viannegao/ChromaFold | preprocessing_pipeline/fragment_to_input.sh | .sh | 4,001 | 105 | #/bin/bash
# Copy from chromafold_data_preparation.sh
# Usage:
#
# screen
# bash /chromafold/scripts/pipeline/fragment_to_input.sh
#######################################################
# Step 0. Filter and merge fragment files #
#######################################################
'''
This section... | Shell |
3D | viannegao/ChromaFold | preprocessing_pipeline/scATAC_preparation.py | .py | 9,050 | 203 | #!/usr/bin/env python
'''Script for processing scATAC fragment files.
Usage example:
screen
python chromafold/scripts/scATAC_preparation.py \
--cell_type_prefix cell_type_prefix \
--fragment_file /data/merged_fragments.tsv.gz \
--barcode_file /data/archr_data/archr_filtered_barcode.csv \
--lsi_file /data/archr_data... | Python |
3D | viannegao/ChromaFold | chromafold/train.py | .py | 9,525 | 336 | import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
import numpy as np
from tqdm import tqdm
import h5py
from utils import *
from dataloader import *
from model import *
from training_utils import *
# DEVICE = 'cuda' if torch.cuda.is_availab... | Python |
3D | viannegao/ChromaFold | chromafold/R_env.sh | .sh | 1,713 | 61 | #/bin/bash
mkdir -p /chromafold/packages
cd /chromafold/packages
# /miniconda3/condabin/conda install -c r r-base
#1. Create conda environment
cd /chromafold/packages
/miniconda3/bin/conda create -n chromafold_env
#2. activate conda env and install essential packages
source /miniconda3/etc/profile.d/conda.sh
conda... | Shell |
3D | viannegao/ChromaFold | chromafold/testing.py | .py | 4,019 | 136 | import os
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from datetime import datetime
from utils import *
"""
Dataset for testing with both aggregated accessibility and coaccessibility
"""
class test_Dataset(torch.utils.data.Dataset):
def __init__(
self,
input_siz... | Python |
3D | viannegao/ChromaFold | chromafold/model.py | .py | 9,594 | 346 | import numpy as np
import torch
import torch.nn as nn
class resblock(nn.Module):
def __init__(self, ni):
super(resblock, self).__init__()
self.blocks = nn.Sequential(
nn.Conv1d(ni, ni, 3, 1, 1),
nn.BatchNorm1d(ni),
nn.ReLU(),
nn.Conv1d(ni, ni, 3, 1,... | Python |
3D | viannegao/ChromaFold | chromafold/train_bulkOnly.py | .py | 8,587 | 312 | import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
import numpy as np
from tqdm import tqdm
import h5py
from utils import *
from dataloader import *
from model_bulk_only import *
from training_utils import *
# DEVICE = 'cuda' if torch.cuda.... | Python |
3D | viannegao/ChromaFold | chromafold/model_bulk_only.py | .py | 7,102 | 251 | import numpy as np
import torch
import torch.nn as nn
class resblock(nn.Module):
def __init__(self, ni):
super(resblock, self).__init__()
self.blocks = nn.Sequential(
nn.Conv1d(ni, ni, 3, 1, 1),
nn.BatchNorm1d(ni),
nn.ReLU(),
nn.Conv1d(ni, ni, 3, 1,... | Python |
3D | viannegao/ChromaFold | chromafold/training_utils.py | .py | 6,358 | 230 | import os
import numpy as np
import torch
import torch.nn as nn
from tqdm import tqdm
from datetime import datetime
def train_bulk_only(
train_loader, model, criterion, optimizer, device, min_stripe_signal
):
model.train()
running_loss = 0
with tqdm(train_loader, unit="batch") as tepoch:
fo... | Python |
3D | viannegao/ChromaFold | chromafold/inference.py | .py | 6,029 | 184 | import argparse
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import torch.backends.cudnn as cudnn
import numpy as np
from numpy import savez_compressed
from tqdm import tqdm
import h5py
from utils import *
from dataloader import *
from model import *
from testing import *
from util_chro... | Python |
3D | viannegao/ChromaFold | chromafold/utils.py | .py | 7,626 | 251 | import pickle
import os
import numpy as np
import pandas as pd
import scipy
from scipy import sparse
import torch
def get_effective_genome_size(genome):
if "hg" in genome:
effective_genome_size = 2913022398
elif "mm" in genome:
effective_genome_size = 2652783500
else:
raise Value... | Python |
3D | viannegao/ChromaFold | chromafold/dataloader.py | .py | 10,059 | 346 | import numpy as np
import torch
import torch.nn as nn
from utils import *
"""
Dataset with only aggregated accessibility
"""
class Dataset_bulk_only(torch.utils.data.Dataset):
def __init__(
self,
input_size,
effective_genome_size,
hic_dict,
pbulk_dict,
ctcf_dict,... | Python |
3D | viannegao/ChromaFold | chromafold/util_chrom_start.py | .py | 4,111 | 159 | def get_chrom_starts(genome):
if genome == "hg38":
start_dict = {
"chr1": 0,
"chr2": 0,
"chr3": 0,
"chr4": 0,
"chr5": 0,
"chr6": 0,
"chr7": 0,
"chr8": 0,
"chr9": 0,
"chr10": 0,
... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/setup.py | .py | 1,252 | 45 | #!/usr/bin/env python
import os
import setuptools
def readme():
with open('README.md') as f:
return f.read()
def get_requirements_filename():
if 'READTHEDOCS' in os.environ:
return "REQUIREMENTS-RTD.txt"
elif 'DOCKER' in os.environ:
return "REQUIREMENTS-DOCKER.txt"
else:
... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_augmenter/synapse_augmenter.py | .py | 47,797 | 1,075 | import torch
import numpy as np
from synapse_augmenter import consts
from typing import Tuple, List, Union, Optional
from boltons.cacheutils import cachedmethod
from scipy.spatial.transform import Rotation
import cc3d
# for cachedmethod
_cache = dict()
# constants
GAUSSIAN_BLUR_KERNEL_SIZE = 3 # must be an odd num... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_augmenter/__init__.py | .py | 48 | 2 | from .synapse_augmenter import SynapseAugmenter
| Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_augmenter/consts.py | .py | 256 | 12 | MASK_PRE_SYNAPTIC_NEURON = 1
MASK_SYNAPTIC_CLEFT = 2
MASK_POST_SYNAPTIC_NEURON = 3
MASK_INTEGER_VALUES = [
MASK_PRE_SYNAPTIC_NEURON,
MASK_SYNAPTIC_CLEFT,
MASK_POST_SYNAPTIC_NEURON]
INPUT_DATA_INTENSITY_CHANNEL = 0
INPUT_DATA_MASK_CHANNEL = 1
| Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_dataset/__init__.py | .py | 43 | 1 | from .synapse_dataset import SynapseDataset | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_dataset/synapse_dataset.py | .py | 4,981 | 119 | import os
import numpy as np
import pandas as pd
from typing import List, Tuple, Optional, Union
from torch.utils.data.dataset import Dataset
from boltons.cacheutils import cachedmethod
_cache = dict()
class SynapseDataset(Dataset):
def __init__(
self,
dataset_path: str,
h... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_utils/vis.py | .py | 18,928 | 546 | import torch
import numpy as np
import matplotlib.pylab as plt
import pandas as pd
from synapse_dataset import SynapseDataset
from synapse_simclr import utils
from synapse_utils import vis
from synapse_augmenter import SynapseAugmenter
from synapse_augmenter import consts as syn_consts
from scipy.ndimage import binar... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_utils/__init__.py | .py | 0 | 0 | null | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_utils/io.py | .py | 2,831 | 75 | import os
import numpy as np
import pandas as pd
from typing import List, Tuple, Optional
def load_features(
checkpoint_path: str,
node_idx_list: List[int],
reload_epoch: int,
feature_hook: str,
dataset_path: str,
l2_normalize: bool,
contamination_indices_path:... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_utils/commons.py | .py | 6,419 | 129 | import pandas as pd
import numpy as np
import torch
def log1p_zscore(a):
a = np.log1p(a)
m = np.mean(a)
s = np.std(a)
return (a - m) / s
def load_imputed_annotations(
meta_df: pd.DataFrame,
imputed_cell_types_df_path: str,
imputed_meta_ext_df_path: str,
cell_type_stra... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/synapse_simclr_pretrain.py | .py | 7,778 | 232 | import os
import numpy as np
import torch
import argparse
import pkg_resources
from operator import itemgetter
from typing import Union, List
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from synapse_simclr import SynapseSimCLRWorksp... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/synapse_simclr_extract.py | .py | 8,583 | 240 | import os
import numpy as np
import torch
import argparse
import pkg_resources
from operator import itemgetter
from typing import Union, List, Dict, Iterable, Callable
from collections import defaultdict
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataPa... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/__init__.py | .py | 61 | 2 | from .synapse_simclr_workspace import SynapseSimCLRWorkspace
| Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/synapse_simclr_workspace.py | .py | 9,285 | 248 | import os
import numpy as np
import torch
import argparse
import pkg_resources
from typing import Union, List
from operator import itemgetter
import torch.distributed as dist
import torch.multiprocessing as mp
from torch.nn.parallel import DistributedDataParallel as DDP
from synapse_augmenter import SynapseAugmenter... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/identity.py | .py | 156 | 9 | import torch
class Identity(torch.nn.Module):
def __init__(self):
super(Identity, self).__init__()
def forward(self, x):
return x
| Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/nt_xent.py | .py | 2,080 | 52 | import torch
import torch.distributed as dist
from .gather import GatherLayer
class NT_Xent(torch.nn.Module):
def __init__(self, batch_size, temperature, world_size):
super(NT_Xent, self).__init__()
self.batch_size = batch_size
self.temperature = temperature
self.worl... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/synapse_simclr.py | .py | 2,548 | 78 | import os
from scipy.stats import truncnorm
import numpy as np
from typing import List, Tuple, Union, Optional
import torch
from synapse_simclr.modules import Identity, Projector
class SynapseSimCLR(torch.nn.Module):
"""TBW.
"""
def __init__(
self,
encoder: torch.nn.Module,
... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/lars.py | .py | 5,961 | 166 | """
LARS: Layer-wise Adaptive Rate Scaling
Converted from TensorFlow to PyTorch
https://github.com/google-research/simclr/blob/master/lars_optimizer.py
"""
import torch
from torch.optim.optimizer import Optimizer, required
import re
EETA_DEFAULT = 0.001
class LARS(Optimizer):
"""
Layer-wise Adaptive Rate S... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/resnet_3d.py | .py | 8,198 | 260 | #################################################################################
# code is adapted from: #
# https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/models/resnet.py #
##########################################################################... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/projector.py | .py | 1,296 | 38 | from typing import List
import torch
class Projector(torch.nn.Module):
def __init__(
self,
input_features: int,
channel_dims: List[int],
bias: bool = False):
"""MLP projection head for SimCLR."""
super(Projector, self).__init__()
... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/__init__.py | .py | 409 | 13 | from .nt_xent import NT_Xent
from .lars import LARS
from .gather import GatherLayer
from .identity import Identity
from .projector import Projector
from .resnet_3d import generate_model as generate_resnet_3d
from .pre_act_resnet_3d import generate_model as generate_pre_act_resnet_3d
from .synapse_simclr import SynapseS... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/pre_act_resnet_3d.py | .py | 3,404 | 108 | #########################################################################################
# code is based on: #
# https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/models/pre_act_resnet.py #
##################################################... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/synapse_supervised.py | .py | 1,469 | 46 | import os
from scipy.stats import truncnorm
import numpy as np
from typing import List, Tuple, Union, Optional
import torch
from synapse_simclr.modules import SynapseSimCLR
class SynapseSupervised(torch.nn.Module):
"""TBW.
"""
def __init__(
self,
synapse_simclr: SynapseSimCLR,
... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/gather.py | .py | 601 | 21 | import torch
import torch.distributed as dist
class GatherLayer(torch.autograd.Function):
"""Gather tensors from all process, supporting backward propagation."""
@staticmethod
def forward(ctx, input):
ctx.save_for_backward(input)
output = [torch.zeros_like(input) for _ in range(dist.get_w... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/modules/resnet_3d_medicalnet.py | .py | 7,027 | 243 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import math
from functools import partial
__all__ = [
'ResNet', 'resnet10', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
'resnet152', 'resnet200'
]
def conv3x3x3(in_planes, out_planes, stride=1, dilatio... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/utils/train_helper.py | .py | 8,338 | 270 | from typing import List, Tuple, Union, Optional
import os
import hashlib
import pickle
import numpy as np
import torch
from torch.optim.optimizer import Optimizer
from torch.optim.lr_scheduler import CosineAnnealingLR
from synapse_simclr.modules import \
LARS, \
generate_resnet_3d
_SUPPORTED_ENCODERS = [
... | Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/utils/__init__.py | .py | 211 | 10 | from .yaml_config_hook import yaml_config_hook
from .train_helper import \
instantiate_encoder, \
instantiate_optimizer, \
checkpoint_state, \
print_hash, \
write_summary, \
parse_dtype
| Python |
3D | cellarium-ai/SynapseCLR | pytorch_synapse/synapse_simclr/utils/yaml_config_hook.py | .py | 709 | 25 | import os
import yaml
def yaml_config_hook(config_file):
"""
Custom YAML config loader, which can include other yaml files (I like using config files
insteaad of using argparser)
"""
# load yaml files in the nested 'defaults' section, which include defaults for experiments
with open(config_fi... | Python |
3D | cellarium-ai/SynapseCLR | notebooks/misc/01_medicalnet_model_adapt.ipynb | .ipynb | 32,670 | 825 | {
"cells": [
{
"cell_type": "markdown",
"id": "clinical-trust",
"metadata": {},
"source": [
"## Pretrained MedicalNet to SynapseCLR adaptation\n",
"\n",
"Generate a SynapseCLR checkpoint initialized to MedicalNet pre-trained 3D-ResNet18."
]
},
{
"cell_type": "code",
"execution_co... | Unknown |
3D | cellarium-ai/SynapseCLR | notebooks/misc/02_preprocess_annotations.ipynb | .ipynb | 39,271 | 1,094 | {
"cells": [
{
"cell_type": "markdown",
"id": "340d2c22",
"metadata": {},
"source": [
"## Preprocess annotations"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "347cd1c5",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import sys\n",
"import ... | Unknown |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.