sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
ffd770234a0539359780dc764d363849fdcd52f32e494662a8a6594d5a0135f4 | Python | 8,007 | 293 | import torch
import torch.distributed as dist
import os
import os.path as osp
import numpy as np
import cv2
import copy
import json
from ..log_service import print_log
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instances[class_] = c... |
74a8fdaabc6745705a44bfe4ab19b6b4f7eb952535cfb54965942283f35248bb | Python | 8,008 | 222 | #!/usr/bin/env python
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import platform
import shutil
import sys
import warnings
from setuptools import find_packages, setup
import torch
from torch.utils.cpp_extension import (BuildExtension, CppExtension,
... |
4042ab2704c5ddb06f87b95a83982fa2570afd1df1b21dfb9a18b72eb8bac31a | Python | 8,020 | 244 | # Copyright (C) 2022-2025 ETH Zurich, Marc Lehner and other DASH contributors.
from typing import Any, Tuple
import numpy as np
from rdkit import Chem
from serenityff.charge.utils import Molecule
def is_atom_bonded_conjugate(atom: Chem.Atom) -> bool:
for bond in atom.GetBonds():
if bond.GetIsConjugated(... |
bcce6486019e0cdeac2ef24512fa88aa03f51e7232421b3b1b97835c7c189523 | Python | 8,024 | 221 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 12 13:38:23 2022
@author: Daniel
"""
from phase_to_rate.neural_coding import load_spikes, rate_n_phase, load_spikes_DMK
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import os
import sys
import matplotlib as mpl
import pdb
i... |
09b9d95416e1637cf09182b591b95b0bd0002c0d1087428b28efb2dbebd38daf | Python | 8,036 | 221 | '''
ResNet for CIFAR-10/100 Dataset.
Reference:
1. https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
2. https://github.com/facebook/fb.resnet.torch/blob/master/models/resnet.lua
3. Kaiming He, Xiangyu Zhang, Shaoqing Ren, Jian Sun
Deep Residual Learning for Image Recognition. https://arxiv.org... |
b38b3ca83e0670b084a715ee4ad574f25430111f0bf2ef3ffe545db6b867e7f3 | Python | 8,041 | 170 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 19:10:10 2021
@author: fhu14
"""
#%% Imports, definitions
from .base_classes import LossModel
from typing import List, Dict
import numpy as np
import re
import torch
Tensor = torch.Tensor
import torch.nn as nn
#%% Code behind
class TotalEnergyLoss(LossModel):
... |
c5e6252b480d2ca5d5a11cd330c66d396d26011291b9222eed6935a1d8e0ca5a | Python | 8,046 | 262 | import sys
import gzip
import re
import argparse
import util
class Chromosome(object):
"""Represents a chromosome. Has a name, length and a few
descriptive flags, such as whether the chromosome is a sex
chromosome."""
def __init__(self, idnum=None, name=None, length=None,
is_sex=... |
403d62b058fdf615b8150697a28fafc0d3ab01a5b4aecf75facc57db078a5e21 | Python | 8,050 | 194 | """
Lexical-predictability control features (Reviewer 1, comment 1.3).
The reviewer notes that the non-semantic control set used to isolate the unique
neural variance of the GPT-4 QA semantic features (mel-spectrogram, GBFB, speech
presence, phonetic, syntactic) omits basic lexical properties: word frequency,
n-gram p... |
f136798592de6b3b01fc04eab542b07187a9399f6b1a4021ed8162027a434158 | Python | 8,051 | 257 | # ------------------------------------------------------------------------------
# Copyright and License Information
# Adapted from
# https://github.com/microsoft/voxelpose-pytorch/blob/main/lib/models/v2v_net.py
# Original Licence: MIT License
# -------------------------------------------------------------------------... |
f15788221b113d94f7f3aa82a0f1a9b9c5b54696f2187db657f1cbded4f6523f | Python | 8,053 | 233 | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source... |
c25f68faa99e8454b6b17e12935123bff5afd69fdd3a5d141ea415f4a7d72fdc | Python | 8,060 | 213 | '''
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
* By Junnan Li
'''
import argparse
import os
import ruamel_yaml as yaml
import numpy as np
imp... |
67e5726b1937644a1604798143ee15ec2caf6f9f15f88fb62d0f0b8873b0d2b9 | Python | 8,064 | 195 | from statistics.mlp_output_wrappers import *
from statistics.dataframe_validation import *
from statistics.utilities import CONFIG, time_and_progress
from typing import Union
import pandas as pd
@pa.check_types
def load_metadata_pathology_mlp_pivot() -> DataFrame[MlpPathologySchema]:
df_long : DataFrame[MlpSchema]... |
8e4ebec01fef4a0c4bc4f363861442e1e690be508d73927f98354f5cab481e4e | Python | 8,069 | 174 | from typing import List, Union, Tuple
from functools import reduce
from rdkit import Chem
import torch
import torch.nn as nn
from .args import ModelArgs
from .features import BatchMolGraph, get_atom_fdim, get_bond_fdim, mol2graph
from .nn_utils import index_select_ND, get_activation_function
class MPNEncoder(nn.Mod... |
343968388a78ffc795ff2a3bd29659fe4a5c8a10bd7a4d1a443dd5761a89552a | Python | 8,072 | 241 | """
U-Sleep neural network architecture for sleep stage classification.
U-Sleep is a fully convolutional neural network based on the U-Net architecture,
adapted for 1D time-series data. It processes multi-channel EEG/EOG signals and
outputs sleep stage predictions for each 30-second epoch.
Architecture:
Input → E... |
d9025fb81136876472baa22f0cb80f7d23683d623af2fd2041c7df51344e6096 | Python | 8,076 | 140 | from sklearn.linear_model import LassoCV
from sklearn.model_selection import GridSearchCV
from sklearn import linear_model, ensemble
from sklearn.svm import SVR
from sklearn.ensemble import RandomForestRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.gaussian_process import GaussianProcessRegresso... |
2a44472daa0f9b67990e75d1de212eaa7e4ae89ccaec95fa34eeaaf996a97118 | Python | 8,078 | 226 | # Copyright (c) OpenMMLab. All rights reserved.
from typing import Optional
import numpy as np
import torch
from mmcv.runner import load_checkpoint
from torch import Tensor, nn
from .builder import FILTERS
from .filter import TemporalFilter
class SmoothNetResBlock(nn.Module):
"""Residual block module used in Sm... |
03118d1079ccf4423fe6d5e337badbabe8a543577fe3c923bd2040782e0d8bad | Python | 8,083 | 229 | import sys
import gzip
import os
import numpy as np
import util
class TestSNP:
def __init__(self, name, geno_hap1, geno_hap2, AS_target_ref, AS_target_alt,
hetps, totals, counts):
self.name = name
self.geno_hap1 = geno_hap1
self.geno_hap2 = geno_hap2
self.AS_targe... |
6b14a69af7e41906c55ddfa4e560090e44e0e14176d944975e026852a4cad18b | Python | 8,102 | 234 | """keras2c_main.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under MIT License
https://github.com/f0uriest/keras2c
Converts keras model to C code
"""
# imports
from keras2c.layer2c import Layers2C
from keras2c.weights2c import Weights2C
from keras2c.io_parsing import layer_type, get_all_io_name... |
1e69b51984cfef2051f6bc845a6fb46021addb1e196ce6905174c09d92ced007 | Python | 8,106 | 254 | # coding:utf-8
import argparse
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import numpy as np
from keras.optimizers import adam
from keras.layers import Input, Dense, Flatten, Conv2D, MaxPool2D, BatchNormalization
from keras.models import Model, load_model
import glob
from PIL import Image
import math
... |
45076d263f95fcc3d0de41bf7853b257dd0869821fb219c81b76abf13f454d1a | Python | 8,112 | 251 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from argparse import ArgumentParser
import mmcv
import numpy as np
def print_coco_results(results):
def _print(result, ap=1, iouThr=None, areaRng='all', maxDets=100):
titleStr = 'Average Precision' if ap == 1 else 'Average Recall'
... |
b79d8771574021c4e58f427903f4aba0bffe39f18303e575bde4821b7aa79741 | Python | 8,113 | 205 | #!/usr/bin/env python
# coding: utf-8
# # Converting star files to csv
# # Converting particles_selected and particles_excluded star files to csv files in the original cs-empiar cryosparc directories
import pandas as pd
import glob
#Change this according to your structure of Cryo EM project directory or
#comment t... |
f9107210fcc45752f6a20207727f84db1b080d64e987e85dd315ac2449f7160f | Python | 8,115 | 240 | # =========================================================
# from 'mmdetection/configs/_base_/default_runtime.py'
# =========================================================
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
... |
e9d7fde2e8b373b4b84914086ede45151915398410f31d5e98dc62adb583106c | Python | 8,125 | 226 | # Copyright (c) OpenMMLab. All rights reserved.
import copy
from abc import ABCMeta, abstractmethod
import numpy as np
from torch.utils.data import Dataset
from mmpose.datasets import DatasetInfo
from mmpose.datasets.pipelines import Compose
class Kpt3dSviewKpt2dDataset(Dataset, metaclass=ABCMeta):
"""Base clas... |
1546506862d02b91bd5a1af172c6934cfc5713f8f61579c169e91bc2bb560594 | Python | 8,127 | 280 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
import os
from shutil import rmtree
from typing import OrderedDict, Sequence
import numpy as np
import pandas as pd
import pytest
import torch
from rdkit import Chem
from serenityff.charge.gnn.utils import (
ChargeCorrectedNodeWiseAt... |
95b26cee0fa0d866e28e327a5a6f6d7c4df88cd68317383b087e33321aee3cae | Python | 8,135 | 181 |
import logging
import os
import tqdm
import torch.utils.data as data
from . import utils
from .dataset import StackOverflowDataset
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.INFO)
client_ids_train = None
client_ids_test = None
DEFAULT_TRAIN_CLIENTS_NUM = 342477
DEFAULT_TEST_CLIENTS_N... |
476f1c6eeaa21e89ba2bd0e95cb6f521c405ff903eedc0bc573cb49187c444ca | Python | 8,142 | 246 | """check_model.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under LGPLv3
https://github.com/f0uriest/keras2c
Checks a model before conversion to flag unsupported features
"""
# Imports
import numpy as np
from keras2c.io_parsing import layer_type, flatten
from keras2c.weights2c import Weights2C
... |
ac4748c051ff4d6b4417756b37fd1e1a41b983c089d0d567a8a832ca3aa49f98 | Python | 8,146 | 279 | # ------------------------------------------------------------------------------
# Adapted from https://github.com/leoxiaobin/deep-high-resolution-net.pytorch
# Original licence: Copyright (c) Microsoft, under the MIT License.
# ------------------------------------------------------------------------------
import nump... |
c6dea69eeaf0d9d843e7bd7214d44c60102bcf461a7e496963583e1e8c1c7495 | Python | 8,153 | 152 | import numpy as np
import scanpy as sc
import scvelo as scv
import anndata as ad
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics.pairwise import cosine_similarity
from scipy.stats import spearmanr, pearsonr, sem
import pandas as pd
from latentvelo.utils import paired_cosine_similarity, average... |
9c41963f4a472bc226e8c28a0fea1e5ca2c17ae8840d87e95fc2cb4120d8c334 | Python | 8,156 | 208 |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be usef... |
30cfa09e1580cab759211e75e4889a5356147f63f7767ff3a1255d3c97e7d0cb | Python | 8,170 | 230 | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source... |
bf2f35a0bc2139e8094e03659f19980ab328e8adcb7a802021ab80d652d8f28e | Python | 8,174 | 238 | """This module implements an abstract base class (ABC) 'BaseDataset' for datasets.
It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.
"""
import importlib
import random
import numpy as np
import stringcase
import torch.utils.data as data
from P... |
9c549f9501aafb39b055aa1013285c608d9d14388eb41b410430f98534f50c63 | Python | 8,182 | 164 | import os
import sys
import time
import torch
import torch.nn.functional as F
from torch_geometric.data import DataLoader
from sklearn.metrics import mean_squared_error
from graphrepr.graphconv import run_epoch, predict, GraphConvNetwork
from graphrepr.data import load_dataset
from graphrepr.evaluate import test_model... |
955f6bad9995d19ba73fc0482d81da2837b10b99656d9710f68cb82db8429c5a | Python | 8,190 | 253 |
import snptable
import gzip
import os
import numpy as np
import pysam
class Data():
def __init__(self, data_dir="test_data",
snp_filename="test_data/snp_tab.txt.gz",
sam_filename="test_data/test.sam"):
self.data_dir = data_dir
self.snp_filename = snp_filena... |
f157560dc73e69b1a4c712fe7bcd232098b20bf5d49c1ffe4de0daec23f8c695 | Python | 8,198 | 227 | # SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: BSD-3-Clause
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source... |
f668bf35dfdeaeb2bdf771cfd7a8dd8674190595fa0e49fadd5091fb7d0cdb81 | Python | 8,199 | 205 | """Temporal Convolution model implemented in PyTorch."""
from torch import nn
from daart.models.base import BaseModel, get_activation_func_from_str
# to ignore imports for sphix-autoapidoc
__all__ = ['DilatedTCN']
class DilatedTCN(BaseModel):
"""Temporal Convolutional Model with dilated convolutions and no temp... |
8b25d0910dab765ffedb475d7209cc33c9225aaf6a96bcfdd96740d8a9a4baad | Python | 8,201 | 214 | # Author: Fabi Prezja <faprezja@fairn.fi>
# Copyright (C) 2023 Fabi Prezja
# License: MIT License (see LICENSE.txt for details)
import os
import shutil
import numpy as np
import sys
def update_nested_dict(d, u):
"""
Updates a nested dictionary with values from another dictionary.
Args:
d (dict): ... |
7973a90f07ef416a75917833b3656ec02ad0c89ca08d16162dcd9ff915b1d904 | Python | 8,202 | 223 | from typing import Union, Tuple, Any, Optional
from functools import partial
import numpy as np
import eagerpy as ep
from ..devutils import flatten
from ..devutils import atleast_kd
from ..types import Bounds
from ..models import Model
from ..distances import l2
from ..criteria import Misclassification
from ..crit... |
b3a3470ee0b733b2f2e4efd19f75d95886bdb7888ca6d6bd3cf8a44f61c651c8 | Python | 8,204 | 239 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
hyperparameters.py:
Wrapper for using grid search for optimizing the prior
kernel's hyperparamters for the DiagonalFourierLowrank
model class.
"""
from numpy import *
from lgcpspatial.gridsearch import grid_search
from lgcpspatial.lgcp2d import DiagonalFourierLowrank
fr... |
2f72f5f77a05cdcb89f2814914961b88ede052e5e6aeee7787b5d213dcd26975 | Python | 8,216 | 186 | import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from torch.utils.data.sampler import SubsetRandomSampler
class CustomDataset(Dataset):
def __init__(self, data, labels, transform=None):
self.data = data
self.labels ... |
eb040630db7e4189c47db3ffbead90415510c863827d94d35dbc7f2878f6483a | Python | 8,218 | 222 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import (build_conv_layer, build_upsample_layer, constant_init,
normal_init)
from mmpose.models.builder import build_loss
from ..builder import HEADS
@HEADS.register_module()
class AEMultiStageHead(nn.Module):
... |
7791a3ffb39da2ab3f911fe8d62c79e6d50b924cd69665df577dc2dbbda3c3dc | Python | 8,219 | 211 | import utils
import sqldbutils as dutil
import json
from os.path import join, isfile, split
from study_analyzer import StudyAnalyzer, StudyConcept
from datetime import datetime
import joblib as jl
my_host = 'localhost'
my_user = ''
my_pwd = ''
my_db = ''
my_sock = ''
db_connection = 'sql'
# get anns by doc set an... |
090359f3624e350890ee665282e146823f57d788550765e1d2cf72980fe8aadf | Python | 8,225 | 190 | import os, sys
from glob import glob
from os.path import join, isfile
import numpy as np
import pandas as pd
import time
from datetime import datetime
from copy import deepcopy
from sklearn.metrics import balanced_accuracy_score, roc_auc_score, get_scorer, make_scorer
from joblib import Parallel, delayed, dump, load... |
dd76899bf23d1bfba0a6053dc237b3088153e962d70f9039b200760df4bde43e | Python | 8,230 | 183 | import torch as th
import torch.nn as nn
from latentvelo.dataloader_nogcn import DatasetNoGCN
from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor
import os
import numpy as np
import matplotlib.pyplot as plt
from latentvelo.utils import batch_func
from .collate import collate
def train_vae_nogcn(mo... |
65e792b3f74fa3fdb42862758cf6946b29ac8d498faa3cb48b8427a917557463 | Python | 8,233 | 213 | # Copyright (c) OpenMMLab. All rights reserved.
# Copyright (c) 2019 Western Digital Corporation or its affiliates.
import warnings
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmcv.runner import BaseModule
from torch.nn.modules.batchnorm import _BatchNorm
from ..builder import BACKBONES
class ResBlo... |
01cd2b776092749674683400b16690539b53086377014395c111e37e9665e06c | Python | 8,241 | 241 | # Copyright (c) OpenMMLab. All rights reserved.
import os
import warnings
from argparse import ArgumentParser
import cv2
import mmcv
from mmpose.apis import (collect_multi_frames, get_track_id,
inference_top_down_pose_model, init_pose_model,
process_mmdet_results, vis... |
981bb34aa1b7ef2422eac8e184a48957f68f7a0f7bc748621dec2b8849382b7c | Python | 8,242 | 253 | #!/usr/bin/env python
import CNVworkflowlib
import argparse
####################################
### Parse command-line arguments ###
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("CNV_file", type=str, help="CNV file", default=None)
args = parser.parse_ar... |
dca86aaacb0816595612d704de265e5ba8e2bfee471a6736c90f2478a67d4cc1 | Python | 8,250 | 230 | import ete3
import numpy as np
import pandas as pd
import argparse
# argument parser
arp = argparse.ArgumentParser()
# Add the arguments to the parser
arp.add_argument("-tree", "--tree", required=True, help="newick file with species tree")
arp.add_argument("-ort", "--ort", required=True, ... |
4108149512463f0b573d2c0a4bb058d39c21602ecdc26d42e1e50f95e4f18dab | Python | 8,254 | 256 | import numpy as np
import pandas as pd
import pytest
from sklearn.base import clone
from sklearn.linear_model import LinearRegression
import doubleml as dml
from ..datasets import make_plpr_CP2025
dim_x = 30
learner = LinearRegression()
ml_l = clone(learner)
ml_m = clone(learner)
df_int = pd.DataFrame(
{
... |
d1cf35eb53cddb31a5bfaae70c91ecf16715323291b4d67639176fb94254804a | Python | 8,256 | 193 | #!/usr/bin/python
"""
Model architecture definition
Multiple inputs: https://www.pyimagesearch.com/2019/02/04/keras-multiple-inputs-and-mixed-data/
Multiple outputs: https://github.com/rahul-pande/faces-mtl/blob/master/faces_mtl_age_gender.ipynb
"""
from deeplearning.architecture_features import *
from tensorflow.ke... |
58031646c5f3d6dd5b3ace193f297b8ce6f0d88ac3ee297b603d8f8c89f2e166 | Python | 8,257 | 216 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
import numpy as np
import torch
from ..builder import BBOX_CODERS
from .base_bbox_coder import BaseBBoxCoder
@BBOX_CODERS.register_module()
class LegacyDeltaXYWHBBoxCoder(BaseBBoxCoder):
"""Legacy Delta XYWH BBox coder used in MMDet V1.x.
Following... |
fbea1defc21ff1c00286947cb93b5ad7b9daa0e13991dce7666486c929f60fb1 | Python | 8,257 | 188 | import logging
import datetime
import yaml
from sklearn.model_selection import StratifiedKFold, KFold
from data.data_access import Data
# from features_processing.feature_scaler import FeatureScaler
from model.model_factory import get_model
from pipeline.one_split import OneSplitPipeline
import pandas as pd
from os.pa... |
9df94372ccba0348995209403059751fa5e44e03ea3ce903a526665c437dc48a | Python | 8,273 | 233 | """Validate PLRVector return types and reset behavior."""
import numpy as np
import pandas as pd
import pytest
from sklearn.linear_model import LinearRegression
import doubleml as dml
from doubleml.plm.plr_vector import PLRVector
N_OBS = 200
N_FOLDS = 3
N_REP = 2
N_REP_BOOT = 251
def _make_data(n_obs: int = N_OBS,... |
2f584f1bdf4d6942815712fa32652983d07da4347385bcd9a5195911052773f7 | Python | 8,274 | 208 | """Temporal Convolution model implemented in PyTorch."""
import numpy as np
from sklearn.metrics import accuracy_score
import torch
from torch import nn
from daart.models.base import BaseModel, get_activation_func_from_str
# to ignore imports for sphix-autoapidoc
__all__ = ['DilatedTCN']
class DilatedTCN(BaseModel)... |
4a575626af978f55eb9ac9fef591ebab0615cb52cec00854f9280ba22b540877 | Python | 8,281 | 275 | from typing import Union, Any, Optional, Callable, Tuple
from abc import ABC, abstractmethod
import eagerpy as ep
from ..devutils import flatten
from ..devutils import atleast_kd
from ..types import Bounds
from ..models.base import Model
from ..criteria import Misclassification, TargetedMisclassification
from ..di... |
da0a4be7de1eec34a36de55521fb977b053cd4919f88fde79bc39302448cb3d1 | Python | 8,283 | 199 | import os
import sys
import torch
import torchvision
import numpy as np
import pycocotools.mask as coco_mask
from pathlib import Path
from pycocotools.coco import COCO
from PIL import Image
from fedml_api.data_preprocessing.coco.transforms import Normalize, ToTensor
from fedml_api.data_preprocessing.coco.utils import ... |
fb9628136e54e7dc0ea8ccd682311aaf730b63dec586a11f511fc8a7847c363a | Python | 8,304 | 212 | import os
from copy import deepcopy
from enum import Enum, auto
from abc import ABC, abstractmethod
import imageio as imageio
import numpy as np
from typing import Union, Tuple
import cv2
from PIL import Image
from scipy.stats import mode
from configs.figure import GlobalFigureMixin
from reactiondataextractor.models.... |
aeaa55b359456520d4efec01b84812c7cfa777394853aaa8a47b2a0cf310f4f0 | Python | 8,306 | 215 | """
simulation functions
"""
import numpy as np
import math
import tensorflow as tf
def cut_bound(vp,ve,ktr,vpt=0.01,vpr=0.05,vet=0.2,ver=0.5,ktrt=0.002,ktrr=0.01):
if vp>0.05:
vp = 0.05
if vp<0.01:
vp = 0.01
if ve>0.5:
ve = 0.5
if ve<0.2:
ve=0.2
if ktr>0.01:
... |
2b9187c72b7ea8f7b617eaf1fe0508aa3eccf86eb6471eea112f6a10823457f2 | Python | 8,307 | 231 | """make_test_suite.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under LGPLv3
https://github.com/f0uriest/keras2c
Generates automatic test suite for converted code
"""
# Imports
import numpy as np
from keras2c.io_parsing import get_model_io_names
from keras2c.weights2c import Weights2C
import su... |
748a7442d37a7fa9463193db2fc8b97e43354705ba04a1c2f69ff0f67582a843 | Python | 8,308 | 214 | import numpy as np
import matplotlib.pyplot as plt
from pybrid import utils
PALETTE = (
"#377eb8",
"#4daf4a",
"#984ea3",
"#e41a1c",
"#ff7f00",
"#a65628",
"#f781bf",
"#888888",
"#a6cee3",
"#b2df8a",
"#cab2d6",
"#fb9a99",
"#fdbf6f",
)
def get_mean_std(arr):
arr ... |
7e673ed385f9eaed43d6d3885ea86ebdc2974c6834ec9f2a5b7744d6aa751d70 | Python | 8,308 | 220 | """
This file generates the clean version of the ANI-1ccx dataset used for our calculations as of July 10th, 2023
"""
# %%
from h5_converter import h5_handler
from pathlib import Path
import numpy as np
# %%
def load_dset_to_dict():
r"""Uses the h5 handler to load the entire h5 dataset directly into a dictionary
... |
483a50929e9a999f9ba5c12da59bf51ff4d1fd3533d83fa0ed5f5d161320804b | Python | 8,309 | 199 |
import numpy as np
import scipy.linalg
from .util import TriuToSymm, BMatArr
TOLSAMEDIST = 1.0e-5
MINHUBDIFF = 0.3125e-5
# Helpers of (regular) gamma
def _Gamma12(r12, hub1, hub2):
tau1, tau2, smallHubDiff = _Tau1Tau2SmallHubDiff(hub1, hub2)
if r12 < TOLSAMEDIST:
return _GammaDiag(hub1, hub2)
el... |
cc8c62a98181cf1b972781043447b8153c264ef3f07b9e900dfaca4312c03f92 | Python | 8,310 | 230 | import ete3
import numpy as np
import pandas as pd
import argparse
# argument parser
arp = argparse.ArgumentParser()
# Add the arguments to the parser
arp.add_argument("-tree", "--tree", required=True, help="newick file with species tree")
arp.add_argument("-ort", "--ort", required=True, ... |
28e0f7bfd9533545d0403df4f9c4199b93e76ab208832c28b0af7cf9cd84d0a8 | Python | 8,319 | 180 | import pickle
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.gridspec as gridspec
from absl import app, flags, logging
import sys
sys.path.append('../')
from jax.config import config
import tensorflow as tf
import os
os.environ['XLA_PYTHON_CLIENT_PREALLOCATE']... |
a9445752c9ff680be78ab355f609e3ea68bf4cb60f679c9f6958b651ef56e145 | Python | 8,320 | 228 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmdet.models.builder import HEADS
from mmdet.models.utils import build_linear_layer
from .bbox_head import BBoxHead
@HEADS.register_module()
class ConvFCBBoxHead(BBoxHead):
r"""More general bbox head, with ... |
e52a5428aa1f8b5187ac0465c3f4bdb1496a9f9733a53c4fb6c0ccee8157012a | Python | 8,324 | 159 | #!/usr/bin/env python
"""
Plugin workflow to add coregistration steps from SWI to T1 when doing CMB
segmentation while a T1 is available from another segmentation
"""
from nipype.interfaces import ants
from nipype.pipeline.engine import Node, Workflow
from nipype.interfaces.quickshear import Quickshear
from shivai.int... |
5c9016dfe5de224f156c015de7196c430c25c1d66e25580150765fef4e897cc5 | Python | 8,329 | 292 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import copy
import functools
import itertools
import matplotlib.pyplot as plt
########
# unit #
########
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
... |
3230b5c612cadd594a4b68a4dfb5c6b4e9012d67edac60b9ba2b5a45638a854f | Python | 8,332 | 255 | import getpass
import datetime
import itertools
import matplotlib
import mne
import numpy as np
import pandas as pd
from eegml import entropy as en
from eegml import preprocessing as pp
from eegml import toolkit as tk
if getpass.getuser() == "emilelemoine":
matplotlib.use("macosx")
mne.set_log_level(verbose=Fal... |
0abb47f84008ef14113d39ee84a5fc7b1e6d3496139f3f9699bb0e524422a8bb | Python | 8,336 | 182 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
from typing import Dict, Optional, Union
import torch
from torch import Tensor
from torch.distributions import Distribution
from torch.utils.tensorboard.... |
3c27773ce58217262f9e1a592e2f50470cabfef1b15d140faf7ce6e7207f5628 | Python | 8,336 | 183 | import argparse
import importlib
import json
import numpy as np
import os
import plotly.graph_objects as go
import torch
from plotly.offline import plot
from tqdm import tqdm
from data_loader.general_data_loader import GeneralDataset
from parse_config import ConfigParser
SEED = 123
torch.manual_seed(SEED)
torch.back... |
b05618e55389a941b08f738b1e7cfd03e4546fc6608db560e6132a1a777e5276 | Python | 8,342 | 231 | """ ONNX backend """
import collections
import enum
import json
import os
class ModelFactory:
""" ONNX backend model factory """
def open(self, model):
return _Model(model)
class _Model:
def __init__(self, model):
""" Serialize ONNX model to JSON message """
# import onnx.shape_i... |
f5b5fbb29e89fb137d21eece1173cf91ea088cbb15b46888005a2ecba0198403 | Python | 8,349 | 186 | import argparse
import os
import platform
import shutil
import time
from pathlib import Path
import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random
from models.experimental import attempt_load
from utils.datasets import LoadStreams, LoadImages
from utils.general_split import (
check... |
4a2ddb2caa072d050942b68a13cb2a2e66c0e689e8f0fec8137133508142cdae | Python | 8,352 | 263 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 14 09:45:23 2022
@author: mathildelpx
"""
#%% Init
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import multipagetiff as mtif
from glob import glob
import seaborn as sns
# %% Load data
in_path = './'
total_cel... |
ca8a5885ccc1ee5ff0323b481ad41bd70bd3fda9ecc9c436ee4885d7060be5af | Python | 8,358 | 211 | import scipy
import abagen
import numpy as np
import pandas as pd
import nibabel as nib
from sklearn import decomposition
from neuromaps import datasets,resampling
from neuromaps.parcellate import Parcellater
from nibabel.freesurfer.io import read_annot
gitrepo_dir = '/Users/gshafiei/gitrepos/shafiei_megdynamics/'
par... |
613d5a44f16dfe263ac6bf3ac3916b11c367158185d0db257b9cba543906434e | Python | 8,367 | 223 | # Copyright (c) OpenMMLab. All rights reserved.
import os
import torch
def dynamic_clip_for_onnx(x1, y1, x2, y2, max_shape):
"""Clip boxes dynamically for onnx.
Since torch.clamp cannot have dynamic `min` and `max`, we scale the
boxes by 1/max_shape and clamp in the range [0, 1].
Args:
x1... |
e27541e636713a86c3fab009dc2dd298619dbdd0dd18fec4d92a90e2c2b46746 | Python | 8,378 | 188 | from deprecated.model_v1 import LinearLoss, ModelZ
from scipy.linalg import block_diag
import cvxopt
import numpy as np
# TODO: consider packing alpha, beta, loc, etc into a single class,
# then passing that class to Solver
# TODO: see Solver.solve
class Solver:
def __init__(self, modelZ: ModelZ, loss_func... |
70bd3f1088f426e73af3ee456530429d7ff9ff1fdb512fab137328c7d0af0905 | Python | 8,382 | 189 | import torch as th
import torch.nn as nn
from latentvelo.anvi_dataloader_nogcn import ANVIDatasetNoGCN
from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor
import os
import numpy as np
import matplotlib.pyplot as plt
from latentvelo.utils import batch_func
from .collate import collate_anvi
def trai... |
445d847c9a4392f8b3bcfea4afb5191e5acbaed44b04d5679c7fc359be69976b | Python | 8,386 | 151 | import numpy as np
from scipy import stats
def add_yield_trend_estimate(yxDatac, ny):
"""
Add a feature YFromTrend (the y value estimated by the y time trend of a given admin unit).
The type of trend computation is different depending on how long is the time series of stats data we have.
if we have at... |
42c489a655be6d6fcccb129cb14c4a6d19538ad2d651af0b0f0ead9f75ee0565 | Python | 8,388 | 214 | from sklearn.cluster import AgglomerativeClustering
from scipy.cluster.hierarchy import dendrogram, linkage
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import os
def build_neuron_traces(Exp, Cells):
for i, Cell in enumerate(Cells):
spks_t... |
63e45c9b57df70e5efaf7ba71034f314615e7c9a0161d3fc94ea9bde55c502f4 | Python | 8,388 | 206 | '''
* Copyright (c) 2022, salesforce.com, inc.
* All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
* By Junnan Li
'''
import argparse
import os
import ruamel_yaml as yaml
import numpy as np
imp... |
8db92587719fdae878f7cb952fee522324bf5b615cf57ad208531f85987f2f21 | Python | 8,393 | 238 | """
Variance partitioning using himalaya MultipleKernelRidgeCV.
----------------------
If the solver's diagonalisation step with `diagonalize_method='eigh'` fails
(e.g. because the kernel is ill‑conditioned), the code automatically
retries with `diagonalize_method='svd'`. This behaviour is fully transparent
for downs... |
136c088bd2e0b618ccfbf75835b053752104ed5a791eb340b111ce523f661a76 | Python | 8,394 | 163 | import os
import sys
import time
import torch
import torch.nn.functional as F
from sklearn.metrics import mean_squared_error
from graphrepr.evaluate import test_model
from graphrepr.savingutils import save_configs, save_history, LoggerWrapper
from graphrepr.config import parse_model_config, parse_representation_config,... |
20cd109e4961eb499d00748e667f2cf68e5db93e224fe3a7fb0273dfd6244a06 | Python | 8,395 | 222 | from dataclasses import dataclass
from enum import IntEnum
import hashlib
import io
import pathlib
import warnings
import zipfile
from typing import Optional, Tuple
from .util import get_root_uuid
from .version_parser import parse_version
@dataclass
class ChecksumDiff:
"""
All files added to, removed from, o... |
56f7427409b876b4ca48b20273fde03467d8472544639f84f5cc383bb46b9156 | Python | 8,395 | 195 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pyabf
import seaborn as sns
from utils.utils_behavior_dataset import run_ZZ_extraction
from utils.import_data import load_summary_csv
master_path = '/network/lustre/iss01/wyart/analyses/mathilde.lapoix/SCAPE/analysis_001/'
# summary_csv = ... |
7a1fee343e683c3eeed200522a35597124d53bc8e7181ffc866e42bb48087812 | Python | 8,396 | 170 | import subprocess
#subprocess.call(['C:\\Program Files\\Bitplane\\Imaris 9.9.0\\Imaris.exe', 'id101'])
import ImarisLib
import numpy as np
import math as m
import random
import nrrd
from tifffile import imwrite
import sys
sys.path.inse... |
f4bc5a8a3b69099bf4387769a7b3060f5eeffac19cb2b7b945ef6c6d427e4c31 | Python | 8,396 | 185 | #!/usr/bin/env python
import unittest
from os import path
from picrust2.util import system_call_check, TemporaryDirectory
# Paths to input files.
test_dir_path = path.join(path.dirname(path.abspath(__file__)))
test_study_seqs = path.join(test_dir_path, "test_data", "place_seqs",
"study_se... |
13053aeef68765648948d0e2eb789b5d77419a4db566caf40843ddfd0793bf7d | Python | 8,421 | 206 | # Copyright (c) OpenMMLab. All rights reserved.
import sys
from inspect import signature
import torch
from mmcv.ops import batched_nms
from mmdet.core import bbox_mapping_back, merge_aug_proposals
if sys.version_info >= (3, 7):
from mmdet.utils.contextmanagers import completed
class BBoxTestMixin(object):
... |
1d358f1c59e3ce978c91c651784fe55874343b6fc01d7bc5c59c7ad0ce41bc26 | Python | 8,422 | 268 | ## Acquired from https://github.com/pytorch/vision/tree/master/references/detection
from collections import defaultdict, deque
import datetime
import pickle
import time
import torch
import torch.distributed as dist
import numpy as np
import errno
import os
import pathlib
class SmoothedValue(object):
"""Track a s... |
5d83f50ce756491427beb94943cdfe055e94a0fad33c33e04b5ddc0363385682 | Python | 8,431 | 222 | import math
import torch
import torch.nn as nn
from .functional import switch_function
from typing import Optional
"""
computes electrostatic energy, switches between a constant value
and the true Coulomb law between cuton and cutoff
"""
class ElectrostaticEnergy(nn.Module):
def __init__(
self,
k... |
15dc8facb38a040f1a580a93df72d6e5e41526df3e55e423a211f90065d7303d | Python | 8,437 | 227 | from statistics.utilities import CONFIG
from typing import Dict
from statistics.dataframe_validation import *
from pandera.typing import DataFrame
import pandera as pa
import numpy as np
import pandas as pd
import re
__all__ = [
'DemoDataFrameDict',
'retrieve_age_gender_from_demo',
'retrieve_age_gender_fro... |
e08011a8a6530e9a74f5ea56d8bcb580e336fbd89989be11efc1830192239c99 | Python | 8,445 | 255 | from typing import Union, Optional, Tuple, Any, Callable
from typing_extensions import Literal
import eagerpy as ep
import logging
from abc import ABC
from abc import abstractmethod
from ..devutils import flatten
from ..devutils import atleast_kd
from ..models import Model
from ..criteria import Criterion
from ..di... |
d9c33f66382a9144c0ac87527c01ddd1ad9e8c13b8ed0cf00adc16073713fff9 | Python | 8,457 | 172 | import pandas as pd
import os, sys
import outputfiles.evaluation as ev
import mysrc.constants as cst
def weighed_average(grp):
return grp._get_numeric_data().multiply(grp['Production'], axis=0).sum() / grp['Production'].sum()
def model_evaluation(fn_in, crop_ID, forecast_time, model_name, fn_asapID2AU, fn_stats... |
4a612e588e02418986ccf090e0e064583a2d6dabeeaf74b96b8df3efe9dbd757 | Python | 8,467 | 249 | """keras2c_main.py
This file is part of keras2c
Copyright 2020 Rory Conlin
Licensed under LGPLv3
https://github.com/f0uriest/keras2c
Converts keras model to C code
"""
# Imports
from keras2c.layer2c import Layers2C
from keras2c.weights2c import Weights2C
from keras2c.io_parsing import get_model_io_names
from keras2c.... |
7619183f7c80a83f521962ade213290e261e722d53f46bd69b1c9cf70b4bb130 | Python | 8,471 | 210 | # -*- coding: utf-8 -*-
"""
Created on Thu Mar 10 10:50:46 2022
@author: olive
"""
import pandas as pd
import os
import shelve
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import pickle
from matplotlib import colors
mpl.rcParams['pdf.fonttype'] =... |
1de3589454fd648738a555f05cefe99d5df75b6a428eb8b6e5559c103c51016d | Python | 8,474 | 278 | import math
def cosine_lr_schedule(optimizer, epoch, max_epoch, init_lr, min_lr):
"""Decay the learning rate"""
lr = (init_lr - min_lr) * 0.5 * (1. + math.cos(math.pi * epoch / max_epoch)) + min_lr
for param_group in optimizer.param_groups:
param_group['lr'] = lr
def warmup_lr_schedule(opti... |
7cc5a4bea4af25f5f80dd82b447f7cd54a6a7ded8d7d0a33d8131a1eeb6398ae | Python | 8,478 | 269 | # -*- coding: utf-8 -*-
import yaml
def caption_parse_rules(offset, position_key, separate, char_type, char_num):
"""Create matching rules and based on custom characteristics of caption text.
:param offset: characters used to set off material that is amplifying or explanatory
:param position_key : positi... |
941491b50b5b2ffbca54c061b9697414f3b941406833f9522f1545c2111e4bc0 | Python | 8,481 | 172 | import torch
from torch import nn
from .perception_loss import vgg16_feat, perceptual_loss
from .base_model import BaseModel
from . import networks
# from parse_config import ConfigParser
# import parse_config
import numpy as np
class DadganModel(BaseModel):
""" This class implements the pix2pix model, for learn... |
2fe2bacad718c17a745558e5db372acbac8748a954b76fb6d59dee858e75c361 | Python | 8,487 | 148 | import argparse
import os
from util import util
import torch
import models
import data
class BaseOptions():
"""This class defines options used during both training and test time.
It also implements several helper functions such as parsing, printing, and saving the options.
It also gathers additional opti... |
b342f1fde23dd341b0cf9b37f639c1e186a2675e4eab1128d9d4a7b32c9793d0 | Python | 8,492 | 178 | import torch as th
import torch.nn as nn
from latentvelo.atac_dataloader import ATACDataset
from latentvelo.utils import normalize, sparse_mx_to_torch_sparse_tensor
import os
import numpy as np
import matplotlib.pyplot as plt
#class Trainer:
def train_atac(model, adata, epochs = 50, learning_rate = 1e-2, batch_size = ... |
811876b925b60b1490e485a2673426e7ce5f8b064ae1b7be9c1ff3c3a756b70f | Python | 8,494 | 214 | import argparse
import glob
import logging
import os
import sys
import time
import numpy as np
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.utils
import torchvision.datasets as dset
import wandb
from fedml_api.model.cv.darts import utils
from fedml_api.model.cv.darts import Net... |
f5aa10bdd425f184dbba3244b121af2eb53f7605669a5a006703ac91917f1350 | Python | 8,512 | 199 | """GPU checks of graph fallback warnings, padded-graph reuse validation, release and capture side effects."""
import warnings
import pytest
import torch
from conftest import CAFFEINE_FILE, load_mol
from aimnet.calculators import AIMNet2Calculator
from aimnet.calculators.cuda_graph import _capture
pytestmark = [pyte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.