sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
777d0bc696bed29deca556281b2e76b9d62eb32083d79605aa07600893d9d3ec | Python | 1,966 | 73 | import torch
from torch import nn
from torch.nn import functional as F
import numpy as np
class INIT(nn.Module):
def __init__(self):
super(INIT,self).__init__()
self.conv1_unit=nn.Conv2d(in_channels=1, out_channels=1, kernel_size=3, stride=1, padding=1,bias=False)
self.c... |
c5e0bf50eff2bcd0e6a0fe18c63e248634bab28c52cd44eb2947c6862c0235c5 | Python | 1,967 | 33 | """Check cached fractions against direct geometry on offset native grids."""
from pathlib import Path
import tempfile,os
os.environ.pop('PROJ_LIB',None);os.environ.pop('PROJ_DATA',None)
import numpy as np,rasterio
from rasterio.transform import from_origin
from shapely.geometry import box
from population_overlay import... |
0b275e981bfb2403f4fba8dc117809ac3889824423f82d4e04d9d2db739fd107 | Python | 1,969 | 80 | """
Tests the usecols functionality during parsing
for all of the parsers defined in parsers.py
"""
from io import StringIO
import pytest
import pandas as pd
import pandas._testing as tm
xfail_pyarrow = pytest.mark.usefixtures("pyarrow_xfail")
skip_pyarrow = pytest.mark.usefixtures("pyarrow_skip")
_msg_pyarrow_req... |
3b88f0310250ffe9731730916eff86a983a12895ed9abe09712e16d86684b0ec | Python | 1,969 | 58 | import re
from collections import namedtuple
from typing import Optional
import ngs_tools as ngs
import pysam
from typing_extensions import Literal
Technology = namedtuple('Technology', ['name', 'chemistry', 'additional_args'])
BARCODE_UMI_TECHNOLOGIES = [
Technology('dropseq',
ngs.chemistry.get_c... |
4070d3a09a96278f26016a16d498a31d006bb43fad79049a60dfefd4bf3ad2bd | Python | 1,969 | 50 | import os
import pysam
def convert_vcf_to_bed(vcf_path):
bed_path = vcf_path.replace(".vcf", ".bed")
with open(bed_path, "w") as bed_out:
for record in pysam.VariantFile(vcf_path):
if "BND" in str(record):
continue
record_chrom = record.contig
i... |
526f432843f13570de1218f049b015cfec6e87783099a983ae5956c621bbfc97 | Python | 1,969 | 48 | # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
e416b25ccd48ce68ac86c7a074c9060c50288c2b51711cce4c7e61163f32a904 | Python | 1,970 | 69 | import sys
import pandas as pd
stories = sys.argv[1:]
def match_story(x):
for y in stories:
if y.lower() == x.lower():
return y
return x
def get_date(x):
_x = x.split('_')
found = False
for __x in _x:
if __x.startswith('201'):
found = True
year ... |
f4bf71d258872006319fd717ed0ddf4e974fb8e4d4ca289993485836deef11a6 | Python | 1,970 | 47 | from Environment import *
from Parameter import *
def data_list(train_data, ratio, test_id, save_list, test_single=None, test_whole_brain=None):
path = train_data
name_list = os.listdir(path)
name = []
for vlaue in name_list:
protions = vlaue.split('.')
line = '{}\n'.format(protions[0])... |
72c4ebd7a254daf3410a428b34017c084e49e0665022d51bccccd90487b54417 | Python | 1,973 | 57 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Step S6p (CheckM): Run CheckM taxonomy workflow.
This helper integrates CheckM taxonomy workflows with BASALT by
driving CheckM on selected binsets and reading back the results.
"""
import pandas as pd
# import seaborn as sns
# import matplotlib.pyplot as plt
from Bi... |
8ec44ab67fc356467ac7c62eff8d175f447d2b01b2f7da61a04cf1dc9efa129a | Python | 1,973 | 49 | import numpy as np, matplotlib.pyplot as plt, sys
import wormdatamodel as wormdm
plt.rc("xtick",labelsize=18)
plt.rc("ytick",labelsize=18)
to_paper = "--to-paper" in sys.argv
im_fname='off_target_xy_image.png'
im=plt.imread(im_fname)
folder = "/projects/LEIFER/francesco/pumpprobe/AKSxneuropal/20211021/pumpprobe_20... |
84dd6430e567dd50b6855a549101a2d983ee48e5d338a36c895ef4ed88733298 | Python | 1,974 | 57 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# ex: set sts=4 ts=4 sw=4 et:
"""
.. _annotations_lda:
==================
LDA topic modeling
==================
This example trains a latent Dirichlet allocation model with scikit-learn
using abstracts from Neurosynth.
"""
i... |
eee594c3175ae7f73609083895da2b0c2be71b891e5073f4a26ef61523e990b4 | Python | 1,975 | 85 | import pathlib
import os
import numpy as np
home = os.getenv('PT_DATA_DIR')
if home is None:
home = str(pathlib.Path.home())
WEIGHTS_DIR = home + '/sm_weights/'
# It's helpful to separate out the twenty canonical amino acids from the rest
CAN_AAS = 'ACDEFGHIKLMNPQRSTVWY'
AMB_AAS = 'BZX'
OTHER_AAS = 'JOU'
ALL_AA... |
f8078f46af943e2799fb61d111a89f83072770b5ebca0180f95a0d934ed3c6ae | Python | 1,977 | 51 | import numpy as np
class CategoricalQ:
def __init__(self, n_atoms, v_min, v_max):
self.n_atoms = n_atoms
self.v_min = v_min
self.v_max = v_max
self.delta_z = (v_max - v_min) / (n_atoms - 1)
def distr_projection(self, next_distr, rewards, dones, gamma):
"""
Perf... |
dc11ec9509d4c647d54a62563aa8d95a63083831316cccd951a49a11b9554993 | Python | 1,978 | 48 | from pkg_resources import parse_version
from configparser import ConfigParser
import setuptools
assert parse_version(setuptools.__version__)>=parse_version('36.2')
# note: all settings are in settings.ini; edit there, not here
config = ConfigParser(delimiters=['='])
config.read('settings.ini')
cfg = config['DEFAULT']
... |
180757ef5ce3f1fd3afecad645305377ea9ca11a3d24953ec7437b1a420eb939 | Python | 1,979 | 46 | def compute_terrain_factor(samples, terrain):
'''
This function computes the ratio of the amount of fluid data in a sample or a batch of samples vs the total amount
of data in the samples. This factor is used to correct the loss, where samples with more terrain have a loss that is
underestimated (data i... |
1cfe67f9376dc5c87103dd4ae1e9d140717ce699dc130bb4d73cee562bdd1062 | Python | 1,979 | 53 | """Test nimare.dataset (Dataset IO/transformations)."""
import os.path as op
import nibabel as nib
import numpy as np
import pytest
import nimare
from nimare import dataset
from nimare.tests.utils import get_test_data_path
def test_dataset_smoke():
"""Smoke test for nimare.dataset.Dataset initialization and get... |
ef61446e9741376053ffa458ed1f12ec5cc865b8cafffb226c1d59f986477d87 | Python | 1,979 | 60 | """ObjectStore factory — single entry point the rest of the app uses.
The driver is selected once at process start based on
``PYCARET_STORAGE_BACKEND`` and cached. Tests can override via
``reset_for_tests`` so each fixture spins up its own local-fs root.
"""
from __future__ import annotations
import threading
from t... |
097030c6e0c7506e34c0e7e10d4bbbf94344220104b846ddd12cec3decdbcccc | Python | 1,983 | 52 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by Roberto Preste
import click
import sys
from mtoolnote.constants import SPECIES
from mtoolnote.human import HumanAnnotator
from mtoolnote.nonhuman import NonHumanAnnotator
@click.command()
@click.version_option()
@click.argument("input_vcf")
@click.argument("... |
b4b633a2df64f0898f5ed8b565f58ea2434295ba6fe4f912116fe032c0107cba | Python | 1,984 | 58 |
# TODO: color lines with ==> using `colorama`
# TODO: add a step to verify that the genome build is correct using detect_ref (once on first 10k of each input file, and again on `sites`)
from ..utils import fmt_seconds
import time
import importlib
from typing import List
scripts = '''
phenolist verify
parse_input_f... |
d789875c35e3263da97067862612c1ec2027daa0df68cdf24d24be354d1e12e0 | Python | 1,984 | 56 | # Copyright 2018-2025 Xanadu Quantum Technologies 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... |
412c75cfb1ad2be6c9fedabd87740a366b733b344b1118c644974c43eac396c0 | Python | 1,987 | 49 | #! /usr/bin/env python
import os.path
import glob
#import argparse
import subprocess
def createLongitudinalSurfaceScripts(minL=3):
#Directory where the data is. One subfolder per subject.
targetDir = '/cis/home/younes/MorphingData/TimeseriesResults/'
#python directory for registration
source = '/cis... |
b6b28e7e64d35587a243017893c73da17282b54018a30a5ed85c0f29e41770e1 | Python | 1,988 | 65 | import numpy as np
import pandas as pd
try:
import pandas.core.computation.expressions as expr
except ImportError:
import pandas.computation.expressions as expr
class Eval:
params = [["numexpr", "python"], [1, "all"]]
param_names = ["engine", "threads"]
def setup(self, engine, threads):
... |
a704fe1e2ae5ae3f90e7ed1f02945c15c90a623d23e64fa18f9147c052fce19a | Python | 1,989 | 55 | import tensorflow as tf
import numpy as np
from skimage.transform import resize
import os
PB_FILE = os.path.join(os.path.dirname(__file__), "models", "extractor", "graph_v2.pb")
CHECKPOINT_DIR = os.path.join(os.path.dirname(__file__), "models", "extractor", "v2")
class Extractor:
def __init__(self):
sel... |
e214b21501495e6d9270576d00387260760f9808cd3604a4405e3f0a2039c9a3 | Python | 1,989 | 66 | """Test CLI argument types."""
import argparse
import pytest
class TestConfigFile:
"""Test the config_file type validator."""
def test_config_file_valid(self, tmp_path):
from lightning_pose.cli.types import config_file
f = tmp_path / "config.yaml"
f.write_text("")
result = ... |
f37a28f950791b3e7491c204529344be0b2c1111268f78d0b9e17fab07f8fb58 | Python | 1,989 | 64 | from datetime import UTC
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestTZLocalize:
# See also:
# test_tz_convert_and_localize in test_tz_convert
def test_tz_localize(self, frame_or_series):
rng = pd.date_range("1/1/2011", periods=100, freq="h")
... |
107c1e6ae60d24f21e316c5ff1a3b1786c3f822a9b89b21e42a0a9948e9e9d7a | Python | 1,990 | 69 | #!/usr/bin/env python
'''
Testcases for the yaml tools
'''
import windseer.utils as utils
import windseer
import os
import unittest
windseer_path = os.path.dirname(windseer.__file__)
config_filename = os.path.join(
os.path.split(windseer_path)[0], 'configs', 'example.yaml'
)
config_wind_filename = os.path.jo... |
4c6c7e1f5b180fe06a843dd0862a930d5ad1fb64d73fd3c1f286f698eae509f4 | Python | 1,990 | 74 | from copy import deepcopy
import pandas as pd
from sklearn.pipeline import Pipeline
from sklearn.utils.validation import check_is_fitted
from pycaret.internal.logging import get_logger
def is_sklearn_pipeline(object):
from sklearn.pipeline import Pipeline
return isinstance(object, Pipeline)
def is_sklear... |
bc2288ee3ce1f2dd885f81fc43daaab74109d25fea4f1996f0dd531455dcae51 | Python | 1,990 | 52 | import io
import zipfile
from pathlib import Path
import requests
def fetch_test_data_if_needed(dir: Path, dataset_name: str) -> None:
datasets_url_dict = {
"test_cropzoom_data":
"https://github.com/paninski-lab/lightning-pose-test-fixtures/releases/download/v1/"
"test_cropzoom_da... |
560e0c8f66de0c463fc136bd0c3d92287e4d907e992d2306bb9d70ece4fd4cab | Python | 1,992 | 61 | from unittest.mock import Mock
import pytest
import pyaging.utils as utils
import pyaging.utils._utils as utils_module
def test_download_is_public_and_uses_cached_flat_basename(monkeypatch, tmp_path):
cached_path = tmp_path / "metadata.csv"
cached_path.write_text("cached")
logger = Mock()
urlretriev... |
665ffc16b0f41ee28dab59a24b9ca57d6259fb8c5f798f27a3365bf5be93801c | Python | 1,993 | 64 | #####################################################################################################################
# Date created : 10/21/2022
# Date modified: 10/21/2022
# Purpose : To generate features from PSSM
###############################################################################################... |
78dfe493a47c1fdb1f36781d7eefcac0429abea562109d74c85444c020df70bc | Python | 1,993 | 79 | from math import floor
class Config():
def __init__(self) -> None:
self.defaultConfig()
pass
def defaultConfig(self,):
self.displayINFO()
self.subINFO()
self.expINFO()
self.connectINFO()
self.tkinterINFO()
pass
def sub... |
38d8922de495965bdcb359c3ca9c9bd6761f2ef930f31f8c92b64f29ce89848b | Python | 1,994 | 72 | import time
import logging
import os
import numpy as np
import torch
import ismrmrd
import gadgetron
from modules.schemas.edsr_sr import (
EdsrModel,
EdsrPretransformations,
EdsrPosttransformations,
)
from modules.schemas.mlc_tracking import (
MLCImageArrayParser,
MLCSocketmake... |
45760c62fe3aebc4b8036a857b40ca438ab3aca581300f871aff41a6744af8d2 | Python | 1,996 | 53 | #Runs and saves results of sweeps over time constants for 1 fields.
#Date written and executed: 2021-12-18
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
from placerg.avafunc import *
N0 = 4096 # number of cells
N = 1024 # numb... |
ac8291e77bebf2f3b5cb2718a7c5a69993150b1d2c99a8c338d3416fda8a93a5 | Python | 1,998 | 79 | import pandas as pd
import pytest
from pycaret.datasets import get_data
def test_datasets():
#########################
# Load Local File ####
#########################
# # loading dataset
# os.chdir(os.path.dirname(os.path.realpath(__file__)))
# data = get_data("test_files/dummy_dataset")
... |
bf1b204f6d2f8ef4758a049b16c5905c62058bb914e17c1b8751d624053f532b | Python | 1,998 | 76 | #!/usr/bin/env python
"""
Neural network architectures used in the BASALT DL modules.
"""
import torch.nn as nn
class LBR(nn.Module):
"""
Linear -> BatchNorm -> ReLU block used as a building unit.
"""
def __init__(self, hidden_size):
super(LBR, self).__init__()
self.fc1 = nn.Linear(... |
812cb9386a70559ce8bfbe28c45192eaba43e4a0d580e793ce693d51974abe1b | Python | 1,999 | 71 | import time
import logging
import torch
import numpy as np
import ismrmrd
import gadgetron
from modules.schemas.bicubic_sr import (
BicubicModel,
BicubicPretransformations,
BicubicPosttransformations,
)
from modules.schemas.mlc_tracking import (
MLCImageArrayParser,
MLCSocketmak... |
f7a1033cb11bca4282bbdb255040134e4c2dc78c5d23d18e995fbaff29238380 | Python | 1,999 | 54 | """This script runs the preprocessing of the raw EEG data.
The preprocessing chain is defined in lemon_preproc.yml - you can adapt the
preprocessing by changing the values in this file.
The script can be set to preprocess just the single example subject by changing
'subj' in the main body.
"""
import os
import osl... |
fa950263c9bc89ce206069a2b007eaabc395093c6cfa60e1c7bae9ce98b2465d | Python | 2,000 | 78 | """Sphinx configuration for the BASALT documentation."""
from __future__ import annotations
import os
project = "BASALT"
author = "PKU-EMBL Laboratory"
copyright = "2023–2026, PKU-EMBL Laboratory"
version = "1.2.2"
release = "1.2.2"
extensions = [
"myst_parser",
"sphinx_copybutton",
"sphinx_design",
]
... |
2de83348206eac5ec936d7949e9a1ff4311b5e132146f95f0a63259de5a6c5ec | Python | 2,002 | 76 | from datetime import (
UTC,
datetime,
)
from zoneinfo import ZoneInfo
import pytest
import pandas as pd
from pandas.tseries.offsets import (
BMonthBegin,
BMonthEnd,
BQuarterBegin,
BQuarterEnd,
BYearBegin,
BYearEnd,
MonthBegin,
MonthEnd,
QuarterBegin,
QuarterEnd,
Ye... |
ba4372a6747822d7dce962d29d87a9329cb0bf331b467357ed7f1d5c8673a728 | Python | 2,003 | 40 | # Copyright (c) 2018-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... |
1d939af4a0f88a4ab7ece15d97735f5188fbca3215d525b7d1921f70716656c1 | Python | 2,004 | 57 | #testing.py
'''
Old Module:
'''
#
# # Import everything:
# import sys
# sys.path.append("..") # Adds higher directory to python modules path.
# from old_module.config import *
# from old_module.comparative_visualization import *
# from old_module.spacetimecube import *
# from old_module.data_visualization import *... |
671620bcd24fb3d82f654cb8a0c764810f90fec6670eb213801347b329ae74e1 | Python | 2,004 | 59 | # -*- coding: utf-8 -*-
"""
Created on Fri Feb 9 14:52:57 2023
@author: Elida
"""
import os
import BTools as bt
import numpy as np
import generate_parameters as gp
import time
inicio = time.time()
inicio=time.time()
def main():
# Input Parameters (default settings change them for your applic... |
e8093c43162eb29eba307063e1df176c8800e84ded2ad341f6221642c35143d1 | Python | 2,004 | 43 | #!/usr/bin/python
import os
import numpy as np
import argparse
from read_grd import create_blockMeshDict
from stl import mesh
def generate_blockMeshDict(stl_file, block_mesh, infile='blockMeshDict.in', nx=128, ny=128, nz=128, pad_z=3.0):
if os.path.basename(block_mesh) is not 'blockMeshDict':
print "Warni... |
7d8500902c46bb6fbf57da61da3785c2a1b845b78639ed0bdf27fd369d8701ee | Python | 2,005 | 64 | #!/usr/bin/env python
from setuptools import setup
import sys
import os
if sys.version_info[0] < 3:
print("Sorry, but wordfreq no longer supports Python 2.")
sys.exit(1)
classifiers = [
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT Lic... |
cbfcef15186640aac5e94fa86ccca21477520124518ade71a51280edf5a32bef | Python | 2,005 | 40 | # Copyright (c) 2012-2019, NECOTIS
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# - Redistributions of source code must retain the above copyright notice,
# this list of conditions and th... |
e0fee9c46d1aa4479b943ced3008f3bf16a9086696e851889052998dc1f8a5ad | Python | 2,006 | 48 | """Optional rollout KL reference stays fixed through all PPO mini-epochs."""
import pytest
import torch
from tests.test_ppo_masking import make_ppo_agent
from tests.test_sac_correctness import SameStepFakeVecEnv
@pytest.mark.parametrize('reference', [None, 'previous_mini_epoch', 'rollout'])
def test_kl_reference_ac... |
5d35ce7151ceb64cc6b0a1a3d3ecf5733ceb5b0fa996202e45d08e93d9896d85 | Python | 2,007 | 74 | import numpy as np
from numpy.fft import fftshift, ifftshift, ifftn
from typing import List, Optional, Sequence, Tuple
def ifftnd(kspace: np.ndarray, axes: Optional[Sequence[int]] = [-1]) -> np.ndarray:
"""
Compute the n-dimensional inverse Fourier transform of the k-space data along the specified axes.
... |
cf36ddee3982caeca26f7a6766689e2eb9b3e970fda5e88d777bb1e9ed71e614 | Python | 2,008 | 54 | import torch
import pandas
import numpy
ligandInput = pandas.read_csv('data/ligandScreen-Ligands.tsv', sep='\t', low_memory=False, index_col=0)
inName = ligandInput.columns.values
ligandInput = ligandInput.loc[:,inName]
sampleName = numpy.array(ligandInput.index.values)
X = torch.tensor(ligandInput.values.copy(), dtyp... |
e448eaa142a8feab867c6abf80261aeedaf2cdcda2e1487209f30bfa5640dfbd | Python | 2,008 | 62 | import numpy as np
def ESS_sampling(log_L, Sigma, f, **hyperparams):
nu = np.random.multivariate_normal(mean=np.zeros_like(f), cov=Sigma)
u = np.random.rand()
log_y = log_L(f, **hyperparams) + np.log(u)
# print(log_y)
# print('1', f)
theta = np.random.rand() * 2 * np.pi
theta_min... |
3becf9ec58d2e245de09c6f7e07eb54fef83cbad4b97968106f989430ffa024b | Python | 2,009 | 53 | #Runs and saves results of sweeps over time constants for 5 fields.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
from placerg.avafunc import *
N0 = 4096 # number of cells
N = 1024 # numb... |
312557b45d08664f1e8112a7962e945d7b46b860d0d008cbd7ff8d74d38dcd42 | Python | 2,011 | 43 | #! /usr/bin/env python
##############################################################################
## DendroPy Phylogenetic Computing Library.
##
## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder.
## All rights reserved.
##
## See "LICENSE.rst" for terms and conditions of usage.
##
## If you use this wo... |
5bdc4ddb6d71721f30252800abfeffa8fe00b02ae497306fb5265e553604523a | Python | 2,011 | 54 | """
.. _segmentation:
====================================================
Segmentation of the Cortical Gradient
====================================================
Gradec provides two methods for splitting the gradient spectrum.
"""
from gradec.fetcher import _fetch_principal_gradients
##########################... |
176f5a12dc9a832a0c6996acada07921a005dc0e83a8ffb55ad433afbdad4116 | Python | 2,012 | 67 | import sys
import argparse
def parse_settings(path):
settings = {}
with open(path, 'r') as f:
in_settings = False
for line in f:
if line.strip().startswith('MODEL SETTINGS:'):
in_settings = True
elif in_settings:
if not line.strip():
... |
3991d161b12d2810db5124008d86f1cd7133654286719637417af6c1cb83e911 | Python | 2,014 | 57 | #!/usr/bin/env python3
from SALib.analyze import sobol
import numpy as np
import sys, getopt
import csv
import utils
data_folder = '../data/'
output_folder = '../output/'
inputfile = "qoi.csv"
outputfile = 'sobol'
sobol_index = 'All'
opts, args = getopt.getopt(sys.argv[1:], "h:i:o:s:", ["ifile=", "ofile=", "sfile="])... |
27b33eed6fc68a91585bd772d89c4b59bdda461eb1c3fd0fa85affa0393e20a5 | Python | 2,016 | 64 | import torch
import torch.nn as nn
import geffnet
sigmoid = nn.Sigmoid()
class Swish(torch.autograd.Function):
@staticmethod
def forward(ctx, i):
result = i * sigmoid(i)
ctx.save_for_backward(i)
return result
@staticmethod
def backward(ctx, grad_output):
i = ctx.saved_... |
3938128503e27320ecc61a7c753917f6a440fd45ad26eab4310fe6fdf67bdd21 | Python | 2,017 | 61 | # %% codecell
#Imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import seaborn as sns
sns.set_context('poster')
import glob
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from scipy import signal
from sklearn.... |
6a1fb2e4ffec275ad162d89d7a6d16abfdb0d0720ec1733d3214bd82299a0898 | Python | 2,017 | 42 | #!/usr/bin/env python3
import pysam
def filter_bam_by_coverage(input_bam, output_bam, min_cov=0.9, filter_secondary=False, filter_supp=False):
reader = pysam.AlignmentFile(input_bam, 'rb', check_sq=False)
writer = pysam.AlignmentFile(output_bam, 'wb', template=reader)
for r in reader:
# calculate... |
c3c30446d078ea4de1351cb7efdba3cbacaded1f02d3ad96ed81ebd590d7bb08 | Python | 2,018 | 40 | ##################################################################################
# Date created : 10/21/2022
# Date modified: 10/21/2022
# Purpose : Generate intermediate features from sequences and structures
##################################################################################
import optparse... |
d608333fc40e86985f9e9547d7ffbd6443bb7c5d49f77ff90b3c5ff787df3814 | Python | 2,018 | 56 | import numpy as np
from numpy.random import randn
from scipy.linalg import toeplitz
from torch.utils.data import Dataset
import torch
class StripesDataset(Dataset):
def __init__(self):
self.samples = create_stripes()
def __len__(self):
return self.samples[0].shape[0]
def __getitem__(self... |
154570fdb6d929a64039eab4400481365b4b7b6711d9ea2bf034dd78cc019239 | Python | 2,019 | 72 | # -*- coding: utf-8 -*-
import numpy as np
import pytest
from emcee import EnsembleSampler
from emcee.state import State
def check_rstate(a, b):
assert all(np.allclose(a_, b_) for a_, b_ in zip(a[1:], b[1:]))
def test_back_compat(seed=1234):
np.random.seed(seed)
coords = np.random.randn(16, 3)
log... |
7182b8a54560b85097f2841090ee87bcb4b66f9453ca25b84931c8d3632dc220 | Python | 2,019 | 44 | from Surfaces.surfaces import *
from Common.kernelFunctions import *
from affineRegistration import *
from Surfaces.surfaceMultiPhase import *
def compute():
## Build Two colliding ellipses
fv01 = Surface(filename = '/Users/younes/Development/Data/multishape/biocard/Atlas_hippo_L_separate.byu')
fv02 = Su... |
e2d5ba058654d045060ac0f33ba0b4728f0c79ff53d33aad63098be7b39aa037 | Python | 2,019 | 48 | from GATR import prepare_cross_validation, get_model, train_epoch, test_epoch
import json
import torch
import numpy as np
if __name__ == '__main__':
with open("params/optimal_config_GATR.json", "r") as f:
config = json.load(f)
partitions = prepare_cross_validation(config)
device = torch.device('cud... |
03c8f0d3113b745331df90e1e435f1b415ee8aecb36c4381cca95c83b858d5ca | Python | 2,020 | 52 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
from placerg.avafunc import *
N0 = 4096 # number of cells
N = 1024 # number of cel... |
1499b550ce175acde8a53146eb0f7f71b5c923d3ccd8012a892cc86f456dfbb0 | Python | 2,020 | 61 | import pandas as pd
import numpy as np
def map_return_to_series(fun, *args, **kwargs):
def inner(*args, **kwargs):
dummy = fun(*args, **kwargs)
return pd.Series(dict(A = dummy))
return inner
def is_int(x):
'''checks an object is int. surpringingly fast.'''
try:
int(x)
r... |
6b0f796f08f85c0feeda083b2f5169e54a7b8c28d3a7cb9619ea770fd15e84d8 | Python | 2,020 | 82 | import torch
import numpy as np
import random
def seed_everything(seed):
# option to add numpy, random, etc.
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
d... |
f77fcd2978a84702b04ce82ef0b815ecb7b1f3997ff90f122962381b35246044 | Python | 2,020 | 52 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
from placerg.avafunc import *
N0 = 4096 # number of cells
N = 1024 # number of cel... |
5031fdfb334b6e5f9973d797a688643b3d20a8eb657fa76747da6d34d039330f | Python | 2,021 | 49 | # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
9cbc5d3807eca64b9a127b7c4951b595aefe587ce3dca0c43450932ad9ac873a | Python | 2,021 | 68 | __all__ = ["PeptideMS2SpectrumAnnotator"]
from typing import Union
from ....chem.pep.mods import ModifiedSequence, modified_sequence_to_str
from ....chem.pep.pepmass import PeptideMassCalculator
from ....specio.spec import MassSpectrum
from ...common.annotation import MS2SpectrumAnnotatorBase
from ..spec import Pepti... |
463f28e2b226093e17beebd425bd13373938a8188fa6aa71fde7f3afd299f2f7 | Python | 2,022 | 45 | #!/usr/env/python
import argparse
from brand import *
# -----------------------------------------------------------
# running the function as a script -- for C and Bash usage
def main():
description = """
Tools for initializing processes. The default behavior is to look into a YAML file
and the... |
b1f262adc0dcb48759b5b8a145be5f85943478aaf2babe83103d302e0cca3b8b | Python | 2,024 | 60 | import numpy as np
import pytest
import pandas as pd
from pandas.api.executors import BaseExecutionEngine
class MockExecutionEngine(BaseExecutionEngine):
"""
Execution Engine to test if the execution engine interface receives and
uses all parameters provided by the user.
Making this engine work as t... |
e6774b7176ab71d0180584304bd79bc0df6f2ec60fba81d83df95d2efed6c279 | Python | 2,024 | 58 | # Copyright 2018-2023 Xanadu Quantum Technologies 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... |
e79a6fa3e4330d2df865dcecbd8b559fac9d69c9de6d4ea6849f6c3d8400d4e7 | Python | 2,024 | 52 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
from placerg.avafunc import *
N0 = 4096 # number of cells
N = 1024 # number of cel... |
c2230e0224415deea0c0378507e8638faf3809de3b881b0a6c2709ce1d338406 | Python | 2,025 | 59 | #!/usr/bin/env python
# Filename: rename_images.py
# Author: Alessandro Gerada
# Date: 2023-03-23
# Copyright: Alessandro Gerada 2023
# Email: alessandro.gerada@liverpool.ac.uk
"""Script to batch the renaming of a set of agar dilution images. Use rename_images.py -h for help."""
from aigarmic._img_utils import r... |
e0d114a9a974645a91b8fae553c8398ecd11d8bb80017edfbc7e2626193a5f39 | Python | 2,027 | 57 | import torch
import numpy as np
# Typing
from torch import Tensor
from typing import Optional, Tuple, List
class VariancePreservingDiffuser:
def __init__(self, schedule: str = 'cosine', t_min: float = 1e-3, t_max: float = 0.999) -> None:
assert schedule in ['cosine', 'linear']
self.t_min = t_min... |
683796f2c242c0bb12fca6e80c8a9b4f48d6b20c45e30accd3d828fc2b30f00e | Python | 2,028 | 61 | import os
import pysam
import random
def collect_all_reads(origin_bam_path):
read_list = []
origin_bam = pysam.AlignmentFile(origin_bam_path)
for align in origin_bam:
if align.qname not in read_list:
read_list.append(align.qname)
origin_bam.close()
return read_list
def d... |
c08b890171e1096d4978c953a44f8eab6c64a24cd9e4a5663e19559bf3f61b41 | Python | 2,030 | 42 | ###############################################################################
# This script execute an automated search of all possible combinations of two #
# sets of terms. The search is done in pubmed. The script retrieves all pubmed#
# ids and store them in text files. The search can be updated by changing the #
... |
2578afd6b197da6d72a0311fc3eb8c30d23a5a9ec78e2e07a84a144466c317df | Python | 2,032 | 53 | import numpy as np
import pandas as pd
import pandas._testing as tm
class TestTimedeltaIndexFactorize:
def test_factorize(self):
idx1 = pd.TimedeltaIndex(["1 day", "1 day", "2 day", "2 day", "3 day", "3 day"])
exp_arr = np.array([0, 0, 1, 1, 2, 2], dtype=np.intp)
exp_idx = pd.TimedeltaIn... |
43fe2e83c8faa493ca772e8b5b35c1b7afe0710e35e885b07c72099f01274ba7 | Python | 2,033 | 58 | import open3d as o3d
import argparse
import os
import numpy as np
import os.path as osp
import trimesh
class MyVertexColor(trimesh.visual.color.VertexColor):
"""
Create a simple visual object to hold just vertex colors
for objects such as PointClouds.
"""
def __init__(self, colors=None, obj=None):... |
695d009d6ea6fda5bba44c18504a35f1909977519110af67be100a7386792ef1 | Python | 2,034 | 42 | import pandas as pd
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "..")))
from app import create_app, db
from app.models import Subject, SourceDataset
from config.globals import ENVIRONMENT
... |
9a53bbcb97228f21a821ee6c9fa90290a312ad10385a61981a83fa281a6374fc | Python | 2,034 | 70 | import io
import pathlib
from unittest import mock
import sys
import shapeout2
from shapeout2.gui.main import ShapeOut2
from shapeout2 import session
import pytest
data_path = pathlib.Path(__file__).parent / "data"
@pytest.fixture(autouse=True)
def run_around_tests():
# Code that will run before your test, for... |
4bb14cc9ba287dd429c295580c4286b8f60fba540b94b9fb8b950d4001cc1dab | Python | 2,036 | 68 | import collections
import gymnasium
import numpy as np
from dm_control import suite
from gymnasium import spaces
def dmControlGetTasks():
return suite.ALL_TASKS
class dmControlGymWrapper(gymnasium.Env):
def __init__(self, domain_name, task_name):
self.env = suite.load(domain_name=domain_name, task_... |
969a10771b7727497f53189fb530979ecea0a52f32f0fb1ff8f126c77f23d779 | Python | 2,036 | 46 | """
Module for reading, writing data methods
"""
def _read_fs_table(bids_path, subject_code):
fs_table = {'fs_version': np.loadtxt(os.path.join(bids_path,'derivatives','freesurfer','sub-%s' % subject_code,'ses-%d','freesurfer_version'))}
if fs_table['version'] == '6.0.0':
for hemi in ['lh', 'rh']:
... |
e70352d4ed93834b6b7bbd34a236d76f897cb0a470a4702e1ac32df8799de438 | Python | 2,036 | 65 | """Stats module for gradec."""
import nibabel as nib
import numpy as np
from joblib import Parallel, delayed
from netneurotools.stats import gen_spinsamples
from neuromaps.datasets import fetch_atlas
from nimare.stats import pearson
from nimare.utils import tqdm_joblib
from pymare.stats import fdr
from tqdm.auto import... |
2eda8283423a66e9987648223670789c13473628220824559a147f4a0ed0afc1 | Python | 2,037 | 54 | #Run and save results of sweeps over eps, eta for 5 fields.
#Date written and executed: 2021-12-17
import numpy as np
from placerg.funcs import *
from placerg.funcsrg import *
from placerg.objects import *
from placerg.runfunc import *
from placerg.avafunc import *
N0 = 2048 # number of cells
N = 1024 # number of cel... |
7a30c4b13323a0e4629b41b910cbfbd4a6231e0942c5abd269b46ecc0419d5cc | Python | 2,037 | 82 | import time
import numpy as np
def para_run(process_query, coreNum):
"""
Process management
param:
process_query: Generator; consistant of multiprocess.Process
coreNum: the number of available cpu
"""
process_running = []
for _ in range(coreNum):
p = next(p... |
8afeced1e5a92f17c8adebfca480b57a8a488a18b601f3d32df15dbbc1bc7175 | Python | 2,040 | 70 | import argparse
import numpy as np
from src.np_implementation.data import generate_random_nonlinear_data
from src.np_implementation.model import TPC
class ProgramArguments(object):
def __init__(self):
self.activation = None
self.timepoints = None
self.sampling_freq = None
def main():
... |
31100ece20264115e522094b2af17907c8c07ce8000fff13d5565acca4af6f10 | Python | 2,042 | 54 |
from .. import conf
from ..file_utils import write_json, write_heterogenous_variantfile, get_filepath
from .top_hits import get_all_hits, stringify_assocs
def get_loci():
hits = get_all_hits()
hits_by_chrom = dict()
for hit in hits:
hits_by_chrom.setdefault(hit['chrom'], []).append(hit)
fo... |
218e4eda0312d46af46165f76e2bcba9b1f0a25c1b3d6e590c2dff6d2d18145e | Python | 2,044 | 66 | from ._decorators import *
@dask_to_pandas
@return_figure_or_axis # has to be before subsequent_calls_per_line
@subsequent_calls_per_line
def histogram(hist_bins,
colormap = None,
fig = None,
label = None,
groupby_attr... |
eece52073c16a0b04a94082c9e3b0bbb60b853e2f7ce2d748f7f4286c4c91bef | Python | 2,044 | 80 | from math import floor
class Config():
def __init__(self) -> None:
self.defaultConfig()
pass
def defaultConfig(self,):
self.displayINFO()
self.subINFO()
self.expINFO()
self.connectINFO()
self.tkinterINFO()
pass
def sub... |
7f23070e9aba73f40160f12502541c84aab40fdbbb688997c4764e983843ca4a | Python | 2,045 | 82 | import numpy as np
from pandas._libs.tslibs.fields import (
get_date_field,
get_start_end_field,
get_timedelta_field,
)
from .tslib import _sizes
class TimeGetTimedeltaField:
params = [
_sizes,
["seconds", "microseconds", "nanoseconds"],
]
param_names = ["size", "field"]
... |
61e91ab191cd9bf285b53b5a5f094075a92dedb233fa7a467b87b163138e81dc | Python | 2,047 | 57 | import matplotlib.pyplot as plt
import os
import sys
from matplotlib.colors import ListedColormap
paths = [os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))),'src')]
sys.path.extend(paths)
from src.draw import draw_angle_stimu... |
ac13629491cfdb447c328bd6374f5561db3f542f39cf5fc660c0d35d599748d4 | Python | 2,047 | 59 | #!/usr/bin/env python
"""Parse the output of GNU time (gtime), along with a profile name ($item)
and write a tab-delimited row to stdout with the following fields:
1. Program name
2. Number of threads
3. The dataset - either an error rate (for simulated data) or a data type (WGBS or RNA-Seq)
4. Quality cutoff
5. Durat... |
21f0b92443995793c2dd70f9f77e809b9533b4d036fa6970624a02fba3baac75 | Python | 2,048 | 78 | # -*- coding: utf-8 -*-
"""
Created on Thu Dec 9 14:18:03 2021
@author: jeanbaptiste
"""
import matplotlib.pyplot as plt
import deepcellcontrol as dcc
import delta
from pycromanager_tessie.acquisitions import experiment, processors
delta.cfg.load_config("updateme")
#%% Init experiment:
xp = experiment.MotherMachi... |
d66b5652168cd1f0a18ab0183689dcefa9efdd64bf4ab31c662323081dcaf2fd | Python | 2,048 | 76 | import numpy as np
import pandas as pd
import pandas._testing as tm
def test_pipe():
# Test the pipe method of DataFrameGroupBy.
# Issue #17871
random_state = np.random.default_rng(2)
df = pd.DataFrame(
{
"A": ["foo", "bar", "foo", "bar", "foo", "bar", "foo", "foo"],
... |
e5c273b19a628f56adf74ac5c7480e0bf68dfaa694dc1eece1dbfe7735bdcc50 | Python | 2,048 | 50 | from wordfreq import tokenize
from wordfreq.preprocess import preprocess_text
def test_transliteration():
# "Well, there's a lot of things you do not understand."
# (from somewhere in OpenSubtitles
assert (
tokenize("Па, има ту много ствари које не схваташ.", 'sr') ==
['pa', 'ima', 'tu', '... |
cb3e6e67e160c45f9fb610df294e483e8e87e47bb3212459325373bf1a04be68 | Python | 2,050 | 70 | import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import sys
import matplotlib.ticker as ticker
import matplotlib.transforms as transforms
from pathlib import Path
import math
from statistics import mean, stdev
from plotting_functions import *
#create figure and set font
fig, ax = plt.subplots()
... |
5361f530882e283eacfa9f8092b0b87f125bc2453ac692776ab4b7b15751e061 | Python | 2,051 | 65 | """
Three Gaussians spread along the diagonal of a six-dimensional hypercube.
This coding style for the integrand is almost as simple as slow.py
but much faster because the integrand is coded in Cython and compiled.
Run times are 20x shorter than slow.py.
Runtime is about the same for faster.py and fastest.py. This ... |
0fd79f3e3cdfcd81d6fcfda58711d00a327ff6cfc82a1c67d0149af56999bc86 | Python | 2,053 | 56 | import os
from os.path import join
from jinja2 import Environment, select_autoescape, FileSystemLoader
def generate_assets(scales, min_volume, max_volume, generated_assets_dir, base_mesh):
template_dir = join(os.path.dirname(os.path.abspath(__file__)), "../../../assets/asset_templates")
print(f'Assets templa... |
2f4ab1f51e5e35ff31a5b3eb942ebf4044aa0f1cacc8e64ec3d8877f0ba51955 | Python | 2,053 | 90 | import sys
import pickle
import tree
#26062 trees in CTB
ip = sys.argv[1]
lineNum = 0
cat = []
for line in file(ip):
lineNum += 1
t = tree.Tree()
t.read(line)
for c in t.cats():
if c not in cat:
cat.append(c)
print "Number of categories in Chinese Penn Treebank", len(cat)
print li... |
17582d39bc513767d8456049b6cfe3ec0a8d93b6626307df39407d13872f3dab | Python | 2,054 | 58 | import torch.nn as nn
from tnn.layers import tLinearLayer, tAntiSymmetricLayer, tHamiltonianLayer
class tResidualLayer(nn.Module):
def __init__(self, width, dim3, h=1.0, activation=None, bias=True, M=None, device=None, dtype=None):
factory_kwargs = {'device': device, 'dtype': dtype}
super(tResidu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.