sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
9fda605e626f969d48c312c172b88480aab0b5c1363679af3a84707c7dc87531 | Python | 5,094 | 135 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 4 15:36:51 2021
@author: athanasiadis
"""
"""
attack
______________________
This is a script that runs the adversarial decoder on the dataset of choise.
Input:
- several functions needed for the adversarial decoder.
Output... |
05f3054ddb2a8e7baa79d56d56e1c99d316bbd4183d85f2f9226698b335b3135 | Python | 5,096 | 98 |
import argparse
# Training settings
parser = argparse.ArgumentParser(description='PyTorch implementation of pre-training of graph neural networks')
parser.add_argument('--device', type=int, default=0,
help='which gpu to use if any (default: 0)')
parser.add_argument('--distributed', default=False, ... |
146f297643c70ec7930070ab11bd9c84cc1cb61ceb4db4e366cfec5e2d7a2a7f | Python | 5,097 | 147 | import numpy as numx
import pydeep.base.numpyextension as numxExt
from pydeep.base.activationfunction import Sigmoid
import pydeep.misc.visualization as VIS
import pydeep.misc.io as IO
# Set the same seed value for all algorithms
numx.random.seed(42)
# Load Data
data = IO.load_mnist("../../../../data/mnist.pkl.gz",Fa... |
2e201ceb2a19418f0d09dafebec324218507f179d35f2ab6ecea8a4dd4f28959 | Python | 5,102 | 146 | from typing import Any, cast
from langchain_core._api import deprecated
from langchain_core.language_models import BaseLanguageModel
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_core.output_parsers import BaseLLMOutputParser
from langchain_core.output_parsers.openai_functions import (... |
6bad747364bdb8973f3424883a1a56806da7626f4a15c001b784f11b49ed700e | Python | 5,102 | 142 | # -- coding: utf-8 --
# @Time : 2022/12/13 19:53
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : main_sr_rsc.py
import numpy
import torch
import sys
sys.path.append('../../')
import warnings
import datetime
import pickle as pkl
import os
import random
from BrainAlign.code.utils.logger import setup... |
b79e2e04ef900a91aaf37fce177c4a4352b8ef56521d7c9003463bb55699daf6 | Python | 5,106 | 100 | import copy
import warnings
warnings.filterwarnings("ignore")
class Enrichmentscope():
from .EnrichmentVisualization import dotplot
from .EnrichmentVisualization import enrichment_map
from .EnrichmentVisualization import enrichment_network
from .EnrichmentVisualization import gsea_heatmap
from .E... |
4ad26f1cbcc47576bcb9a2714be2d0b77bbb4838d5735f5441f31dfb9daec206 | Python | 5,112 | 125 | import numpy as np
import os
import pandas as pd
#SETUP
# Python file should be copied and run in the same folder as the csv files gathered from the Wavebreaker plugin
root = os.path.dirname(os.path.abspath(__file__))
# Set the frequency range (in µm) to be considered for the analysis
freqrange = [0.17, 0.23]
# Set ... |
54c1c745b32d83ea5860161b5e39615ecca58fb09fcd1b76c6e016b895da4492 | Python | 5,117 | 143 | import networkx as nx
import pandas as pd
from pgmpy.base import DAG
from pgmpy.metrics import BaseSupervisedMetric
class OrientationConfusionMatrix(BaseSupervisedMetric):
"""
Computes confusion matrix based metrics for comparing edge orientations in DAGs.
Treats edge direction as a binary classificatio... |
c0a9842f25568c591daebdbd448cfadc991d0e993fd8f9f22f611e40b3ff1aff | Python | 5,123 | 156 | import os
import pickle
import numpy as np
import csv
from OCC.Core.STEPControl import STEPControl_Reader, STEPControl_Writer, STEPControl_AsIs
from OCC.Core.TopLoc import TopLoc_Location
from OCC.Core.STEPConstruct import stepconstruct_FindEntity
from OCC.Core.TCollection import TCollection_HAsciiString
from OCC.Core... |
ad227759a469cb66f76e9390fe32f44ab2681266d60e4c4333161c38d62faf43 | Python | 5,125 | 128 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Hyperparameter search spaces for sklearn / XGBoost classifiers used in the
BERNN head sweep (train_ae_head_sweep.py) and the legacy GP sweep
(sklearn_train3_gp2.py).
All classifiers are now active (none commented out). XGBoost is included with
a richer parameter spac... |
db7c9bc59eae72a1eacb458e0bbf6867bf02f3b874ce697290ed9170c4553ec4 | Python | 5,126 | 153 | #!/usr/bin/env python
import argparse
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument("data_files")
arg_parser.add_argument("source_directory")
arg_parser.add_argument("target_directory")
arg_parser.add_argument("--suffix", default="")
arg_parser.add_argument("--save_separate_components", action="store_... |
999a7f7560f45a55983495cb3e0959c9d195b879ebc8c5ce7e1fe5e14056a0a6 | Python | 5,127 | 141 | # 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 typing import Optional
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from unicore.modules import TransformerEncoderLayer, Lay... |
cd7e3060dc4bdae3116b49797b1cb343d96407e34388eacbdcd91d73fa411990 | Python | 5,128 | 92 | """
Entry point script.
"""
import argparse
from scripts.ilp.kmer_frequency import compute_kmer_frequency
from scripts.ilp.ilp_kmer import solve_kmer_ilp
from scripts.deepsignal.label_deepsignal_extract import label_extract
def main_kmer_freq(args):
compute_kmer_frequency(
args.genome_ref,
args.m... |
fdd119f75164ae02bd147ca613b6dd3691015275230646473e5152d81ff2594e | Python | 5,128 | 142 | # -- coding: utf-8 --
# @Time : 2022/10/15 16:11
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : heco_config.py
import time
from yacs.config import CfgNode as CN
# --------------------------------------------------------------
# Config of model
# -----------------------------------------------------... |
fff63f703d6c8ae843542c615777105cd4cf0a490b3e0677a0e997199005928a | Python | 5,129 | 203 | """Internal representation of a structured query language."""
from __future__ import annotations
from abc import ABC, abstractmethod
from enum import Enum
from typing import TYPE_CHECKING, Any
from pydantic import BaseModel
if TYPE_CHECKING:
from collections.abc import Sequence
class Visitor(ABC):
"""Defi... |
d235913895cdf4c84d0c781e30e2a68a19d5554276bd2c445d3aa070614f1f1d | Python | 5,135 | 151 | import numpy as numx
import pydeep.base.numpyextension as numxExt
from pydeep.base.activationfunction import Sigmoid
import pydeep.misc.measuring as MEASURE
import pydeep.misc.visualization as VIS
import pydeep.misc.io as IO
# Set the same seed value for all algorithms
class CrossEntropyError(object):
''' Cross en... |
4f0a918fb592067dc9af40601eb47de085cfd6648bb815a73e726dffc0f548fc | Python | 5,136 | 134 | from keras.models import Model
from keras.layers import Input, Dense, LSTM, Masking, Dropout
from keras.layers.wrappers import TimeDistributed
from mimic3models.keras_utils import Slice, GetTimestep, LastTimestep, ExtendMask
from keras.layers.merge import Concatenate, Multiply
class Network(Model):
def __init__(s... |
81529714b14a2c86eed3d4c00ab0ea1c4aecc4612643479afe8e87d07af567f4 | Python | 5,136 | 122 | from nltk.parse.dependencygraph import DependencyGraph
from nltk.parse.malt import MaltParser
import os
import tempfile
from .stemmer import FindStems
from .postagger import POSTagger
from .tokenizer import Tokenizer
from .normalizer import Normalizer
class MyMaltParser(MaltParser):
def __init__(self, parser_dirn... |
28cb27330b4db66d128987195a7a65651780df3d8bb9f8ca7b2f70884939d7e7 | Python | 5,139 | 126 | """**Memory** maintains Chain state, incorporating context from past runs."""
from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
from langchain_classic.memory.buffer import (
ConversationBufferMemory,
ConversationStringBufferMemory,
)
from langchain_classic.memory.buffer_... |
a09214dea7daadd62cabc1248368f527a355c28e638e25740d42f64cfd7ea27d | Python | 5,139 | 126 | import tqdm, os
import numpy as np
from skimage import transform, morphology
from sklearn import preprocessing, linear_model, neural_network
from morgana.ImageTools import processfeatures
def generate_training_set( _input, gt,
sigmas=[.1,.5,1,2.5,5,7.5,10],
down_shape=... |
956f68dac017c3ad911f59733e047ea556c47675e78783b8a8e46eea28f03def | Python | 5,141 | 110 | import copy
import torch
from torch import nn
import torch.nn.functional as F
import numpy as np
class GaussianFourierProjection(nn.Module):
"""
Gaussian random features for encoding time steps.
"""
def __init__(self, embed_dim, scale=30.):
super().__init__()
# Randomly sample weights... |
931b5ebc64c9d114b90e975c0b3588cab63a227ca41d18a44df5e3e4a8141ae6 | Python | 5,142 | 154 | ####################################################################################
#
# 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... |
c2e28d07740fdd3c3aa79ccc972f00f6f8475f98faddc9568a22df8e6acfc96d | Python | 5,142 | 148 | import numpy as numx
import pydeep.base.numpyextension as numxExt
from pydeep.base.activationfunction import Sigmoid
import pydeep.misc.measuring as MEASURE
import pydeep.misc.visualization as VIS
import pydeep.misc.io as IO
# Set the same seed value for all algorithms
numx.random.seed(42)
# Load Data
data = IO.load_... |
05fcdc93c73f865acfe8d1b3c2627dbc7a86b690886ef12a8ebcdc646408ec99 | Python | 5,143 | 186 | import logging
import tempfile
from pathlib import Path
from MRdataset import MRDS_EXT
from MRdataset.config import MRException
from protocol import UnspecifiedType
THIS_DIR = Path(__file__).parent.resolve()
def configure_logger(log, output_dir, mode='w', level='WARNING'):
"""
Initiate log files.
Param... |
d78e1e69e627a2635d94cc4feb5bde71f0eb4d633d1fb4328ee5faa016f29125 | Python | 5,143 | 166 | #!/usr/bin/env python
import numpy as np
import gzip
import argparse
import os, warnings, sys
# with warnings.catch_warnings():
# warnings.filterwarnings("ignore", category=FutureWarning)
import nibabel as nib
PRECISION= 17
np.set_printoptions(precision= PRECISION, suppress= True, floatmode= 'maxprec')
import sys
im... |
a37aa5f33dbd5b65760c6403ffb79763a63fec1a340f72cad6f213c1792d4563 | Python | 5,146 | 104 | import torch
import torch.nn as nn
class convBlock(nn.Module):
def __init__(self, in_channels, out_channels):
super(convBlock, self).__init__()
self.cnn = nn.Sequential(
nn.Conv1d(in_channels, out_channels, kernel_size=3,padding=1,bias=False),
nn.ReLU(),
n... |
b19018f04fc200c3a816e4de027db3936ea0d5ba5cb1c2cd0bdb153f34e35c03 | Python | 5,148 | 140 | """API test for POST /api/cohort/facial-measurements/load
(api/routers/cohort.py's load_facial_measurements) - the endpoint that
attaches a Facial Anthropometrics batch export (api/routers/facial.py's
export_batch) to an existing cohort as a lazily-joined dataset. Pure request/
response plumbing; the join logic itself ... |
200b404b1f51ad4e8f4f181a7f4573358656c72565c601335b72888db25de1bb | Python | 5,149 | 163 | """Internal utilities for the in memory implementation of `VectorStore`.
!!! warning
These are part of a private API, and users should not use them directly as they can
change without notice.
"""
from __future__ import annotations
import logging
import warnings
from typing import TYPE_CHECKING
try:
imp... |
a6a3ed02f6a813170c068df6aaa730302bbe08b199a8c77ad19f6a5aa1818ad5 | Python | 5,149 | 171 | import logging
from typing import Dict, Optional, Tuple, Union
import pytorch_lightning as pl
import torch
from torch import nn
from torch.optim import Optimizer
from torch.optim.lr_scheduler import LRScheduler
from torch_geometric.nn import MessagePassing, radius_graph
from torch_scatter import scatter, segment_coo
... |
fcac763bb020f6fbbc9ab5808f60d87d141522b7b4c4a3f2446128a3a70aec27 | Python | 5,149 | 147 | # coding=utf-8
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.cuda.amp import autocast
from alg.modelopera import get_fea
from network import common_network
from alg.algs.base import Algorithm
import numpy as np
import re
class ERM(Algorithm):
"""
Empirical Risk Minimization (ER... |
889a38665d94b10b97d5538eb4ce32d3166fa5763a3eea84d3df09ccc69ea03f | Python | 5,150 | 130 | import pandas as pd
import numpy as np
import pickle, os, shutil
from math import sqrt
from zipfile import ZipFile
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from tensorflow.keras.optimizers import Adam
from tensorflow import cast,float32
from keras import backe... |
d02b759bf1aa1bcd2f47bd70f2915aa7b8c33631f83f8e725433ce630d6371cd | Python | 5,151 | 154 | from sklearn.model_selection import GridSearchCV
import pandas as pd
import numpy as np
import random
import sys
from pathlib import Path
from sklearn.metrics import roc_auc_score
from sklearn.ensemble import RandomForestClassifier, ExtraTreesClassifier, GradientBoostingClassifier
from sklearn.svm import SVC
i... |
a602a62b869298eabec8a60c4b82b16bd01b7986713a1f11d1a51a163c954262 | Python | 5,152 | 109 | # -- coding: utf-8 --
# @Time : 2022/12/18 20:53
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : load_mouse_region_tree.py
import json
from treelib import Node, Tree
tree = Tree()
tree.create_node('Human brain', 'Human brain')
def add_node(tree_dict, key_input):
#print(type(tree_dict[key_inp... |
342a6e6f3fef4bfcbdcc3c52e2120a7fdf23a0f752cb9692b08aef895456ed62 | Python | 5,153 | 137 | import torch
from CEL.networks.models.meta_model import ModelClass
from torch.autograd import Function
from itertools import chain
class InvariantPhy(torch.nn.Module, ModelClass):
def __init__(
self,
y_channels: int,
Wc_channels: int,
hidden_channels: int,
... |
565199904ae17abf9fe0f5236e561e48d6ff61c316536f1730b9284635d456a8 | Python | 5,153 | 109 | # -- coding: utf-8 --
# @Time : 2022/12/18 20:53
# @Author : Biao Zhang
# @Email : littlebiao@outlook.com
# @File : load_mouse_region_tree.py
import json
from treelib import Node, Tree
tree = Tree()
tree.create_node('Mouse brain', 'Mouse brain')
def add_node(tree_dict, key_input):
#print(type(tree_dict[key_inp... |
a2f18609a630ab3e5438690c5969af9bceca36e9ed36874327d0d26341bd7dd3 | Python | 5,154 | 119 | import unittest
import os
from EPI_MRI.EPIMRIDistortionCorrection import *
class TestPreconditioners(unittest.TestCase):
def setUp(self):
""" Initialize any common data or setup needed for the tests. """
torch.manual_seed(81) # reproducibility with randomness
self.device = 'cuda' if torch... |
520d8aaef1dbc85c777f936cd589da5a71936fbd65006b86b2cbf74d69400a13 | Python | 5,158 | 122 | import os
import argparse
import pandas as pd
import yaml
import random
random.seed(49297)
from tqdm import tqdm
def process_partition(args, definitions, code_to_group, id_to_group, group_to_id,
partition, eps=1e-6):
output_dir = os.path.join(args.output_path, partition)
if not os.path.e... |
e7cd24c5ab2b61c1d708f2191f6bb946be6b78c0efea6ec27d010e7566b0eea2 | Python | 5,159 | 148 | import numpy as numx
import pydeep.base.numpyextension as numxExt
from pydeep.base.activationfunction import Sigmoid
import pydeep.misc.visualization as VIS
import pydeep.misc.io as IO
# Set the same seed value for all algorithms
numx.random.seed(42)
# Load Data
data = IO.load_MNIST("../../../../data/mnist.pkl.gz",Fa... |
decf7327d2a41417e2698237f17819ae7fc0363534047a6cbd5b8097fde0e6ce | Python | 5,160 | 131 | import warnings
from typing import Any, Literal, Mapping, Optional
import torch
from torch import nn as nn
from torch.nn.modules import Module
from torch.nn.parameter import Parameter
Reduction = Literal["sum", "mean", None]
class ConfigurationError(Exception):
pass
# ------------------ Base Classes ---------... |
c60699bf418915c549b7af04fd5cce127639a13f538f6a3bd9f97334e7a69fd6 | Python | 5,164 | 109 | """Export unnormalized DTI scalar maps on the original DWI voxel grid."""
import argparse
import json
import logging
from pathlib import Path
import sys
if __package__ in (None, ''):
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import nibabel as nib
import numpy as np
import SimpleITK as sitk
fro... |
f1e527740a6bf72490d18e9dbd24c0d4f99d31d5d82ece590125a9b7b9db6ea5 | Python | 5,164 | 163 | import os
import numpy as np
from pathlib import Path
from eeg_utils import EEGLoader, EEGDownSegmenter
from utils import parse_arguments, ica, IC_dict, load_config
import mne
mne.set_log_level('WARNING')
def cortex_pipeline(
raw_dir: str,
out_dir: str,
aep_out_dir: str,
file_extension: str,
subj... |
4735b9e2043c7bc196f37a16059e0f0c514f268207688513d1779d211aa75abb | Python | 5,167 | 167 | import torch as tr
from sklearn.metrics import f1_score
from grakel import Graph
from grakel.kernels import WeisfeilerLehman, VertexHistogram, WeisfeilerLehmanOptimalAssignment, ShortestPath
import numpy as np
from sincfold.utils import mat2bp
def contact_f1(ref_batch, pred_batch, L, th=0.5, reduce=True, method="tr... |
5bc8c81182a73f217bf9326cf3a7bafdb959a1efd4ff2c498773462e21d1a009 | Python | 5,167 | 132 | """
Built-in ToolkitWrapper for very basic functionality. Intended for testing and not much more.
"""
__all__ = ("BuiltInToolkitWrapper",)
from typing import TYPE_CHECKING
from openff.toolkit import Quantity, unit
from openff.toolkit.utils import base_wrapper
from openff.toolkit.utils.exceptions import ChargeMethodU... |
7e69f08f3b435901b8c6e750cfbd6cc1e1085c9df888ea774abce2dde2976260 | Python | 5,168 | 134 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Description: :
@Date : 2022/06/15 15:59:24
@Author : Zilan Yu
@version : 1.0
'''
import torch
import torch.nn.functional as F
import torchmetrics
import pandas as pd
import sys, os
from HeteroModel import *
from data_process import *
from config i... |
6e136b9283bcc6dabd21c74b084f2a33d246b0e16a6efa484250b3cd23084e39 | Python | 5,170 | 144 | from keras.models import Model
from keras.layers import Input, Dense, LSTM, Masking, Dropout
from keras.layers.wrappers import Bidirectional, TimeDistributed
from mimic3models.keras_utils import Slice, LastTimestep
from keras.layers.merge import Concatenate
from mimic3models.keras_utils import ExtendMask
class Networ... |
d6a78b3b1220fdb48f7cb87ba91a4ae5f6f76bb3329b17942902945d4a639fbf | Python | 5,174 | 153 | import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import scipy.stats
import numpy.ma
import Stats
import Histogram
from cgatReport.Tracker import *
from cpgReport import *
##########################################################################
class MacsSum... |
4061d41277d11832dee3184db8c8bdab1f771be72df238174fc23df292378526 | Python | 5,175 | 165 | from math import pi, sqrt, atan
# cached constants
sqrt_2 = sqrt(2)
square_circle_const = (pi - 10./(3. * sqrt_2))
# volume of cylinder of height `h` and radius `r`
def VC(r, h):
return pi * h * r * r
# volume of cylinder with unit height and squared radius `r_sq`
def VC_h1(r_sq):
return pi * r_sq
# volu... |
bb5df77f0e7655d659fd8bf07c62296948afc9b2d0944329e3491f5bb0e5d94f | Python | 5,175 | 94 | """Indexed mesh topology and native-coordinate regression tests."""
from pathlib import Path
import tempfile
import unittest
import numpy as np
import SimpleITK as sitk
import trimesh
from inference.coordinates import export_crop_mesh, Geometry
from utils.surface_io import index_triangles, load_mesh, write_obj
from i... |
44798aab7516e6ba070576da9ba5fd7a670a0bc99ad18730559847461ce03e93 | Python | 5,176 | 161 | import torch
import torch.nn as nn
from einops import rearrange
from utils.vit import ViT
class EncoderBottleneck(nn.Module):
def __init__(self, in_channels, out_channels, stride=1, base_width=64):
super().__init__()
self.downsample = nn.Sequential(
nn.Conv2d(in_channels, out_channel... |
ca80a0777ebec4e1f37f7df1c3f2596674ece19bb4532db784672c5b9f29f490 | Python | 5,176 | 188 | from contextvars import copy_context
from pathlib import Path
import numpy
import numpy as np
from src.callbacks import get_callbacks, get_callbacks_pdb
from src.preprocessing import DataPreprocessor
from src.structurecontainer import StructureContainer
from src.visualization.visualizator import Visualizator
from da... |
133dc67d5d02bb2780b474c23ecedb84ea883fc113ad62b61fb28ee726f7fd9f | Python | 5,178 | 118 | import simtk.openmm as openmm
import simtk.unit as unit
from perses.annihilation.relative import HybridTopologyFactory
import numpy as np
from perses.tests.utils import generate_solvated_hybrid_test_topology
kB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA
temperature = 300.0 * unit.kelvin
kT = kB * tempera... |
42b0980b7df569c367abe4a5295aabfeffb11ebde289a529ed19d66fabb496fc | Python | 5,178 | 85 | """Few-cell target adaptation under P4: how many labeled cells of the NEW dataset restore accuracy and valid, tight intervals?
For each held-out dataset and n_cal in {0,1,2,3,5,10,20} target cells (random draws):
point model : (a) source-only LightGBM; (b) source + n_cal target cells, target rows up-weighted (w=5)
... |
a155c5f4292ea432e7ad839f065ca93769194d798f96f372f8f5ed7c2e9be8c7 | Python | 5,179 | 94 | import numpy as np
import cv2
import os
class Cams:
def __init__(self, grads, fmap):
self.grads = grads
self.fmap = fmap
#self.gap_weight = gap_weight
#def bas_cam(self):
#self.cam = np.zeros(self.fmap.shape[1:], dtype=np.float32)
#for i in range(np.array(self.gap_weigh... |
dd27fb5dec615593d2c3886b922f442958bc1a45b1269a367fa07b76aa91bd9a | Python | 5,179 | 159 | #!/usr/bin/env
"""
# Author: Kai Cao
# Modified from SCALEX
"""
import numpy as np
import scipy
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics import silhouette_score
__all__ = ['batch_entropy_mixing_score', 'silhouette', 'label_transfer']
def batch_entropy_mixing_score(data, batches, n_neighb... |
a0f7536de481c8b1c142838e1aa9b5a03044149796cfd26488b90546167880e1 | Python | 5,180 | 102 | """Checks for model components and shared processing helpers."""
import ast
from pathlib import Path
import unittest
import numpy as np
import torch
from model import cmunext
from model.attention import DeformableConv2D, LKAAttention3D, LargeKernelAttention3D
from model.cmunext import (CMUNeXtBlock3D, CMUNeXtSEBlock3... |
905154130ded5918c548eaab5cc628c5e4474a7fb9e6334b8601f22af65d65ec | Python | 5,183 | 143 | import torch
import torch.nn as nn
from torch.distributions import Normal, StudentT
class ZeroInflationLossBase(nn.Module):
def __init__(self, avg=False, per_neuron=False, return_logdet=False):
super().__init__()
self.avg = avg
self.per_neuron = per_neuron
self.return_logdet = retu... |
d0a43daa73c5af35afa0b6cdcd45e8bb0e14a87cc51e76aacc668eb035d12309 | Python | 5,184 | 179 | '''simple implementation of unet in keras. For a more generic and
flexible version, see more recent versions of dlutils.
'''
from keras.engine.topology import get_source_inputs
from keras.engine import Input
from keras.engine import Model
from keras.layers import Convolution2D
from keras.layers import MaxPooling2D
fro... |
201186bd88c70011a24066ff4775a643123bf45efef56ee9e4cfd2fc782930c1 | Python | 5,187 | 119 | # TODO this is a copy of experiments/hko_factory.py and should be removed
# after nowcasting/models/deconvolution.py has been refactored to use a factory
# to get the symbols.
# Currently it needs to import the the factory directly to construct the symbol
# based on the cfg.DATASET variable
import mxnet as mx
from now... |
9ab441fe19e92aad5c0cbc3c7a9dbe613b07ed4e61ba26314f682c5e34da3eff | Python | 5,190 | 171 | # -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
ecba17ba6d8120395763b9a4c12525fff17e042ff55b8344c99d2e764e823d43 | Python | 5,194 | 134 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.pyplot as mpl
def get_burst(events) :
'''returns timestamps list of the first and last spike for all bursts'''
# String algorithm for the Burst Detection
maxISI = 100
minintrabur... |
000877661bcd29d0559798c0971e86a2c0e069a926f5ba7a188a949452a8d7e6 | Python | 5,196 | 144 | """Filter that uses an LLM to rerank documents listwise and select top-k."""
from collections.abc import Sequence
from typing import Any
from langchain_core.callbacks import Callbacks
from langchain_core.documents import BaseDocumentCompressor, Document
from langchain_core.language_models import BaseLanguageModel
fro... |
519da232a86744ff2a28144d7f02c54aaeae3e16a667d6521ec742508c88c7d9 | Python | 5,198 | 140 | import numpy as np
import pandas as pd
from scipy import stats
from sklearn.cross_decomposition import CCA
from pgmpy.utils import preprocess_data
from ._base import BaseCITest, _CITestResult, _ResidualMixin
class RoysLargestRoot(_ResidualMixin, BaseCITest):
r"""
Roy's largest root CI test for mixed data [1... |
cf56bfd0cd6386f9ea473d54f02ff9a0a50aeac832d1779c3eb04148867902d8 | Python | 5,200 | 170 | """Helper function for high-throughput GNN trainings."""
"""Implementation based on the template of Matformer."""
import matplotlib.pyplot as plt
# import numpy as np
import time
from comformer.train import train_main
# from sklearn.metrics import mean_absolute_error
plt.switch_backend("agg")
def train_prop_model(
... |
797fdd7bc721c7ecf8039d98977b91f122093314f39f5cd110ef0e583d5a71d1 | Python | 5,204 | 105 | import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
class Omicscope_Snapshot():
from .GeneralVisualization import bar_ident
from .GeneralVisualization import PPInteractions
from .GeneralVisualization import volcano
def __init__(self, Table,
pval... |
caa7c2517e04c79e16e52f3cf4fbe66e25ba8425eaf2939e0b5f5b8688b59baf | Python | 5,204 | 149 | import numpy as numx
import pydeep.base.numpyextension as numxExt
from pydeep.base.activationfunction import Sigmoid
import pydeep.misc.measuring as MEASURE
import pydeep.misc.visualization as VIS
import pydeep.misc.io as IO
# Set the same seed value for all algorithms
numx.random.seed(42)
# Load Data
data = IO.load_... |
3638d913411a4ade6f9027f4a3648d71fbd13fe45767d4f8d8101c3bc1b82a41 | Python | 5,207 | 117 | #!/usr/bin/env python3
import os
import sys
import tempfile
import argparse
from zscores import ActiveRegions
from combinedbams import CombinedBAMs
from combinedfragments import CombinedFragmentFiles
EX_USAGE = 64
EX_NOINPUT = 66
def argument_parser():
parser = argparse.ArgumentParser(description='train a human... |
94987c8961a0fa435d5210e8ac6bb2d4bcace680517203110651bc151742f073 | Python | 5,207 | 108 | from config import args
from VGG_3D import VGG
from VGGgap_3D import VGGgap
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import torch.optim as optim
from torch.autograd import Variable
import os
import sys
import nibabel as nib
from data_make import Mydataset
from torch.utils.da... |
2d9cea426f5d792c99546fd474c0b73c641d9898560877a8aba0452b9654681b | Python | 5,210 | 143 | """Exercise the actual upstream sampler under JIT, vmap, and scan.
`guided` takes alphafold3-colabfold's DENOISED_HOOK when the installed release
has it (3.1.18+) and instruments the pinned 3.1.11 sampler otherwise, so these
hold the same expectations against whichever is installed."""
from types import SimpleNamespa... |
d5419d79b683ec5a575a8335736de80df089a009ffb70893ab084bd60cfd3446 | Python | 5,210 | 137 | """Test base workflows."""
import pytest
from ..base import init_sdc_estimate_wf
EPI_METADATA = {
'MultibandAccelerationFactor': 8,
'PhaseEncodingDirection': 'i',
'RepetitionTime': 0.72,
'TaskName': 'Resting-state fMRI',
}
EPI_FMAP_METADATA_1 = {
'BandwidthPerPixelPhaseEncode': 2290,
'EPIFacto... |
60f59d68c6e4398cccf0df2ff65ecaa6db5bb22c83663aa46576b2e82f67ebed | Python | 5,211 | 154 | ####################################################################################
#
# 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... |
020150efba33d369468af94d247511149ef45cb8a3eb728b914eef2d88ac4276 | Python | 5,212 | 176 | #!/bin/env python3
import voxcell as vc
import numpy as np
from scipy.spatial import ConvexHull
from scipy.ndimage.measurements import label, labeled_comprehension
import matplotlib.pyplot as plt
from pathlib import Path
import json
import sys
flatmap = sys.argv[1]
atlas_hierarchy = sys.argv[2]
atlas_regions = sys.ar... |
23d74eba643af3f54569204199cfe87719b6ebe06e24a4b0cb6b17c037673157 | Python | 5,216 | 172 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# atlaskit documentation build configuration file, created by
# sphinx-quickstart on Mon Oct 30 12:26:28 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# a... |
aaef86d15d40e7d4256bcebb8acbcc0f02a8ac016c4f0c0c101dfdbdde7c0ee3 | Python | 5,218 | 118 | import simtk.openmm as openmm
import simtk.unit as unit
from perses.annihilation.relative import HybridTopologyFactory
import numpy as np
from perses.tests.utils import generate_solvated_hybrid_test_topology
kB = unit.BOLTZMANN_CONSTANT_kB * unit.AVOGADRO_CONSTANT_NA
temperature = 300.0 * unit.kelvin
kT = kB * tempera... |
ac00a050fe7386562a27040392fab931a005a6975b246fbfab3c4c88a56ebe2d | Python | 5,223 | 135 | import os
# this stops jax from stealing all the memory
os.environ["XLA_PYTHON_CLIENT_PREALLOCATE"]="false"
import jax
import jax.numpy as jnp
import jax.random as jrng
import tensorflow as tf
import optax
import seaborn as sns
import hydra
from omegaconf import DictConfig
from orbax.checkpoint import (CheckpointMana... |
c18f9135d1d59b3c5f7b890afe769a956bf0917231c313b68c9a6c92dd9b466f | Python | 5,225 | 140 | import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import numpy as np
import sys
sys.path.append("../../")
from TCN.copy_memory.utils import data_generator
from TCN.copy_memory.model import TCN
import time
parser = argparse.ArgumentParser(description='Se... |
41db3411047d476ce037d6fa175cd04a2beb1b66e1d531606bc7bf414e5362cf | Python | 5,228 | 151 | ####################################################################################
#
# 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... |
c58d9ad90d95edd8142290cab61968e22e1ccb3026fd6440094cb470f2bd5abb | Python | 5,228 | 105 | import timm
import torch.nn as nn
import torch
# num_atom_type = 120 # including the extra mask tokens
# num_chirality_tag = 3
#
# num_bond_type = 6 # including aromatic and self-loop edge, and extra masked tokens
# num_bond_direction = 3
from core.network.model import model_register
@model_register
class CnnEnco... |
c9a98e0e0134c4c81fd50fbe9dd1bdf6ef07c89cd0ec260ae5ce2cd38b33e5bf | Python | 5,228 | 181 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
import i... |
6d230363b0d4631ee761db9482b94e3d85c2618a7f84f91eb34174c6c6ebb81f | Python | 5,231 | 131 | import torch
def expand_edge_index(edge_index, num_atoms, num_repeats, global_offset, device):
"""
Expands a set of edges 'num_repeats' times.
Shifts indices for each repeat so they form disjoint graphs.
"""
if num_repeats == 0:
return torch.empty((2, 0), device=device, dtype=torch.long)
... |
70aa248e405d32344b8a06ceae73ad91bcc9feeff1014f40b71d33d52d098d9e | Python | 5,232 | 166 | from typing import List
import numpy as np
import pytorch_lightning as pl
import segmentation_models_pytorch as smp
import torch
from src.models.smp.utils import get_metrics, log_predict_model_on_epoch, save_metrics_on_epoch
class HistologySegmentationModel(pl.LightningModule):
"""The model dedicated to the seg... |
9dab82baea0cf2d5d0b15004df9656a9396ee95738b95ecaadaac62e1f35ebff | Python | 5,233 | 146 | import os
from pathlib import Path
from typing import List
import hydra
from omegaconf import DictConfig
from pytorch_lightning import (
Callback,
LightningDataModule,
LightningModule,
Trainer,
seed_everything,
)
from pytorch_lightning.loggers import Logger
from nablaDFT import model_registry
from... |
1c7a45ae5dc0e429394d96649ea24a6eead7336cbe0dbaa035b85aa663d31a3d | Python | 5,234 | 105 | import argparse
from src.configs import AAI_curriculums
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
raise argparse.ArgumentTypeError('Bo... |
39b0608041c34be9c1ef5be31f9be6e94e9116e65ee11e0d084cab90512194d4 | Python | 5,235 | 170 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import nibabel as nib
import numpy as np
import os
import pylab as plt
DESCRIPTION = 'Removal of non-central chi bias with simple method of moments. Pichael Maquette 2020'
def buildArgsParser():
p = argparse.ArgumentParser(description=DESCRIPTION... |
747375d2b5bb471692960ee0ee27e2a2e23e057fd983c755d2cc70831028ccea | Python | 5,238 | 136 | ####################################################################################
#
# 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... |
9a78a78b89453c832a6cd54da6afff16e442e8e177b74323e0e00af70bd6b105 | Python | 5,238 | 131 | ####################################################################################
#
# 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... |
051fd6042c173451444bafe282b322f39b7786d7bfefd34ca01acf401017e7c9 | Python | 5,239 | 89 | # 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... |
5c25b6bd4da45d6777085b0516439def0f697072e838bd7f669ac9fad852e209 | Python | 5,239 | 131 | ####################################################################################
#
# 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... |
7c04b396029ccf015a7ab0a0eb82fbb4b6707928a67be7a80626495de9a12737 | Python | 5,239 | 180 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
import io
import re
from glob import glob
from os.path import basename
from os.path import dirname
from os.path import join
from os.path import splitext
from setuptools import find_packages
from setuptools import setup
def read(*names, **kwargs):
with io.open(join... |
8049747cfeb935741c423cf6f677eeb130594e21a5de619b8091796cc1067cdd | Python | 5,240 | 168 | #!/usr/bin/env python
"""
Create randomly subsampled midspace template variants
- Requires BIDS source directory with participants.tsv
- Subsamples are used to generate template variants lists for a midspace
- If odd number of participants, drop final participant
- Sample half of participants randomly for one template
... |
be53b4ad589af5b12bda561782a72d8135bf800c3acace1e82affcc7d1f10cb6 | Python | 5,247 | 151 | import torch
import torch.nn as nn
import sys
import numpy as np
from torch.nn.init import calculate_gain
#torch.set_num_threads(36)
def get_zero_grad_hook(mask):
def hook(grad):
return grad * mask
return hook
class SoftsignMod(nn.Module):
def __init__(self):
super().__init__() # in... |
39fbccd6d7578576cb9f75ee9286d64b112a32e8d6b5514105565be4a5859312 | Python | 5,248 | 157 | #!/usr/bin/env python
import networkx as nx
import numpy as np
import pandas as pd
from pgmpy.causal_discovery._base import BaseCausalDiscovery, _TreeSearchMixin
class ChowLiu(_TreeSearchMixin, BaseCausalDiscovery):
"""
Chow-Liu algorithm for learning tree-structured Bayesian networks.
Constructs the m... |
7a76c52166f313d117a0cb870c10462b47ba1a0532e1823680d7a2e29cc3774b | Python | 5,248 | 131 | import os
from morgana.DatasetTools.morphology import overview as overviewDT
if __name__=="__main__":
input_folder = "V:/Lilli_Hahn/data/EH23H_signaling-perturbation/EH24H_DIF01/MOrgAna/images/Control_CHIR/24h"
"""
overviewDT.createCompositeOverview(input_folder)
"""
import numpy as np
import... |
ed9a7496a69536bc7c98c56a6c28a31509ad686c1a6e209509e2237598a467eb | Python | 5,248 | 121 | # Copyright Generate Biomedicines, 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 agreed to ... |
3cf639506243d905182feafc8c4dcdd4088d7380bc80b93c2957897411ca0746 | Python | 5,254 | 136 | ####################################################################################
#
# 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... |
fe5685dd9bc857dd4f47cf0f05a7db7f6a4b869d4cabd2570522b62e92b48405 | Python | 5,255 | 157 | """
This script processes voxel data and computes various statistics of the shape and size of the barrels and barrel columns. The computed statistical measures include volumes and surface areas. One of the critical steps involves calculating the convex hull for each identified barrel. The convex hull provides insights ... |
e4490ff3f794069e5802d852cafcb1b878e9615bf713c1b9492f35441b3d93dd | Python | 5,256 | 125 | # Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved.
#
# NVIDIA CORPORATION and its licensors retain all intellectual property
# and proprietary rights in and to this software, related documentation
# and any modifications thereto. Any use, reproduction, disclosure or
# distribution of this sof... |
d264db98729d3719237d87ff3c2f031816dcf4853ae8074534488c873fc03d99 | Python | 5,258 | 187 | import json
import math
import os
import cv2
import numpy as np
import torch
import yaml
import random
import torch.backends.cudnn as cudnn
from collections import OrderedDict
import torchvision
INT_MAX = 0x3f3f3f3f
def mkdir(path):
if not os.path.exists(path):
os.makedirs(path)
def ordered_load(strea... |
be36f3af2e7f11a1dc3ed0dedf1934432aaca7e3ae651f8a80a5e488abc484ef | Python | 5,262 | 128 | # -*- coding: utf-8 -*-
# @title Hardware Configuration File handling class
# @file HwConfigFile.py
# @author Romain Beaubois
# @date 19 Oct 2022
# @copyright
# SPDX-FileCopyrightText: © 2022 Romain Beaubois <refbeaubois@yahoo.com>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# @brief Han... |
0ff5f418d65f5b600c0c22cea31218d6dc79585ae382f3aa8a1ccbdd7d543215 | Python | 5,266 | 113 | import os
import pickle
import argparse
import logging
from pathlib import Path
from simtk import openmm
from simtk.openmm import unit
from openmmtools import mcmc
from openmmtools import cache, utils
from openmmtools.multistate import MultiStateReporter
from perses.dispersed.utils import configure_platform
from per... |
a2858d875ae6d45f9f22d72dc5a129458f8fce5a11112b8f3f1e3c5071722525 | Python | 5,266 | 135 | import os, sys
import re
import pandas as pd
import numpy as np
from collections import Counter,defaultdict
import logging
import argparse
FORMAT = '%(levelname)s %(asctime)-15s %(name)-20s %(message)s'
logging.basicConfig(level=logging.DEBUG, format=FORMAT)
logger = logging.getLogger("window")
def parse_args(args):... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.