sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e1c77c3e8e8d43692d7b882791525ebb65c0c185421d4f811f41cc897ac5a2b3 | Python | 576 | 24 | import networkx as nx
import matplotlib.pyplot as plt
from graphxai.datasets.ba_houses_with_synth import BAHouses
bah = BAHouses(
num_hops=2,
n=100,
m=1,
num_houses=1,
shape_insert_strategy='local',
shape = 'random')
print(bah.shapes_in_graph)
print(bah.graph.y)
ylist = bah.graph.y.tolist()
n... |
29294556426655c909787279252cd5d576419352275d7c12dfb0f14845af1367 | Python | 579 | 16 | from rdkit import Chem
def make_mol(s: str, keep_h: bool):
"""
Builds an RDKit molecule from a SMILES string.
:param s: SMILES string.
:param keep_h: Boolean whether to keep hydrogens in the input smiles. This does not add hydrogens, it only keeps them if they are specified.
:return: RDKit mol... |
653010dac655e4b34ab9f77295ae8a24d9e518ac1bf802c406dac5f150dbb5a7 | Python | 580 | 26 | import hydra
from omegaconf import DictConfig
from engine import main
# args = OmegaConf.load('/nfs/Workspace/brats_brain_segmentation/src/config/config.yaml')
# main(cfg, 0)
# CONFIG_PATH = "/nfs/Workspace/brats_brain_segmentation/src/"
# def load_config(config_name):
# with open(os.path.join(CONFIG_PATH, ... |
f19e8000943153aaf78f6eef886ef0e555911200e542ae18b20ba59554359ceb | Python | 581 | 22 | from torch.utils.data import Dataset
from PIL import Image
from utils import data_utils
class InferenceDataset(Dataset):
def __init__(self, root, opts, transform=None):
self.paths = sorted(data_utils.make_dataset(root))
self.transform = transform
self.opts = opts
def __len__(self):
return len(self.paths)
... |
caae627f7fa47e833b1a53cb55b5d4e044df35d755d6e602ec43231f0d573994 | Python | 584 | 15 | import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import ks_1samp, uniform
def subuniformity_plot(x, ax=None, write_pvalue=True, **kwargs):
if ax is None:
_, ax = plt.subplots(1, 1, figsize=(6, 6))
sns.histplot(x, ax=ax, stat="density", cumulative=True, **kwargs)
stat, pvalue ... |
086238a464714c1251305fa73d28a92e5fec3533dd645678e240082f95682120 | Python | 585 | 23 | import mne
from matplotlib import pyplot as plt
# ----------------------------------------------------------------------
def topoplot(data, channels, montage_name='standard_1020', ax=None, **kwargs):
""""""
info = mne.create_info(
channels,
sfreq=1,
ch_types="eeg",
)
info.set_m... |
9ae60645c8cfa7a2ba4e59011782b54ae1aff1b011233d53228bf863a08c7f5c | Python | 585 | 18 | import os
import torch
from torch.utils.cpp_extension import load
cwd = os.path.dirname(os.path.realpath(__file__))
cpu_path = os.path.join(cwd, 'cpu')
gpu_path = os.path.join(cwd, 'gpu')
cpu = load('syncbn_cpu', [
os.path.join(cpu_path, 'operator.cpp'),
os.path.join(cpu_path, 'syncbn_cpu.cpp'),
]... |
1e3f60dfa4ef3618e7da2993651817e1f72892f876274e1bfb153106fd82c0f3 | Python | 587 | 30 | r"""A few networks"""
from .lif import SNNLif
from .lifadex import SNNlifadex
# from .lifadexrefrac import SNNlifadexrefrac
from .liflsnn import SNNAlif
from .lifrefrac import SNNLifRefrac
from .states import (
LIFAdExInitState,
# LIFAdExRefracInitState,
LIFInitState,
LIFRefracInitState,
LSNNInitS... |
f0e608d292ae1d4d852762deb3737ac7df03739feab6698f04a68d5f4772cbf7 | Python | 587 | 16 | import torch
from cgtasknet.net import LIFAdExInitState
from cgtasknet.net.lifadex import SNNlifadex
def test_init_lif_refrac():
input_s, hidden_s, output_s = 500, 100, 1
model = SNNlifadex(input_s, hidden_s, output_s)
inputs = torch.rand((300, 1, input_s))
init_state = LIFAdExInitState(1, hidden_s)
... |
50a2cab2ec4c7534dd34360a8bef447fd698452bb9963005979e6cd49d9dde49 | Python | 588 | 24 | __author__ = 'jieqing jiao'
__email__ = "jieqing.jiao@gmail.com"
import numpy as np
def srtm_theta2kp(theta):
# theta - output from models/srtmb
# theta[0] - linear coeff of input(Cr)
# theta[1] - linear coeff of the conv
# theta[2] - exp coeff (no -)
r1 = theta[0] # R1
... |
e0d6561adb401cadb6d38910a9c7d5b4a1b9bdacf7a148cd163f4ff7399e21e7 | Python | 588 | 19 | from deeprank_gnn.NeuralNet import NeuralNet
from deeprank_gnn.ginet import GINet
from deeprank_gnn.foutnet import FoutNet
database = './hdf5/1ACB_residue.hdf5'
database = './1ATN_residue.hdf5'
NN = NeuralNet(database, GINet,
node_feature=['type', 'polarity', 'bsa',
'depth'... |
1a7433a12d58d24197663f0763364b0760c3739b4c971547c2fe7319a13e25d1 | Python | 589 | 18 | from dataclasses import dataclass
from typing import Any, Collection
from oaklib.transformers.ontology_transformer import OntologyTransformer
@dataclass
class ChainedOntologyTransformer(OntologyTransformer):
"""
An ontology graph transformer that chains multiple other transformers
"""
chained_transf... |
e2c80b91ab9ab7215ea365723fa36a6322a4f06674d68c438173271edb0b5523 | Python | 589 | 21 | from Lif_Connections import *
#######################################
# INITIALIZATION
#######################################
for pop_ll in layers:
pop_ll.vm = El
pop_ll.I_synEX = 0 * mV
pop_ll.I_synIN = 0 * mV
pop_ll.I_noise = 0 * mV
#######################################
###################... |
10196d0e538526843b03ef61efb485e077b4b7d56b4c6c8d649c91449dc3ec98 | Python | 591 | 26 | __author__ = "Patrik Smeds"
__copyright__ = "Copyright 2019, Patrik Smeds"
__email__ = "patrik.smeds@gmail.com.com"
__license__ = "MIT"
import os
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
input_bam = snakemake.input.bam
input_recal_data = snakemake.input.recal_data
input_ref = snak... |
00142c7d1ffc6f31f443cf8a0eb27780b5560603c967a82bd104b0d8dd8edc5e | Python | 593 | 38 | from abc import ABCMeta, abstractmethod
class AnalysisBase(metaclass = ABCMeta):
@property
@abstractmethod
def context():
pass
@property
@abstractmethod
def data_io():
pass
@property
@abstractmethod
def cxparser():
pass
@abstractmethod
def get_PCA... |
c778761b584b2086984f0ca8482fe975403c7456628181ebf119f37adab01fad | Python | 593 | 26 | class RSA_World:
def __init__(
self,
target,
speaker,
rationality="DEFAULTBAD",
):
self.target=target
self.rationality=rationality
self.speaker=speaker
def __hash__(self):
return hash((self.target,self.speaker,self.rationality))
def __eq__(self,other):
return self.target==other.target and sel... |
de670ab9ce4778916165af00b0e7b7b0aa8faee818ecd93596ff1339997896d9 | Python | 593 | 16 | import numpy as np
def interp1d_(x, y, x_new):
from scipy.interpolate import interp1d, pchip_interpolate
# return interp1d(x,y,kind='cubic')(x_new)
return pchip_interpolate(x, y, x_new)
def get_baseline_dff(fmean, fneuropil, cont_ratio=0.7, win_=3000, q=0.1):
import pandas as pd
fmean_comp = fme... |
ff4b38f947e94637008a02bfaf5a5753decdb3d10b7ba070fe22cec3c7ad87f0 | Python | 593 | 17 | import torch
import numpy as np
from graphxai.datasets import AlkaneCarbonyl
dataset = AlkaneCarbonyl(split_sizes = (0.7, 0.2, 0.1), seed = 1234)
print('Class imbalance:')
print('Label==0:', np.sum([dataset.graphs[i].y.item() == 0 for i in range(len(dataset))]))
print('Label==1:', np.sum([dataset.graphs[i].y.item() =... |
c6a81dc46d4a43ba7d509b46b2c3d7769d11087008f84436ab7f6ec73515ef10 | Python | 596 | 25 | import torch
from graphxai.datasets import ShapeGGen
from sklearn.metrics import confusion_matrix
SG = ShapeGGen(
model_layers = 3,
num_subgraphs = 100,
prob_connection = 0.08,
subgraph_size = 10,
class_sep = 30,
n_informative = 2,
verify = False,
make_explanations = False,
homphil... |
c001340ce43aaad2b657a4f66270610081b2db0174b42a3179e2c17c0f77077d | Python | 598 | 21 | import os
import numpy as np
from tmkit.topo import from_pdbtm, from_phobius, from_tmhmm
from . import dir_data
def test_from_phobius():
phobius_fpn = os.path.join(dir_data, "1xqfA.jphobius")
topo = "tmh"
from_fasta = False
lower, upper = from_phobius(
topo=topo, phobius_fpn=phobius_fpn, fr... |
1330810d898e843b346aba5252552cbdf003873fb87b2fbe0a585e44b7b37dc9 | Python | 600 | 30 | __author__ = "Patrik Smeds"
__copyright__ = "Copyright 2018, Patrik Smeds"
__email__ = "patrik.smeds@gmail.com"
__license__ = "MIT"
from snakemake.shell import shell
input_flag = "--vcf"
if snakemake.input[0].endswith(".gz"):
input_flag = "--gzvcf"
output = " > " + snakemake.output[0]
if output.endswith(".gz"):... |
601aafecbe498dbe79918f860141524d009c8427def604eb8e9428b9bf27c29e | Python | 601 | 22 | from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
... |
ceb10a3fc0e8e8a8d10c75bbb84dfda066e9c26f8fd89add37ff1949a2f49e98 | Python | 601 | 21 | __author__ = "Johannes Köster"
__copyright__ = "Copyright 2016, Johannes Köster"
__email__ = "koester@jimmy.harvard.edu"
__license__ = "MIT"
import os
from snakemake.shell import shell
prefix = os.path.splitext(snakemake.output[0])[0]
# Samtools takes additional threads through its option -@
# One thread for samto... |
7d7976c691419a71e939a5899c51e0cc4872f7274ea0b638d1843ebc6eee633e | Python | 602 | 23 | import os
def cast_to_bool(var):
if var == "True":
var = True
elif var == "False":
var = False
return var
def get_environment_variables():
RESAVE_DATA = cast_to_bool(os.environ.get("RESAVE_DATA", False))
RERUN_SIMS = cast_to_bool(os.environ.get("RERUN_SIMS", False))
DISPLAY_F... |
77366a0a2d861120a788ede45ee5fe06f8c65a6e59709c23291315eb2a970366 | Python | 603 | 28 | import torch.nn as nn
from .registry import ACTIVATION_LAYERS
@ACTIVATION_LAYERS.register_module()
class HSwish(nn.Module):
"""Hard Swish Module.
This module applies the hard swish function:
.. math::
Hswish(x) = x * ReLU6(x + 3) / 6
Args:
inplace (bool): can optionally do the oper... |
a291ae47187c9b582de78e7da4fbdd5e80d114ce026565fc7f12951c26ec03c4 | Python | 603 | 19 | #!/usr/bin/env python3
#
# Copyright 2015 David Snyder
# Apache 2.0.
#
# Copied from egs/sre10/v1/local/prepare_for_eer.py (commit 9cb4c4c2fb0223ee90c38d98af11305074eb7ef8)
#
# Given a trials and scores file, this script
# prepares input for the binary compute-eer.
import sys
trials = open(sys.argv[1], 'r').readlines... |
b6bd501180a62070df11b633b9eddb7430bf456cecc1c2d51efc270c80431d9c | Python | 603 | 20 | import numpy as np
from utils.image_and_text_utils import max_sentence_length,vectorize_caption
class RSA_State:
def __init__(
self,
initial_world_prior,
listener_rationality=1.0
):
self.context_sentence=np.expand_dims(np.expand_dims(vectorize_caption("")[0],0),-1)
self.dim = {"image":0,"rationality":1,... |
283eb289b5845362ea4826ed646f030722ac0bc59acbcc2b7bb8c29db78c4cbf | Python | 604 | 18 | import os
import pandas as pd
import networkx as nx
import community as community_louvain
from brainNetwork.util.path import get_local_datadir
csv_dir = os.path.join(get_local_datadir(),'connectivity.csv')
connect_mat = pd.read_csv(csv_dir, index_col=0)
# Get the graph
G = nx.convert_matrix.from_pandas_adjacency(co... |
4a3bc64f34d75cdd58ca394a2be4b813074a0cf922add7cc1ffc52ebca2e4d62 | Python | 604 | 24 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import unittest
import glob
import os
import utils
class TestConfigs(unittest.TestCase):
def test_configs_load(self):
''' Make sure configs are loadable '''
cfg_root_path = utils.get_config_root_path()
files = glob.g... |
5b888536e8b653f4ab09e14e7e53d17b4a0d3873579da26dfadd3070cf93b743 | Python | 604 | 19 | import numpy as np
import mrcfile
import cv2
import glob
import os
for mrc_path in glob.glob('/hpc/home/qh36/research/qh36/csplus/srcryoem/ctf_sr/apoferritin/*.mrc'):
print(mrc_path)
print(mrc_path[-55:-10])
name = mrc_path[-55:-10]+'bicubic.mrc'
print(name)
with mrcfile.open(mrc_path) as mrc:
dat = mrc.data
... |
7699f5b8a2cc40cc04c89c4b95de798f7f337568a41a4164b28eabeb4a7a07b1 | Python | 604 | 14 | import pandas as pd
import numpy as np
import connectome_tools.process_matrix as promat
pairs = pd.read_csv('data/pairs-2020-02-27.csv', header = 0)
sample_left = np.random.choice(pairs['leftid'].values, size = int(len(pairs['leftid'])/2), replace = False)
sample_right = np.random.choice(pairs['rightid'].values, size... |
d11e110687a97c0088a7c26a9bab9778c162e76c8398dcb5c44f3877dd39513c | Python | 605 | 22 | import torch
from ctran import ctranspath
net = ctranspath()
td = torch.load(r'./ctranspath.pth')
net.load_state_dict(td['model'], strict=False)
linear_keyword = 'head'
for name, param in net.named_parameters():
if name not in ['%s.weight' % linear_keyword, '%s.bias' % linear_keyword]:
param.requires_g... |
45e314e2eaefcc4b041375635f2be051998cd8dc9dd9204cb570e89136a647a4 | Python | 606 | 19 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
splitters = snakemake.output.splitters.replace('bam', 'sam')
discordants = snakemake.output.discordants.replace('bam', 'sam')
shell(
"samtools view -h {snakemake.input} "
"| samblaster "
"--acceptDupMarks "
"--ex... |
1c97f72490c0bcda6c18b4e1c157b60b23cb9a6f71fe59620cc4a7dd4c88dccd | Python | 608 | 31 | """Tools for constructing constrained models of neural circuits."""
# Model components and tools
from . import AEC # AEC
from . import Filter, Filter_Rect, Filter_Exps # Filters
from . import (
cell_class,
Experiment,
pltools,
ReadIBW,
Simulation,
SpikeTrainComparator,
Tools,
Trace,
)... |
6aaaf2f993c9628e06291467cd71e3fe6ba75926e877d16f9bb7934c29e8fe3d | Python | 608 | 29 | #!/usr/bin/env python3
import sys
import glob
import os
import pandas as pd
indir = sys.argv[1]
def main():
print(indir)
df_list = []
for i in range(1, 23):
fpath = os.path.join(indir, "chr{}".format(i), "GenotypeData.txt.gz")
if not os.path.exists(fpath):
continue
... |
a1b3ecb6c1df0f68c92223b0fabc6da41e38550e0104ae687cbdc031fcaf10e8 | Python | 610 | 17 | import os
import pandas as pd
import numpy as np
from nilearn import plotting
from brainNetwork.util.path import get_data_dir, get_fig_dir
# Note: uses the human atlas for the surface, not usable for the paper
# read coordinate files
csv_name = os.path.join(get_data_dir(), "coords", "initial.csv")
coords_pd = pd.read... |
5a25d3049f366256d7fe69c67d8cc854e8698c48b06767646cee8e58e13d30bf | Python | 612 | 20 |
# This recipe spawns an actor and the spectator camera at the actor's location.
# ...
world = client.get_world()
spectator = world.get_spectator()
vehicle_bp = random.choice(world.get_blueprint_library().filter('vehicle.bmw.*'))
transform = random.choice(world.get_map().get_spawn_points())
vehicle = world.try_spawn_... |
94175a8cc0e05eb81b443822483749b21fce6a4eb4e87cfeaee1ef7143107619 | Python | 612 | 27 | """
Tools for loading data.
The following submodules are available:
eyelink:
Load eyelink ``.edf`` files to datasets. Requires eyelink api available from
SR Research
fiff:
Load mne fiff files to datasets and as mne objects (requires mne-python)
txt:
Load datasets and vars from text files
"""
from ... |
7af0144ff60b9c741e9ec70a220a9dad8f4af954a29ddd038995156f6b7c5f02 | Python | 613 | 20 | import os
import pandas as pd
from flydf.core import _fix_dtypes
import utils_Florian
import utils.list_twoP_exp as list_twoP_exp
l = list_twoP_exp.df3d_processed_list
df = pd.DataFrame(data=l, columns=["Date", "Genotype", "Fly", "Trial"])
df["Date"] = df["Date"].apply(lambda x: int(x))
df["Fly"] = df["Fly"].apply(... |
563f9d259a1cb009519056f0c7a0af98ca85796e58a62e6894c991b45e62e6c8 | Python | 615 | 30 | """
Deep learning and Reinforcement learning library for Researchers and Engineers
"""
try:
install_instr = "Please make sure you install a recent enough version of TensorFlow."
import tensorflow
except ImportError:
raise ImportError("__init__.py : Could not import TensorFlow." + install_instr)
from . i... |
83cf74de051bd8e92e1485e73d9a0e7b8493d7d3b01bccddb8bb64f36b98ede5 | Python | 616 | 20 | """
Test the `Encoder` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_architect as i... |
8379234add4ce0284ec0c271228b8745469cd9d247c5708178002d700971d55c | Python | 617 | 30 | #%%
import numpy as np
from src.data import join_node_meta, load_maggot_graph
mg = load_maggot_graph()
nodes = mg.nodes
nodes = nodes[nodes["has_embedding"]]
n_components = 10
min_split = 32
cols = [
f"dc_level_{i}_n_components={n_components}_min_split={min_split}" for i in range(8)
]
data = nodes[cols].copy()
... |
6ed2de88f64dd968e610b3c2c0bbfdc0919929cb95c824a0aa5c038f37e59906 | Python | 618 | 23 | from impyute.imputation.cs import mice
import pandas as pd
import argparse
parser = argparse.ArgumentParser(description='Use mice imputation on table.')
parser.add_argument('input_file', help='input file')
parser.add_argument('output_file', help='outputf file')
args = parser.parse_args()
df = pd.read_csv(args.input... |
ab2eb28aefe1fcbc4bfd4bb8780b706545477eda94cc0a2f50c4ffa82ea2e587 | Python | 618 | 20 | """
Test the `Generator` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_architect as... |
cf4dd19d676547bc0d1828a820a560b09171563026de8b03c6eb8bd0895c03bd | Python | 619 | 20 | """
Test the `InputNoise` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_architect a... |
5b9968e93138e02a35041ec11f444afb899ee76ea83afe304d14b7baad4c97da | Python | 620 | 20 | """
Test the `StimulusSet` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_architect ... |
9ea6f36b1ee74ee4b74fa8efe299529325c7d45105ea8e394d845a611220be8f | Python | 620 | 25 | import numpy as np
from spotipy.model import Config, SpotNetData, SpotNet
from spotipy.utils import points_to_prob
if __name__ == '__main__':
config = Config(axes = "YXC", n_channel_in=1, train_patch_size=(64,64),
activation='elu', last_activation="sigmoid", backbone='unet')
model ... |
53768605ba422fe629a691a4ee8baf733296ecc11074a3681dcb3202df56ffdc | Python | 622 | 20 | """
Test the `EncodingLayer` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_architec... |
579d0221ea43f455f069c4c1303a95021cfca65c84a863229047fe83f7489310 | Python | 622 | 21 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
if snakemake.params.exclude_chroms:
excludechroms = "--excludechroms {}".format(snakemake.params.exclude_chroms)
else:
excludechroms = ""
shell(
"(export TMPDIR={snakemake.params.outdir}; echo $TMPDIR; "
"smoove ... |
a70459e37c53c762d1b292252c56a08ce96cd1198016af0751c20f281d6645ec | Python | 622 | 20 | from setuptools import setup, find_packages
setup(
name='aug_accuracy',
packages=find_packages(),
version='0.1',
description='Set of tools for reproducible training and testing of claffication networks.',
author='Vladyslav Andriiashen',
author_email='vladyslav.andriiashen@cwi.nl',
url = 'ht... |
19d95f783a63f0b651453a45f06febabda9b8238891046e22645dd493944de87 | Python | 623 | 28 | import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GridSearchCV
X, Y = make_classification(
n_samples = 1500,
n_features = 10,
class_sep = 50,
scale = 1,
n_informative = 4,
n_redundant = 0,... |
7cd56aab5bd3825c5d00453291a73bc68d1094fc6ec568e8d90a6f9aa15c5f50 | Python | 623 | 22 | import backend.root_detection
import tempfile, os
import numpy as np
import PIL.Image
def test_postprocessing_with_exmask():
ypred = np.zeros([100,100,3], 'uint8')
ypred[:50] = 255
#exclusion mask
ypred[:25] = (255, 0, 0)
tmpdir = tempfile.TemporaryDirectory()
ypred_png = os.path.joi... |
bfa96385baaa7f0a34a75810549cf19d651a84df3e0266c1e8f1f85c4f63e583 | Python | 623 | 20 | """
Test the `InputSignalSet` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_archite... |
67182855930139522e0b0039ef33e9bbac68f24f8224ae2f1701a5cad9459b6f | Python | 624 | 14 | from snakemake.shell import shell
log = snakemake.log_fmt_shell(stdout=True, stderr=True,append=True)
family = snakemake.wildcards.family
outdir = snakemake.params.outdir
tool = snakemake.params.tool
pythonpath = tool.replace("bin", "")
python = " export PYTHONPATH={pythonpath}; "
mity = " {tool}/mity normalise --pr... |
e4c175aafed1aff2452f664d9c330cb4505c1e878216da5920ba4390acc570e6 | Python | 624 | 18 | """
This module provides functions and classes for interpreting modules
trained with Selene.
"""
from .vis import sequence_logo
from .vis import heatmap
from .vis import rescale_score_matrix
from .vis import ordered_variants_and_indices
from .vis import sort_standard_chrs
from .vis import load_variant_abs_diff_scores
... |
2871f053c351fa28a51a2795c220bbdee7d2ed28cf254108a8d2e52d3bb97c91 | Python | 625 | 32 | """
Guide 01
=========================
Example with ``basic`` functionality.
- Define dataset
- Define settings.xxx.yaml
- Run GridSearch
- Visualise Results
.. warning::
This is a warning
.. note::
This is a note
"""
# Get your .csv file and save it in a folder within your
# datasets (e.g. /datasets/i... |
009779179a503569b1fc99652cf8bc9a3f83e3b1efccf7c376fe2961d604a034 | Python | 626 | 27 | from setuptools import find_packages, setup
REQUIRED_PACKAGES = [
"colorcet",
# "giskard @ https://github.com/bdpedigo/giskard.git#egg=giskard",
"graspologic",
"matplotlib",
"networkx>=2.5",
"numpy>=1.19",
"pandas>=1.0",
# "python-catmaid>=2.0.2",
"scikit-learn>=0.24.0",
"scipy>... |
f51107bb2ba24efc64539252c7eabc39b82c4c8b919f8189889f1fca366c3106 | Python | 626 | 26 | #!/usr/bin/python3
import sys, os
import pylab
def process_file():
print('Reading %s' % filename)
fp = open(filename, 'r')
for line in fp.readlines():
data = line.split()
# print data
for x in data:
print(x, end=' ')
print()
print("Processing f... |
ce877175b5fe1de27596a117a10208484767a139f6c2803fd9bb5efd933202b3 | Python | 627 | 23 | from typing import Optional, Literal
from zencfg import ConfigBase
class OptimizationConfig(ConfigBase):
n_epochs: int
training_loss: Literal["h1", "l2"] = "h1"
testing_loss: str = "l2"
learning_rate: float = 3e-4
weight_decay: float = 1e-4
eval_interval: int = 1
mixed_precision: bool = Fa... |
112a15992cbda01ae913bfa2f561c83d0980f9ed50572fed217d1bce076431e5 | Python | 628 | 34 | import gzip
import sys
inf=sys.argv[1]
outf=sys.argv[2]
fh=gzip.open(inf,'rt')
fho=gzip.open(outf,'wt')
fho.write(fh.readline())
for line in fh:
elems = line.strip().split("\t")
ds = elems[11].split(";") # datasets
sz = elems[13].split(";") # samplesizes
ctr = 0
nrds = 0
samplesize = 0
while ctr < len(ds):
... |
de7609dbf0bb7c81415d4a445307585c64bbbe40277b6f9f4d0c3501ffdf1eea | Python | 628 | 20 | """
Test the `StochasticGenerator` class in input_architect.py and all its methods.
"""
import sys
sys.path.append('../../../')
sys.path.append('../')
import numpy as np
# nest.init(sys.argv + ['--verbosity=QUIET', '--quiet']) # turn off all NEST messages
from modules import parameters
from modules import input_ar... |
3077d18c2423b901e33e139e6c720c6a29b5699cd445b6a060ceec2497486bb9 | Python | 630 | 25 | from .plotting import (
beautify_mpl,
prettify,
feature_scatter_plot,
embedding_scatter_plot,
)
from .transforms import (
TrainNormalizeTransform,
TsfreshFeaturePreprocessorPipeline,
TsfreshVectorizeTransform,
)
from .encoders import (
SpikeTrainTransform,
DFSpikeTrainTransform,
... |
87a40d821fd92a6b7f2d7710f0dffb1c6afae79cf87e5558c914d91b03b466cb | Python | 630 | 18 | import os
import unittest
from UnitTests.RecommenderTest import RecommenderTest
from UnitTests.RelationshipIdentifierTest import RelationshipIdentifierTest
from UnitTests.QueryParserTest import QueryParserTest
from UnitTests.SearchModuleTest import SearchModuleTest
if os.getcwd().endswith("NeuroML"):
os.chdir("On... |
ebfa241d94292f4056bb5c91c977bed73de711563a4d75bd00011e26b80d3455 | Python | 630 | 22 | """Snakemake wrapper for igv-reports."""
__author__ = "Johannes Köster"
__copyright__ = "Copyright 2019, Johannes Köster"
__email__ = "johannes.koester@uni-due.de"
__license__ = "MIT"
from snakemake.shell import shell
extra = snakemake.params.get("extra", "")
log = snakemake.log_fmt_shell(stdout=True, stderr=True)
... |
9f05ad4584e3482fe70f91f2de76b54f896cd8fcfe3f93c2fb777a1e3e308b53 | Python | 631 | 18 | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
def basic_lstm(n_timesteps, n_features, name="Basic_LSTM"):
inputs = tf.keras.Input(shape=(n_timesteps, n_features))
x = layers.LSTM(units=64,
return_sequences=True,
name='lstm1')(i... |
a95bcbf86066fb01568e42d789f811c8e01f1dbf490c7a52244ad3f20a390d42 | Python | 637 | 29 | __author__ = "Dennis Kao"
__copyright__ = "Copyright 2020, Dennis Kao"
__email__ = "dennis.kao@sickkids.ca"
__license__ = "BSD"
from snakemake.shell import shell
from os import path
import shutil
import tempfile
shell.executable("bash")
fasta = snakemake.params.get("ref")
if fasta:
fastaprefix = "-r {}".format(... |
5ae3aae7c0bc48391482fd52dd4d5569812ba72cb1ac7d61432d3533a3b732c4 | Python | 638 | 19 |
# This recipe changes attributes of different type of blueprint actors.
# ...
walker_bp = world.get_blueprint_library().find('walker.pedestrian.0002')
walker_bp.set_attribute('is_invincible', 'true')
# ...
# Changes attribute randomly by the recommended value
vehicle_bp = random.choice(world.get_blueprint_library().... |
1d9a9c05a5f68e4027aa82f118ae3673c9f51b770b52c7b88732d5385d563d2a | Python | 639 | 11 | # %%
#
import matplotlib.pyplot as plt
colors = ['#00753F', '#1D79B7', '#5D8C90', '#D4E29E', '#FF8734', '#E55560', '#F9EB4D', '#C144BC', '#FF9CFF', '#8C7700', '#77CDFC', '#FFDAC7', '#E0B1AD', '#9467BD','#D88052', '#A52A2A', 'tab:grey']
cell_types = ['sens', 'PN', 'LN', 'LHN', 'MBIN', 'KC', 'MBON', 'MB-FBN', 'FFN', 'CN... |
6e9ea85ce6ca0a835d9b01a02d45e7ff5cd8725e6da60284c2b3e4ba8b7794e6 | Python | 639 | 25 | import sys
import networkx as nx
import matplotlib.pyplot as plt
from graphxai.datasets.utils.bound_graph import build_bound_graph
def parse_argv():
assert len(sys.argv) > 2, \
'usage: python3 build_bound_graph.py <num_subgraphs> <prob_connection> <base_graph (optional)>'
args = {}
args['num_hop... |
856778bee82c46aef0737003af95519c1668b82f8eab5766a99f7f1e08ad6136 | Python | 640 | 24 | """
Module for cv2 utility functions and maintaining version compatibility
between 3.x and 4.x
"""
import cv2
def findContours(*args, **kwargs):
"""
Wraps cv2.findContours to maintain compatiblity between versions
3 and 4
Returns:
contours, hierarchy
"""
if cv2.__version__.startswith(... |
d1a33e05f771ddfce5ece93b5d3a204b22d0ead2d438fe1943e265147bd166de | Python | 640 | 38 | # Utils
import numpy as np
import pickle
def save_dict(fname, data_dict):
with open(fname, 'wb') as handle:
pickle.dump(data_dict, handle, protocol=4)
def load_dict(fname):
with open(fname, 'rb') as handle:
data = pickle.load(handle)
return data
def distance(x, y):
return np.sqrt(np.sum((x-y)**... |
9eb295a207d951da11c916856ba1464ddf7ed5774a86148bd378c9a92cb0b768 | Python | 641 | 27 | """Snakemake wrapper for trimming paired-end reads using cutadapt."""
__author__ = "Julian de Ruiter"
__copyright__ = "Copyright 2017, Julian de Ruiter"
__email__ = "julianderuiter@gmail.com"
__license__ = "MIT"
from os import path
from snakemake.shell import shell
input_dirs = set(path.dirname(fp) for fp in snak... |
073df954965db71b8b363c39044e0b61c9caf504c2de86a14d0a0d9b55cc9791 | Python | 643 | 28 | #!/usr/bin/env python3
import sys
def get_vocab_set(ref_file):
vocab_set = set()
with open(ref_file, 'r') as f:
for line in f.readlines():
word = line.split()[0]
vocab_set.add(word)
return vocab_set
def compare(vocab_set, wordlist):
with open(wordlist, 'r'... |
aee5ecf3aa446bb97feb2a19efef7ad8f521ddcc4d55da9feba0331da162167c | Python | 643 | 24 | import numpy as np
import pandas as pd
experiments = ['learn','reversal','reversal_prat','punish','punish_prat','devalue',]
numSim = 100
def proc_prob( pXc ):
pXc_T = pXc[:,:,0] > pXc[:,:,1]
return np.sum( pXc_T, 1 )/pXc_T.shape[1]
for experiment in experiments:
df = pd.DataFrame()
for ns in range(... |
1c0598008eac4579804ab681fdaba31ff889caa2bd448ecf03a06fddd5ae44aa | Python | 645 | 24 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
try:
from urllib.request import urlopen # python 3
except ImportError:
from urllib2 import urlopen # python 2
import sys
import tarfile
import tempfile
import shutil
dataset = sys.argv[1]
url = "https:... |
528cef1228d9379e3e5e706e5a413914b627e09ffd04f65678a5898e62ddd03c | Python | 646 | 13 | """Grab one X11 window (by id) with xwd and save it as PNG: xwdgrab.py WINDOW_ID OUT.png"""
import struct, subprocess, sys
from PIL import Image
raw = subprocess.run(["xwd", "-silent", "-id", sys.argv[1]], capture_output=True, check=True).stdout
h = struct.unpack(">25I", raw[:100])
header_size, fmt, depth, w, hgt = h[0... |
c80252cde4d9deb956e99dd205318dcd86023facb27a79344cef896af49252af | Python | 647 | 29 | import os
import sys
root_path = os.path.realpath("./")
sys.path.append(root_path)
import pytest # noqa E402
from hebbcl.parameters import parser # noqa E402
def parse_args(args):
return parser.parse_args(args)
class TestArgparse:
def test_none_str(self):
"""tests whether "none" arg correctly re... |
867b929aff9fd625a1a8ce5d868a307cff0039d297f78f6d19d3ec42a293716f | Python | 648 | 23 | import sys, os, importlib
try:
from wmhpypes.interfaces import ibbmTum
from wmhpypes.workflows import ibbmTum_wf
from wmhpypes.interfaces import cat12
except:
sys.path.append(os.path.abspath('../'))
from wmhpypes.interfaces import ibbmTum
from wmhpypes.workflows import ibbmTum_wf
from wmhpy... |
94e69b78966177613b2d5ab64c63d2ef033ba1fc78bdd50c6334f7c764b46086 | Python | 648 | 25 | import torch.nn as nn
import numpy as np
from abc import abstractmethod
class BaseModel(nn.Module):
"""
Base class for all models
"""
@abstractmethod
def forward(self, *inputs):
"""
Forward pass logic
:return: Model output
"""
raise NotImplementedError
... |
ccdb5c6b01750e091d7373464b58e42078cd46a3924aadfddcd24d11a935eedf | Python | 648 | 24 | import torch.nn as nn
from mmcv.utils import build_from_cfg
from .registry import ACTIVATION_LAYERS
for module in [
nn.ReLU, nn.LeakyReLU, nn.PReLU, nn.RReLU, nn.ReLU6, nn.ELU,
nn.Sigmoid, nn.Tanh
]:
ACTIVATION_LAYERS.register_module(module=module)
def build_activation_layer(cfg):
"""Build a... |
087223e4ef0e1fbc8f5ef26a25e5ab180ea9d900fe65b2459b56587d6b7daf80 | Python | 651 | 24 | """HCP Workbench scene files.
These files are downloaded on first use, see
:py:mod:`osl_dynamics.files._fetch`.
"""
from osl_dynamics.files import _fetch
_SUBDIRECTORY = "scene"
def file(name: str):
"""Path to one scene file, downloading it if needed."""
return _fetch.fetch_file(f"{_SUBDIRECTORY}/{name}")
... |
4f9091b1842838e15632d3a6792d50dd029ea6847ffb2a48b2a5f7a098466cf8 | Python | 651 | 24 | """Phase 0 smoke test: load the Winding connectome and extract the MB subgraph.
Validates:
- Data files extracted to the expected path.
- Connectivity matrix loads as expected shape.
- Annotations cell-type counts match Winding 2023.
- MB subgraph extraction produces sane numbers (KCs ~242, MBONs ~24, MBIN ~14).
"""
... |
6daec744d69ae5680bc5dc458c402233fa23a406494866599a3ef1b0b564af09 | Python | 651 | 20 | import tensorflow as tf
def softmax_cross_entrophy_loss(logits, targets):
cross_entropy = tf.nn.sparse_softmax_cross_entropy_with_logits(
logits=logits,
labels=targets,
name="cross_entropy_per_example"
)
cross_entropy_mean = tf.reduce_mean(cross_entropy, name="cross_entropy")
r... |
aa8d1fec5c2bc05b772fe3641c3d72e43124f9bd156c95ed5ace1f86c1bc4c98 | Python | 651 | 22 | import numpy as np
import functions_basic_sak as funsak
import pandas as pd
from tqdm import tqdm
import os
from skimage import data, util, measure
from scipy.ndimage.measurements import label
import inspect
import AIS_downsample
import AIS_neighbors
import AIS_parameters
import AIS_trajectory
import AIS_ge... |
ba762a1250c7a2ac238028313411ac9638c729d141e15f933b87dd13d3966d0c | Python | 651 | 22 | # Copyright (c) 2026 Computer Vision Center (CVC) at the Universitat Autonoma de
# Barcelona (UAB).
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
import carla
import sys
import unittest
from subprocess import check_output
class TestClient(uni... |
d32f4ab9cd40d5bb6fd7fee2a1dd87bcc47b91282cda879c81c196c863343b3e | Python | 652 | 18 | # Let us use a Nifti file that is shipped with nilearn
from nilearn.datasets import MNI152_FILE_PATH
from nilearn import plotting
from nilearn import image
# Note that the variable MNI152_FILE_PATH is just a path to a Nifti file
print('Path to MNI152 template: %r' % MNI152_FILE_PATH)
plotting.plot_img(MNI152_FILE_PATH... |
27a3b8044c8584f1175f0999703400a5d987a66998b086d13548d8a4e33c53cd | Python | 653 | 30 | import logging
import sys
def get_logger():
logging.getLogger(__name__)
def setup_logger():
# clear log
file_to_delete = open("log.log",'w')
file_to_delete.close()
file_handler = logging.FileHandler(filename='log.log')
stdout_handler = logging.StreamHandler(stream=sys.stdout)
handlers =... |
1883b11e91f26078272faaa0aba96faead9a8bfdc369e1b8a28b4194f3eafc3c | Python | 654 | 20 | import unittest
from oaklib.implementations.pronto.pronto_implementation import ProntoImplementation
from oaklib.resource import OntologyResource
from oaklib.utilities.validation.rule_runner import RuleRunner
from tests import INPUT_DIR, OUTPUT_DIR
TEST_OUT = OUTPUT_DIR / "lint-test-output.obo"
TERM_X1 = "X:1"
clas... |
2497a538ea54e1678144f6aecb7c01a9124bae86f39f6de4e22ef792d1267f00 | Python | 654 | 23 | """Volumetric parcellations.
These files are downloaded on first use, see
:py:mod:`osl_dynamics.files._fetch`. For more information see
:ref:`parcellations`.
"""
from osl_dynamics.files import _fetch
_SUBDIRECTORY = "parcellation"
def file(name: str) -> str:
"""Path to one parcellation file, downloading it if ... |
96888b4ef6beb9d78f5afce143b878efc5a9f8b8c3509f3d122bfa7c371800d6 | Python | 654 | 24 | """Parser for KGX"""
from csv import DictReader
from dataclasses import dataclass
from typing import Iterator, TextIO
from oaklib.datamodels.association import Association
from oaklib.parsers.association_parser import AssociationParser
@dataclass
class KgxAssociationParser(AssociationParser):
"""Parsers for KGX... |
9b80a58e4fe1a93977d0e97711d51daf2ecfb2b074261e56e939ce5ff42998f1 | Python | 655 | 17 | from .heuristics import MiddleSpeedResident, MiddleAngleSocial, MiddleAngleSocialIntruder, MiddleSpeedIntruder, MiddleMovementNoseResident, MiddleMovementNoseIntruder, MiddleDistNoseNose, MiddleDistNoseTail, MiddleAngleHeadBodyResident, MiddleAngleHeadBodyIntruder, ReadLabels
# USAGE: import label function and add to... |
b10730eed4209830c657edc5d6c55c61a3ad57daa46e3e67ab023bec9f0d5109 | Python | 655 | 18 | from datetime import datetime
import gzip
today = datetime.now().strftime("%Y-%m-%d")
outfile = today+'-uniprot_ensembl_map.txt.gz'
print('Start reading and writing, can take sometime')
with gzip.open('idmapping_selected.tab.gz','rt') as input_file, gzip.open(outfile,'wt') as out:
out.write('uniprot_id\tensembl_id... |
3daa2d9fd972a3c1eae8d173df68be58618b95a7e5f10c3d52ff056b7641866c | Python | 657 | 27 | import os
from pathlib import Path
dirname = os.path.dirname(__file__)
UK_DALE = os.path.join(dirname, '../../data/UKDALE/UKDALE.h5')
REDD = os.path.join(dirname, '../../data/REDD/REDD.h5')
REFIT = os.path.join(dirname, '../../data/REFIT/REFIT.h5')
MODEL_CKPT_PATH = 'model/'
MODEL_CKPT = 'model/model-{epoch:02d}-{va... |
f2b7b6edcb6e8938c99a7f685945432bed8aaa8b4c81686770f443d57018e264 | Python | 657 | 26 | """
This script mainly contains functions needed for logging
Author: Edward Ferdian
Date: 27/02/2019
"""
from datetime import datetime
from time import time
def calculate_time_elapsed(start):
'''
This function calculates the time elapsed
Input:
start = start time
Output:
... |
1506b356854d35a5ed1e365ef41d4d04aaddb205f48660392492efd40055f59d | Python | 658 | 24 | # converts between two annotation sets. First column of input is assumed to be the "from" annotations, and second column is the "to" annotations
# i.e.
# ENST00000517143 NR_046932
# will convert from ensembl to refseq
from collections import defaultdict
class AnnotationConverter:
def __init__(self, annotC... |
46b07964a755bb4a0f799bc812a620ea6230a37de63181f4b73fac33b640e3e0 | Python | 658 | 14 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# 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
#
# httpwww.apache.orglicensesLICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
666e4d03cbcdde471082bc926d2bc2a28ad641584846fa2e1bfae7bef648ccda | Python | 658 | 14 | # Copyright 2021 Huawei Technologies Co., Ltd
#
# 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
#
# httpwww.apache.orglicensesLICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... |
671fc87214339f502f4958d26be839cc3ec6e262e3c5fbaac13b4e0d5e255194 | Python | 658 | 25 | # Copyright (c) Open-MMLab. All rights reserved.
import torch
from .hook import HOOKS, Hook
@HOOKS.register_module()
class EmptyCacheHook(Hook):
def __init__(self, before_epoch=False, after_epoch=True, after_iter=False):
self._before_epoch = before_epoch
self._after_epoch = after_epoch
s... |
196fb4df7009e4226d4ac6628968004fa6b9fe2289207905fd4cbc4fc0bdf077 | Python | 660 | 37 | import os
import pandas as pd
import tmkit as tmk
from . import dir_data
fdir = os.path.join(dir_data, "lips-")
def test_read_helix_surf():
df = tmk.feature.read_helix_surf(
fp=fdir,
prot_name="1xqf",
file_chain="A",
id=1,
)
assert df.shape == (155, 5)
def test_featur... |
875ce1a390c1daa98e3b4655cdb604b8f08be6afd357d1c9bc2e99e25375f60d | Python | 660 | 14 | """
SFNO - Spherical Fourier Neural Operator
Replaces the default SpectralConv (a convolution in the frequency domain
over Fourier basis functions) with a SphericalConv (a convolution over the
spherical harmonic basis functions)
"""
from ..layers.spherical_convolution import SphericalConv
from .fno import FNO, partial... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.