sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
85c564b732b332abdc5208389d70f32f7cd80bb8406159a434fbbf211f25c5d4 | Python | 6,004 | 203 | #!/usr/bin/env python3
"""
Estimate BAF (Biallelic Allele Fraction) from a single sample's SD (SiteDepth) file.
Reads a single-sample SD compressed table (.sd.txt.gz) produced by GATK's
CollectSVEvidence, and a dbSNP VCF defining REF/ALT alleles. For each site
present in both files, computes:
baf = ALT_depth / (REF_... |
bdf423a22cf2cd08aa2a92dc30698525f9e689ab4e46fc361aa967ecf08f0505 | Python | 6,005 | 186 | import numpy as np
from tqdm.auto import tqdm
from torch import optim
from sklearn.metrics import r2_score
from torch.nn import MSELoss
from torch.utils.data import DataLoader
from torch.cuda import is_available as cuda_is_available
from src.data.load_data import Dataset
from src.models.models import Chebnet, LRUnivar... |
5963f034f80a7daad9567316be2a9687c02f8f961b177dde73d81dda72b9a537 | Python | 6,008 | 142 | #!/bin/python
import argparse
import re
"""
Summary: Validates a PED file for use with GATK-SV. Performs some sample ID validations as well.
Usage: python validate_ped.py -p pedigree.ped -s samples.list
Outputs: The script will write to stdout "PED file passes validation!" if successful, and
otherwise it will ... |
214b182e0e910e7cfcd6a19c17bfaab65c5a5f65e5344a1948bb8a7bf63c5664 | Python | 6,011 | 197 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 05 16:15:00 2023
@author: ju-bar
Implementations of calculating and manipulating
electron probe functions
This code is part of the 'emilys' repository
https://github.com/ju-bar/emilys
published under the GNU General Publishing License, version 3
On box-normalizations o... |
73e3b564d51daa2803a4b795005ae9d7c874591276d8046cce97d1c4df4157fc | Python | 6,013 | 135 | from typing import List
import random
import torch
from einops import rearrange
import torch.nn.functional as F
class Transform:
def __init__(self,operator_list:List,args_list:List):
self.operator_instance_list=[]
assert len(operator_list)==len(args_list)
for operator,args in zip(operator_li... |
b21e4c6793c7e1f96f1c37080df1b9ca74628541f3e1be02c20d980b8b8c1f7d | Python | 6,014 | 202 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# mdgru documentation build configuration file, created by
# sphinx-quickstart on Tue Oct 2 11:26:03 2018.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... |
eb0761339cf90ffc71e5692b496cadb4bb21d89a56767720887b3bd85a37d0ef | Python | 6,016 | 199 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 2 11:31:38 2022
Note you can do NLLs fitting for either time or rate.
The difference is in extrema values and on the covariance parameters, if used
S(eta) = S0 * exp(-eta/T)
S(eta) = S0 * exp(-eta*R)
@author: pbolan
"""
import numpy as np
from sc... |
8ca21bdc96ff432084fb1f850b0e0c012b794213250a7bb94f1dd0e01b929de2 | Python | 6,019 | 179 | import torch
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
class ASD(nn.Module):
def __init__(self):
super(ASD, self).__init__()
self.vgg = VGG()
self.branch1 = Branch1()
self.branch2 = Branch2()
self.branch3 = Branch3()
... |
05fbd807b70ea89f5a8e0b710cef5d59905cd9f4cc3c7a509a1c3241a06c4cd4 | Python | 6,020 | 141 |
# Imports
import time
import logging
import numpy as np
from typing import Iterable
import tensorflow.keras.backend as K
from tensorflow.keras.models import Model
from tensorflow.keras.utils import model_to_dot
def plot_and_time_model(
model: Model,
generate_train: Iterable,
generate_valid: Iterable,
... |
abdfca07571206fb54a855bbaae8c0b0eb906e0914295be9e1660d765c991226 | Python | 6,020 | 161 | """Eeg class unit testing"""
import copy
import unittest
from pathlib import Path
import numpy as np
import pandas as pd
from src.epilepsy2bids.eeg import Eeg, FileFormat
class TestDataLoading(unittest.TestCase):
def test_loadEdf(self):
fileConfigurations = [
{ # CHB-MIT
... |
ddbd60ba06bcaab58c622154bab5f47240736767692d955bb51fbc234c630989 | Python | 6,020 | 195 | import os
import sys
import re
from glob import glob
from os.path import *
import argparse
import data
import shutil
'''
Traverse backwards through the NGSData structure starting
with rbsfile which should be a symlink to ReadData(although sometimesit is RawData)
and rename all files involved
'''
def main(... |
760c74fc8f413db76aeaf91066859a170542ad4ebb1e5a757e69c34acf0123fa | Python | 6,022 | 185 | import os
os.environ["RAY_TRAIN_V2_ENABLED"] = "1"
# __failure_config_start__
import ray.train
# Tries to recover a run up to this many times.
failure_config = ray.train.FailureConfig(max_failures=2)
# No limit on the number of retries.
failure_config = ray.train.FailureConfig(max_failures=-1)
# __failure_config_en... |
28ee2db9c6bd3a16e01f9da0ee9ae5ab07b97d35c22fc7acbc580a405c7e9351 | Python | 6,024 | 198 | import numpy as np
import matplotlib.pyplot as plt
from spinnaker2 import snn, hardware, brian2_sim
plot_flag = False # global flag for plotting results
def run_model(backend, input_spikes, neuron_model, neuron_params, weight,
delay, timesteps):
"""
Runs a simple model with 1 spike source and 1 ... |
f625e89ee643925f75f9a75b8d81ee8db70079893c8b7b6f4208043711c5e1ce | Python | 6,024 | 148 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from triangular_attention import (
TriangleAttentionEndingNode,
TriangleAttentionStartingNode,
)
from triangular_multiplic... |
3e4edce1d8d071d1f558dfa7e6fabd0ad581e651b53a37d225689aeaf299cf73 | Python | 6,026 | 175 | """An example of training Categorical DQN against OpenAI Gym Envs.
This script is an example of training a CategoricalDQN agent against OpenAI
Gym envs. Only discrete spaces are supported.
To solve CartPole-v0, run:
python train_categorical_dqn_gym.py --env CartPole-v0
"""
import argparse
import sys
import gym
... |
425592d74d19db1f50ab4c392a7b9b0c7b882be4692a8b1c3a807bc1d3bbc6b7 | Python | 6,027 | 171 | import pdb
import torch
import torch.nn as nn
import math
def compl_mul1d(input, weights):
# (batch, in_channel, x ), (in_channel, out_channel, x) -> (batch, out_channel, x)
return torch.einsum("bix,iox->box", input, weights)
class Linear(nn.Module):
def __init__(self, x_dim, y_dim, H):
super().__init__()
... |
e0ac490b0d587421cf51e0b153a039d5bae1e52b3aa92700b617276395338347 | Python | 6,027 | 138 | import torch
import time
import argparse
import os, glob
from sklearn.model_selection import train_test_split
from torch_geometric.loader import DataLoader
import lightning as L
from lightning.pytorch.callbacks import ModelCheckpoint
from src import TrainerGANLit
from src import AseReadDatasetAttr
from src import AseR... |
f71dfb3677df299957dff8412cc1bd2d4a468b9bc3be8273a9a6750212236a57 | Python | 6,027 | 148 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
from .triangular_attention import (
TriangleAttentionEndingNode,
TriangleAttentionStartingNode,
)
from .triangular_multipl... |
2f4b6304debdc9141f0e5132385444e7f91befe4f999e279577d1b283a278195 | Python | 6,028 | 155 | from utils import *
if __name__ == "__main__":
SHOW = 0
# Declare the datadir and paramfile
datadir = "/cfs/klemming/scratch/n/nbrav/logs/sparsespk-full/2024-04-21_14:40:38:083781"
paramfilename = f"{datadir}/net.par"
param = parseparam(paramfilename)
nstep_gap = param['nstep_ga... |
8d147f864ea7001ed95cee4c1b5274baebc013f83b6eb39f21779970d602d14b | Python | 6,031 | 133 | import argparse
import sys
import os
import glob
import logging
import pandas as pd
import pysam
class App(object):
def run(self, args):
name = os.path.basename(args[0])
parser = self.create_parser(name)
opts = parser.parse_args(args[1:])
return self.main(name, opts)
def creat... |
7a89694762d335363e4b51c425aff87e8827283a4d9bdb5e9e01917216516db6 | Python | 6,032 | 147 | #
# 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... |
80fdd017f670b9c31017dbe1cab23c26edb666486c6ccf481f3dcaf76aeac6de | Python | 6,032 | 155 | """gRPC client interceptor for token-based authentication."""
import logging
from collections import namedtuple
from typing import Tuple
import grpc
from grpc import aio as aiogrpc
from ray._raylet import AuthenticationTokenLoader
logger = logging.getLogger(__name__)
# Named tuple to hold client call details
_Cli... |
26a7500565946277db703b1fdce50ee6bb3eff95608c9626dcb929ebac175fad | Python | 6,033 | 187 | import numpy as np
import os
import tifffile
import cv2
import logging
from numpy import prod, zeros
def get_type_max(data):
dtype = data.dtype.name
if dtype == 'uint8':
max = 255
elif dtype == 'uint12':
max = 4098
elif dtype == 'uint16':
max = 65535
elif dtype == 'float32... |
68df910d69b22b6991e7a5f818c2c4dbb03675d91fdd4f51ba62bd397ca56092 | Python | 6,034 | 180 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 23 08:53:00 2020
Modified on Mon Nov 15 16:00:00 2021
@author: ju-bar
Constants and functions related to electrons and their physics
Declaration of physical constants based on published CODATA 2018
Source: <https://doi.org/10.1103/RevModPhys.93.025010>
Constant symbols ... |
6f21ecfeaef8d56f76207d06915fe24e5953649b13b4fc492675ce3be79cd35b | Python | 6,035 | 174 | """
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 os
import re
import shutil
from abc import ABCMeta, abstractmethod
from glob import glob
from ty... |
55e1317df2fe5526e452693f13718c55369444b3f97481bb250b3189d4a3a9bc | Python | 6,036 | 96 | import sys
from parameters import ParameterSet
from mozaik.models import Model
from mozaik.connectors.meta_connectors import GaborConnector
from mozaik.connectors.modular import ModularSamplingProbabilisticConnector, ModularSamplingProbabilisticConnectorAnnotationSamplesCount
from mozaik import load_component
from moza... |
86c6db4bbabc80e3e4ce05471989305a23123d92b0249c2abdf4224aa04ca94e | Python | 6,042 | 127 | import random
import torch
from huggingface_hub import HfApi
from diffusers import UNet2DModel
api = HfApi()
results = {}
# fmt: off
results["google_ddpm_cifar10_32"] = torch.tensor([
-0.7515, -1.6883, 0.2420, 0.0300, 0.6347, 1.3433, -1.1743, -3.7467,
1.2342, -2.2485, 0.4636, 0.8076, -0.7991, 0.3969, 0.849... |
0d7785e96ee2c4e048115e4ab20fc2acf189f302efeec74187f3782fb57269a4 | Python | 6,043 | 141 | import exputils as eu
import numpy as np
import rlexp.utils as utils
import torch
class DND(torch.nn.Module):
"""
Implementation of a differentiable neural dictionary as introduced in
Neural Episodic Control (Pritzel et. al, 2017)
"""
@staticmethod
def default_config():
dc = eu.AttrDic... |
a6111d87b3e52f8e22bb3c2f3990d1af79ac5a14dc8be7e9f0917bc9c884b308 | Python | 6,043 | 154 | # run in /benchmark/src_compare_results/
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import pandas as pd
import os
def run_plotter(type):
# # obtain the averaged data from POSITIVE sample
# for db in ['GRCm39', 'Mmul_10', 'NHGRI_mPanTro3', 'TAIR10']:
# avg_df = pd.read_cs... |
4a765dca4b7d5864d7f48e8ebc75dbf00812bcd64ac7e3ff61f989a6164f72e0 | Python | 6,044 | 181 | import inspect
import logging
from functools import wraps
from typing import Any, Callable, Optional, TypeVar, Union, cast, overload
from ray.util import log_once
from ray.util.annotations import _mark_annotated
# TypeVar for preserving function/class signatures through decorators.
# Note: These decorators also accep... |
78dc632f12201bd3b8044bfe94ee9140fda4e338754629bb3dd7492acdd5c210 | Python | 6,045 | 179 | """
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 functools
import os
import random
import tempfile
import numpy as np
import pytest
import torch... |
ef44cb2f76a592d6aa0f31fdcbefa9757641ca080da0c6100971bba35e82a98f | Python | 6,045 | 175 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
for type in ["donor", "acceptor"]:
targets = ["5_GET_REF_JUNCS_MANE", "6_GET_REF_JUNCS_REFSEQ_ALTS", "4_GET_BAM_NEG_OPP_STRAND_JUNCS"]
X_axis = ["Positive_MANE", "Positive_ALT", "Negative_1"]
barWidth = 0.25
dataframes = []
don... |
615312a3a9cad71c5eb7a62f8f67fa90c121c401863888c6a9dd05bb01a946b4 | Python | 6,046 | 148 |
import os
import json
import random
import glob
from collections import defaultdict
from banditopt import algorithms
from .tools import ParameterSpaceGenerator
from .configuration import Configurator
class RoutineGenerator:
"""
Creates a `RoutineGenerator` that allows to modify the configuration of the
... |
84c93f88b2b307adbe823c9ddcf2c28fd100f0e0ccd5377961ddf141d77d94f7 | Python | 6,046 | 174 | # Vendored from `decoupler` (https://github.com/scverse/decoupler) by
# omicverse for in-tree GPU acceleration work. Original copyright by
# the decoupler authors, redistributed under decoupler's GPL-3.0
# license. Cross-module imports rewritten from `decoupler.*` to
# `omicverse.es.*` (see scripts/vendor_decoupler.py)... |
9aba58ae82f9033ac42004a901a22869feecccfdbc552b1bc9f33305acd2018b | Python | 6,047 | 154 | #
# 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... |
c5c79d672c911fe67893cbb81df4e68d197c3325a9a709d3632901acfb6df805 | Python | 6,047 | 128 | import argparse
import pickle
from typing import Dict, List, Tuple, Optional
import visionloader as vl
import numpy as np
import lib.data_utils.sta_metadata
from lib.dataset_specific_stimulus_scaling.data_specific_stimulus_scaling import dispatch_stimulus_scale, \
get_stixel_size_wn, NSCENES_STIXEL_SIZE
from lib... |
d4b94286fcda5488d374e4c6bab307e243985171e6a31f9ab4e8f1a1fa79a87e | Python | 6,047 | 121 | import torch
import torch.nn as nn
from torchEnKF import misc
import math
class AddGaussian(nn.Module):
"""
torch.nn.Module that adds a Gaussian perturbation to a given input.
(softplus function is used to ensure positiveness.)
The Gaussian perturbation is parameterized by q, which may tak... |
a3ad9f31cab33ed88c0c90ef8fb07c03637fb572802a2ff6cf554bbe54d8032a | Python | 6,048 | 226 | # -*- coding: utf-8 -*-
from vtkplotlib._get_vtk import vtk
import numpy as np
from vtkplotlib.figures import gcf
from vtkplotlib.colors import as_rgb_a
from vtkplotlib.plots.polydata import PolyData
from vtkplotlib.nuts_and_bolts import init_when_called
class BasePlot(object):
"""A base class for all plots in ... |
ff51ea05d37b2e195f4b26f2f7c6e1306120ebbee709809857b95087c3f03e8e | Python | 6,049 | 133 | from typing import Union
import torch
from torch._dynamo import OptimizedModule
from nnunetv2.training.lr_scheduler.warmup import Lin_incr_LRScheduler, PolyLRScheduler_offset
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
from nnunetv2.utilities.checkpoints import NO_OPTIMIZER_STATE_WARNING, ... |
33d245e87726065fd0b7c0bdf2ccd6ca7ddf779805712960dcdd7ec268aba631 | Python | 6,052 | 122 | import torch
from typing import Union, Optional
from abc import abstractmethod
from monai.metrics.metric import Metric, Cumulative
from monai.config import TensorOrList
class LongitudinalMetric(Metric):
def __call__(self, y_pred: TensorOrList, y: TensorOrList, y_prev: TensorOrList): # type: ignore
"""
... |
9a070e3473e6d19127f9c4d57bf9b7fafab691bdd3e13b67f39dcec969597027 | Python | 6,053 | 159 | import sys
import os
import argparse
import numpy as np
class Evt(object):
def __init__(self,list):
#roi,quad,dir,startx,endx,ampx,dur,ampy,midx,halfdur,auc
self.roi = list[0]
self.quad = list[1]
self.dir = list[2]
self.startx = list[3]
self.endx = list[4]
... |
8b8d901b8c4d3374508e01f7a797bae10cf3c2cdc6298053e7abd2fb610af59a | Python | 6,055 | 157 | import torch
import torch.nn as nn
import numpy as np
import random
import torch.nn.functional as F
class ZINBReconstructionLoss(nn.Module):
"""ZINB loss class."""
def __init__(self, **kwargs):
super().__init__()
def forward(self, out_dict, x_dict, ridge_lambda = 0.0):
"""Forward propagat... |
2f0b01fde04c35fb7cf7c002713bbe97d9e3c6fd490802e2f186e9d4802c3ead | Python | 6,058 | 131 | import os
import glob
import pytest
import json
from typing import Iterable, Dict, Sequence
import pysam
import pandas
from sv_utils import genomics_io, get_truth_overlap
class Default:
resources_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
small_vcfs_dir = os.path.join(resourc... |
80285aeca7e07d6fc92137a785451f320298407922229d618d55e7727add18f6 | Python | 6,058 | 170 | # __quick_start_begin__
import gymnasium as gym
import numpy as np
import torch
from typing import Dict, Tuple, Any, Optional
from ray.rllib.algorithms.ppo import PPOConfig
# Define your problem using python and Farama-Foundation's gymnasium API:
class SimpleCorridor(gym.Env):
"""Corridor environment where an ag... |
2f69e10d18c82302be0d416cac0a83cd8fab95f22db7e7624322b98a74000aa6 | Python | 6,059 | 152 | """Explicit grayscale/uint8 conversion, bicubic resizing, mean subtraction, and batched loading."""
from pathlib import Path
import math
import numpy as np
from PIL import Image
import torch
from torch.utils.data import DataLoader, Dataset
class _PathImageDataset(Dataset):
"""Decode images in DataLoader workers; ... |
134945d2e460f90e17db6eea67ace2c2d7fabc21eedc54cf9f286fd8d1d0225a | Python | 6,060 | 156 | #!/usr/bin/env python3
import numpy as np
import random
from scipy.ndimage import rotate
from IsoNet.preprocessing.simulate import apply_wedge
import os
import mrcfile
from skimage.transform import iradon
from IsoNet.util.utils import mkfolder
def simulate_noise1(params):
np.random.seed(random.randint(0,100000))
... |
428ce29e3354f7a796fe1039bfd27392a3a5f87444c3b8d8b32c74ea7e74cd31 | Python | 6,060 | 134 | from dataclasses import dataclass
from typing import List, Optional, Union
import numpy as np
import PIL
from PIL import Image
from ...utils import (
BaseOutput,
OptionalDependencyNotAvailable,
is_flax_available,
is_k_diffusion_available,
is_k_diffusion_version,
is_onnx_available,
is_torch... |
5540f080703df249263b2850736031afb001b5f132f28099b60f912e4118382d | Python | 6,060 | 150 | r"""Runtime access to `Rule Set 3 <https://github.com/gpp-rnd/rs3>`_ — the real
on-target sgRNA activity model (DeWeirdt *et al.* 2021, *Nature Biotechnology*;
the maintained successor to Azimuth / Rule Set 2).
``rs3`` cannot be a declared dependency of ``omicverse[synbio]``. Its metadata
pins ``scikit-learn<=1.0.2``,... |
bbafd2906995a8287d09aea37d61c91891fcd0f8a92030759548a7ae48da14b4 | Python | 6,060 | 210 | # Use different polynomials to fit the damage degree-damage threshold curves, and record the solution results.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sp
from goodness_of_fit import goodness_of_fit
def fitting_solving(data, thres_range, file_name1, file_name2, path1):
# The degree ... |
2f46eed0c98c68d177ad11be41ce1231702387162af684dbf933f9f6e78695bc | Python | 6,061 | 155 | import numpy as np
import numpy.typing as npt
import pandas as pd
import torch
from pyJoules.energy_meter import EnergyContext
from pyJoules.device.nvidia_device import NvidiaGPUDomain
from pyJoules.handler.pandas_handler import PandasHandler
def bootstrap_ci(data: npt.ArrayLike, confidence: float = 0.01, num_sampl... |
15e0f0ddccd20303dcf4e8d3d2f970eb0ed2481b5faabc3c76e03194f8cebdd6 | Python | 6,063 | 178 | # coding=utf-8
# Copyright 2023 HuggingFace 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 applicable law or ag... |
23ecba547b9076f25114068d4934aaf67e0c58134c788a82640227b2031aa840 | Python | 6,063 | 162 | #
# 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... |
52d21a1ff8709785e0c510c98f0f04ce254d01c0b9505f627fe1c787ad2af6df | Python | 6,063 | 190 | import torch
import math
import copy
from torch.autograd import Variable
import numpy as np
from progress.bar import Bar
import copy
import time
def group_product(xs, ys):
"""
the inner product of two lists of variables xs,ys
:param xs:
:param ys:
:return:
"""
return sum([torch.sum(x * y)... |
def25498f037dcef0fe99a90f4c5f8349f18da947ff1c464f7b52e22d5cdef95 | Python | 6,064 | 205 | """
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 os
import tempfile
import numpy as np
import pytest
from ase.db import connect
from fairchem.c... |
404b01c74313fa09ae278ad41792f333e3f5ccf9350ab8569294fd42f8b16c93 | Python | 6,065 | 186 | import moabbpatch
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy
import config
import ast
BASELINENAME = "BFull"
datasetname = config.DATASET_NAME
outpath = config.CSP_RESEARCH_OUT_PATH
base16 = pd.read_hdf(outpath / "baseline_16.hdf5")
baseF = pd.read_hdf(outpath / "baseline_ful... |
1781bc28e40b9e7fcf7a4d6b20716fb5be2f676a6badd1bd2996adc35f7efeb6 | Python | 6,067 | 167 | from typing import List, Tuple
from ray.data._internal.execution.interfaces import BlockEntry, RefBundle
from ray.data._internal.split import _calculate_blocks_rows, _split_at_indices
from ray.data.block import (
Block,
BlockMetadata,
BlockPartition,
_take_first_non_empty_schema,
)
from ray.types impor... |
76d159fb355358d681f449a9f78ab26663f32c2a95f305f6a3bf0dd35598a1e2 | Python | 6,067 | 137 | from torch_pgn.graphs.proximity_graph import (yield_full_interaction_graph, yield_tree_reduction)
from oddt.utils import is_openbabel_molecule
import networkx as nx
import numpy as np
import pickle
"""Utility functions used in graph construction."""
def _renumber_nodes(ligand_nodes, protein_nodes):
"""
Tak... |
66a24fcd216fa3439aef1d31f8b47aca3cc8854beac8be8517f30aad7eb53571 | Python | 6,068 | 171 | """GPU edge-sampling SGD — the torch core of non-parametric UMAP.
This reproduces umap-learn 0.5.7's ``optimize_layout_euclidean`` analytic
gradient updates (NOT autograd, NOT a parametric MLP) on the GPU. Each
epoch the whole *active* edge set is updated simultaneously with atomic
``index_add_`` scatter — the standar... |
41376e953e9236c2f8e22143d8b4fcdd818a10c8881b3e5e86d75b8627288aed | Python | 6,069 | 173 | from typing import Callable, List, Tuple
import h5py
import numpy as np
import pandas as pd
from ml4ht.data.data_description import DataDescription
from ml4ht.data.defines import SampleID, LoadingOption, Tensor, Batch
from ml4ht.data.util.data_frame_data_description import DataFrameDataDescription
from ml4h.TensorMa... |
b2b524fe7d3c643cb4fc1233a03ad3d801a79c5d21a4d9a5c30875da0db417ba | Python | 6,069 | 194 | import math
from typing import Optional, TypedDict
try:
from datasketches import kll_doubles_sketch
_DATASKETCHES_AVAILABLE = True
except ImportError:
_DATASKETCHES_AVAILABLE = False
class DistributionStats(TypedDict):
"""Statistics calculated by a ``DistributionTracker``."""
num_samples: int
... |
4fee4eff941dd8353103ebca59191266badacfbb4f66ccf980fa6d5edc4a124a | Python | 6,076 | 102 | import os
import numpy as np
import pandas as pd
from utils.tools import create_directory
from utils.regressor_tools import *
from utils.experiments_tools import *
from utils.plot_tools import *
from utils.constants import *
if __name__ == '__main__':
for problem in problems:
print("#################... |
34d830d29aa1147bf0779101c318a69945b5bc5670bc3416aea4fe35c5a96435 | Python | 6,080 | 172 | import numpy as np
from sklearn.metrics import matthews_corrcoef, confusion_matrix, roc_curve, auc, precision_recall_curve
import prettytable as pt
import torch
def eval_metrics(probs, targets, cal_AUC=True, cal_PRC=True):
threshold_list = []
for i in range(1, 50):
threshold_list.append(i / 5... |
bd8b5acfccb107cd67a046e804aceb9958921685efa4a39327d129a304a232ad | Python | 6,080 | 146 | """Apple-Silicon (MLX/metal) edge-SGD for non-parametric UMAP.
Mirrors :func:`._sgd.optimize_layout_torch` but runs the gradient
computation on Apple's MLX (metal) backend — the same Apple path
omicverse already uses for PCA (``_pca_mlx.MLXPCA``) and Harmony, rather
than torch-MPS (MLX has the float64/sparse coverage ... |
286c8d9f7617468f52297712957271e8f3c2954fb6cdb341c78c0fe651233fc5 | Python | 6,082 | 158 | # -*- 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.
#... |
19f9910277030f4d8a5fbde55657242ff76847a4ba53d6f38e40bf8c9f3fc31b | Python | 6,083 | 166 | # -*- coding: utf-8 -*-
import numpy as np
from scipy.stats import pearsonr
from sklearn.metrics import r2_score
def score_voxelwise(ground_truth, prediction, masker, loss, multioutput="raw_values"):
"""
Calculate loss function for predicted, ground truth arrays.
Supported scores are R2, correlation, and ... |
cf539e90e9c1a07785a2e01842b4b381549a82c5449149abd33592b84d5e46ef | Python | 6,085 | 164 | #!/usr/bin/python
# -----------------------------------------------------------------
# Plot an overview for a single gene:
# TODO LIST:
# 1. Plot it on a UMAP
# 2. Plot % of cells with it for each cell type
# 3. Show if it has specificity to any neuronal subtype (Exc or Inh)
# 4. Show if it has specificity to any regi... |
36c365473d4df463e2a3486f752720507d2e2f3aab1f8d90defa5a0dd8c9b615 | Python | 6,088 | 186 | import os
from itertools import repeat
import numpy as np
import torch
from torch_geometric.data import Data
from torch_geometric.utils import subgraph, to_networkx
from .molecule_datasets import MoleculeDataset
class MoleculeDataset_graphcl(MoleculeDataset):
def __init__(
self,
root,
t... |
8d3784cd13f084132904f3d25d2726034ffd27b377f9320db18b6ea4c0f173b4 | Python | 6,089 | 172 | """
Tests for :mod:`mozaik.tools.experanto_chunks`.
The chunk JSON is a contract between two other modules -- ``RandomizedExperanto`` builds the
stimulus sequence from it, and the chunk exporter checks recorded presentations against it -- and
which stimuli land in which chunk decides what each datastore ends up holdin... |
3bb7300995a39065868d09c4c82b6a4ed2590210a6d44e4d8a745ccfdd507206 | Python | 6,091 | 159 | # -*- coding: utf-8 -*-
"""
pre-processing.py
Created on 08-11-2023
@author: Lorenzo Monti
@email: lorenzo.monti@inaf.it
Pre-processing process in order to prepare the dataset
"""
import pandas as pd
import numpy as np
import glob
from scipy.interpolate import splrep, BSpline, make_smoothing_spline
import matplotli... |
2a88407394f4192320c47f852ec4865de69f437cc3810c6047f6795211b0dc18 | Python | 6,092 | 160 | #
# 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... |
f8bf144473a2fd26518edabbca5cb6b3ec394ac659f72d10dd1b367856118a6c | Python | 6,093 | 126 | """Cell-group (sender -> receiver) summary of cellular-resolution CytoSignal scores.
CytoSignal tests every interaction *at each receiving cell* ``i``: the score
``S[i, k]`` combines the ligand that reaches ``i`` from its spatial neighbours
(Gaussian epsilon ball for diffusible, Delaunay neighbours for contact-depende... |
4feb6bb60d9442a7b206835be68a7aab48c643c3fc6d8dca379259fc73c1bdcd | Python | 6,094 | 200 | import contextlib
import os
from abc import ABCMeta, abstractmethod, abstractproperty
from typing import Any, List, Optional, Sequence, Tuple
import torch
class Agent(object, metaclass=ABCMeta):
"""Abstract agent class."""
training = True
@abstractmethod
def act(self, obs: Any) -> Any:
"""S... |
66f6c1425057031856d9578e68f0dd729cb5c81bf38a004dc841ef03abab7bed | Python | 6,094 | 185 | import numpy as np
import scipy.sparse
import spinnaker2.neuron_models
class Population(object):
"""
Group of neurons with the same neuron model.
"""
_pop_count = 0
def __init__(self, size, neuron_model, params, name=None, record=[]):
"""
TODO: think of setting the record flag to ... |
de15f2a7a0a7b007126f33044cc82e43e0a0b9ed622268959590c51c4fb075e5 | Python | 6,095 | 145 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python version: 3.10.9
pandas version: 1.5.0
numpy version: 1.23.3
ptitprince version: 0.2.6
seaborn version: 0.11.0
matplotlib version: 3.6.3
"""
#%% Import Modules
import pandas as pd
import numpy as np
import ptitprince as pt
import seaborn as sns
import matplotlib... |
108ee829b3d226134abc285200913cd45d5f1eb4d9b54d77e7bddd470e36ea02 | Python | 6,096 | 160 | #!/usr/bin/env python3
import os
import sys
from datetime import datetime
import argparse
import subprocess
import numpy as np
from aptnn.io.xyz import Trajectory
from aptnn.box import Box
import torch
# Home directory of all aptnn related scripts
scriptpath = os.path.dirname(__file__)
# Command line argument pa... |
7d1e86e7436154047f69bc21f849ef9e5b8bdbeb4ca4eb8c622c3ffdce7568fd | Python | 6,096 | 165 | import logging
import os
import platform
import sys
import time
import ray # noqa F401
# Import ray before psutil will make sure we use psutil's bundled version
from ray._common.utils import get_system_memory
import psutil # noqa E402
logger = logging.getLogger(__name__)
def get_rss(memory_info):
"""Get the... |
d782d67ee6df9b4709438110258a65fd44a57d29eb9131f9077ee6dfcb945cd2 | Python | 6,096 | 150 | import os
import sys
sys.path.append(os.getcwd())
from gensim import corpora
from gensim.models import TfidfModel
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from sklearn import preprocessing
from scipy import stats
from matplotlib.colors import LogNorm
import re
def tf... |
1f9a15d1e8ebc3ec8b52d62d26a88fec161c3532b4d78facfc1d7b8fd3595275 | Python | 6,097 | 181 | # 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, ... |
e2f4f815647bffc79d59f0597d16aa2abdc40edda123c66d2128c1896a2fcd4d | Python | 6,097 | 143 | import anndata
import numpy as np
import pandas as pd
from tqdm import tqdm
from numpy.random import choice
def generate_simulated_data(sc_data, outname=None,
d_prior=None,
n=500, samplenum=5000,
random_state=None, sparse=True, sparse... |
a6c7d08a800718c5c5283d51ab6f814391e56fbc13fa35381debda11492c558f | Python | 6,098 | 220 | # coding: utf-8
import copy
import os
import sys
from unittest import mock
import pytest # noqa
from ray.autoscaler.v2.instance_manager.instance_storage import InstanceStorage
from ray.autoscaler.v2.instance_manager.storage import InMemoryStorage
from ray.core.generated.instance_manager_pb2 import Instance
def cre... |
3269b3c7a6eaf385e626c468aa00cf6f4dff7010b89adbce24522fab740b9a21 | Python | 6,099 | 142 | # -*- coding: utf-8 -*-
"""Imported from https://github.com/prlz77/ResNeXt.pytorch/blob/master/models/model.py
and added support for the 1x32x32 mel spectrogram for the speech recognition.
Creates a ResNeXt Model as defined in:
Xie, S., Girshick, R., Dollár, P., Tu, Z., & He, K. (2016).
Aggregated residual transform... |
7a46207b35a7deaa13c995b7d657e3a214a8504f0ffe747897d96547ab56243a | Python | 6,099 | 156 | """
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 os
from typing import TYPE_CHECKING, Any, ClassVar
import numpy as np
import pandas as pd
from ... |
3e6fa9d33abe7731989770f91810f1c74e4fe8a64fcd0bf7e2b45a552f2c2311 | Python | 6,100 | 208 | import torch
import numpy as np
from .model import reconstruction_loss
def train_one_epoch(
model,
data_types,
dataloader,
optimizer,
epoch,
device,
):
model.train(True)
optimizer.zero_grad()
omics_num = model.omics_num
loss_rec_epoch = [0 for _ in range(omics_num)]
loss_... |
bf631357ed3e059b960017bedaed4fd1c0594ded28b33372866bb215a8a3a564 | Python | 6,100 | 177 | import numpy as np
from copy import deepcopy
class SimpleContext():
def __init__(self, context_dim, stickiness, concentration, try_reset_h):
self.context_dim = context_dim
self.stickiness = stickiness
self.concentration = concentration
self.try_reset_h = try_reset_h
self.pr... |
f31d32e316eb028abf7d8c39c4b921a7c51aa41a42c295611ae0f792df0ff588 | Python | 6,100 | 184 | # coding=utf-8
# Copyright 2023 HuggingFace 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 applicable law or ag... |
a863c48469cf7706353145dd73113b32bd965ad6fbaa1a3306d168b4d8507add | Python | 6,103 | 161 | import torch
from ..utils import common_functions as c_f
from ..utils import loss_and_miner_utils as lmu
from ..utils.module_with_records import ModuleWithRecords
class CrossBatchMemory(ModuleWithRecords):
def __init__(self, loss, embedding_size, memory_size=1024, miner=None, **kwargs):
super().__init__(... |
6109b06d179132d1cc767d4266bd185e3a7e7a4865e866efc418768092953c2a | Python | 6,104 | 134 | import os, pickle, sys, datetime, logging
import pandas as pd
sys.path.append(os.path.join(os.getcwd()))
from Data_Managment.publication_sanitisation import sanitise_publication
# APIs
from pymed import PubMed
from misc.Icite_API import get_citation_single, get_citations
from multiprocessing import Pool
from misc.sa... |
63818f273324f3c4a0b0413a1c703d1e1f43e0cc372e8109d2e70587e5a3662d | Python | 6,105 | 187 | """Tests for ci.ray_ci.ray_image.RayImage."""
import sys
import pytest
from ci.ray_ci.configs import DEFAULT_ARCHITECTURE
from ci.ray_ci.docker_container import RayType
from ci.ray_ci.ray_image import IMAGE_TYPE_CONFIG, RayImage, RayImageError
class TestWandaImageName:
DEFAULT_TEST_CUDA_PLATFORM = "cu12.1.1-cud... |
f23edcf44f839b344e821390972874e9a23bdd4d4fdd534e7988f860a4c8f468 | Python | 6,109 | 211 | from typing import Union, Iterable
import os
import numpy as np
import torch
import torch.nn.functional as F
from rdkit import Chem
import networkx as nx
from networkx.algorithms import isomorphism
from Bio.PDB.Polypeptide import is_aa
class Queue():
def __init__(self, max_len=50):
self.items = []
... |
031af46db0709baf20879abd246cbb94ffe3ad093c927aacf014a0efeba96567 | Python | 6,113 | 176 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
for type in ["donor", "acceptor"]:
targets = ["5_GET_REF_JUNCS_MANE", "6_GET_REF_JUNCS_REFSEQ_ALTS", "4_GET_BAM_NEG_OPP_STRAND_JUNCS"]
X_axis = ["Positive_MANE", "Positive_ALT", "Negative_1"]
barWidth = 0.25
dataframes = []
don... |
84e37df291647a6e05a7af3445ed070738709d6383ff8d48f102a803a1ddad50 | Python | 6,113 | 133 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""
"""
import argparse
import pysam
def merge_annotations(vcf, protein_coding_vcf, lincRNA_vcf, promoter_vcf, noncoding_vcf):
record_iter = zip(vcf, protein_coding_vcf, lincRNA_vcf,
promoter_vcf, noncoding_vcf)
gene_classes = ['PROTEIN... |
18ec58044c0c2d38e505356617154bea978bec1e31879e805d109ecfc5944acb | Python | 6,114 | 160 | '''
Keras implementation of BL network
'''
import tensorflow as tf
class BLConvLayer(object):
'''BL recurrent convolutional layer
Note that this is NOT A KERAS LAYER but is an object containing Keras layers
Args:
filters: Int, number of output filters in convolutions
kernel_size: Int or... |
0c60851e20b15990b71239e37133553d00a4f2d9d0b31617426d0daec0a6f50a | Python | 6,115 | 152 | import numpy
import os, glob
import json
import random
from skimage import filters
from collections import defaultdict
class DatamapGenerator:
"""
Creates a `DatamapGenerator` that allows to create a datamap
Only one mode is available:
- `real`: Samples from real datamaps
"""
def __init__(
... |
bd905c59da32046fa20d8ab18bc62e5bd046fd257ed12254cf92d13e7a851ff6 | Python | 6,115 | 140 | # -*- coding: utf-8 -*-
"""Differential phase contrast with space-time modeling.
This module contains the forward models for differential phase contrast (DPC) and differential phase contrast with
space-time modeling. The loss functions used for the DPC reconstruction are also provided.
"""
import numpy as np
import j... |
2c32d829922693db6a36ab8e95f331f90f09fca88677b2b7080130d8b3928e89 | Python | 6,118 | 130 | import numpy as np
import torch
import torch.nn.functional as F
from typing import List, Dict, Tuple, Callable
import lib.data_utils.dynamic_data_util as ddu
from lib.data_utils.movie_processing import multiresolution_spatial_basis_application
def frame_rate_wn_lnp_multidata_bin_spikes(
wn_movie_blocks: Lis... |
0f2b274d68c872de4a5f59c4bc0ac053ceb00deccdcabb9b62344d664ca36dcf | Python | 6,119 | 168 |
import torch
import torch.nn as nn
#import torchvision.transforms.functional as F
class Attn(nn.Module):
def __init__(self, channels: int):
super().__init__()
self.channels = channels
self.filter_x = nn.Sequential(
nn.Conv3d(channels, channels, kernel_size=1, stride=1, padding=... |
73555d532de0de58746c2d76da530100d6c05b8ed544eefa9530c88dc0c6d151 | Python | 6,119 | 149 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Python version: 3.10.9
pandas version: 1.5.0
numpy version: 1.23.3
ptitprince version: 0.2.6
seaborn version: 0.11.0
matplotlib version: 3.6.3
"""
#%% Import Modules
import pandas as pd
import numpy as np
import ptitprince as pt
import seaborn as sns
import matplotlib... |
1e6c944bb1825cb4f5a97f2fb7d9224160dec8db4b411f7b005cca222318910e | Python | 6,120 | 138 | import pandas as pd
import os
import sys
def get_hg38_chrom_size():
f_chrs = open("../hg38_chrom_size.tsv", "r")
lines = f_chrs.read().splitlines()
chrs = {}
for line in lines:
eles = line.split("\t")
chrs[eles[0]] = int(eles[1])
return chrs
def main():
chrs = get_hg38_chrom_s... |
85ad35ec44a593f1c6176fa6c17431bf055d2abde23363086546a3157cc62008 | Python | 6,125 | 210 | """Unit tests for AIR telemetry."""
import json
import os
import sys
from unittest.mock import MagicMock, patch
import pyarrow.fs
import pytest
from packaging.version import Version
import ray
from ray import train, tune
from ray._common.usage.usage_lib import TagKey
from ray.air._internal import usage as air_usage
... |
eb3208a8e319b1c2e34a9d1da4cdc460867190eb637b2c674ebaaffbdf4cba1d | Python | 6,126 | 166 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
import zlib
# Third-party imports
import pandas as pd
import pyspark.sql.functions as F
import pyspark.sql.types as T
from pyspark.sql.window import Window
f... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.