sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
a53423f6ed0b7a3189dfc17357dc3bda87d3cd291e25a0d48e7661146a3cedd6 | Python | 2,867 | 89 | import torch
from bindsnet.network import Network
from bindsnet.network.monitors import Monitor, NetworkMonitor
from bindsnet.network.nodes import IFNodes, Input
from bindsnet.network.topology import Connection
class TestMonitor:
"""
Testing Monitor object.
"""
network = Network()
inpt = Input(... |
64a5d1172e0cc6448f9223a3e5a264e6a238f15fea3bbeb859149bbf7c6c3239 | Python | 2,868 | 73 | from dival import TaskTable
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.utils.data.datasets import CachedDataset
from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset
from dliplib.utils.reports import save_results_table
from dliplib.utils.weights im... |
81c26c8c0041c96b6e4ad06444e233b7dc174014951ef75613616fb0f5e8d392 | Python | 2,868 | 85 | """
This script conducts enrichment analysis for XCI and sharing.
"""
import numpy as np
import pandas as pd
import session_info
from pyhere import here
from functools import lru_cache
from scipy.stats import fisher_exact
from statsmodels.stats.multitest import multipletests
@lru_cache()
def get_deg():
fn = here("... |
545c0a1433d20bc78c6c0fb52bef02672acb17a65d5ed3cc7a3dbefe5d6972b8 | Python | 2,870 | 82 | # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Writing out outputs."""
from nipype.pipeline import engine as pe
from nipype.interfaces import utility as niu
from niworkflows.interfaces.bids import DerivativesDataSink
def init_sdc_unwarp_report_wf(n... |
0ba2c6fe78c8107989cd9c1ab8d8f9ee769e2d2c502961bf23b5f96bf729d52b | Python | 2,872 | 78 | import numpy as np
import pandas as pd
from scipy import optimize
from sklearn.linear_model import LinearRegression, HuberRegressor
eps = 1e-2
class SaturationModel():
"""
Saturation model with two linear models
"""
def __init__(self, thr_saturation=0.01, model_type='huber') -> None:
self.thr... |
59c0c652ebafb5377520e669128a7b9c2cd06fe3caa9b525a93ab3e9603e0678 | Python | 2,873 | 79 | """
Wrapper for KNNSurvival to work with the experiments script.
Authors: George H. Chen, Lexie Li, Ren Zuo
"""
import numpy as np
import pandas as pd
import sys
from sklearn.neighbors import KNeighborsClassifier
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn_pandas... |
afcef21d7db12a7296d67fce6842333fa8c43d8d1cb214d58d4c64b1aa92f1d2 | Python | 2,878 | 88 | from __future__ import annotations
from collections import defaultdict
from typing import List
import numpy as np
from libs.common.metrics import Metrics
class NS:
def __init__(self, p: int, num: int, obj_var: List) -> None:
self.p = p
self.num = num
self.obj_var = obj_var
def fit... |
f254f216b0ae225b6e0796b2abfc2de82eeff08daf5218044b788ac76f1eb70c | Python | 2,879 | 92 | from typing import Any, Optional
import numpy as np
import torch
from torch.nn import functional as F
from tqdm import trange
class TransformerBase(torch.nn.Module):
def __top_k_logits(logits: torch.Tensor, k: int) -> torch.Tensor:
""" From https://github.com/karpathy/minGPT/blob/master/mingpt/utils.py ... |
2fc1b2755f2d03e5bf93b7cb2ed8d50f30fffbb62dadbc759c4ec213667b7ca3 | Python | 2,880 | 82 | import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import numpy as np
class IRadonMap(nn.Module):
def __init__(self, ray_trafo, post_process, fully_learned, coord_mat=None):
super(IRadonMap, self).__init__()
self.num_detectors = ray_trafo.range.shape[-1]
self.line... |
676dcc6cae4ab79d7bb11644e66a299a8b419db5c456af16c0c82d7d6901e945 | Python | 2,882 | 60 | import torch.nn as nn
from torchdiffeq import odeint
from CEL.networks.models.aphynity_networks import DampedPendulumParamPDE, ReactionDiffusionParamPDE, DampedWaveParamPDE, MLP, ConvNetEstimator
from functools import partial
from typing import Literal
from CEL.utils.register import register
# from CEL.networks.networ... |
fc051b3d13e2bdf015ddd633070dc7ff801cb107a3970ac2d634b6d31d631fcf | Python | 2,882 | 83 | #!/usr/bin/env python
# coding:utf8
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
torch.manual_seed(123456)
class LSTM(nn.Module):
"""
Implementation of BLSTM Concatenation for Stance Classification Task
Final representation is concatenati... |
2d922f2d36b1110e90338f656fced41296f1d297e02a6e4cb83a3802af9c195f | Python | 2,883 | 93 | import h5py
import numpy as np
from collections import Counter
def get_sparse_tensor(adj_matrix, default_value=0.):
idx = np.where(np.not_equal(adj_matrix, default_value))
values = adj_matrix[idx]
shape = np.shape(adj_matrix)
idx = np.transpose(idx).astype(np.int32)
values = values.astype(np.floa... |
9eb7ea556301c37e41933642118135a7e5150c0aa1327c672f43e546ad1bcd6f | Python | 2,883 | 99 | import numpy as np
import torch
import torch.nn.functional as F
from equivariant_diffusion.utils import assert_mean_zero_with_mask, remove_mean_with_mask,\
assert_correctly_masked
def rotate_chain(z):
assert z.size(0) == 1
z_h = z[:, :, 3:]
n_steps = 30
theta = 0.6 * np.pi / n_steps
Qz = to... |
ee3f53ccb6803c82fd308be717b3bf5946627f4010a28f1e07eec35b5c9bcac6 | Python | 2,883 | 78 | # add electrophysiology cellsdata to the trial
# retrieving and processing on LFP recordings from the .Paq file
from typing import Union
import numpy as np
from matplotlib import pyplot as plt
from scipy import signal
from imagingplus.main.core import ImagingTrial
from imagingplus.plotting._utils import plotting_dec... |
03eb9fb899812530bc816981684dbd5c4b3b409ea4dd6e27220b567e68346bf5 | Python | 2,884 | 80 | # https://github.com/CuriousAI/mean-teacher/blob/546348ff863c998c26be4339021425df973b4a36/pytorch/mean_teacher/losses.py#L15
import torch
from torch.nn import functional as F
from torch.autograd import Variable
from torch import nn
def softmax_mse_loss(input_logits, target_logits):
"""Takes softmax on both sides ... |
65f525b40f37b28ee4059aeae1cdf8ea2ca79e57dff7064535411c89d707c73d | Python | 2,884 | 81 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for d... |
8e8eb6e70cf80ca4fb7559214a8611d37f005a75331865c50abf6cbf3edf09bf | Python | 2,884 | 68 | # Copyright (c) 2008-2026 the MRtrix3 contributors.
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Covered Software is provided under this License on an "as is"
#... |
0c370aec1fbd03da5cdc4aa75f1b51a7bd90248cf8178cccb3beef1c886733b8 | Python | 2,885 | 85 | # Copyright (c) Open-MMLab. All rights reserved.
import os.path as osp
import time
from tempfile import TemporaryDirectory
import torch
from torch.optim import Optimizer
import mmcv
from mmcv.parallel import is_module_wrapper
from mmcv.runner.checkpoint import weights_to_cpu, get_state_dict
try:
import apex
exce... |
9494396e9bf270c1ec212728ea0629af0ca60c311e774c80f63f551d52cfd6bb | Python | 2,886 | 90 | import io
from copy import copy
import pandas as pd
def deps(self, pvalue=0.05):
data = copy(self)
groups = data.groups
regulation = data.original
regulation = [x[x[data.pvalue] < pvalue] for x in regulation]
regulation = [x[['gene_name', 'log2(fc)']] for x in regulation]
regulation = [x.rena... |
d3db3344140e4e0c0760673951b221fccf5af028c875dedeb32a5c387211c08b | Python | 2,886 | 95 | import os
import nrrd
import argparse
import skimage.io
import numpy as np
from pathlib import Path
from allensdk.core.reference_space_cache import ReferenceSpaceCache
def generate_region_mask(brain_regions, resolution=25, is_half_brain=False):
print("Downloading atlas...")
reference_space_key = os.path.join(... |
ce20d22e577e960baf106135b3faccce2653bec45eda83ee741153e237151b96 | Python | 2,888 | 81 | """
Performer implementation.
Wrapper for the Performer implementation from https://github.com/lucidrains/performer-pytorch
"""
from performer_pytorch import PerformerLM
from .transformer import TransformerBase
class Performer(TransformerBase):
def __init__(
self,
ordering,
voc... |
d948a659338862b250822e86f825c9a1002609767dc2e978996a5eeba63c9ec6 | Python | 2,889 | 83 | from ..utils.utils import *
from ..models.zephir import ZephIR
from ..zephod.model import ZephOD
def build_models(
container,
dimmer_ratio,
grid_shape,
fovea_sigma,
n_chunks,):
"""Compile PyTorch models for tracking.
Models are built according to user arguments. Zephod is only built when... |
0c273b0445a10492c00448f9b6abc08e2bdefb59be22e5d5f0087e2c4efc589f | Python | 2,890 | 117 | """Data structure for leaf node of tries.
The leaf nodes should support specificity queries.
"""
from easyDesign.utils import trie
class KmerLeaf(trie.LeafInfo):
"""Store info in each leaf node on the k-mer leading to the leaf.
This stores a dict, d: {taxonomy identifier: {sequence identifiers}}
giving... |
2fd471ab0830bc43e79f0db98284902ed2017ed9a986ef21c28d9907aec52e7d | Python | 2,890 | 86 | #'#################################################################################
#'#################################################################################
#' Standardize Gene expression data
#'#################################################################################
#'##############################... |
41975342de980cc0907f651eee62e7466d6af2a3b66cf7a83bcf4068ebc7e6c7 | Python | 2,891 | 66 | """Test memory functionality."""
from langchain_classic.memory.summary_buffer import ConversationSummaryBufferMemory
from tests.unit_tests.llms.fake_llm import FakeLLM
def test_summary_buffer_memory_no_buffer_yet() -> None:
"""Test ConversationSummaryBufferMemory when no inputs put in buffer yet."""
memory =... |
698a10dbb5a1cf5b3e26682dc154d54a0063d8c5cf5cbe44bc5a41a7b8c068c8 | Python | 2,891 | 61 | from NeuronModel.NeuronClass import neuronClass
import numpy as np
import matplotlib.pyplot as plt
hsv = plt.get_cmap('hsv')
def colors(n):
return hsv(np.linspace(0., 1.0, len(n)+1))
class integrate_and_fire(neuronClass):
parameters = {'save': True, 'spike': True, 'tau': 10., 'R': 10., 'E_l': -65., 'V_th': -5... |
9b5ef2b033e4fb3ceee85f2f2a15c6349af410e83a48e8a8d1aaed0451252143 | Python | 2,892 | 79 | ## This script extracts XCI and generates a heatmap.
import session_info
import polars as pl
import seaborn as sns
from pyhere import here
def get_degs(region):
fn = here(f"differential_expression/{region.lower()}",
"_m/genes/diffExpr_maleVfemale_full.txt")
return pl.read_csv(fn, separator="\t")... |
a566207b9b3d70a3113e5227046819b221b79878096629a9e85fea862988c272 | Python | 2,892 | 81 | import subprocess
import re
import os
def get_current_version():
try:
completed_process = subprocess.run(["git", "describe", "--tags", "--abbrev=0"], check=True, text=True, stdout=subprocess.PIPE)
current_version = completed_process.stdout.strip()
except subprocess.CalledProcessError:
c... |
7207a52fed4685fc25fea4e1116f39e63c7ac6aa0900992aeb626b707973fada | Python | 2,893 | 89 | from typing import Dict, Optional
import torch
import torchvision
from bindsnet.encoding import Encoder, NullEncoder
def create_torchvision_dataset_wrapper(ds_type):
# language=rst
"""
Creates wrapper classes for datasets that output ``(image, label)`` from
``__getitem__``. This applies to all of th... |
33d32f19108cce10d5720b62bbbf1b2b361e9053c18c20f0eb77fe39377ca962 | Python | 2,897 | 99 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
import nibabel as nib
from time import time
from dipy.data import get_sphere
from dipy.core.gradients import gradient_table
from dipy.io.gradients import read_bvals_bvecs
from dipy.reconst.shm import Csa... |
0d110c8c6e5de5b3a5a7a0da3ceaed3c6ba89b6058217f60bac478fdea395eed | Python | 2,899 | 67 | from bindsnet.models import DiehlAndCook2015, TwoLayerNetwork
from bindsnet.network.nodes import DiehlAndCookNodes, Input, LIFNodes
from bindsnet.network.topology import Connection
class TestTwoLayerNetwork:
def test_init(self):
for n_inpt in [50, 100, 200]:
for n_neurons in [50, 100, 200]:
... |
dae224395401a774b4f61005eb232d650c7154b540c4381ebee33ef55275c17a | Python | 2,901 | 73 | import os
import matplotlib.pyplot as plt
plt.rc('savefig', format='pdf')
plt.rc('axes', titlesize=8) # fontsize of the axes title
plt.rc('legend', fontsize=8) # legend fontsize
import torch
import torch.nn as nn
from data import generate_recog_data, recog_chance
from plotting import plot_tr... |
6d58b8f819010e7a8fcb0a0d0861ffbc8b98ef5f1e5369aef0cd5a8fa1768a7c | Python | 2,902 | 81 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
0375a8da977bde46cb87394fe9fc982f5fffe2114256b0e6b91ddb8177a39015 | Python | 2,906 | 89 | from typing import Optional, Tuple, Union, Dict
import math
import torch
import torch.nn.functional as F
from torch import Tensor
from torch_geometric.nn.models.schnet import ShiftedSoftplus
from torch_sparse import SparseTensor
import torch.nn as nn
from torch_geometric.nn import Linear
from torch_geometric.nn.conv im... |
010cf4c286656d7b808db7182bcb31294a38d716719673ffd1d8c375bb65183f | Python | 2,907 | 77 | # Load in model weights and evaluate its goodness (ECE, MCE, error) also saves logits.
import keras
import numpy as np
from keras.datasets import cifar10, cifar100
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, Dense, ... |
553f6bbf9dbba830538b4dc6df9599258683639cef11e0a32828463d16544f25 | Python | 2,907 | 81 | from typing import Any
from typing import List
from typing import Optional
from typing import Tuple
import numpy as np
import torch
from neuralpredictors.training import device_state
from neuralpredictors.training import eval_state
from torch.utils.data import DataLoader
from ..models.model import Model
def compute... |
ed2541618eb176c32ab554ec570469525dc0101397f333a735e3320a20e3cbd3 | Python | 2,908 | 90 | # -*- coding: utf-8 -*-
"""
Created on 20 may 22
@author: degano
"""
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from scipy import stats
import pandas as pd
import scipy.stats
from mlxtend.evaluate import permutation_test
from statsmodels.stats.multitest import multipletests
... |
61d9a850927b320d26d3cc110daa3483b963188d85e3b6156f87005f4fde4849 | Python | 2,911 | 86 | # Copyright 2024 DeepMind Technologies Limited
#
# AlphaFold 3 source code is 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... |
659d97bf441e59ca15f5c9a7f6b2a34882787b5336883bedf66d04f1dc8ee206 | Python | 2,912 | 81 | import numpy as np
import copy
from InitFunctions import gaussian
import matplotlib.pyplot as plt
hsv = plt.get_cmap('hsv')
def colors(n):
return hsv(np.linspace(0., 1.0, len(n)+1))
class neuronClass:
parameters = {'save': True, 'spike': False}
def __init__(self, P=1, init=gaussian(-60., 1.), **kwargs):
... |
78f68beda3c0844dc3c257f9cb3909ae59993bf8a2ea07a830c61ba044df3d3d | Python | 2,913 | 69 | from .dopri5 import Dopri5Solver
from .bosh3 import Bosh3Solver
from .adaptive_heun import AdaptiveHeunSolver
from .fixed_grid import Euler, Midpoint, RK4
from .fixed_adams import AdamsBashforth, AdamsBashforthMoulton
from .dopri8 import Dopri8Solver
from .misc import _check_inputs, _flat_to_shape
SOLVERS = {
'dop... |
f2e7625e3260ef9e8fdf131fb265e5a8d22ecde5fdba5ce22d318dbe9d0bd305 | Python | 2,913 | 73 | import torch
import numpy as np
import csv
try:
from torchdiffeq.__init__ import odeint_adjoint as odeint
except ImportError:
from torchdiffeq import odeint_adjoint as odeint
def expression_maker(val):
#return(1/6 *(val + 3))
return(val)
def readcsv(fp, device, noise_to_add, scale_expression):
pri... |
0d7aef5dd2492283697ea9a01f94f8a8027dade036aa902c0c72330ecd08f5db | Python | 2,915 | 73 | import numpy as np
import os
import pandas as pd
from mimic3benchmark.util import dataframe_from_csv
def read_stays(subject_path):
stays = dataframe_from_csv(os.path.join(subject_path, 'stays.csv'), index_col=None)
stays.INTIME = pd.to_datetime(stays.INTIME)
stays.OUTTIME = pd.to_datetime(stays.OUTTIME)
... |
1218e746523f27d8297aa02f5eb29944a4d9aaaa4981d056c81d3a8543e04976 | Python | 2,915 | 104 | import functools
from pathlib import Path
import pyteomics.mztab
from click.testing import CliRunner
from casanovo import casanovo
def test_train_and_run(
mgf_small, mzml_small, tiny_config, tmp_path, monkeypatch
):
# We can use this to explicitly test different versions.
monkeypatch.setattr(casanovo, "... |
bfa3b77b825a58bc3339345be6006f2720d42d6bacc20acae9a80246cdc92202 | Python | 2,915 | 92 | from .balanced_class_indices import balancedClassIndices
from .class_weights import classWeights
from .load_data import ClassificationDatasetMemory
from .load_data import loadDataset
from .mlp import MLP
from .load_module import loadModule
from .add_weight_decay import addWeightDecay
__all__ = [
"balancedClassIndi... |
6088e711ae2486f327d5fcbe7d6e703c5dd46792c0932847eefada29d4a59623 | Python | 2,916 | 82 | import torch.nn as nn
import torch
class vgg2(nn.Module):
"""
VGG version 2.
"""
def __init__(self, drop, model_depth, num_classes, in_channels):
super().__init__()
# Define convolutional block configurations based on number of layers
if model_depth == 1:
cfg = [8,... |
9eace515bd3edb08091750f3cdd4b82563e368c4e4d23f49955316a3076d35dd | Python | 2,916 | 63 | # Copyright (c) DP Technology.
# 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 absolute_import, division, print_function
import numpy as np
import csv
from typing import List, Optional
from collections import defaultdic... |
4358fbe04c94b9f86a139ce7144fa5623647239369632464985a60f8e3ba98f3 | Python | 2,917 | 58 | # Copyright 2020 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... |
091ec179f7abf759b78769a0bf122696f3c004cdcc1a5cbcad33a03d13bf72a7 | Python | 2,919 | 89 | """
Test classes and function in module openff.toolkit.typing.engines.smirnoff.plugins
"""
import pytest
from openff.toolkit import ForceField, Quantity
from openff.toolkit.typing.engines.smirnoff.plugins import (
_load_handler_plugins,
load_handler_plugins,
)
def test_force_field_custom_handler():
"""T... |
dc97e3828e040efdc433df5d14268ff0d4e398cdef885939ce8f289a8728c420 | Python | 2,920 | 79 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-white')
plt.rcParams.update({'font.size':15})
plt.rc('xtick', labelsize=36)
plt.rc('ytick', labelsize=36)
LR_Results = pd.read_csv("../../logs/linear_Regression/prediction_per_actual.csv")
XG_Results = pd.read_csv("../../l... |
ee3cbfc026102a12a5b724e1c14e64d21956adbadd8bd49e696df701b699013d | Python | 2,920 | 85 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
5cd5c200b80a8a3a7dc92a9c56db7f744e744c6ae59099e361030ee2be87fee6 | Python | 2,924 | 68 | import numpy as np
import os
import matplotlib
def binwidth2binedges(binwidth: np.ndarray, fmin: float, fmax: float) -> np.ndarray:
nbins = int(np.ceil((fmax-fmin)/binwidth))
return fmin + np.arange(nbins+1)*binwidth
def construct_firings_from_spktrains(spk_trains, prim_channels=None):
""" Construct Moun... |
811318689a5f3af7c8e8f6f15faba0e9099f6eb4a74061737f38a17fc6d5d13f | Python | 2,932 | 89 | '''
Author: Zhenyu Yuan
Email: zhenyuyuan@outlook.com
Brief: model defination for sequence super resolution model
Refer: https://github.com/leekh7411/Fast-Audio-Super-Resolution/blob/master/model.py
'''
import tensorflow as tf
import tensorflow.keras as keras
import math
## Define function for upsampling
... |
2d0d42f177302f8f5eedf8e9d9ebe2fb34ec90f9c2f1ee26041ac8f7aa719ce6 | Python | 2,933 | 85 | import numpy as np
import itertools
import multiprocessing
from dipy.reconst.shm import sh_to_sf_matrix, order_from_ncoef
def convert_sh_basis_parallel(args):
sh = args[0]
B_in = args[1]
invB_out = args[2]
chunk_id = args[3]
for idx in range(sh.shape[0]):
if sh[idx].any():
sf =... |
cb7f73130af6934924c49bfd43a65a011b29a1f7f4a8aed9a43b1520e47e0989 | Python | 2,933 | 74 | from dival import TaskTable
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.utils.data.datasets import CachedDataset
from dliplib.utils.helper import select_hyper_best_parameters, load_standard_dataset
from dliplib.utils.reports import save_results_table
from dliplib.utils.weights im... |
9ef45b3beac072364683a7a6120a74bd7dccba531761c5deb756eeb5876f0e6e | Python | 2,934 | 80 | # Load in model weights and evaluate its goodness (ECE, MCE, error) also saves logits
import keras
import numpy as np
from keras.datasets import cifar10, cifar100
from keras.preprocessing.image import ImageDataGenerator
from keras.layers.normalization import BatchNormalization
from keras.layers import Conv2D, Dense, I... |
51de6b72e3bc58ed4cec5bdbf6a8e696773cc6d520582a1e870d53aab2d1c69b | Python | 2,936 | 76 | """
Plot the correlation across subjects of a behavioral measure between two
halves of the sessions within a task.
"""
import argparse
import data_analysis_utils as dana
import data_behavioral_measures as bmeas
import itertools
import matplotlib.pyplot as plt
import numpy as np
import os.path as op
import pandas as pd
... |
9e1d6dcad17c903bd1cd4af66d4773403e338970455f725dac140c606c1d40e3 | Python | 2,937 | 60 | import numpy as np
import nibabel as nib
import os
import sys
rep=sys.argv[1]
d="/jukebox/griffiths/bert-brains/"
#mask=nib.load(d+"21styear_data/whole_brain_mask.nii.gz").get_fdata().astype('bool')
parce1="/jukebox/griffiths/bert-brains/black_data/Schaefer1000_3mm.nii.gz"
parce2="/jukebox/griffiths/bert-brains/sl... |
d26ccfac5e2afb34ca57f9f9792502a245051781b7b8f0d12bb1b37de608a923 | Python | 2,937 | 80 | # coding=utf-8
import torch
import copy
import torch.nn.functional as F
from alg.opt import get_optimizer
import torch.autograd as autograd
from datautil.util import random_pairs_of_minibatches_by_domainperm
from alg.algs.ERM import ERM
class MLDG(ERM):
def __init__(self, args):
super(MLDG, self).__init_... |
1371e3c234d2d29be783ee817ecc7e65e8e0b36024b95b6c3c256b2054a9720d | Python | 2,938 | 85 | import math
import torch
import torch.nn as nn
from einops import rearrange
class RotaryEmbedding(nn.Module):
def __init__(self, dim, min_freq=1 / 2, scale=1.):
super().__init__()
inv_freq = 1. / (10000 ** (torch.arange(0, dim, 2).float() / dim))
self.min_freq = min_freq
self.scale... |
8c6f0dab48798bf425978e0f3a41f43ec35b654ff50948e190bd98ffbe82c94e | Python | 2,939 | 90 | # -- coding: utf-8 --
# @Time : 2022/10/15 11:20
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : homo_random_config.py
from yacs.config import CfgNode as CN
# --------------------------------------------------------------
# Config of model
# --------------------------------------------------------... |
79ed9c3875b775a39c764c5fc38d116866b4a2549920bd052bc80c908a9ff1bb | Python | 2,941 | 97 | #! /usr/GenNet/env_GenNet/bin/python
#'#################################################################################
#'#################################################################################
#' Train a neural network defined in Keras
#'####################################################################... |
d53e0ff9356b01cafd91b0d49284c27bdd96fb2db89df11132e4b49abd6c7c01 | Python | 2,941 | 95 | from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error... |
9ab252ba28e27b1cae44474c1467a1d0170d7ec738366c8b4f362640cf512a81 | Python | 2,942 | 63 |
import torch
import torch.nn as nn
from torch_geometric.utils import to_dense_batch
class Combine(nn.Module):
def __init__(self, ligand_model, target_model, d_model=256, nhead = 8, num_encoder_layers=3, num_decoder_layers=3, dropout_rate=0.15):
super(Combine, self).__init__()
self.... |
8cc509b14d75adc27c84609e44be5935ac315ac4ff35365c05eb0285d19a2fe2 | Python | 2,945 | 58 | """Follow-up: are the state-discriminating lncRNAs enriched for natural antisense transcripts (NATs)
of canonical T-cell genes, and do those antisense lncRNAs co-vary with their SENSE partner?
If yes, the 'novel catch' is a distributed antisense-lncRNA programme tracking T-cell identity."""
from __future__ import annot... |
d1de433228fc1fc14efb348fd2ae8ac326236964837c3f5601afb46de43872c1 | Python | 2,945 | 73 | import tqdm
from src import constants
from src import utils
def collect_tools_from_repos():
repositories = utils.load_json(constants.PROCESSED_REPOSITORIES)
tools = {}
for repository in tqdm.tqdm(repositories.values(), desc="Retrieving descriptions"):
if not repository["processed"]:
... |
0ddb0992675ba2bef3c3e73b7f2f6198f88714c5eec9ce36c401a2483ade9cd8 | Python | 2,948 | 112 | #!/usr/bin/env python
"""
Extract aseg volumes from a set of FS6 processed subjects
- Output an R-compatible CSV summary file
- Include volumes normalized to estimated total intracranial volume (eTIV)
Usage
----
label_volumes.py <FS subjects directory>
label_volumes.py -h
Authors
----
Mike Tyszka, Caltech Brain Imagi... |
b3e9996578d1478a07686a12b57c4cd848cf688023781b29972ef91cd2eb6a0a | Python | 2,949 | 117 | from __future__ import annotations
import numpy as np
from libs.function.function import Tanh
from libs.model.network import Network, NetworkRandom
from libs.model.neurons import Identify, Linear
class Model:
def __init__(
self,
input_dim: int,
hidden_dim: int,
output_dim: int,
... |
940fc7e5a39930982ed62990980641fe22fb2dfd08bde7d25741ccf3b1a924b8 | Python | 2,950 | 83 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 12:26:12 2020
@author: gritti
"""
import os, glob, shutil, tqdm
import numpy as np
from numpy.random import default_rng
###############################################################################
# select folder containing all image folders to be analysed
parent_... |
234ff00da212da76a2c105cc89ed092fe7b12f1cd3c4d1a4614cdbbff7a62c40 | Python | 2,951 | 77 | import pathlib
import re
from urllib.request import Request, urlopen
import pytest
def find_readme_links() -> list[str]:
"""Yield all the links in the main README.md file.
Returns
-------
readme_examples : list[str]
The list of links included in the README.md file.
"""
if "site-packa... |
30c455def598e97b2d9186d91aa089a9bb02a706f3b7fa7162df477598d37379 | Python | 2,955 | 74 | import pandas as pd
import numpy as np
from skimage.morphology import binary_dilation, disk, medial_axis
from skimage.measure import find_contours
def read_example_data(fname, N_modes=50):
# read points
contour = pd.read_csv(fname)
if contour.x.values[-1] != contour.x.values[0]:
# print('Appending... |
4e99c848b30981e92b39e8a3c39ae545665508641e88e44a524693cafdf9dfbc | Python | 2,955 | 92 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 15:53:06 2024
@author: jkosnoff
"""
import numpy as np
def IQR_Outlier_test(data):
"""
A test for outliers based on interquartiles
See https://online.stat.psu.edu/stat200/lesson/3/3.2
Parameters:
- x: array-like, input ... |
2be94305e719076630b144e83fb0aeecd22e5c3ac2cc316bbee944094472bcba | Python | 2,956 | 85 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
1c290143ca931ffd419a8903821f4f934080b91c6b4433201604cbc4f244a223 | Python | 2,959 | 75 | import gzip
if __name__ == "__main__":
array_file = open("../mammalianChip_36K_probes.tsv", "r")
scored_probes_file = gzip.open("../allProbes_scored_GW.tsv.gz", "rt")
output_file = gzip.open("../36K_probes_SNV_species.tsv.gz", "wt")
# Construct dictionary of probes submitted to Bret
inf_type_dict ... |
2b61e8d824a753ed2cc47c607f745cb3dc6546b5c12043171a4aed09ba6ba8f6 | Python | 2,959 | 86 | ###########################################################################################
# Elementary tools for handling irreducible representations
# Authors: Ilyes Batatia, Gregor Simm
# This program is distributed under the MIT License (see MIT.md)
#################################################################... |
6e117dbf72ea1013d61fdfdea4a61573bcaa9b248b6c6122f1f6e47ec7172351 | Python | 2,959 | 64 | import pandas as pd
import numpy as np
import re
def get_id(x,gtf_data_new):
chr=x.split(':')[0]
site=int(x.split(':')[1].split('.')[0])
gtf=gtf_data_new.loc[(gtf_data_new['chr']==chr)&(gtf_data_new['strat']<=site)&(gtf_data_new['end']>=site),:]
if len(set(gtf['strand']))>1:
gtf=gtf.loc[gtf['st... |
6f99eac5638bffe7d913a07f6f735718b5beee89b57b2826b69788913a3e7d3d | Python | 2,964 | 80 | # -*- coding: utf-8 -*-
"""
Created on Sun Aug 23 19:24:22 2020
@author: nishe
"""
import numpy as np
from scipy import signal
#import pdb
#%%
def bandpassSig(sigIn, subBand, Fs, timeDim=-1, badChannels=None, filterOrder=8, discardTime=None):
if len(sigIn.shape) == 1:
if not (timeDim==0 or timeDim==-... |
46846803ad6cff71917c731e3c8ae77e3d21f3e3ad899d102305ccd9a8fbd150 | Python | 2,965 | 118 | import os
import sys
import re
import types
import itertools
from cgatReport.Tracker import *
from RnaseqReport import *
class MappingSummary(RnaseqTracker, SingleTableTrackerRows):
table = "view_mapping"
class TophatSummary(RnaseqTracker, SingleTableTrackerRows):
table = "tophat_stats"
class BamSummary(... |
5f5761c13e509e18b678e68f327a42e9a4f2c25d35e21ae82653ba623312aca6 | Python | 2,966 | 85 | import warnings
from typing import Any
from pydantic import field_validator
from langchain_classic.base_memory import BaseMemory
from langchain_classic.memory.chat_memory import BaseChatMemory
class CombinedMemory(BaseMemory):
"""Combining multiple memories' data together."""
memories: list[BaseMemory]
... |
a5f2daa5d059cad3a229a921347b5abcd4e8e0513b1fba6deb152fa57336b74d | Python | 2,969 | 84 | """Get the outer-shell of each layer within SSp-bfd (voxels on the borders of the layer).)"""
import json
import numpy as np
import pandas as pd
import voxcell as vc
from tqdm import tqdm
from scipy import ndimage
def get_shell(indices, depth, return_mask=False):
"""
Generate a shell around specified indices ... |
1b610eea33b3eef774c330eb90a3638e1ee3a6eee0e6f52850d0dfe46d14c5cc | Python | 2,970 | 81 | import logging
import os
import socket
import sys
import pandas as pd
from configs.configs import get_config_dict
from helpers.evaluation import leave_every_other_out_split, get_tvfc_estimates
from helpers.hcp import get_human_connectome_project_subjects, load_human_connectome_project_data
if __name__ == "__main__"... |
6d4582d92aed9149c03d11927026f3ce8faf608cbc209f8199a1a477dfa5bc25 | Python | 2,970 | 65 | """
2023.08.30
author: femke.hurtak@epfl.ch
Script to make all the plots for the paper.
"""
import os
from flower_plots import draw_all_flower_plots
from connectivity_stats import compute_connectivity_stats, compare_connectivity_stats
from distribution_fit import compare_distributions
from louvain_clustering import dr... |
c7ffa26aa82a813f2a80fcd0829206a373e22b17164b14452debda3f10185002 | Python | 2,970 | 88 | import os
import torch
from torch.autograd import Variable
import pickle
"""
Note: The meaning of batch_size in PTB is different from that in MNIST example. In MNIST,
batch_size is the # of sample data that is considered in each iteration; in PTB, however,
it is the number of segments to speed up computation.
The g... |
732f99ef9a32301239e9da9e3bab24d09e13767131d1e3cd5ee3d25cb605de19 | Python | 2,973 | 84 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for d... |
ab10c3337ccc2827dc3d1741f8a6a2a06211c4c9b91d2d0a3dc188ac8c9c393c | Python | 2,973 | 72 | """Plateau early-stopping, the pure decision logic (no torch).
Reproduces the Keras ``EarlyStopping(monitor, patience, min_delta,
restore_best_weights=True)`` behaviour that the original TF DeepMapper used and
that was lost in the PyTorch port: train until the monitored held-out metric
stops improving for ``patience``... |
bcf9f2e10530de1a4829aee6c6f1c97ebbdd9349a282c476122bb32e4b7ddea9 | Python | 2,974 | 84 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
d60248d06f6cfaf92b1f6551d72908cffa184f33caaa7a1fbaa806d149a5bc94 | Python | 2,974 | 87 | #
#
# Import SWC XTension
#
# @Biswanath Saha
#
# <CustomTools>
# <Menu>
# <Item name="SWC Importer 1.0" icon="Python3" tooltip="Calls the Imaris to import SWC">
# <Command>Python3XT::XTImportSWC(%i)</Command>
# </Item>
# </Menu>
# </CustomTools>
import ImarisLib... |
74039e3c0a2ffb5c05007a07bb287f1bb8ce2aaffc8db6981b48ca71e1f2bdfd | Python | 2,975 | 82 | from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D
from tensorflow.keras.backend import clear_session
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import layers, Input, Model
def model_S_half_minimum(model_num):
... |
1311b2826fee39acbf2941abe5cf59e464a9510c5f5bbd4e86d739b9ba841c8f | Python | 2,979 | 99 | import unidecode
import torch
from torch.autograd import Variable
from collections import Counter
import observations
import os
import pickle
cuda = torch.cuda.is_available()
def data_generator(args):
file, testfile, valfile = getattr(observations, args.dataset)('data/')
file_len = len(file)
valfile_len... |
2aa52eeb3ae74f02caf78d11f81d046dae6ae69b5b302fdafc94ee6447a5bc70 | Python | 2,980 | 77 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from scipy.special import binom
from ..functional import cutoff_function, softplus_inverse
from math import pi as PI
"""
computes radial basis functions with exponential Bernstein polynomials
"""
class Envelope(torch.nn.Module):
... |
70953eeeb487db8bf1440b386a28924d22dff20edca5edaa7ac7ddea8aac3450 | Python | 2,980 | 95 | #!/usr/bin/env python3
"""
Separate bilateral prob atlas into hemispheric atlases
- assumes original atlas is centered on the anatomic midline and uses the voxel midplane to split the volumes
- Outputs a new 4D prob atlas with twice as many label volumes
Authors
----
Mike Tyszka, Caltech Brain Imaging Center
License
... |
e0420941eb675e4144fa862fc099c4708b96bef17c30a887c0acb05f66a7de76 | Python | 2,981 | 72 | from torch.utils.data import Dataset
import numpy as np
from torchvision import transforms
import torch
from .PredictionDataset import max_to_1, min_max_norm
import torch
import json
if torch.cuda.is_available() is True:
try:
import cupy as cu
from cucim.skimage.morphology import dilation, ball
... |
6db48306d1275615b5d12e420a6ea1403608fca97744d265ed435da5f89651e5 | Python | 2,982 | 113 | """Pydantic model for default configuration and validation."""
import subprocess
from typing import Optional, Union
import os
from pydantic import root_validator
# vfrom pydantic import Field, root_validator, validator
from pydantic.typing import Literal
# from typing import List
from models.base import BaseSettings... |
2849040a7458bae8f169733916a47c1ab151b99c9907931a088430556c690dee | Python | 2,983 | 74 | import torch
import torch.nn as nn
from typing import List
from typing import Union
from typing import TypeVar
Self = TypeVar('Self', bound = 'SiameseVGG')
class SiameseVGG(nn.Module):
"""Siamese VGG network for primary and neighbor-gene matrices"""
def __init__(self: Self,
cfg: List[Union[... |
88d0338223e47989648760ebc2645dd5dd155991c7e59fc9420c7c9e7c9fb9d1 | Python | 2,983 | 81 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for d... |
9f30e3c9e5f9c1a6cc861b850c4b6f623754eec67887b647baebdd8e91f4ef1c | Python | 2,983 | 86 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for d... |
1ac13f36488c4d146b4a3b39e0d23c4811cba21841dd29c1f9c54cae7196adae | Python | 2,984 | 86 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
643fe52d4faec41caba9d1244602e51938dabdf869c27ef89f0fb2a8fa3f841c | Python | 2,985 | 67 | import os
import socket
import sys
from configs.configs import get_config_dict
from helpers.rockland import get_rockland_subjects
from helpers.slurm import save_slurm_job_to_file, send_slurm_job_to_queue
if __name__ == "__main__":
hostname = socket.gethostname()
assert hostname == "hivemind" # all parallel... |
63c0211540423d921aea36c539fa2301f87486a504c9b55793ce6a5ea2c9b217 | Python | 2,986 | 83 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.pyplot as mpl
def shape_data(data):
timestamps = []
activeneurons = []
neuron = data[:,1]
neuron_list = np.unique(data[:,1])
for k in range(len(neuron_list... |
91a90f540c661270fc2e3d5a220efcd73ad22488b0dd4b0f0814b0a83fdd7cfa | Python | 2,991 | 103 | '''test_import - test importing all modules and pipelines
=========================================================
:Author: Andreas Heger
:Release: $Id$
:Date: |today|
:Tags: Python
Purpose
-------
This script attempts to import all the python libraries and
pipeline scripts in the cgat code collection.
Importing a... |
704c3e0674199c9cb6564db5e625bc49200fe85e36c5184667907a22d335fcc6 | Python | 2,993 | 98 | import re
# this is inspired by the tokenizer from NLTK
# https://www.nltk.org/_modules/nltk/tokenize/treebank.html
STARTING_QUOTES = [
(re.compile(r"^\""), r"``"),
(re.compile(r"(``)"), r" \1 "),
(re.compile(r"([ \(\[{<])(\"|\'{2})"), r"\1 `` "),
]
# punctuation
PUNCTUATION = [
(re.compile(r"([:,])... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.