repo
stringlengths
1
99
file
stringlengths
13
215
code
stringlengths
12
59.2M
file_length
int64
12
59.2M
avg_line_length
float64
3.82
1.48M
max_line_length
int64
12
2.51M
extension_type
stringclasses
1 value
VSR-Transformer
VSR-Transformer-main/basicsr/test.py
import logging import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.models import create_model from basicsr.train import parse_options from basicsr.utils import (get_env_info, get_root_logger, get_time_str, make_exp_dirs) from basics...
1,827
29.983051
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/train.py
import argparse import datetime import logging import math import random import time import torch from os import path as osp from basicsr.data import create_dataloader, create_dataset from basicsr.data.data_sampler import EnlargedSampler from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher from b...
9,685
37.436508
128
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/lr_scheduler.py
import math from collections import Counter from torch.optim.lr_scheduler import _LRScheduler import pdb class MultiStepRestartLR(_LRScheduler): """ MultiStep with restarts learning rate scheme. Args: optimizer (torch.nn.optimizer): Torch optimizer. milestones (list): Iterations that will decr...
4,373
34.852459
80
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/base_model.py
import logging import os import torch from collections import OrderedDict from copy import deepcopy from torch.nn.parallel import DataParallel, DistributedDataParallel from basicsr.models import lr_scheduler as lr_scheduler from basicsr.utils.dist_util import master_only from basicsr.utils.utils_modelsummary import ge...
14,045
37.168478
90
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/video_base_model.py
import importlib import torch from collections import Counter from copy import deepcopy from os import path as osp from torch import distributed as dist from tqdm import tqdm from basicsr.models.sr_model import SRModel from basicsr.utils import get_root_logger, imwrite, tensor2img from basicsr.utils.dist_util import g...
7,244
40.4
78
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/count_flop.py
import torch from torch import nn as nn from torch.nn import functional as F import numpy as np from archs.arch_util import (ResidualBlockNoBN, make_layer, ResidualGroup, default_conv) from einops import rearrange, repeat from einops.layers.torch import Rearrange from positional_encodings import PositionalEncodingPerm...
10,073
47.200957
161
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/crop_validation.py
import torch from IPython import embed import pdb def lr_crop_index(n, N, D, base_size, overlap): n_end = D if n == N - 1 else (n + 1) * base_size + overlap n_start = n_end - base_size - overlap return n_start, n_end def hr_crop_index(n, N, D, Dmod, base_size, overlap): if n == 0: n_start = 0...
4,069
33.786325
126
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/sr_model.py
import importlib import torch import torch.nn as nn from collections import OrderedDict from copy import deepcopy from os import path as osp from tqdm import tqdm from basicsr.models.archs import define_network from basicsr.models.base_model import BaseModel from basicsr.utils import get_root_logger, imwrite, tensor2i...
10,099
37.403042
113
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/edvr_model.py
import logging import torch from torch.nn.parallel import DistributedDataParallel from basicsr.models.video_base_model import VideoBaseModel import pdb logger = logging.getLogger('basicsr') class EDVRModel(VideoBaseModel): """EDVR Model. Paper: EDVR: Video Restoration with Enhanced Deformable Convolutional...
3,523
39.976744
104
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/archs/vgg_arch.py
import os import torch from collections import OrderedDict from torch import nn as nn from torchvision.models import vgg as vgg VGG_PRETRAIN_PATH = 'experiments/pretrained_models/vgg19-dcbb9e9d.pth' NAMES = { 'vgg11': [ 'conv1_1', 'relu1_1', 'pool1', 'conv2_1', 'relu2_1', 'pool2', 'conv3_1', 'relu3...
6,230
35.226744
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/archs/spynet.py
import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import ConvModule from mmcv.runner import load_checkpoint from mmedit.models.common import (PixelShufflePack, ResidualBlockNoBN, flow_warp, make_layer) from mmedit.models.registry import BACKBONES from mmedit.utils import get_root_logger ...
6,356
39.490446
134
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/archs/arch_util.py
import math import torch from torch import nn as nn from torch.nn import functional as F from torch.nn import init as init from torch.nn.modules.batchnorm import _BatchNorm from basicsr.utils import get_root_logger try: from basicsr.models.ops.dcn import (ModulatedDeformConvPack, modulated_deform_conv) excep...
12,223
33.727273
134
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/archs/vsrTransformer_arch.py
import torch from torch import nn as nn from torch.nn import functional as F import numpy as np from basicsr.models.archs.arch_util import (ResidualBlockNoBN, make_layer, RCAB, ResidualGroup, default_conv, RCABWithInputConv) from einops import rearrange, repeat from einops.layers.torch import Rearrange from positional...
13,404
46.200704
140
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/archs/spynet_arch.py
import math import torch from torch import nn as nn from torch.nn import functional as F from basicsr.models.archs.arch_util import flow_warp class BasicModule(nn.Module): """Basic Module for SpyNet. """ def __init__(self): super(BasicModule, self).__init__() self.basic_module = nn.Seque...
9,197
36.696721
128
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/ops/dcn/deform_conv.py
import math import torch from torch import nn as nn from torch.autograd import Function from torch.autograd.function import once_differentiable from torch.nn import functional as F from torch.nn.modules.utils import _pair, _single from . import deform_conv_ext class DeformConvFunction(Function): @staticmethod ...
14,808
36.87468
80
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/ops/upfirdn2d/upfirdn2d.py
# modify from https://github.com/rosinality/stylegan2-pytorch/blob/master/op/upfirdn2d.py # noqa:E501 import torch from torch.autograd import Function from torch.nn import functional as F from . import upfirdn2d_ext class UpFirDn2dBackward(Function): @staticmethod def forward(ctx, grad_output, kernel, gra...
5,760
29.321053
102
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/ops/fused_act/fused_act.py
# modify from https://github.com/rosinality/stylegan2-pytorch/blob/master/op/fused_act.py # noqa:E501 import torch from torch import nn from torch.autograd import Function from . import fused_act_ext class FusedLeakyReLUFunctionBackward(Function): @staticmethod def forward(ctx, grad_output, out, negative_s...
2,496
29.45122
101
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/losses/losses.py
import math import torch from torch import autograd as autograd from torch import nn as nn from torch.nn import functional as F from basicsr.models.archs.vgg_arch import VGGFeatureExtractor from basicsr.models.losses.loss_util import weighted_loss import pdb _reduction_modes = ['none', 'mean', 'sum'] @weighted_loss...
17,005
34.355509
108
py
VSR-Transformer
VSR-Transformer-main/basicsr/models/losses/loss_util.py
import functools from torch.nn import functional as F def reduce_loss(loss, reduction): """Reduce loss as specified. Args: loss (Tensor): Elementwise loss tensor. reduction (str): Options are 'none', 'mean' and 'sum'. Returns: Tensor: Reduced loss tensor. """ reduction_en...
2,903
29.25
78
py
VSR-Transformer
VSR-Transformer-main/basicsr/metrics/fid.py
import numpy as np import torch import torch.nn as nn from scipy import linalg from tqdm import tqdm from basicsr.models.archs.inception import InceptionV3 def load_patched_inception_v3(device='cuda', resize_input=True, normalize_input=False): # we may ...
3,497
32.961165
78
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/test_flop_count.py
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # pyre-ignore-all-errors[2,3,53] import typing import unittest from collections import Counter, defaultdict from typing import Any, Dict, Tuple import torch import torch.nn as nn from fvcore.nn.flop_count import _DEFAULT_SUPPORTED_OPS, FlopCountAn...
24,561
30.692903
88
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/face_util.py
import cv2 import numpy as np import os import torch from skimage import transform as trans from basicsr.utils import imwrite try: import dlib except ImportError: print('Please install dlib before testing face restoration.' 'Reference: https://github.com/davisking/dlib') class FaceRestorationHelpe...
9,588
42.986239
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/misc.py
import numpy as np import os import random import time import torch from os import path as osp from .dist_util import master_only from .logger import get_root_logger def set_random_seed(seed): """Set random seeds.""" random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual...
4,480
31.007143
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/logger.py
import datetime import logging import time from .dist_util import get_dist_info, master_only class MessageLogger(): """Message logger for printing. Args: opt (dict): Config. It contains the following keys: name (str): Exp name. logger (dict): Contains 'print_freq' (str) for l...
6,114
33.353933
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/img_util.py
import cv2 import math import numpy as np import os import torch from torchvision.utils import make_grid def img2tensor(imgs, bgr2rgb=True, float32=True): """Numpy array to tensor. Args: imgs (list[ndarray] | ndarray): Input images. bgr2rgb (bool): Whether to change bgr to rgb. float3...
5,555
32.46988
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/matlab_functions.py
import math import numpy as np import torch def cubic(x): """cubic function used for calculate_weights_indices.""" absx = torch.abs(x) absx2 = absx**2 absx3 = absx**3 return (1.5 * absx3 - 2.5 * absx2 + 1) * ( (absx <= 1).type_as(absx)) + (-0.5 * absx3 + 2.5 * absx2 - 4 * absx + ...
13,747
36.977901
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/dist_util.py
# Modified from https://github.com/open-mmlab/mmcv/blob/master/mmcv/runner/dist_utils.py # noqa: E501 import functools import os import subprocess import torch import torch.distributed as dist import torch.multiprocessing as mp def init_dist(launcher, backend='nccl', **kwargs): if mp.get_start_method(allow_none=...
2,617
30.166667
102
py
VSR-Transformer
VSR-Transformer-main/basicsr/utils/utils_modelsummary.py
import torch.nn as nn import torch import numpy as np import pdb ''' ---- 1) FLOPs: floating point operations ---- 2) #Activations: the number of elements of all ‘Conv2d’ outputs ---- 3) #Conv2d: the number of ‘Conv2d’ layers # -------------------------------------------- # Kai Zhang (github: https://github.com/cszn) ...
16,112
33.577253
129
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/vimeo90k_dataset.py
import random import torch from pathlib import Path from torch.utils import data as data from basicsr.data.transforms import augment, paired_random_crop from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor from basicsr.utils.flow_util import flowfrombytes import pdb class Vimeo90KDataset(dat...
8,072
37.8125
107
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/single_image_dataset.py
from os import path as osp from torch.utils import data as data from torchvision.transforms.functional import normalize from basicsr.data.data_util import paths_from_lmdb from basicsr.utils import FileClient, imfrombytes, img2tensor, scandir class SingleImageDataset(data.Dataset): """Read only lq images in the t...
2,554
36.573529
78
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/reds_dataset.py
import numpy as np import random import torch from pathlib import Path from torch.utils import data as data from basicsr.data.transforms import augment, paired_random_crop from basicsr.utils import FileClient, get_root_logger, imfrombytes, img2tensor from basicsr.utils.flow_util import dequantize_flow, flowfrombytes i...
10,125
40.162602
107
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/prefetch_dataloader.py
import queue as Queue import threading import torch from torch.utils.data import DataLoader class PrefetchGenerator(threading.Thread): """A general prefetch generator. Ref: https://stackoverflow.com/questions/7323664/python-generator-pre-fetch Args: generator: Python generator. num_p...
3,156
23.858268
77
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/paired_image_dataset.py
from torch.utils import data as data from torchvision.transforms.functional import normalize from basicsr.data.data_util import (paired_paths_from_folder, paired_paths_from_lmdb, paired_paths_from_meta_info_file) from basicsr.data.transforms impor...
4,804
40.068376
79
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/data_sampler.py
import math import torch from torch.utils.data.sampler import Sampler class EnlargedSampler(Sampler): """Sampler that restricts data loading to a subset of the dataset. Modified from torch.utils.data.distributed.DistributedSampler Support enlarging the dataset for iteration-based training, for saving ...
1,652
32.06
75
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/data_util.py
import cv2 import numpy as np import torch from os import path as osp from torch.nn import functional as F from basicsr.data.transforms import mod_crop from basicsr.utils import img2tensor, scandir def read_img_seq(path, require_mod_crop=False, scale=1): """Read a sequence of images from a given folder path. ...
11,801
34.548193
78
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/video_test_dataset.py
import glob import torch from os import path as osp from torch.utils import data as data from basicsr.data.data_util import (duf_downsample, generate_frame_indices, read_img_seq) from basicsr.utils import get_root_logger, scandir import pdb class VideoTestDataset(data.Dataset): """Video test dataset. Support...
12,579
37.707692
89
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/ffhq_dataset.py
from os import path as osp from torch.utils import data as data from torchvision.transforms.functional import normalize from basicsr.data.transforms import augment from basicsr.utils import FileClient, imfrombytes, img2tensor class FFHQDataset(data.Dataset): """FFHQ dataset for StyleGAN. Args: opt (...
2,369
34.909091
78
py
VSR-Transformer
VSR-Transformer-main/basicsr/data/__init__.py
import importlib import numpy as np import random import torch import torch.utils.data from functools import partial from os import path as osp from basicsr.data.prefetch_dataloader import PrefetchDataLoader from basicsr.utils import get_root_logger, scandir from basicsr.utils.dist_util import get_dist_info __all__ =...
4,624
35.417323
76
py
onestage_grounding
onestage_grounding-master/train_yolo.py
import os import sys import argparse import shutil import time import random import gc import json from distutils.version import LooseVersion import scipy.misc import logging import matplotlib as mpl mpl.use('Agg') from matplotlib import pyplot as plt from PIL import Image import numpy as np import torch import torch...
34,104
46.8331
153
py
onestage_grounding
onestage_grounding-master/dataset/referit_loader.py
# -*- coding: utf-8 -*- """ ReferIt, UNC, UNC+ and GRef referring image segmentation PyTorch dataset. Define and group batches of images, segmentations and queries. Based on: https://github.com/chenxi116/TF-phrasecut-public/blob/master/build_batches.py """ import os import sys import cv2 import json import uuid impo...
14,194
36.75266
120
py
onestage_grounding
onestage_grounding-master/utils/misc_utils.py
# -*- coding: utf-8 -*- """ Misc download and visualization helper functions and class wrappers. """ import sys import time import torch from visdom import Visdom def reporthook(count, block_size, total_size): global start_time if count == 0: start_time = time.time() return duration = ti...
1,177
28.45
79
py
onestage_grounding
onestage_grounding-master/utils/losses.py
# -*- coding: utf-8 -*- """ Custom loss function definitions. """ import torch.nn as nn import torch.nn.functional as F class IoULoss(nn.Module): """ Creates a criterion that computes the Intersection over Union (IoU) between a segmentation mask and its ground truth. Rahman, M.A. and Wang, Y: O...
987
27.228571
74
py
onestage_grounding
onestage_grounding-master/utils/utils.py
import random import cv2 import numpy as np import torch import torch.nn.functional as F class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 sel...
5,102
31.922581
110
py
onestage_grounding
onestage_grounding-master/utils/word_utils.py
# -*- coding: utf-8 -*- """ Language-related data loading helper functions and class wrappers. """ import re import torch import codecs UNK_TOKEN = '<unk>' PAD_TOKEN = '<pad>' END_TOKEN = '<eos>' SENTENCE_SPLIT_REGEX = re.compile(r'(\W+)') class Dictionary(object): def __init__(self): self.word2idx = {...
3,175
30.137255
139
py
onestage_grounding
onestage_grounding-master/utils/parsing_metrics.py
import torch import numpy as np import os # from plot_util import plot_confusion_matrix # from makemask import * def _fast_hist(label_true, label_pred, n_class): mask = (label_true >= 0) & (label_true < n_class) hist = np.bincount( n_class * label_true[mask].astype(int) + label_pred[mask], minlength=n_class ** ...
5,879
35.75
89
py
onestage_grounding
onestage_grounding-master/utils/transforms.py
# -*- coding: utf-8 -*- """ Generic Image Transform utillities. """ import cv2 import random, math import numpy as np from collections import Iterable import torch.nn.functional as F from torch.autograd import Variable class ResizePad: """ Resize and pad an image to given size. """ def __init__(se...
8,669
37.533333
114
py
onestage_grounding
onestage_grounding-master/model/grounding_model.py
from collections import OrderedDict import torch import torch.nn as nn import torch.nn.functional as F import torch.utils.model_zoo as model_zoo from torch.utils.data import TensorDataset, DataLoader, SequentialSampler from torch.utils.data.distributed import DistributedSampler from .darknet import * import argparse...
13,670
45.030303
113
py
onestage_grounding
onestage_grounding-master/model/darknet.py
from __future__ import division import math import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable import numpy as np from collections import defaultdict, OrderedDict from PIL import Image # from utils.parse_config import * from utils.utils import * # import matplotlib...
21,948
40.102996
136
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 21 14:58:02 2022 @author: ce423 """ import torch from time import time as t from data_generator.struct2d import struct2d_gen struct_features = { 'box_side': 20, 'hands': [25, 10], 'arrowheads': [8,5], 'delta': 3.5, ...
5,366
23.175676
127
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/tools/training.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 17 15:56:40 2022 @author: carlosesteveyague """ import torch class Dataset(torch.utils.data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, eigen_vecs, labels): 'Initialization' self.labels = labels s...
5,237
32.793548
103
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/tools/graph.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 14 13:52:52 2022 @author: carlosesteveyague """ import numpy as np import torch def graph_gaussian_kernel(data, sigma_gauss_kernel): v_size = data.shape[1]*data.shape[2] data = data.reshape([data.shape[0], v_size]) dists = torch.c...
1,176
19.293103
80
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/tools/particle_densities.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 14 09:35:41 2022 @author: carlosesteveyague """ import numpy as np import torch def density_comp(X, Y, Gamma, sigma, density_type = 'Gaussian'): Gamma_ext = Gamma.unsqueeze(-1).unsqueeze(-1) X_diff = X - Gamma_ext[:,0] Y_diff...
2,532
27.144444
83
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/data_generator/dataset.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Jun 15 10:26:09 2022 @author: carlosesteveyague """ import torch def dataset_gen(dataset_features, loop = True): struct = dataset_features['struct'] n = dataset_features['n_imgs'] scaling = 2*torch.pi*torch.Tensor(dataset_f...
1,994
30.171875
99
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/data_generator/struct2d.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jun 14 17:49:50 2022 @author: carlosesteveyague """ import numpy as np import torch from tools.particle_densities import density_comp, RadonTransform_Gaussians class struct2d_gen: def __init__(self, clock_features): if clo...
5,532
34.696774
141
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/2d_struct/model/model_2d.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jun 17 14:58:20 2022 @author: carlosesteveyague """ import torch import torch.nn as nn class model_2dCT(nn.Module): def __init__(self, model_features): super(model_2dCT, self).__init__() self.struct = model_features...
2,480
31.644737
126
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/main.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 10:22:16 2022 @author: ce423 """ import torch import numpy as np import mdtraj as md ## We load an MD trajectory. ## The molecular structure must be in a pdb or psf file. ## The trajectory is stored in a dcd file. struct = 2 if struct == 1: ...
8,743
29.788732
124
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/fft.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 9 10:30:39 2022 @author: ce423 """ from torch.fft import fft2, fftshift, ifft2, ifftshift def fft2_center(img): img = fftshift(img, dim = (-1,-2)) img = fft2(img) img = fftshift(img) return img def ifft2_center(img): img = ...
411
17.727273
54
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/orientation.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Apr 8 18:29:24 2022 @author: carlosesteveyague """ import torch from scipy.linalg import logm A_1 = torch.tensor([[[0.,1.,0.],[0.,0.,0.],[0.,0.,1.]]], dtype = torch.float) A_2 = torch.tensor([[[-1.,0.,0.],[0.,0.,1.],[0.,0.,0.]]], dtype = torch.float)...
1,838
25.271429
92
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/training.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 18:22:38 2022 @author: ce423 """ import torch class Dataset(torch.utils.data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, eigen_vecs, labels): 'Initialization' self.labels = labels self.eigen_ve...
5,604
32.76506
111
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/graph.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 18:10:29 2022 @author: ce423 """ import numpy as np import torch def graph_gaussian_kernel(data, sigma_gauss_kernel): v_size = data.shape[1]*data.shape[2]*data.shape[3] data = data.reshape([data.shape[0], v_size]) dists = torch...
1,170
20.685185
80
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/CTF.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 6 12:31:15 2022 @author: ce423 """ import torch import numpy as np def voltage_to_wavelength(voltage): Lambda = 12.2643247/np.sqrt(voltage*1e+3 + 0.978466*voltage**2); return Lambda def CTF(xi_norm_sq , voltage, Df, C_s, alpha, B_facto...
1,167
28.2
94
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/particle_densities.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 14:37:52 2022 @author: ce423 """ import numpy as np import torch def density_comp(X, Y, Gamma, sigma, density_type = 'Gaussian'): Gamma_ext = Gamma.unsqueeze(-1).unsqueeze(-1) X_diff = X - Gamma_ext[:,0] Y_diff = Y - Gamma...
975
26.885714
71
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/tools/DFF.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 10:35:59 2022 @author: ce423 """ import torch from tools.orientation import params_from_rotation def compute_DFF(X): """ This function computes the Discrete Frenet Frames for each of the discrete curves in a batch of discrete curves. ...
5,902
27.936275
116
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/data_generator/Imaging.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 6 11:46:49 2022 @author: ce423 """ import torch from tqdm import tqdm from tools.particle_densities import density_comp from tools.CTF import CTF_filters from tools.fft import fft2_center, ifft2_center def image_CT(struct, orient_diffs, n_p...
4,858
37.563492
112
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/data_generator/dataset.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 15:06:13 2022 @author: ce423 """ import torch from data_generator.structure_batch import chain_structure import torch.nn as nn def dataset(dataset_features): struct = dataset_features['struct'] n_imgs = dataset_features['n_imgs...
3,451
33.868687
180
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/data_generator/structure_batch.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 14:02:38 2022 @author: ce423 """ import torch from tools.DFF import R_from_angles from tools.orientation import rotation_from_params from tools.particle_densities import density_comp from data_generator.Imaging import image_CT, CTF_image_CT ...
4,440
36.635593
163
py
Atomic-structure-reconstruction-for-cryoEM
Atomic-structure-reconstruction-for-cryoEM-main/3d_struct/model/model_chain.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 2 17:52:44 2022 @author: ce423 """ import torch import torch.nn as nn from tools.DFF import R_from_angles from tools.orientation import rotation_from_params from tools.particle_densities import density_comp class model_chain(nn.Module): ...
7,234
35.540404
140
py
OVE6D-pose
OVE6D-pose-main/evaluation/LMO_RCNN_OVE6D_pipeline.py
import os import cv2 import sys import json # import yaml import time import torch import warnings import numpy as np from PIL import Image from pathlib import Path from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor from os.path import join as pjoi...
13,771
44.302632
139
py
OVE6D-pose
OVE6D-pose-main/evaluation/utils.py
import os import time import glob import math import torch import numpy as np import torch.nn.functional as F from lib import geometry, rendering, three, preprocess from evaluation import pplane_ICP from lib import preprocess def rotation_to_position(R): t = torch.tensor([0, 0, 1], dtype=torch.float32, device=R.d...
32,071
46.095448
151
py
OVE6D-pose
OVE6D-pose-main/evaluation/LM_RCNN_OVE6D_pipeline.py
import os import cv2 import sys import json # import yaml import time import torch import warnings import numpy as np from PIL import Image from pathlib import Path from detectron2 import model_zoo from detectron2.config import get_cfg from detectron2.engine import DefaultPredictor from os.path import join as pjoi...
13,769
42.714286
139
py
OVE6D-pose
OVE6D-pose-main/evaluation/config.py
import math import torch from pytorch3d.transforms import euler_angles_to_matrix RANDOM_SEED = 2021 # for reproduce the results of evaluation VIEWBOOK_BATCHSIZE = 200 # batch size for constructing viewpoint codebook, reduce this if out of GPU memory RENDER_WIDTH = 640 # the width of rendered images REND...
2,732
34.493506
108
py
OVE6D-pose
OVE6D-pose-main/evaluation/TLESS_MPmask_OVE6D_sixd17.py
import os import sys # import glob import json import yaml import time import torch import warnings import numpy as np from PIL import Image from pathlib import Path from os.path import join as pjoin warnings.filterwarnings("ignore") base_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.ap...
9,995
43.035242
116
py
OVE6D-pose
OVE6D-pose-main/evaluation/pplane_ICP.py
""" The code for point-to-plane ICP is modified from the respository https://github.com/pglira/simpleICP/tree/master/python """ import time import torch import numpy as np from datetime import datetime from scipy import spatial, stats def depth_to_pointcloud(depth, K): if not isinstance(depth, torch.Tensor): ...
7,387
34.690821
143
py
OVE6D-pose
OVE6D-pose-main/utility/visualization.py
from collections import namedtuple import math from contextlib import contextmanager from pathlib import Path import imageio import numpy as np import structlog import tempfile import torch import torchvision from matplotlib import cm from matplotlib import pyplot as plt from matplotlib.colors import LinearSegmentedC...
10,889
30.565217
94
py
OVE6D-pose
OVE6D-pose-main/dataset/TLESS_Dataset.py
import json import torch from pathlib import Path class Dataset(): def __init__(self, data_dir, type='recon'): """ type[cad, recon]: using cad model or reconstructed model """ super().__init__() assert(type == 'cad' or type == 'recon'), "only support CAD model (cad) or reco...
2,256
36.616667
125
py
OVE6D-pose
OVE6D-pose-main/dataset/LineMOD_Dataset.py
import json import torch from pathlib import Path class Dataset(): def __init__(self, data_dir): self.model_dir = Path(data_dir) / 'models_eval' self.cam_file = Path(data_dir) / 'camera.json' with open(self.cam_file, 'r') as cam_f: self.cam_info = json.load(cam_f) ...
1,249
35.764706
84
py
OVE6D-pose
OVE6D-pose-main/training/pyrenderer.py
import os import torch import random import structlog from torch.utils.data import Dataset from lib import rendering from lib.three import rigid from training import data_augment from training import train_utils os.environ['PYOPENGL_PLATFORM'] = 'egl' logger = structlog.get_logger(__name__) class PyrenderDataset(D...
11,376
45.627049
153
py
OVE6D-pose
OVE6D-pose-main/training/data_augment.py
import cv2 import torch import numpy as np import imgaug.augmenters as iaa import torchvision.transforms.functional as tf from lib import geometry def divergence_depth(anchor_depth, query_depth, min_dep_pixels=100, bins_num=100): hist_diff = 0 anc_val_idx = anchor_depth>0 que_val_idx = query_depth>0 ...
7,546
44.191617
143
py
OVE6D-pose
OVE6D-pose-main/training/train_utils.py
import torch import math import torch.nn.functional as F from lib import geometry def background_filter(depths, diameters, dist_factor=0.5): """ filter out the outilers beyond the object diameter """ new_depths = list() unsqueeze = False if not isinstance(diameters, torch.Tensor): diame...
18,659
37.553719
132
py
OVE6D-pose
OVE6D-pose-main/training/config.py
import torch BASE_LR = 1e-3 # starting learning rate MAX_EPOCHS = 50 # maximum training epochs NUM_VIEWS = 16 # the sampling number of viewpoint for each object WARMUP_EPOCHS = 0 # warmup epochs during training RANKING_MARGIN = 0.1 # the triplet margin for ranking USE_DATA_AUG = True ...
2,067
46
111
py
OVE6D-pose
OVE6D-pose-main/training/train_on_shapenet.py
import os from pickle import load import sys import time import math import matplotlib import torch import random import shutil import structlog import torchvision import copy from pytorch3d.transforms import matrix_to_euler_angles import numpy as np from pathlib import Path from torch import optim from torch.nn i...
25,399
49.8
137
py
OVE6D-pose
OVE6D-pose-main/example/misc.py
import torch import numpy as np from scipy import spatial def str2dict(ss): obj_score = dict() for obj_str in ss.split(','): obj_s = obj_str.strip() if len(obj_s) > 0: obj_id = obj_s.split(':')[0].strip() obj_s = obj_s.split(':')[1].strip() if len(obj_s) > 0:...
4,059
33.40678
94
py
OVE6D-pose
OVE6D-pose-main/lib/network.py
import torch import math from torch import nn import torch.nn.functional as F from lib.geometry import inplane_2D_spatial_transform from lib import preprocess class OVE6D(nn.Module): def __init__(self): super(OVE6D, self).__init__() ###################################### backbone ###############...
11,408
45.190283
131
py
OVE6D-pose
OVE6D-pose-main/lib/geometry.py
""" This code is borrowed from LatentFusion https://github.com/NVlabs/latentfusion/blob/master/latentfusion/modules/geometry.py """ import torch from skimage import morphology from torch.nn import functional as F from lib import three def inplane_2D_spatial_transform(R, img, mode='nearest', padding_mode='border', ali...
19,744
36.82567
123
py
OVE6D-pose
OVE6D-pose-main/lib/rendering.py
""" This code is partially borrowed from LatentFusion """ import os import math import torch import trimesh import pyrender import numpy as np import torch.nn.functional as F from pyrender import RenderFlags from pytorch3d.transforms import matrix_to_euler_angles, euler_angles_to_matrix from utility import meshutils ...
14,781
37.494792
119
py
OVE6D-pose
OVE6D-pose-main/lib/preprocess.py
import torch import torch.nn.functional as F from lib import geometry def background_filter(depths, diameters, dist_factor=0.5): """ filter out the outilers beyond the object diameter """ new_depths = list() unsqueeze = False if not isinstance(diameters, torch.Tensor): diameters = torch...
18,061
37.348195
132
py
OVE6D-pose
OVE6D-pose-main/lib/three/rigid.py
from typing import Tuple import torch from torch.nn import functional as F from lib.three import core def intrinsic_to_3x4(matrix): matrix, unsqueezed = core.ensure_batch_dim(matrix, num_dims=2) zeros = torch.zeros(1, 3, 1, dtype=matrix.dtype).expand(matrix.shape[0], -1, -1).to(matrix.device) mat = tor...
3,819
23.487179
102
py
OVE6D-pose
OVE6D-pose-main/lib/three/core.py
import torch @torch.jit.script def acos_safe(t, eps: float = 1e-7): return torch.acos(torch.clamp(t, min=-1.0 + eps, max=1.0 - eps)) @torch.jit.script def ensure_batch_dim(tensor, num_dims: int): unsqueezed = False if len(tensor.shape) == num_dims: tensor = tensor.unsqueeze(0) unsqueezed...
2,950
23.591667
68
py
OVE6D-pose
OVE6D-pose-main/lib/three/batchview.py
import torch @torch.jit.script def bvmm(a, b): if a.shape[0] != b.shape[0]: raise ValueError("batch dimension must match") if a.shape[1] != b.shape[1]: raise ValueError("view dimension must match") nbatch, nview, nrow, ncol = a.shape a = a.view(-1, nrow, ncol) b = b.view(-1, nrow,...
1,093
26.35
79
py
hyperspherical_community_detection
hyperspherical_community_detection-main/experiments/observation1_demonstration.py
import numpy as np import matplotlib.pyplot as plt import pandas as pd from ..algorithms import pair_vector as pv from ..random_graphs.generators import PPM, HeterogeneousSizedPPM, IndependentLFR default_lats = np.linspace(0, np.pi / 2, 12)[1:] def short2mathjax(desc, name='x'): if desc == 'l(b(T))': ret...
8,979
38.043478
109
py
pose-gan
pose-gan-master/test.py
import os from conditional_gan import make_generator import cmd from pose_dataset import PoseHMDataset from gan.inception_score import get_inception_score from skimage.io import imread, imsave from skimage.measure import compare_ssim import numpy as np import pandas as pd from tqdm import tqdm import re def l1_sc...
5,945
37.36129
119
py
pose-gan
pose-gan-master/stn.py
from keras.engine.topology import Layer import tensorflow as tf class SpatialTransformer(Layer): """Spatial Transformer Layer Implements a spatial transformer layer as described in [1]_. Borrowed from [2]_: downsample_fator : float A value of 1 will keep the orignal size of the image. ...
6,874
38.97093
123
py
pose-gan
pose-gan-master/conditional_gan.py
from keras.models import Model, Input, Sequential from keras.layers import Flatten, Concatenate, Activation, Dropout, Dense from keras.layers.convolutional import Conv2D, Conv2DTranspose, ZeroPadding2D, Cropping2D from keras_contrib.layers.normalization import InstanceNormalization from keras.layers.advanced_activation...
13,649
39.746269
119
py
pose-gan
pose-gan-master/demo.py
from compute_coordinates import cordinates_from_image_file from create_pairs_dataset import filter_not_valid import cmd import os from shutil import copy, rmtree import pandas as pd from pose_dataset import PoseHMDataset from conditional_gan import make_generator from tqdm import tqdm from test import generate_images, ...
4,480
39.369369
115
py
pose-gan
pose-gan-master/pose_transform.py
from keras.models import Input, Model from keras.engine.topology import Layer from keras.backend import tf as ktf import pose_utils import pylab as plt import numpy as np from skimage.io import imread from skimage.transform import warp_coords import skimage.draw import skimage.measure import skimage.transform from...
18,211
33.041121
134
py
pose-gan
pose-gan-master/baseline.py
from keras.models import Model from keras.layers import Dense, Reshape, Flatten, Activation, Input from keras.layers.convolutional import Conv2D from keras.layers.normalization import BatchNormalization from keras_contrib.layers.normalization import InstanceNormalization from gan.wgan_gp import WGAN_GP from gan.datase...
2,214
34.15873
114
py
pose-gan
pose-gan-master/compute_coordinates.py
import pose_utils import os import numpy as np from keras.models import load_model import skimage.transform as st import pandas as pd from tqdm import tqdm from skimage.io import imread from skimage.transform import resize from scipy.ndimage import gaussian_filter from cmd import args mapIdx = [[31,32], [39,40], [33...
9,281
40.070796
129
py
pose-gan
pose-gan-master/sup-mat/search.py
### Script for retriving images from paper in large datasets, script uses vgg conv5 descriptors for comparizon. ### usage: python search.py /path/to/dataset/folder /path/to/images/from/paper/folder from skimage.color import rgb2gray, gray2rgb from skimage.transform import resize import os from keras.applications impor...
1,704
33.1
111
py
pose-gan
pose-gan-master/ssd_score/compute_ssd_score.py
import numpy as np ##Caffe from ssd branc import caffe caffe.set_device(0) caffe.set_mode_gpu() from skimage import img_as_float from tqdm import tqdm class SSDScorer(object): def __init__(self, model_def='deploy.prototxt', model_weights='VGG_VOC0712_SSD_300x300_iter_120000.caffemodel'): self.net = caffe.N...
2,857
40.42029
116
py
SSeg
SSeg-master/demo_folder.py
import os import sys import time import argparse from PIL import Image import numpy as np import cv2 import torch from torch.backends import cudnn import torchvision.transforms as transforms import network from optimizer import restore_snapshot from datasets import cityscapes from config import assert_and_infer_cfg ...
3,199
36.209302
162
py