sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
f9d12c483a041dfe2dd7e37c8f730bba36b9cfd55657be3d791496752e184185
Python
2,935
108
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Aug 27 11:01:35 2021 @author: baris """ import torch import torch.nn as nn from torch import optim import numpy as np # labels maker # output for training the network, 5 for each trajectory def _label(n_poiss): a = np.tile([1, 0], (n_poiss, 1))...
0cc20d1a231ea2192bd08b344d11824876b585c8cdfd500ee4bf524e20d07836
Python
2,940
79
from dtor.logconf import logging import numpy as np from sklearn.metrics import f1_score log = logging.getLogger(__name__) # Used for computeBatchLoss and logMetrics to index into metrics_t/metrics_a METRICS_LABEL_NDX = 0 METRICS_PRED_NDX = 1 METRICS_LOSS_NDX = 2 METRICS_SIZE = 3 def process_metrics(metrics_t, class...
10ff86fcedb6bd837ee6a2a0c3f3fe934f76d3858c45f978abea3dace7204225
Python
2,940
77
import os import gzip from typing import Callable from tqdm import tqdm from Bio import AlignIO from .shrinked_force_permutations import ShrinkedForcePermutationsDataset from ._utils import get_family_ids, _download splits = ['train', 'val', 'test'] polymers = {'rna': 'Rfam', 'protein': 'Pfam'} modes = ['seed', 'en...
b08c9ac1b0c6894f780cef60f40acebba23061bef864031a3497c879a9720748
Python
2,940
100
# Module containing the elements necessary to serialise objects. # # Author: Fernando García Gutiérrez # Email: fgarcia@fundacioace.org # import pickle import os import traceback from datetime import datetime from tqdm import tqdm from .wrapper import FeatureSelectionGA, MultiObjFeatureSelectionNSGA2 from ...
7e77d7c5990fa33029b971ad301d579acb7bfc1013895ec93db8288449b6cb84
Python
2,944
104
import fastReducedRF import numpy import pyublas # not explicitly used--but makes converters available nTax = 7 import string tNames = list(string.ascii_uppercase[:nTax]) # Here is a supertree, the first of many. var.warnReadNoFile = False read("(((D, E), A), B, (C, (F, G)));") bigT = var.trees.pop() bigT.taxNames = ...
b83700c0ba730004923eeb5295d5d09a0a230cae9348decee951cc91a80b00cd
Python
2,944
97
''' assumes that the user has already generated .json file(s) containing data ''' import argparse import json import os import matplotlib.pyplot as plt import numpy as np from scipy import stats parser = argparse.ArgumentParser() parser.add_argument('--name', help='name of dataset to parse; defa...
1c0268d1e30429f6ec5553e87e85f7ea9cce4728d1e7549c792847d031813a71
Python
2,945
73
"""Download model ZIPs after establishing a Synology sharing session.""" import argparse import requests from pathlib import Path import tkinter as tk from tkinter import filedialog import zipfile LATEST_MODELS = { 'PVS': 'https://cloud.efixia.com/fsdownload/Zvbj1CpkM/T1-PVS.zip', # V4 'WMH': 'https://cloud....
c16f9cfc3266c2c8d680873cbb4f9c41eb31d0543794bf4835e8779ce53a2436
Python
2,947
92
import pandas as pd import matplotlib.pyplot as plt import sys import re import math """ need to check if there is atrophy there should be no nan values """ # start from mri_pet working directory csv = pd.read_csv("./metadata/data_raw/MCIADSubtypeAssessment.csv") # Need to create a tree of a loop lobes = [ "me...
20b6be07086c6413364473aecf1dcbd5f8d154a50aa31093dc9e2408df21ffee
Python
2,949
77
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import ATSSHead def test_atss_head_loss(): """Tests atss head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_sh...
915a56f76110eb374684daa0bc7bf5860fb4dab6c89d57bd8ea88a6179420a98
Python
2,949
72
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmcv.cnn import ConvModule, DepthwiseSeparableConvModule from mmdet.models.dense_heads import YOLOXHead def test_yolox_head_loss(): """Tests yolox head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ '...
79f02897cbb51714e6afed335a1dfff80d683b59934b691af5e36d1cd9520ec4
Python
2,950
69
import argparse import os import pandas as pd def parse_excel(filepath): # Given an excel file, returns the relevant assessment and stimulation information in visit_dict # relying on thei constant position df = pd.read_excel(filepath) visit_dict = {} visit_dict['date'] = df.iloc[3, 4] #string form...
485bd23f3cc156f7fce7af53e303f981c975dde870e0a061b1f7222eece8e737
Python
2,954
49
# Copyright (c) OpenMMLab. All rights reserved. from ...deprecated import (TopDownFreiHandDataset, TopDownOneHand10KDataset, TopDownPanopticDataset) from .animal import (AnimalATRWDataset, AnimalFlyDataset, AnimalHorse10Dataset, AnimalLocustDataset, AnimalMacaqueDataset, ...
07c85a9ac924e6c07abf05bf3baefcb410b475e09c5bdfba2ecbf4a2c6630fdd
Python
2,957
75
import argparse import collections import importlib import stringcase import numpy as np import torch import json from parse_config import ConfigParser # fix random seeds for reproducibility SEED = 123 torch.manual_seed(SEED) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random.se...
475595d178961824f36d5f4bef1459a719f657d0f76464373be697bf2e8aaaee
Python
2,959
81
# -*- coding: UTF-8 -* from collections import defaultdict from graph import Graph import numpy as np from utils import cmap2C ,graph2nx import networkx as nx def create_coarse_graph(stru_comms,graph): in_comm = stru_comms NewGraph=create_NewGraph(in_comm,graph) return NewGraph,in_comm #$$$$$...
c26d606ba1db3621c638437b0a9d806648575e7e3703f17ad47304f920f15bcf
Python
2,961
74
import torch from torch import Tensor from sbi import utils as utils class ExamplePosterior: """ Class that builds a density with broad marginals and narrow conditionals. This is used only for the tutorial on conditional correlations. It has the key function that a `NeuralPosterior` object would al...
fe37093b73ed65ce61f0a0c0f6969cef387448ec6cd7cdc383cfda6b2f04cbd5
Python
2,961
111
import sys, signal import numpy as np import moderngl from PyQt5 import QtWidgets from PyQt5.QtWidgets import QOpenGLWidget from PyQt5.QtGui import QSurfaceFormat def make_qt_format(): fmt = QSurfaceFormat() fmt.setVersion(3, 3) fmt.setProfile(QSurfaceFormat.CoreProfile) return fmt class StimDisplay(...
ab5113a0343a5a8fde701f944c882eda63f7b4a4101363d8b95f75b84fa5f1af
Python
2,965
53
#! /usr/bin/env python # *********************************************************************************** # * Copyright 2010 - 2016 Paulo A. Herrera. All rights reserved. * # * * # * Redistribution and use in source ...
34a74286c8f70bd843f1e0a9abd75866fb5d83cdcc5217849029b6f886dec1dd
Python
2,968
56
# Author: Fabi Prezja <faprezja@fairn.fi> # Copyright (C) 2023 Fabi Prezja # License: MIT License (see LICENSE.txt for details) import os from tensorflow.keras.callbacks import Callback class CustomSaveWeights(Callback): """ Custom Keras callback to save model weights during training based on a specified metr...
4a75b0fc187ac333f6ac594251827cb3ad608fbfc4a2455393d0b43a4068e181
Python
2,972
83
import pytest from clipkit.parser import create_parser @pytest.fixture def parser(): return create_parser() class TestParser(object): def test_required_only(self, parser): input_path = "my/input/file.fa" parsed = parser.parse_args([input_path]) assert parsed.input == input_path ...
b9731e33953bab8a0bbaf4b277557f1c82bd27203822a7f16c593900a38965c7
Python
2,972
97
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Setup Parallel WaveGAN libarary.""" import os import pip import sys from distutils.version import LooseVersion from setuptools import find_packages from setuptools import setup if LooseVersion(sys.version) < LooseVersion("3.7"): raise RuntimeError( "para...
dc93e46b4248019731916da750ff03b152ed49a3feef67f0c3cda29aa1295cdb
Python
2,975
105
import os from pathlib import Path from typing import Any import numpy as np import torch import yaml from typeguard import typechecked from daart.data import DataGenerator from daart.models.base import Segmenter from daart.transforms import ZScore @typechecked class Model: """High-level API wrapper for daart m...
adbc8dd45504fefa1c5d6addc11ce4680188583b5308e6bb544706303795daf9
Python
2,979
77
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.core import bbox2roi from mmdet.models.roi_heads.bbox_heads import SABLHead from .utils import _dummy_bbox_sampling def test_sabl_bbox_head_loss(): """Tests bbox head loss when truth is empty and non-empty.""" self = SABLHead...
23550f64a5f4f10dc32b2e557e0ebe54617e106e4877a5af3f3f6d03ddc28b73
Python
2,980
123
# coding: utf-8 import json import fancyimpute import numpy as np import pandas as pd X = [] Y = [] Z = [] for ctx in open('json/json'): z = json.loads(ctx)['label'] ctx = json.loads(ctx)['forward'] x = np.asarray(ctx['values']) y = np.asarray(ctx['evals']) x_mask = np.asarray(ctx['masks']).asty...
43a952a30f140aef0120d3cbe3dceae0a3d42265396ee1bd18f96f19f9ad1927
Python
2,980
74
import argparse import typing import argparse_types from models.abstract import ModelClassMetaData, input_data from models.keras.geography_weighted_model import GeographyWeightedKerasModelMeta, GeographyWeightedKerasModel # Import bez importu :) if False: import tensorflow.keras as keras class GeographyWeighted...
7c74ab598f5e0321dad43508d3be04e57a330999b0e5d06e108b2d1d5104fddf
Python
2,982
83
# 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/> import warnings from typing import Optional from torch import Tensor, nn, tensor, unique from sbi.neural_nets.estimators import ( CategoricalMADE, ...
090be5a5c61422994e7e0b03fe6104ca9d9a764c5a0f12a37e4d55d7d79f547f
Python
2,984
98
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright 2019 Tomoki Hayashi # 2023 Jiatong Shi # Adapated from ESPnet Fastspeech LengthRegulator # Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """Length regulator related modules.""" import logging import torch def pad_list(xs, pad_value)...
604d03048feb08630b19fc1901c0fceec84be0acf916f5c8f43d3564a2a1848c
Python
2,984
75
import torch from torch import nn class LitEma(nn.Module): def __init__(self, model, decay=0.9999, use_num_updates=True): super().__init__() if decay < 0.0 or decay > 1.0: raise ValueError('Decay must be between 0 and 1') self.m_name2s_name = {} self.register_buffer('de...
8ddb0f5cef38ccbc2fbb9ceae48c458a67e03393580e74fa80af40a7a9dbe126
Python
2,988
54
import torch from torchmdnet.priors.base import BasePrior from torchmdnet.models.utils import Distance, CosineCutoff class ZBL(BasePrior): """This class implements the Ziegler-Biersack-Littmark (ZBL) potential for screened nuclear repulsion. Is is described in https://doi.org/10.1007/978-3-642-68779-2_5 (equat...
cf98a2434d228151b7f46b77325732f1a0f967e8de3d48ba297e291ceff0d759
Python
2,988
70
import torch import torch.nn as nn from layers.Transformer_EncDec import Decoder, DecoderLayer, Encoder, EncoderLayer from layers.SelfAttention_Family import FullAttention, AttentionLayer from layers.Embed import DataEmbedding class Model(nn.Module): """ Vanilla Transformer with O(L^2) complexity """ ...
4ba0c8d194c293da7d1470891ade781da2bf52367af4f6fa6496bd9f80552103
Python
2,990
79
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch.nn as nn @mmcv.jit(coderize=True) def accuracy(pred, target, topk=1, thresh=None): """Calculate accuracy according to the prediction and target. Args: pred (torch.Tensor): The model prediction, shape (N, num_class) targe...
28a38957508aab35815234a7af7eda733ba7ba8bcdbb476ed8218541731b5528
Python
2,994
93
import csv import json import os import numpy as np import time import argparse import yaml class LogWriter(object): # kind of inspired form openai.baselines.bench.monitor # We can add here an optional Tensorboard logger as well def __init__(self, path, keys, header="", name="monitor.csv"): self.k...
25ded6d8c4a446b444a5f1e37d4364c2a964972e93eef5b8e70ad9ae833f6430
Python
2,995
97
# Copyright (c) OpenMMLab. All rights reserved. import argparse import numpy as np import torch from mmcv import Config, DictAction from mmdet.models import build_detector try: from mmcv.cnn import get_model_complexity_info except ImportError: raise ImportError('Please upgrade mmcv to >0.6.2') def parse_ar...
7ba7cd0f40fc04b864b89d85f2c21b10f487dffb58cb9fae4c6cac4bd83ee0c3
Python
2,996
87
from logging import getLogger import numpy as np from base.results.sleep_stage_tracker import SleepStageResultTracker logger = getLogger(__name__) class AnySleepNChannelsSSResultTracker(SleepStageResultTracker): """ Result tracker that handles duplicate recording IDs in AnySleep evaluation. When evalu...
d49cf6dc20aadedeeed18d51af27ea8d5a6a08edc176b76889d731bf52db7b9d
Python
2,996
113
# coding:utf-8 import argparse import os import numpy as np import glob from PIL import Image import cv2 import math import random from keras.callbacks import ModelCheckpoint, EarlyStopping import pyexcel as pe import pandas as pd import shutil def check_file(filename): if os.path.exists(filename): ...
4c1f662aa48660a0d7521c9782dda7b3ac3c867539aed0077440083589480385
Python
2,998
88
# Copyright (c) OpenMMLab. All rights reserved. import torch import torch.nn as nn import torch.nn.functional as F from mmcv.cnn import CONV_LAYERS from .builder import LINEAR_LAYERS @LINEAR_LAYERS.register_module(name='NormedLinear') class NormedLinear(nn.Linear): """Normalized Linear Layer. Args: ...
da73366bf87c4aab6b08d414b47b9e4d37197d1800b52f72e0dfdea9272b2652
Python
2,998
98
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) import os import os.path as osp from typing import Callable, List, Optional import numpy as np import torch from torch_...
ff11380e330e351e8ede48dfdb350a3ed06396267b59f9f03bb68772148eb7c8
Python
2,998
63
import time import os import json import pandas as pd from D_modelling import d100_modeller # to avoid all warnings (GPR was triggering ConvergenceWarnings) os.environ["PYTHONWARNINGS"] = "ignore::UserWarning" def fit_and_validate_single_model(fn, config, runType, run2get_mres_only=False, debug=False): # when ...
3d96459546f11b202d8c8dd90ad00e64f3f017f1360787c78b9a084784c41f5d
Python
3,000
106
import tensorflow.keras as keras import typing from tensorflow.keras import backend as K class WeightLayer(keras.layers.Layer): def __init__(self, x: float, y: float, r: float,*args, **kwargs): super().__init__(*args,**kwargs) self._x = x self._y = y self._r = r def get_confi...
2bf7d27bba80d58b3a6fc9503ad7c52b1c0a7b84594e75c888a66aae07f634f1
Python
3,002
88
# Copyright (c) OpenMMLab. All rights reserved. from abc import ABCMeta, abstractmethod import torch import torch.nn as nn from mmcv import ops from mmcv.runner import BaseModule class BaseRoIExtractor(BaseModule, metaclass=ABCMeta): """Base class for RoI extractor. Args: roi_layer (dict): Specify R...
8f28371294a93a72fb6ba3c169e7887fa7e6146e6a50d801c869a9f95e501ab5
Python
3,004
77
""" model.py Defines the Multi-View Linear Manifold (MVLM) architecture and the Hybrid Geometric Loss function for drug-target interaction prediction. """ import torch import torch.nn as nn import torch.nn.functional as F class MultiViewLinearManifold(nn.Module): """ Projects pre-trained molecular and prote...
b51cbcd0642cf60fc9023e44a3b2ca67df2788889a1c9d9e3d12d65a864ff984
Python
3,012
63
import argparse from create_patient_instance import * import numpy as np import pandas as pd import matplotlib.pyplot as plt plt.rcParams.update({'font.size': 17}) def functional_profile(functional_df,destination_folder,vta,day): os.makedirs(os.path.join(destination_folder,'functional','profiles'),exist_ok=Tru...
046e29ff1292b1aa4f9cae7b4d8c2548e15fab2a2f9bd98988ab359884753b6b
Python
3,025
100
import argparse import os import librosa import numpy as np UTT_PREFIX = "kising" DEV_LIST = ["435_all.wav"] TEST_LIST = ["434_all.wav"] def pack_zero(string, size=20): if len(string) < size: string = "0" * (size - len(string)) + string return string def train_check(song): return (song not in ...
5421b0975e41c7fd7648224a34160565ccd41342f29dc05079770498665bbd03
Python
3,027
97
#!/usr/bin/env python3 import argparse import os import random import shutil import sys from shutil import copyfile UTT_PREFIX = "kiritan" DEV_LIST = ["13", "14", "26", "28", "39"] TEST_LIST = ["01", "16", "17", "27", "44"] def train_check(song): return (song not in DEV_LIST) and (song not in TEST_LIST) def de...
e3dc340299cde78d7294ea00e9c8f6f5e3215d1af7ec0f138567ad4a245cddc1
Python
3,027
87
#!/usr/bin/env python # Author: Heng Li and Aaron Quinlan # License: MIT/X11 import sys from ctypes import * from ctypes.util import find_library import glob, platform def load_shared_library(lib, _path='.', ver='*'): """Search for and load the tabix library. The expectation is that the library is located in...
e860893173f218a6a2c5da116a257745e6199d474adbe123e9d9aff426015253
Python
3,031
79
import argparse import collections import json import torch import numpy as np import data_loader.data_loaders as module_data import loss.loss as module_loss import metric.metric_nuclei_seg as module_metric # import model.unet as module_arch # import optimizer.optimizer as module_optimizer # import optimizer.lr_schedu...
c00ca2d9a3b297f9468c5815089fcb0b4f91f35ae79a18716bae72087c62d27e
Python
3,033
107
#!/usr/bin/env python3 import argparse import math import os import sys class LabelInfo(object): def __init__(self, start, end, label_id): self.label_id = label_id self.start = start self.end = end class SegInfo(object): def __init__(self): self.segs = [] self.start =...
c9f8f8dd30d952f23cb026d08291200a67cf3290ff58f293eca38082856238d4
Python
3,033
71
############################################ # imports ############################################ from oligo_designer_toolsuite.database import OligoDatabase from oligo_designer_toolsuite.oligo_specificity_filter import BaseSpecificityFilter from oligo_designer_toolsuite.utils import check_if_key_in_database #####...
3805af5f6fca09e6b298e19918d65bff7783d23477884a7bfd2a29db0c7e08b8
Python
3,034
96
# -*- coding: utf-8 -*- """ Created on Mon Aug 2 20:34:10 2021 @author: fhu14 Utilities related to analyzing inter-atomic distances in all molecules of a dataset """ #%% Imports, definitions from itertools import combinations from typing import List, Dict from scipy.spatial.distance import pdist from functools impo...
ff66d64a694ee98f9a120868679f34805d5b01415c54951b3b64aff0d0f4d2fc
Python
3,040
40
# ----------------------------------------------------------------------- # # Copyright (c) 2023, UChicago Argonne, LLC. All rights reserved. # # # # Software Name: Fast Autonomous Scanning Toolkit (FAST) # # By: Argonne Na...
956cd782d7b800a409a69b262a24f7f0349a21cf5d2a98ab8e9a83639e221dbf
Python
3,053
69
import sys import glob import shutil import os from pathlib import Path from F_post_processsing import F100_analyze_hindcast_output from A_config import a10_config import tuner import threading import manager_0_user_params as upar from manager_20_tune import monitor_condor_q if __name__ == '__main__': """ Thi...
cf3843525b9d37d172d77992c6171b1f00b4ff55a3bb07bca76d89d1a9441b7f
Python
3,054
78
# Copyright (c) OpenMMLab. All rights reserved. import numpy as np from mmdet.core.mask import BitmapMasks, PolygonMasks def _check_fields(results, pipeline_results, keys): """Check data in fields from two results are same.""" for key in keys: if isinstance(results[key], (BitmapMasks, PolygonMasks)):...
04922d3a09be038d60a46bd47a0d67c135c4bb808fdb2ccd670077d42ace691c
Python
3,058
77
import pandas as pd import numpy as np from utils.functions_ZZ_extraction import load_ZZ_output def load_clustering_results(path): output = pd.read_pickle(path) return output['dfParam'], output['pca_result'] def reassign_bout_cluster(id, df_bout_all, df_clustering): start, end = df_bout_all.BoutStart[id...
0ac74b93952782db2eb0a8a158ae786a729be50448a8b09f29cbf51246b2cb81
Python
3,061
72
# Copyright (c) OpenMMLab. All rights reserved. import random import warnings import torch from mmcv.runner import get_dist_info from mmcv.runner.hooks import HOOKS, Hook from torch import distributed as dist @HOOKS.register_module() class SyncRandomSizeHook(Hook): """Change and synchronize the random image size...
b510f26c270a8b04377223d1c2081652a11ec2755593f11b1f171005b0aa4398
Python
3,061
106
import numpy as np import plotly.graph_objects as go def _sensitivity_contour_plot( x, y, contour_values, unadjusted_value, scenario_x, scenario_y, scenario_value, include_scenario, rho, benchmarks=None, fill=True, ): if fill: text_col = "white" contours...
a937a04a1c475321ccfe324df35e2e883085201bc0dc8fafedae48012d1d2877
Python
3,065
72
from torchvision import datasets, transforms from base import BaseDataLoader from data_loader.mura_dataset import MuraDataset from data_loader.BraTS_seg_dataset import BraTSSegDataset import data_loader.my_transforms as my_transforms class MnistDataLoader(BaseDataLoader): """ MNIST data loading demo using Ba...
42092531939b1ccfdc524c5ffe5e39b3c9c02f9086929dc098edab766acea93d
Python
3,066
81
import pathlib import setuptools # build with python setup.py bdist_wheel # upload to testpypi w/ python3 -m twine upload --repository testpypi dist/* here = pathlib.Path(__file__).parent.resolve() with open(here / "README.md", "r") as fh: long_description = fh.read() with open(here / "requirements.txt", "r"...
ace2fd69950306406aff4e6399a6daf6c6a712d2557cce09ee33859895f626d5
Python
3,071
82
# Copyright (c) OpenMMLab. All rights reserved. import torch from ..builder import BBOX_SAMPLERS from .base_sampler import BaseSampler @BBOX_SAMPLERS.register_module() class RandomSampler(BaseSampler): """Random sampler. Args: num (int): Number of samples pos_fraction (float): Fraction of po...
333145dcc554155cc8968c545adc5c9fbd3708e3327052e1324f4fb2b9f00149
Python
3,073
64
""" General Data Loader and General Dataset General purpose data loader and dataset. ## GPL License ## Author: Qi Chang<qc58@cs.rutgers.edu> """ import h5py import math import numpy as np from data_loader.general_data_loader import GeneralDataset from skimage.util import view_as_windows from torch.utils import data fro...
ea84b07582157c938681951b2a182a4507f778e58c19aa06d83bb8396feb74c8
Python
3,073
85
# -*- coding: utf-8 -*- # Copyright 2020 Tomoki Hayashi # MIT License (https://opensource.org/licenses/MIT) """Residual stack module in MelGAN.""" import torch from parallel_wavegan.layers import CausalConv1d class ResidualStack(torch.nn.Module): """Residual stack module introduced in MelGAN.""" def __i...
987c3ee455dbe31734619ed7542bbce8b09a72bd9664dd3d5413d9800c7190da
Python
3,076
80
# Copyright (C) 2023-2025 ETH Zurich, Marc Lehner and other DASH contributors. from rdkit import Chem from serenityff.charge.tree.atom_features import AtomFeatures from serenityff.charge.utils.rdkit_typing import Molecule def new_neighbors(neighbor_dict, connected_atoms) -> tuple: connected_atoms_set = set(conn...
5ea0c78c5fe285cb94ec120fa52d821348ec39fc4b6f71044f384f670bcc1316
Python
3,080
76
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import SABLRetinaHead def test_sabl_retina_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, ...
547e65837675860f27282ebdac9496aa5946222332e36fa8a3dd766b28116405
Python
3,081
83
# -*- coding: utf-8 -*- """ Created on Tue Jun 28 16:27:04 2022 @author: fhu14 Quick functions for energy analysis """ #%% Imports, definitions import os, pickle from typing import List, Dict from DatasetGeneration import test_strict_molecule_set_equivalence #%% Code behind def determine_nelectrons(mol: Dict) -> ...
a3e9ef2ab44a6abbfd643cf0d16daf48b51825099113cb5db6d0a5dcf90bde5a
Python
3,081
97
r""" This test file contains tests that involve generating synthetic data and then fitting to make sure we get the expected result for power law distributions. We generate power law data using inverse sampling transform; so essentially the same process as is used internally, but the idea here is to compare to a genera...
8954064265e4f17711b9f30e95bd3816ba94db292109ccf86c6ea032bb0c5deb
Python
3,083
87
from collections import Counter import numpy as np from sklearn.linear_model import LinearRegression from .consts import SYM2ATOM from .dataset import Dataset class Shifter: def __init__(self, fit_intercept=True) -> None: self.fit_intercept = fit_intercept self.shifter = LinearRegression(fit_int...
de0a6f356c5baf8bb6181b3d6aa9c4f0c6993a7c273c099ef57a241da0dc7c47
Python
3,084
63
import logging from fedml_api.distributed.fedgkt.message_def import MyMessage from fedml_core.distributed.communication.message import Message from fedml_core.distributed.server.server_manager import ServerManager class GKTServerMananger(ServerManager): def __init__(self, args, server_trainer, comm=None, rank=0,...
59983a3a4f4648ce4a667b46047834b3574999a4e296d7f60814709480743c16
Python
3,087
98
# -*- coding: utf-8 -*- """Process our data choice""" __author__ = "Sean Benson" __copyright__ = "MIT" from dtor.datasets.dataset_nominal import CTImageDataset from dtor.datasets.dataset_mnist import MNIST3DDataset from torchvision import transforms from torchvision.transforms import transforms import torch import to...
e47fe5ad4718755e2b576410e22ab358c909d4e7e66dcb69f99474be3256ad59
Python
3,087
104
import multiprocessing as mp def run_experiment(): import tensorflow as tf import tensorflow_datasets as tfds from tensorflow.keras import mixed_precision from gradient_accumulator import GradientAccumulateModel import os def normalize_img(image, label): """Normalizes images: `uint8`...
77e2ac0077fe39c63bc8b43314d582da10fe625af55b7977c32c8d7ddf33283b
Python
3,088
99
import os import subprocess import pkg_resources import logging import numpy as np import multipagetiff as mtif logging.basicConfig(level=logging.DEBUG) log = logging.getLogger(__name__) log.setLevel(logging.WARNING) matlab_script_path = pkg_resources.resource_filename( "pycroscopy3D", 'Matlab/skew_correct.m') ...
09c1f89839f6a19f68372ef970adb8803e2815f00305d7280e1970d0e75f60d5
Python
3,089
100
# Copyright (c) OpenMMLab. All rights reserved. import multiprocessing as mp import os import platform import time import cv2 import mmcv import torch import torchvision from mmcv import Config import mmpose from mmpose.utils import StopWatch, collect_env, setup_multi_processes def test_collect_env(): env_info ...
8f5518f95efaca7406614547b08afdb8019712fa5531da5bc975fd93f583ec01
Python
3,095
89
# -*- coding: utf-8 -*- """ Created on Mon Aug 9 18:17:58 2021 @author: fhu14 Used to generate a parameter dictionary from a set of SKF files. This circumvents the need to copy and paste/depend on external file structures. """ #%% Imports, definitions import pickle, os from DFTBrepulsive import SKFSet from SKF impo...
6239507b2e332dbb1743810f236fa2f2f9648a8bca4a113ff71eb18252868efd
Python
3,097
82
# Copyright (c) OpenMMLab. All rights reserved. import mmcv import torch from mmdet.models.dense_heads import FSAFHead def test_fsaf_head_loss(): """Tests anchor head loss when truth is empty and non-empty.""" s = 256 img_metas = [{ 'img_shape': (s, s, 3), 'scale_factor': 1, 'pad_...
2a790f978cb68be91d35313140b12544c9f58b4acfb00710b97a2a73ccf15e4b
Python
3,100
91
from collections import namedtuple Genotype = namedtuple('Genotype', 'normal normal_concat reduce reduce_concat') PRIMITIVES = [ 'none', 'max_pool_3x3', 'avg_pool_3x3', 'skip_connect', 'sep_conv_3x3', 'sep_conv_5x5', 'dil_conv_3x3', 'dil_conv_5x5' ] NASNet = Genotype( normal=[ ...
2b7c7a2eaafd9ef0384b52c980b65817de59d65e7a8b2f022a9d39cba22626af
Python
3,103
66
#! /usr/bin/env python # *********************************************************************************** # * Copyright 2010 - 2016 Paulo A. Herrera. All rights reserved. * # * * # * Redistribution and use in source ...
fc1558665cbc847772653c73cc100ce2386d0107af0473e3b72e677707f514c3
Python
3,103
101
# Copyright (c) OpenMMLab. All rights reserved. import functools import mmcv import torch.nn.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". Return: ...
274253fbc8fd516b893b751aff8035002cca5087699b8c64fcb6b6f9e8d87233
Python
3,104
146
# %% import pycroscopy3D as pycro import os from glob import glob from tqdm import tqdm import pipeline_tools as pt # %% folders preparation run = '220127' root_path_in = f"/media/mathilde.lapoix/T7 Touch/SCAPE_new/" def relative_in(path): return os.path.join(root_path_in, path) root_path_out = f"/media/mathilde.l...
604713f61f3ee34f799f229efebf2ae60adf4d6ca48ce3aa11758db9b1082506
Python
3,108
74
import logging import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../../FedML"))) try: from fedml_core.distributed.client.client_manager import ClientManager from fedml_core.distributed.communicat...
37e0ff869e6e80309abe04fea29803bb799ac94c2141481be5fb8ffafe12af34
Python
3,109
75
import logging import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../"))) sys.path.insert(0, os.path.abspath(os.path.join(os.getcwd(), "../../../../FedML"))) try: from fedml_core.distributed.client.client_manager import ClientManager from fedml_core.distributed.communicat...
cb8d252bf23c715964debf0cc88cb23f8bf503839e40687663788a0ea4b74041
Python
3,109
101
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os import mmcv from PIL import Image def parse_args(): parser = argparse.ArgumentParser( description='Convert images to coco format without annotations') parser.add_argument('img_path', help='The root path of images') parser.a...
64bf863ad95d3a2f86e66a89fbe2900e031a3b7f252522f994ba1dcd8a7731ce
Python
3,110
80
####################################################################### # Software License Agreement (AGPL-3 License) # # OpenViBE SDK Test Software # Based on OpenViBE V1.1.0, Copyright (C) Inria, 2006-2015 # Copyright (C) Inria, 2015-2017,V1.0 # # This program is free software: you can redistribute it and/or modify ...
769ae3effebf96ece6f8c68b423f13d81c97678e0570d7520bb92c1c7e28c65b
Python
3,110
132
import h5py import numpy as np from sklearn.svm import SVC, LinearSVC from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler from sklearn.metrics import confusion_matrix, f1_score, accuracy_score, roc_auc_score train_set_n = 300 data = np.load('closet_train_4ch_300_feat.npz') X...
80888699bfb1bd5059d787ca9e2799e7001e78a7c7716362142dd28566e77f06
Python
3,112
111
import getpass import ntpath import os from datetime import datetime def path_leaf(path): head, tail = ntpath.split(path) return tail or ntpath.basename(head) def log_parameters_to_file(to_log, script_path): """Write script parameters to file. Writes a log of the experiment with parameters used for...
b6500b7222f058943185998d6f713001d94ff552d79ddc563293d0d59365a5a7
Python
3,112
116
from typing import Optional, Tuple, Any import eagerpy as ep import warnings import os import numpy as np from .types import Bounds from .models import Model def accuracy(fmodel: Model, inputs: Any, labels: Any) -> float: inputs_, labels_ = ep.astensors(inputs, labels) del inputs, labels predictions = f...
78ebd5c2a8bff6ec07f26997eaad56c606d3ff1e7e4639876a1118c46f02182b
Python
3,113
96
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F class FFN(nn.Module): def __init__(self, in_dim, dim_hidden, out_dim, hidden_layers): super().__init__() # self.dropout = dropout self.hidden_layers = hidden_layers self.midlin = nn.ModuleList() ...
d63f86bff28e101b675270eb705f27756ecdc6035e8d063e90dffe0db332bdf0
Python
3,114
107
import re from Bio import SeqIO from Bio.Align import MultipleSeqAlignment import numpy as np from typing import Optional from .ambiguity import is_nucleotide_alphabet from .msa import MSA from .modes import AmbiguityHandling, TrimmingMode from .settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS from .files i...
539083ec1218f70c19175af6aba69dc8b1a871f1567b9a25d231462562a4ced5
Python
3,116
115
#--------------------------------------- # Compute all section areas and lengths # 1 Feb 2023 #--------------------------------------- import os import json import pandas as pd import numpy as np import shapely from shapely import affinity from shapely.geometry import Polygon, MultiPolygon data = pd.read_csv("../data...
7441c07e82c932e745ba675f6d6ba4d1ace45bc21091a85f2126654159f07203
Python
3,116
99
# Copyright (c) OpenMMLab. All rights reserved. import argparse import os.path as osp from datetime import datetime import mmcv from mmcv import Config from mmpose.apis.inference import init_pose_model try: from mmcv.cnn import get_model_complexity_info except ImportError: raise ImportError('Please upgrade m...
02b65c52400998cd0e6002ea7903c6c73f588d02efc9c9ae672d6522081d97d8
Python
3,120
120
''' Author: ---- Date: 2022-06-30 11:56:44 LastEditors: GhMa LastEditTime: 2022-09-20 14:35:29 ''' import torch import torch.nn as nn import torch.distributions as distrib import numpy as np import math def heaviside(x: torch.Tensor): return (x >= 0.0).to(x) def triang(x, a): fc = 0.5 mask = (x ...
c8da9ba6a7482af71104ccdabdb6ec8a53e202864ce7b6ef9d828181fdaeafcc
Python
3,120
103
# Copyright (c) OpenMMLab. All rights reserved. import argparse from functools import partial import torch from mmpose.apis.inference import init_pose_model try: from mmcv.cnn import get_model_complexity_info except ImportError: raise ImportError('Please upgrade mmcv to >0.6.2') def parse_args(): parse...
3eb2fe2a31f8cbe37c4fddc9efb31e8511f482a2734d1521c627258bae198353
Python
3,123
90
# Copyright (c) OpenMMLab. All rights reserved. from collections import OrderedDict import numpy as np import torch import torch.distributed as dist from mmcv.runner import get_dist_info from torch._utils import (_flatten_dense_tensors, _take_tensors, _unflatten_dense_tensors) def _allreduc...
0eeb72e78f2eeaafdbd0d241f8eff978f882f6c8d01b0f984ef0434a44e477d3
Python
3,124
93
# Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org # Distributed under the MIT License. # (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT) from typing import Optional, Tuple import torch as pt from .models.model import TorchMD_Net from .models.torchmd_gn imp...
80908222f41615b1e1a998713bfb872572e45701b4eb0f432da10ec8600e690b
Python
3,124
98
import math from torch import nn as nn from dtor.logconf import logging log = logging.getLogger(__name__) # log.setLevel(logging.WARN) # log.setLevel(logging.INFO) log.setLevel(logging.DEBUG) log = logging.getLogger(__name__) # log.setLevel(logging.WARN) # log.setLevel(logging.INFO) log.setLevel(logging.DEBUG) clas...
3122d43b275f330a7170320704ab9e08e627898b02cb9fb8f729fbfa071c5403
Python
3,128
79
from abc import ABC, abstractmethod import numpy as np class DatasetError(Exception): pass class Dataset(ABC): """ Abstract base class representing a dataset. All datasets should subclass from this baseclass and need to implement the `load` function. Initializing of the dataset and a...
c7a0ce139a0895a82f216f2dbcec19e221ae2d7bf1c7bd8e30ce7534633577b2
Python
3,130
91
# # The MIT License # # Copyright (c) 2011 Seoul National University. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, ...
4b6008180255d3a05164a1f4ec616105ef6960ed5d479bc7dd0895026cdb4b6d
Python
3,131
65
import numpy as np from skimage.transform import resize class RandomResize: def __init__(self, scale, interp="bilinear", training=True): """ Resize the image: C x H x W to the C x load_size[0] x load_size[1] order will apply to image and mask separately. 0: nearest-neighbor, 1: bi-linear(d...
9983f5ef859c958b0c8326d606e3861e4eb46e3e06c31c07d3997902854d1a60
Python
3,132
96
import numpy as np def crop(img, top, left, new_h, new_w, padding=(0, 0)): if len(img.shape) == 2: img = img[top: top + new_h, left: left + new_w] if padding != (0, 0): img = img[padding[0]:(img.shape[0] - padding[0]), padding[1]:(img.shape[1] - padding[1])].copy(...
da87ee93bc0ecae95776661731113ad0f0e41498e445f81b9188366cfa605ccf
Python
3,133
111
#!/bin/python import mne from mne.preprocessing import ICA import numpy as np import scipy.stats import statistics import json import sys def isIn(intervals, start, stop): for begin, end in intervals: if begin < start < end or begin < stop < end: return True return False #mne.set_...
dc75b11e40c6c60d54183e0390e3728335c0407d68fea87cfafaeabb3519b11a
Python
3,133
97
import argparse import os import shutil UTT_PREFIX = "oniku" DEV_LIST = ["chatsumi", "goin_home", "aoimeno_ningyou", "momiji", "tetsudou_shouka"] TEST_LIST = ["usagito_kame", "sousyunfu", "romance_anonimo", "momotarou", "furusato"] def train_check(song): return (song not in DEV_LIST) and (song not in TEST_LIST) ...
f3b98c64874273112f4f1bcf3b38cff58d2c57b1d550fb944612fe0cc3531c05
Python
3,134
98
import math from torch import nn as nn from dtor.logconf import logging log = logging.getLogger(__name__) # log.setLevel(logging.WARN) # log.setLevel(logging.INFO) log.setLevel(logging.DEBUG) log = logging.getLogger(__name__) # log.setLevel(logging.WARN) # log.setLevel(logging.INFO) log.setLevel(logging.DEBUG) clas...
96d142c75a933d80ff1dc1f847dd0a2765c7cafc3bc98cda4bbd39ff3562d25f
Python
3,135
94
from configparser import ConfigParser from distutils.util import strtobool from tpot import TPOTRegressor, TPOTClassifier utils_section = "UTILS" csv_section = "CSV" metrics_section = "METRICS" force_classification_metrics_section = "FORCE_CLASSIFICATION_METRICS" def str_to_bool(val): # distutils.util.strtobool...
fac2ecea2b9ca42b04dc79e0cd654c43673b09ce2c37dd98b165201e0fe2eef4
Python
3,137
84
import logging import torch from torch import nn try: from fedml_core.trainer.model_trainer import ModelTrainer from fedml_api.standalone.fedopt.optrepo import OptRepo except ImportError: from FedML.fedml_core.trainer.model_trainer import ModelTrainer from FedML.fedml_api.standalone.fedopt.optrepo imp...