sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
a29e4c3746d188852c36fbedd0c01d13e0a72e6ecbef847ab48b292033f75639
Python
1,865
60
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn import torch.nn.functional as F from Actor1 import init_weights class Critic(nn.Module): def __init__(self, OBS_DIM, ACTION_DIM, TARGET_DIM, RNN_SIZE, FC_SIZE, RNN): super().__init__() self.OBS_DIM = OBS_DIM self.AC...
e5ff811d3858ea61ba00f4aadc2470d8c2f670e34e9eae837e890345fecabbd1
Python
1,866
60
# Copyright 2023 Google LLC # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
69ee28d5c212627c595bdd331714444f7f91e0ef5d969a80f40705073deabf8c
Python
1,867
47
import numpy as np def reformat_syn_parameters_eglif(CELL, params, M): """ valid if CELL is specified in cell_library """ # M : row = connected cells("from"), column post synaptic target ("to"_cell). if CELL == 'RS': # synapsi to_RS params['Qe'], params['Te'], params['Ee'] = M[0...
7d8db1230df44a83e05139e920ec4719c44899eddc218fc635b27e2f24497520
Python
1,867
76
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ Creates a genetic relatedness matrix (GRM) from biallelic sites in an input VCF """ import argparse import sys import pysam def get_allele_dosage(record): ads = [] for s in record.samples: GT = list(record.samples[s]['GT']) if len([a for a ...
3195cb043a718c48b07bc211f88920e3b75b1d8a46fd01c9b9da7fcc9d9d23f8
Python
1,868
44
import math import torch import torch.nn.functional as F import pytest from einops import rearrange from src.ops.vandermonde import log_vandermonde, log_vandermonde_fast @pytest.mark.parametrize('L', [3, 17, 489, 2**10, 1047, 2**11, 2**12]) @pytest.mark.parametrize('N', [4, 8, 16, 32, 64, 128, 256]) # @pytest.mark...
57a5c9e2c4fd6d710a290f28aa4d72e8ea1195ef2fb80ba63d1c2174796f3997
Python
1,868
56
from deepsith import DeepSITH from torch import nn as nn import numpy as np import torch import matplotlib.pyplot as plt import seaborn as sns sns.set(style='white', palette='colorblind', context='poster') class DeepSITH_Classifier(nn.Module): def __init__(self, out_features, layer_params, dropout=0): su...
4feb5296f36492f19c9257d840d3486dcc64acf629e0f2554c9305a043235004
Python
1,870
51
from unittest.mock import patch import numpy as np import pytest from skorch.utils import to_numpy class TestGradientNormClipping: @pytest.fixture def grad_clip_cls_and_mock(self): with patch('skorch.callbacks.regularization.clip_grad_norm_') as cgn: from skorch.callbacks import Gradient...
c098381fb9bc3017dff2a4143a01410bcf29fc29049c6238f7bac63568a7be62
Python
1,870
55
#!/usr/bin/env python import numpy.testing as npt import os from caiman.source_extraction import cnmf from caiman.paths import caiman_datadir def demo(): fname = [os.path.join(caiman_datadir(), 'example_movies', 'demoMovie.tif')] fr = 10 # frame rate (Hz) decay_time = .75 # a...
fcec4982beb68f75651d528f6c817ea586d42e2be733ea6d204ffaff1faf8915
Python
1,870
53
import torch from torch.nn.parameter import Parameter import numpy as np from torch import sigmoid import copy class SoftConcrete(torch.nn.Module): def __init__(self, threshold = 0.5, remove_key_parts = False, use_top_k = False, k = 0.05): super(SoftConcrete, self).__init__() self.loc_bias = 3 ...
bb313841e9f00df6d4a67528ef672971e773a75edfc6f3bc46f594b4e6ab04e7
Python
1,872
56
from Bio import SeqIO import random import os import sys from pathlib import Path import pandas as pd # /ccb/cybertron/khchao/splam-analysis-results/train/results/tool_benchmark SEQ_LEN = 800 project_root = '/ccb/cybertron/khchao/splam-analysis-results' test_junc_out_f = f'{project_root}/train/results/tool_benchmark/{...
3af3201ef9602701f47f88d064224bf9bc5e1053f8745109fbd7b17c8d7f708d
Python
1,873
62
import numpy import random import sys sys.path.insert(0, "..") from sklearn.preprocessing import PolynomialFeatures from matplotlib import pyplot import algorithms # numpy.random.seed(42) # random.seed(42) class Sampler: def __init__(self, degree=3): self.degree = degree self._min, self._max = ...
472a555e3c7511a77400540fe1af8d1b029c37198564211edd2ae5116b41e252
Python
1,873
50
import numpy as np import scipy.stats as stats from hic3defdr.util.scaled_nb import logpmf, fit_mu_hat def lrt(raw, f, disp, design, refit_mu=True): """ Performs a likelihood ratio test on raw data ``raw`` given scaling factors ``f`` and dispersion ``disp``. Parameters ---------- raw, f, dis...
795bbb5f0426f685ec3e0e3275623f5234cd48874070dca7f7ca1ec06ec1dc59
Python
1,873
54
import kaggle import pandas as pd from data_profiling import ProfileReport from data_profiling.utils.paths import get_data_path # The dataset in this example is obtained using the `kaggle` api. # If you haven't done so already, you should set up the api credentials: # https://github.com/Kaggle/kaggle-api#api-...
c82f502799384b287c86b117016d9f4f3d8f69390bf600e600bb38adc5a7505c
Python
1,873
39
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns from io import StringIO # for log in [False, True]: for log in [False]: for thresholds in range(2, 101): neg_pred_file = f'/ccb/cybertron/khchao/splam-analysis-results/src_tools_evaluation/splam_result/RELEASED/neg_{thresholds}/LOG/_...
650392c63abc9ba33016a0b90408088af34b093db18adcbbdf90078af27cc906
Python
1,874
71
from dataclasses import dataclass import numpy as np from .node import NIRNode @dataclass(eq=False) class Affine(NIRNode): r"""Affine transform that linearly maps and translates the input signal. This is equivalent to the `Affine transformation <https://en.wikipedia.org/wiki/Affine_transformation>`_ ...
f0882a1fd8529cfb88845e9568eb07a3af30289a09ec36134a391f35aae8396d
Python
1,874
104
#!/usr/bin/env python # coding: utf-8 # In[1]: import os import numpy as np import pandas as pd import matplotlib.pyplot as plt from allensdk.brain_observatory.ecephys.ecephys_project_cache import EcephysProjectCache # In[2]: # this path determines where downloaded data will be stored manifest_path = os.path.j...
34db9020072fca86dad26ce09ae4230e5a03e43863c4c0269de051aa2ae5ccaf
Python
1,875
47
import torch import torch.nn.functional as F def multiresolution_spatial_basis_application(raw_frames: torch.Tensor, full_scale_basis: torch.Tensor) -> torch.Tensor: ''' * big_height must be an integer multiple of small_height * big_width must be an integer m...
207e572024b53fd2469dc5df31616648c24cb249d9a599171154ed04cf7ebc08
Python
1,876
70
#!/usr/bin/env python """ Collect sample list metrics. Writes stats to stdout. Metrics: sample_list_count : Number of samples """ import argparse import sys import svtest.utils.IOUtils as iou KEY_PREFIX = "sample_list_" def main(argv): parser = argparse.ArgumentParser( description=__doc__, ...
8413cf5558393391512ecb4df77ded2c99555b916e6fa3adf1b40b89982e87ee
Python
1,876
55
import os import pickle import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from utils import padded_corr from utils import EventLabel, TrainValidSplit, HumanBondaries, DataLoader sns.set(style='white', palette='colorblind', context='talk') tvs = TrainValidSplit() evlab = Even...
bf7b35a224cebb1a8a0417965341493db87655799a3e4c6278b9fd9db7e6a7cf
Python
1,877
62
#!/usr/bin/env python # coding: utf-8 import torch import torch.nn as nn import torch.nn.functional as F from Actor1 import init_weights class Critic(nn.Module): def __init__(self, OBS_DIM, ACTION_DIM, TARGET_DIM, RNN_SIZE, FC_SIZE, RNN): super().__init__() self.OBS_DIM = OBS_DIM self.AC...
1ac8865ec4a5ca5042fd343456ef7dad016a8cdb70b48b9e2bf057cbf42b458d
Python
1,878
57
#!/usr/bin/env python # Copyright (c) 2017-present, Facebook, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by a...
a63e9695c66605d4958832c80ae4c07e2c25f3937afd28a0c68c9e55d0f3b589
Python
1,879
51
import os import nibabel as nib import numpy as np import IVIMNET.deep as deep from hyperparams import hyperparams as hp output_root = '/mnt/d/fc-ivim-estimation/results' subs = [sub for sub in os.listdir(output_root) if sub.startswith('sub')] pars = ['D','f','vd'] times = [] for sub in subs: # Gather input file...
238dbc9cbf523ed306281c2f1003f04a46a6df78196533420ced3eb4ed412c98
Python
1,880
47
import argparse def main(xyz_filepath: str, dataset: str, memory: str, num_threads: int, verbose: bool = True): if dataset == "qm9": import psi4 # Set memory and number of threads psi4.set_memory(memory) psi4.set_num_threads(num_threads) # Set computation options ...
663b26657ddfb7b1c5596b78b34b55ad93bb710291045046a3439866d4fee784
Python
1,880
116
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. Atomic radii in picometers NaN stored for unavailable parameters. """ from __future__ import annotations ATOMIC_RADII = { 0: float("NaN"...
bf8e8e195cbf8f3a43358dbe572b49bad6a46d520b191d7c9cc8fac022df4b7c
Python
1,880
69
''' Example for visualizing the fitness transition throughout the evolutionary process. ''' import os import pickle import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd from matplotlib.colors import Normalize path = os.path.join(os.path.dirname(__file__), 'examples/xor/resu...
cfdfa6964682408d0acf3cd95ee6882b720b01cf4f5ba1c91bd051990cd645e4
Python
1,880
59
import os import shutil import tempfile import gym import pytest from gym.wrappers import TimeLimit import pfrl @pytest.mark.parametrize("n_episodes", [1, 2, 3, 4]) def test_monitor(n_episodes): steps = 15 env = gym.make("CartPole-v1") # unwrap default TimeLimit and wrap with new one to simulate done=T...
29118da47d0f0a4a1e3e1ad1e8cefdef598a31e7d3bda11b98d652d4784c2ee7
Python
1,881
73
"""OmicVerse-style console output helpers for the vendored gsMap pipeline.""" from __future__ import annotations from datetime import datetime class Colors: """ANSI color codes for terminal output styling.""" HEADER = "\033[95m" BLUE = "\033[94m" CYAN = "\033[96m" GREEN = "\033[92m" WARNING...
5c93ce64cfd989109076c961bf3082dd01322746310e6e7bd1ed164cab8b8478
Python
1,881
51
#!/usr/bin/env python from distutils.core import setup from distutils.command.install import INSTALL_SCHEMES import os for scheme in INSTALL_SCHEMES.values(): scheme['data'] = scheme['purelib'] data_files_list=[] data_path="mozaik/stimuli/vision/textureLib/" for root, dirs, files in os.walk(data_path): for f ...
92c624eefb22a3d6ecdee093c39efd2d32a3c62a2e5c57167c37542af2f3bd0f
Python
1,882
82
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Jul 30 11:28:50 2019 @author: sam """ import numpy as np import scipy.signal import pywt def haar_wavelet(X,a,mode='same'): if a==0: return X haar = np.ones(2*a) haar[a:] = -1 return np.convolve(X,haar,mode=mode)/a#[a:-a+1] ...
919165e49407b22d002eaa503e74041e1ed0b399b872b9f4f66ed65f9fdf2761
Python
1,883
53
""" Creates a ukbb_dev dataset which is a miniature version of a typical ukbbs. NOTE: dataset names, tables to be copied are currently hardcoded, will fail if dev dataset already exists. """ from google.cloud import bigquery # CONSTANTS ORIGINAL_DATASET = 'ukbb7089_201904' DEV_DATASET = 'ukbb_dev' EXACT_TABLES = ['c...
cbfda16f2e0d9ff48cb587785f2add425290477c74bfff7a3f9b5321c0ea774b
Python
1,884
56
import argparse import OmegaConf import torch from diffusers import DDIMScheduler, LDMPipeline, UNetLDMModel, VQModel def convert_ldm_original(checkpoint_path, config_path, output_path): config = OmegaConf.load(config_path) state_dict = torch.load(checkpoint_path, map_location="cpu")["model"] keys = lis...
47dea5c294fd8655fb8b87de2ebe365811fc738e92d95bfd5315a089fcc43641
Python
1,885
52
"""build_session(dynamic_shapes=True) must accept inputs in shapes other than declared ones.""" import numpy as np import pytest from deepface.commons import onnx_utils onnx = pytest.importorskip("onnx") ort = pytest.importorskip("onnxruntime") def make_model(): # (1, 3, 4, 4) declared conv graph, which works ...
50dc742d07f5a5e5db879e5711e7f9ce44db450cdecabe99857d9e12f06145eb
Python
1,885
55
import numpy as np import scipy.special as special from .basic_distributions import Distribution from ..utils import * class Beta(Distribution): """ Class to define Beta distributions Equations: p(x|a,b) = GammaF(a+b)/(GammaF(a)*GammaF(b)) * x**(a-1) * (1-x)**(b-1) log p(x|a,b) = log[GammaF(a+b)/...
8ced045bfa80767cd7b64a7853d1f3c371e30465aa9b58ad7694036370076ae0
Python
1,885
51
""" Date: Oct 25 2019 Author: Shaoju Wu Email: swu3@wpi.edu see also: https://github.com/Jilab-biomechanics/CNN-brain-strains """ import numpy as np import scipy.io import tensorflow as tf import keras from keras.models import load_model from scipy.io import loadmat from scipy.io import savemat from sklearn.metrics i...
9bfdc97eec2c24607ff76c363756fe32b1ab37ae3b1b68079e58e471d3383bdd
Python
1,885
50
import torch from projectmetis.proto import metis_pb2 from projectmetis.python.logging.metis_logger import MetisLogger from projectmetis.python.models.model_dataset import ModelDataset from projectmetis.python.models.model_ops import ModelOps class PyTorchModelOps(ModelOps): def __init__(self, model_filepath="/...
cf10c0e23fa52b4cda8d4205c8aa6f72f02cda108e28927742d7054708286cd1
Python
1,885
49
import sys from ray._private.utils import open_log from ray._raylet import StreamRedirector def redirect_stdout_stderr_if_needed( stdout_filepath: str, stderr_filepath: str, rotation_bytes: int, rotation_backup_count: int, ): """This function sets up redirection for stdout and stderr if needed, b...
9e3ae3d51e34e37387734914e725f3a8acd00e71c1e5d0100da61749fb452e1f
Python
1,886
64
#!/usr/bin/env python # -*- coding: utf-8 -*- # """ """ import warnings from .annotate_intersection import split_gencode_fields def annotate_nearest_tss(sv, gencode): """ Annotate each variant record with its nearest TSS. Parameters ---------- sv : pbt.BedTool columns = (chrom, start, ...
a735f23a5ba955494aacfd254680ef4aaa16dc3f524af207fb276d0b201c3c98
Python
1,886
47
import tensorflow import keras.optimizers import keras.initializers from sak.losses import * def select_loss(loss): switcher = { 'dice' : DiceLoss, 'jaccard' : JaccardLoss } return switcher.get(loss.lower()) def select_optimizer(optim): switcher = { ...
0da0f754e943a9fb1f15ae5b48f74f68d54b00356411f51b5bb4a43bb23ecdba
Python
1,887
42
import math import torch from scipy import ndimage, spatial def rotate_vol_around_axis(vol, rot_angle, rot_axis, output_shape=None, order=3): """ Rotates the 3D tensor 'vol' by 'rot_angle' degrees around 'rot_axis'. The rotated tensor, which is typically larger than the original one, is center-cropped such t...
38744c479502481311d1074726a0ae4abdf96dd36305bbac6610f4bc47e68f38
Python
1,887
64
import torch import torch.nn as nn import numpy as np class conv_encoder(nn.Module): def __init__(self, n_components=2): super().__init__() self.encoder = nn.Sequential( nn.Conv2d( in_channels=1, out_channels=64, kernel_size=3, stride=2, padding=1, ), ...
f504d5c2e9706c81b0f6e5659023adc4ce8397e682dc5aa1207564c882f6d147
Python
1,887
52
import pfrl from pfrl.agents import categorical_dqn from pfrl.agents.categorical_dqn import _apply_categorical_projection from pfrl.utils.recurrent import pack_and_forward class CategoricalDoubleDQN(categorical_dqn.CategoricalDQN): """Categorical Double DQN.""" def _compute_target_values(self, exp_batch): ...
4d054440a5985d148f5dc84166c5af45299f1062ef61db36aa265ff417b3fc9e
Python
1,888
75
# -*- coding: utf-8 -*- """ Created on Wed May 11 12:46:10 2022 @author: gagan """ import numpy as np from scipy.stats import wilcoxon as wx from scipy.stats import ttest_rel as tr import matplotlib.pyplot as plt def get_pval(output,keys=None,verbose=1): nexps = len(output) if 'var' in output: nexp...
c5478c5b9c6b9bd82bd29a30e5de39f17dea0c0cb4627b9d79461fdddf4e6c00
Python
1,889
81
'''fitting a periodic function using an rnn this is the basis of a bunch of learning hierachical seqs with crp-rnn ''' import numpy as np import torch import torch.nn as nn import matplotlib.pyplot as plt import seaborn as sns from utils import to_np, to_pth from model import CRPLSTM_REG as Agent sns.set(style='white'...
227ad22b577cde5d972101bc68acefaee166d70b177afdac7307a1595c8c2cd6
Python
1,890
49
# ----------------------------------------------------------------------------- # I/O # learning data directory, train.bin and valid .bin are expected. You should prepare them using tokenize.py data_dir = 'directory_containing_train.bin/val.bin' out_dir = 'output_directory' # output directory log_dir = os.path.join(o...
444e3cc614e6c5203f85f415e5f6b4a624dc3d3cb85e113eefe39f7b130bb0cc
Python
1,890
57
# Copyright 2023 The HuggingFace Team. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicabl...
bbff971c49b9049931f25ac6e37df735386e99debae220e3c571d1b261941e03
Python
1,890
55
from dataclasses import dataclass, field from typing import Any, Dict, Optional import numpy as np from .node import NIRNode from .typing import Types from .utils import calc_flatten_output, parse_shape_argument @dataclass(eq=False) class Flatten(NIRNode): """Flatten node. This node flattens its input tens...
ba94e3813e918bf4f01b3740724771b698e70f7c3382c83203f50af11c4fd661
Python
1,891
64
import unittest import numpy import torch from pfrl.nn import to_factorized_noisy def names_of_parameters(module): return set([name for name, tensor in module.named_parameters()]) class TestToFactorizedNoisy(unittest.TestCase): def test_modulelist(self): model = torch.nn.ModuleList([torch.nn.Linea...
1a07b531cdbea76b66c45348295973cfed8922d4303c95a74802e7a330766a11
Python
1,892
40
import nibabel as nb import numpy as np BBOX = {'sub-05': {'RH': {'xlower': 435, 'xrange': 162, 'ylower': 55, 'yrange': 162, 'zlower': 95, 'zrange': 158}, 'LH': {'xlower': 263, 'xrange': 162, 'ylower': 35, 'yrange': 162, 'zlower': 79, 'zrange': 158}}, 'sub-06': {'LH': {'xlower': 271, 'xrange...
0738d841608eb3101002dd1a1f7d455b9f8ee1fcd8b215aeeb0d6d07e3f71eab
Python
1,893
68
# -*- coding: utf-8 -*- """ Created on Mon Jul 17 12:27:40 2023 @author: gagan """ from identification import get_exp_data, compare_ARX_params, get_best_model from identification import compare_switch, compare_bilin, regret import os from tqdm import tqdm import pickle as pkl from glob import glob import numpy as np ...
6a41899605e13ad700e336072dfc8f5ee325cf88c79290594b1d0ad0349c6c5a
Python
1,893
49
#!/usr/bin/env python from __future__ import print_function import argparse import gzip import sys import os def parse_args(): parser = argparse.ArgumentParser("Produce a BED based on VCF calls") parser.add_argument('--input_vcf', '-i', dest='input_vcf', required=True, type=str, help='V...
ed388b0d66228458c8deebac82f88a9efbb3fb34c35eadefa34d90bada2912bc
Python
1,893
39
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
1679c24e5dff3fd77859d69b74b51915ed2eb74dd76595f0666c7ed1a03c5bb9
Python
1,894
32
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: i_output_file.proto """Generated protocol buffer code.""" from google.protobuf.internal import builder as _builder from google.protobuf import descriptor as _descriptor from google.protobuf import descriptor_pool as _descriptor...
19e9a2a0690d45fa2327909fcb41e7a046b3a7a85aec77a711da748301e54e1b
Python
1,894
59
from splam_utils import * from splam_dataset_Chromsome import * # from splam_Conformer import * from SPLAM import * import numpy as np import torch import torch.nn as nn import sys from torch.optim import Optimizer, AdamW from torch.optim.lr_scheduler import LambdaLR from tqdm import tqdm import math import os def mai...
c0d9099ebbc53983f36bb1d41b618f47d466093f959e712baf0c85ac527ff6e6
Python
1,894
53
#Imports relevant modules import os import nibabel as nb import numpy as np #Defines the pipeline ID. pipeline = '0' #Defines the path in which FEAT output is stored for this pipeline. pipeline_dir = '/<directory root>/FEAT/Pipeline_{}'.format(pipeline) #Full path removed for purpose of public sharing. #Creates an e...
85b6896f0f253ee38b6a0cecd9434a89330d0256d77454767605d1fbf3e7554d
Python
1,896
55
import sys import torch import shutil from pathlib import Path from rdkit import Chem from tqdm import tqdm basedir = sys.argv[1] structure_dir = Path(basedir, 'crossdocked_pocket10') test_set = torch.load(Path(basedir, 'split_by_name.pt'))['test'] receptor_dir = Path(basedir, 'receptor_pdbs') receptor_dir.mkdir(e...
254776c59cc2649554b3fd28abf2eb13c8f78faf60e6cb15379f0f645661e210
Python
1,897
51
#this script with assistance from ChatGPT3.5 20231204 # the function is to create a mean of all the normalized images: # python nii2meanFLAIR.py import os import nibabel as nib import numpy as np import fnmatch def create_mean_image(folder_path, output_path): # Ensure the output folder exists os.makedirs(os....
0c86bc1e4c3be49c90528a8c96ca9fc567d4c92728801f08442c81ea8d3ff536
Python
1,898
62
import numpy import random import sys sys.path.insert(0, "..") from sklearn.preprocessing import PolynomialFeatures from matplotlib import pyplot import algorithms # numpy.random.seed(42) # random.seed(42) class Sampler: def __init__(self, degree=3): self.degree = degree self._min, self._max = ...
8bc9ad116a4be8a834ae54002113e208b545761610398a2a791f0d719d1008de
Python
1,898
51
import csv import code # code.interact(local=dict(globals(), **locals())) import os file = "score_sum_indiv_F1.profile" dir, _ = os.path.split(file) with open(file, 'r') as f, open(file + '.reformat', 'wt', newline='') as f2, open(os.path.join(dir, "PRS_MetS_F1.csv"), 'wt', newline='') as f3: reader = csv.reader(...
9bad73901f54557d97d15c7a8344def7454a387a2e8279db4ca35ccfab9fce69
Python
1,899
50
from loguru import logger import os import argparse import torch import copy import pandas as pd from deltasplice.constant import default_model_paths, model, Fapath, EL, SeqTable, repdict, IN_MAP from pyfasta import Fasta def main(): # load config file parser = argparse.ArgumentParser() parse...
a854cc0cfa903995a8331d169d1f49c3f1b44155940e92c885fb53f3994d47b3
Python
1,899
55
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
0e3915c902fb9d1a2d217bc6ad5331729a84b1b7abcaca37b88d115069485484
Python
1,901
55
import torch, math class Embeddings(torch.nn.Module): def __init__(self, d_model, vocab, pad): super(Embeddings, self).__init__() self.lut = torch.nn.Embedding(vocab+2, d_model, pad) self.d_model = d_model def forward(self, x): return self.lut(x) * math.sqrt(self.d_model) ...
3a32b7805facc4fe67a95cf7cc5ccffef7e320e2d50cb843f7a2910a897f9fb6
Python
1,901
49
from pathlib import Path import pandas as pd from data_profiling import ProfileReport from data_profiling.utils.cache import cache_file if __name__ == "__main__": file_name = cache_file("auto2.dta", "http://www.stata-press.com/data/r15/auto2.dta") df = pd.read_stata(file_name) # In case that ...
f113a65db51bee552f7511d3c51f1034a1afa296819c085bd29d95061e288226
Python
1,901
74
import requests # __doc_import_begin__ from ray import serve from ray.serve.handle import DeploymentHandle from ray.serve.gradio_integrations import GradioIngress import gradio as gr import asyncio from transformers import pipeline # __doc_import_end__ # __doc_models_begin__ @serve.deployment class TextGeneration...
f94c75f91b1ff087a16ab2ebc98cd76b18228023c8f3c499c400aac74d5e3e9e
Python
1,901
57
# -*- coding: utf-8 -*- """ This is implementation of model of self-sustained activitity in balanced networks from: Vogels, T. P., & Abbott, L. F. (2005). Signal propagation and logic gating in networks of integrate-and-fire neurons. The Journal of neuroscience : the official journal of the Society for Neuroscience,...
2671be80f18a49f10c32953507ea220b7fbe4830f42d18c28c57bb7ab9157fe8
Python
1,902
68
#!/usr/bin/env python import glob import os import torch from setuptools import find_packages from setuptools import setup from torch.utils.cpp_extension import CUDA_HOME from torch.utils.cpp_extension import CppExtension from torch.utils.cpp_extension import CUDAExtension requirements = ["torch", "torchvision"] d...
0c73c079b417ca2658284629c722af6e03d5ea4e0576de757f3913b8a2c49322
Python
1,904
53
# -*- coding: utf-8 -*- # (C) Copyright 2026 IBM. All Rights Reserved. # # Licensed under the MIT license. See LICENSE file in the project root for details. """Download helper for SVHN from the Hugging Face hub, for aihwkit tests. The original host of the dataset (``ufldl.stanford.edu``) used by torchvision is not a...
c245db8d9f18bb00ee805e2217b861573292d8f75d92ff12cfce8fb668f0de46
Python
1,907
47
# # CEBRA: Consistent EmBeddings of high-dimensional Recordings using Auxiliary variables # © Mackenzie W. Mathis & Steffen Schneider (v0.4.0+) # Source code: # https://github.com/AdaptiveMotorControlLab/CEBRA # # Please see LICENSE.md for the full license document: # https://github.com/AdaptiveMotorControlLab/CEBRA/bl...
825ed82850b2a9116d9e6d972fa3ac4276c283b16f14a696356b7cb490cf8e23
Python
1,908
60
import warnings from io import BytesIO from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Union import numpy as np from ray.data.block import Block, BlockAccessor from ray.data.datasource.file_based_datasource import FileBasedDatasource if TYPE_CHECKING: import pyarrow class NumpyDatasource...
8a3b35a4ab5419017a9afbad3c8363648aff57a3c05d8b8f1c598f1d685f8716
Python
1,909
62
import numpy import random import sys sys.path.insert(0, "..") from sklearn.preprocessing import PolynomialFeatures from matplotlib import pyplot import algorithms # numpy.random.seed(42) # random.seed(42) class Sampler: def __init__(self, degree=3): self.degree = degree self._min, self._max = ...
ba1e457ef7d28f95d777d5fa2ff33007b274ff8df4925a9dfbaf880c1b57b84e
Python
1,909
39
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
19270eea312569a459fd2569cb4a8945efbb757d775b87d56df5faf8e76c07b1
Python
1,910
37
#################################################################################################### # Copyright (c) 2016 - 2024, EPFL / Blue Brain Project # Author(s): Marwan Abdellah <marwan.abdellah@epfl.ch> # # This file is part of NeuroMorphoVis <https://github.com/BlueBrain/NeuroMorphoVis> # # This program is fre...
996ee5e48d059a109ca160dcb553913524785ad72c7a5d5e8093144ad0aaba48
Python
1,910
63
# -*- coding: utf-8 -*- # (C) Copyright 2020, 2021, 2022, 2023, 2024 IBM. All Rights Reserved. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. #...
4c8e680eac605a644e530359880d7f74ab268bf807aea0c6001e820100836621
Python
1,912
73
# import GNNSubNet from GNNSubNet import GNNSubNet as gnn # import ensemble_gnn import ensemble_gnn as egnn # Synthetic data set ------------------------- # loc = "data/synthetic" ppi = f'{loc}/NETWORK_synthetic.txt' feats = [f'{loc}/FEATURES_synthetic.txt'] targ = f'{loc}/TARGET_synthetic.txt' # Read in the synthet...
7bddad8a037f3c9f877e7db597fffaa45839e25aa6157c915c98e265a6f64be9
Python
1,914
57
from typing import List, Tuple from ipywidgets import GridspecLayout, VBox, widgets from data_profiling.report.presentation.core.frequency_table import FrequencyTable def get_table( items: List[Tuple[widgets.Label, widgets.FloatProgress, widgets.Label]] ) -> VBox: table = GridspecLayout(len(items), 3) f...
2b8ed949805cd0f1cceccb00030b014996ab3082f10d979369ce6dbded048734
Python
1,915
54
from exputils.gui.jupyter.multi_selection_widget import MultiSelectionWidget import exputils as eu import numpy as np class RepetitionIDsSelectionWidget(MultiSelectionWidget): ''' MultiSelectionWidget to select experiment ids in a experiment_data dict. ''' @staticmethod def default_config(): ...
59269f531d72117d1356f7c77c6821480a42d8bf5e533c4cf2d4091f39f06cfc
Python
1,915
62
# This file is autogenerated by the command `make fix-copies`, do not edit. from ..utils import DummyObject, requires_backends class FlaxStableDiffusionControlNetPipeline(metaclass=DummyObject): _backends = ["flax", "transformers"] def __init__(self, *args, **kwargs): requires_backends(self, ["flax",...
6180d48a074a0049f9eb14b74cd63824ebfa5c57010d1ca0c31b4f0d0b01d224
Python
1,916
59
import argparse import functools as ft import swap_errors.analysis as swan def create_parser(): parser = argparse.ArgumentParser(description="fit linear models") parser.add_argument( "data_file", type=str, ) parser.add_argument("--region_str", default="no_pfc", type=str) parser.ad...
64a3a5a137b9cf71907fca7ed383835027483bc4b121341c543d18e2fd832133
Python
1,916
51
import csv import code # code.interact(local=dict(globals(), **locals())) import os file = "score_sum_indiv_F1.profile" dir, _ = os.path.split(file) with open(file, 'r') as f, open(file + '.reformat', 'wt', newline='') as f2, open(os.path.join(dir, "PRS_MetS_F1.KoGES.csv"), 'wt', newline='') as f3: reader = csv.r...
be859700bd0721bb6241527ea601619ff9cf6c046be28aa423368aca85173718
Python
1,916
71
import numpy as np __all__ = ["correlation", "quick_correlation_one_to_many"] def add_noise_to_constant_rows(x, epsilon=1e-15): """Adds noise to rows that are constant to avoid division by zero. Args: x: m x n values Returns: m x n values """ if epsilon is not None: x = ...
c3696f263eb804d26284cbbe5de424026acfbde93bfce6fb1f963ced79e5ae48
Python
1,916
49
import argparse import os import easygrid import re if __name__ == '__main__': parser = argparse.ArgumentParser('Script to gather stats from log and results file from an LD score regression run.') parser.add_argument('results_file_list', help='List of results files to gather statistics from. Note that the cor...
f9d62b873bc496adf196ea818c7fd2049be27653af27be320f275435998f8c8f
Python
1,916
72
""" Copyright (c) Meta Platforms, Inc. and affiliates. This source code is licensed under the MIT license found in the LICENSE file in the root directory of this source tree. """ from __future__ import annotations import argparse import errno import os import ase import ase.io from ase.io.trajectory import Trajecto...
45af3f22ddd24deb6b2ea749ad82fa883973674632aff5e18cc3502e8c3286ad
Python
1,919
44
import logging from datetime import datetime from agent.data.entities.config import ROOT_LOGGER_ID from agent.nlp.spo_extractor import extract_spos_from_sentences, match_tokens_cuis_in_sentences from agent.nlp.spo_extractor import extract_spos_from_sentences_given_predicate, clear_spos from agent.nlp.spo_extractor imp...
a8fa82087f359fe68e07a7672904f81e997321d6cf63d75ccefa29aeb883e7dd
Python
1,919
66
import snntorch as snn import numpy as np import torch import matplotlib.pyplot as plt from snntorch import spikeplot as splt V_THR = 2.0 # TODO: STRANGE BEHAVIOR FOR *V_THR = 2.5* class TestNet(torch.nn.Module): def __init__(self, reset_after=False) -> None: super().__init__() self.lif = snn.S...
ed30365c8a7406fe8da4f21de9f18e6e6c058663f3336b8573aa24f9da83ca08
Python
1,919
63
# stdlib dependencies from typing import Any, List, Union # 3rd party dependencies from numpy.typing import NDArray # project dependencies from deepface.models.demography.DemographyUtils import GENDER_LABELS from deepface.models.demography.onnx.OnnxDemography import OnnxDemography from deepface.commons.onnx_utils imp...
28e9376cb1c4d30c5fdde772eed50c139999054395b010ad847b9520e1e3e4bf
Python
1,920
75
from spinnaker2 import snn, hardware def run_model(n_pre, n_post, timesteps): neuron_params = { "threshold":100., "alpha_decay":0.9, } stim = snn.Population( size=n_pre, neuron_model="spike_list", params={0:[1,2,3], 5:[20,30]}, ...
ec8872e7368b8a814fd453743e6a600302de9755c9330ea548c5716c930d1d47
Python
1,921
47
from .model_dummy_1 import batch_size as batch_size_1 from .model_dummy_1 import expected_output as expected_output_1 from .model_dummy_1 import input_shape as input_shape_1 from .model_dummy_1 import snn as snn_1 from .model_dummy_2 import batch_size as batch_size_2 from .model_dummy_2 import expected_output as expect...
50f35393c9eb95d78e0e350984102f8ab9f50aeae5ed5d86218c0abd14ac37ed
Python
1,922
63
from setuptools import setup, find_packages from hic3defdr._version import version_scheme, local_scheme with open('README.md') as fobj: long_description = fobj.read() extras_require = { 'evaluation': ['scikit-learn>=0.20.3'], 'test': [ 'nose>=1.3.7', 'nose-exclude>=0.5.0', 'doctes...
566e9a87a69629afb34e98d1186f117e44a745c561adb56f07b485597fc9aa2b
Python
1,922
49
import logging from datetime import datetime from agent.data.entities.config import ROOT_LOGGER_ID from agent.classifiers.data.liwc_management import export_sentence_data_for_liwc_features, get_sentence_liwc_features from agent.classifiers.tree_classifiers import tree_classifier logging.basicConfig(format='%(levelna...
8c534e0511b28484208f90d5b2bd7d4f9e456a16e67cb0f94b898154c11b3322
Python
1,922
68
from datamate import Namespace, set_root_context from flyvis.task.tasks import Task def test_task(mock_sintel_data, connectome, tmp_path_factory): task_config = Namespace( type="Task", dataset=Namespace( type="MultiTaskSintel", tasks=["flow"], boxfilter=dict(ex...
7269b137ef4f7e927c74ed4ef7827dedca245b8c0e5f607d8375a52be57de2bd
Python
1,924
56
import os import argparse def main(args): fin = os.popen(r'''zcat %s''' % (args.vcf)) header = [] body = {} SVID_key = [] for line in fin: pin = line.strip().split() if pin[0][:2] == '##': header.append(pin) else: body[pin[2]] = pin SVID_...
adf85d4e98a00742ad51ade4c7a156c016b4b3014b29ca86b559a6ae1163bfac
Python
1,925
53
import argparse import os def replace_in_markdown_files(folder_path, old_path, new_path): # Check if the folder_path exists and is a directory if not os.path.exists(folder_path) or not os.path.isdir(folder_path): print(f"Error: {folder_path} does not exist or is not a directory") return #...
e4e12f5b063a05290d7c4b9fa153c0ce90ca6552ae12889e1ce04f7cda3c641f
Python
1,926
58
import torch import numpy as np from kornia import create_meshgrid from einops import rearrange @torch.cuda.amp.autocast(dtype=torch.float32) def get_ini_position(H, W, device='cpu', flatten=True): grid = create_meshgrid(H, W, False, device=device)[0] i, j = grid.unbind(-1) ini_position = \ tor...
bdbed8b427e244c9d08463049a9385bfea3ce7e2d51740591f6e1809b57f5146
Python
1,927
69
# -*- coding: utf-8 -*- # """ std_wham.py Standardize WHAM record. """ from .standardize import VCFStandardizer @VCFStandardizer.register('wham') class WhamStandardizer(VCFStandardizer): def standardize_info(self, std_rec, raw_rec): """ Standardize Wham record. """ # Add placeh...
c11bf4670845f6a59b6eac6256368fe9c9630b5b807f9de1b9565a440fd82454
Python
1,928
72
import json import logging import subprocess from contextlib import contextmanager from functools import lru_cache from pathlib import Path from typing import Any @lru_cache(100) def warn_once(logger: logging.Logger, msg: str) -> None: """ Log a warning message only once for a given logger and message combina...
10a172057edf3f6377c6183cd77a5765249efb31d11b841de2103fd70997b473
Python
1,929
43
import torch import math def sparse_diag(x): indices = torch.arange(len(x), device=x.device).unsqueeze(0).repeat(2, 1) values = x return torch.sparse_coo_tensor(indices, values, (len(x), len(x)), device=x.device) def sparse_normalize(x): size_factor = sparse_diag(1. / (torch.sparse.sum(x, dim=1).to_de...
a2980b551f00253a5bdf5908b884bb3d7523d2c8f404fd5b7c083df8a85381d6
Python
1,929
62
"""Average echoes for before registration.""" import os import nibabel as nb import glob # ============================================================================= DATADIR = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti' DIRECTIONS = ['AP', 'PA', 'RL', 'LR'] # Set subs to work on SUBS = ['sub-07...
8876dc0403a6a957e43a745958a4a6d3ad5825f09111f9dc5221f8ad842872ad
Python
1,930
57
from __future__ import division import torch import torch.nn as nn import torch.nn.functional as F from gcn.layers import GConv class GCN(nn.Module): def __init__(self, channel=4): super(GCN, self).__init__() self.channel = channel self.model = nn.Sequential( GConv(1, 10, 5, pad...
0d1675a616fd6d40d1c1ff403870aaecf95688ba2f9c7a05e6c0c152cba90df9
Python
1,931
58
import torch import torch.nn as nn from ..utils import create_activation from ..layer import CosformerLayer, PerformerLayer, VanillaTransformerLayer, FlowformerLayer from ..utils.pe import select_pe_encoder class TransformerEncoder(nn.Module): def __init__(self, num_hidden, nhead,...
8be3388663031412e49ee5215a5cd6141d9d0ef6b96dd7bb706499c4fb5b0696
Python
1,931
63
import os from typing import Tuple import pandas as pd from data_profiling.config import Settings from data_profiling.model.summary_algorithms import describe_path_1d def path_summary(series: pd.Series) -> dict: """ Args: series: series to summarize Returns: """ # TODO: optimize usin...
9b446c0f13e545a9f77ea777bc23fd8e7345c9583c042c4d907cdbe5bc3dd568
Python
1,931
57
# __begin_class_based_autoscaling_policy__ import asyncio import json import logging from pathlib import Path from typing import Any, Dict, Tuple from ray.serve.config import AutoscalingContext logger = logging.getLogger("ray.serve") class FileBasedAutoscalingPolicy: """Scale replicas based on a target written ...