sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
d50bfe151bebb1001e71892f8ff13e4b38147eea1d9261ed7ce9f9a604104845 | Python | 992 | 35 | import os
from torchdrug import data, utils
from torchdrug.core import Registry as R
@R.register("datasets.Cora")
class Cora(data.NodeClassificationDataset):
"""
A citation network of scientific publications with binary word features.
Statistics:
- #Node: 2,708
- #Edge: 5,429
- #... |
2ca685e9589a5e098c0e323bb3d5f1ec0e00d1e8354ebe0e1d9a4309bde6d4b4 | Python | 993 | 43 | from typing import Dict, List, Union
from sharc.pysharc.interface import SHARC_INTERFACE
import spainn
from spainn.calculator import SPaiNNulator
class SHARC_NN(SHARC_INTERFACE):
"""
Class for SHARC NN
"""
# Name of the interface
interface = 'NN'
# store atom ids
save_atids = True
# ... |
5e959101b7e270290f1591f64ceb5248b26b4740b9ee4d8e871b76ca8ccf164f | Python | 993 | 27 | import sys, os
from pandas.io.parsers import read_csv
import numpy as np
import pandas as pd
gtffile = 'transcripts.gtf'
#### Convert gtf file in an easy to handle data frame ####
df = read_csv(gtffile, comment='#', header=None, sep = '\t')
df.columns = ['seqname', 'source', 'feature', 'start', 'end', 'score', 'stran... |
9fa0803d6df39fbbd98c49593c208739ee98e5d1cc7f5f48d37e218a2121a040 | Python | 993 | 26 | #----Figure_S06A_preparation----------------------------------------------------
#-------------------------------------------------------------------------------
# This is the code which has to be run in preparation for Figure S06 Panel A to
# obtain the clock neuron meshes used in Reinhard and Fukuda et al. 2024
... |
8a1a30fc2e872103b6e94cbf64cdbaf2f702fcb6fc28de1bb903585640f0ab14 | Python | 994 | 29 | #!/usr/bin/env python
# ========================= #
# Training of network model #
# ========================= #
# Usage: python <path-to-this-file>/train.py <your_config>.ini [-n NUM_THREADS]
# Default train config file is DeepH-E3/deephe3/default_configs/train_default.ini
import os
import argparse
parser = argpars... |
aed12902ff3b66aac0e792291f0e0fd56d1e0bb8e2d93164e9e6ae84eae940eb | Python | 994 | 43 | import numpy as np
import labgraph as lg
class SampleMessage(lg.TimestampedMessage):
'''
Raw data samples should be communicated in this
format for logging.
'''
#timestamp: float
data: np.ndarray
class StringMessage(lg.TimestampedMessage):
'''
For timestamped event codes, which can be... |
df6d3ad27fe856224d534beebb8e86eb200553e1be326a89005e67280b5fb7de | Python | 994 | 41 | from __future__ import annotations
import pytest
pytest.importorskip("openbabel")
from custodian import Custodian
from quacc.calculators.qchem.qchem_custodian import run_custodian
def mock_custodian_run(*args, **kwargs):
"""Instead of running Custodian, we will mock it to return True when .run() is called."""... |
049a0d3204ac8a06a286b49c461ba29451c85ba3e8c94ae167851a70295aac1b | Python | 995 | 35 | # A simple script to draw smiles from CSV with rdkit
import os
import argparse
import numpy as np
import pandas as pd
import rdkit.Chem as Chem
from rdkit.Chem import Draw
from rdkit.Chem.Draw import DrawingOptions
import cairosvg
parser = argparse.ArgumentParser()
parser.add_argument('--csv', type=str)
parser.add_a... |
387d4ec45fc551001f4870b5371fe61d1fd5cc30ec9858c588f4315a55eb4bc1 | Python | 995 | 31 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 23 00:16:27 2023
@author: daltonm
"""
import subprocess
from pathlib import Path
import os
import sys
import time
script_directory = Path(os.path.dirname(os.path.abspath(sys.argv[0])))
code_list = ['generate_functional_networks_MG_demo.py',
... |
3fc96e8a465c2a135303cb71796fa973f6c70ba142626c039ce378f4a7c425f1 | Python | 995 | 37 | import anndata
import numpy as np
import pandas as pd
import pytest
from anndata import AnnData
import pertpy as pt
pt_drug = pt.md.Drug()
@pytest.fixture
def adata() -> AnnData:
rng = np.random.default_rng()
gene_names = ["SLC6A2", "SSTR3", "COL1A1", "RPS24", "SSTR2"]
adata = anndata.AnnData(X=rng.sta... |
a14b7c390eac0aa74a2e92e1bbacec02f1129441d1d2398602ebb003a979ae72 | Python | 996 | 25 | import unittest
from unittest.mock import mock_open, patch
import sys
import os
sys.path.append(os.path.dirname(os.path.realpath(__file__)) + "/../../src")
from hornet.input import get_parameter
class TestGetParameter(unittest.TestCase):
@patch('builtins.open', new_callable=mock_open, read_data='# test\n# case... |
a4e9b0b525400935fa147c9ca92888f2608dc9d2e80dba54d80fe3c4bd9cd6b1 | Python | 996 | 25 | from .autoencoder import Autoencoder
# from .train_autoencoder import fit_autoencoder
import torch
def fit_trafo_autoencoder(x_train, x_test, ae_params):
net = Autoencoder(input_dim=x_train.shape[1],
d=ae_params["n_components"])
net, time, stats = fit_autoencoder(net, x_train,
... |
a11e5b8aa61a4714455925a85e054cdb9485fc9bbed7ac783e1fbf9ecda532ad | Python | 997 | 29 | # Plot all effect sizes for all corticospinal waves for S1 Appendix Fig F
# Originally: Analysis/plot_fig_sensitivityanalysis.py
from os.path import join
from get_paths import *
from TVATPlotting import TVATPlotting
import matplotlib.pyplot as plt
if __name__ == "__main__":
save_flag = 0
## ... |
c10b1762deed0c166a1817bd0d6a11affd6662389786d3911a6fe4de41338d85 | Python | 997 | 35 | from . import loadDefaultParams as dp
from . import timeIntegration as ti
from neurolib.models.model import Model
class KuramotoModel(Model):
"""
Kuramoto Model
Based on:
Kuramoto, Yoshiki (1975). H. Araki (ed.). Lecture Notes in Physics, International Symposium on Mathematical Problems in Theoretic... |
02bd493739408dacbb3530fcb12c1b7584232e955d0b7c981b0f462c64dd838e | Python | 998 | 33 | import logging
import os
c_formatter = logging.Formatter("%(asctime)s %(message)s", datefmt='%H:%M:%S')
f_formatter = logging.Formatter("%(message)s")
log_level = {
"DEBUG": logging.DEBUG,
"INFO": logging.INFO,
"WARNING": logging.WARNING,
"ERROR": logging.ERROR}
def set_logger(name=None,... |
206ecb19dda1d8059160f82733b95d441e37f28ad302f6d6bee422e13026d6f8 | Python | 998 | 30 | from elasticai.creator.file_generation.savable import Path
from elasticai.creator.file_generation.template import (
InProjectTemplate,
module_to_package,
)
from elasticai.creator.nn.fixed_point.hard_sigmoid import HardSigmoid
from elasticai.creator.nn.fixed_point.hard_tanh.design import HardTanh
from elasticai.... |
6f1d8e1d3366ba88eedfd3ff5fd3312b2025e90d30622baabcec1aa637ef1ff7 | Python | 998 | 23 | import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import Divider, Size
# The following two functions are written by Nathaniel Linden, provided May 2024
def export_legend(legend, filename="legend.pdf"):
fig = legend.figure
fig.canvas.draw()
bbox = legend.get_window_extent().transformed(fig.dpi_... |
b14b73f5ca35df1af756dffd191c4fc8ce106b137a4578f57020e5f5c8e23f08 | Python | 998 | 22 | # 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
#
# ht... |
b5f8dc81b8f29695f66bc0d5c6f5a9f8d1d1f94d17ea2bc9aa1dc7cea9a36e8e | Python | 998 | 33 | from unittest import TestCase
from pyseg.vtk_ext import vtkSurfBorderAlgorithm
import vtk
__author__ = 'martinez'
class TestVtkSurfBorderAlgorithm(TestCase):
def test_Execute(self):
reader = vtk.vtkXMLPolyDataReader()
reader.SetFileName('../data/surf.vtp')
reader.Update()
filte... |
97ea1fb89d8e163c90fe8edbccdff4112bee39a33fe611169cfe703d07b68ff0 | Python | 1,000 | 36 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import os
from lab.environments import LocalEnvironment, BaselSlurmEnvironment
from downward.reports.compare import ComparativeReport
import common_setup
from common_setup import IssueConfig, IssueExperiment
from relativescatter import RelativeScatterPlotReport
DIR = ... |
5137f781f31f98457f321ac4d8933491647b67604a4fc75800b8709e4674b0cc | Python | 1,001 | 33 | from .graph_element import GraphElement
class Edge(GraphElement):
"""Class for representing an edge in a graph."""
def __init__(self, node_indices: list[int], features: dict = {}, is_directed: bool = False, label: str = None, id: str = None):
"""Constructor
Args:
node_indices (... |
74a924609c2c6e686e79811f708c7298fff89711ea0122163a20b2e1efa1338a | Python | 1,001 | 31 | from __future__ import annotations
from importlib.util import find_spec
from pathlib import Path
from shutil import rmtree
import pytest
TEST_RESULTS_DIR = Path(__file__).parent / "_test_results"
TEST_SCRATCH_DIR = Path(__file__).parent / "_test_scratch"
has_prefect = bool(find_spec("prefect"))
if has_prefect:
i... |
ea2282c89ff330d6e25908681a0531db6f990f62008f0cf4f35e29f6f38f415a | Python | 1,001 | 24 | """
The below `sys.path.append` code will add the root directory to sys.path in order to
correctly import files from the 'dreamcoder' Python package.
Additionally, some bin scripts depend on the pregex code.
This sys.path manipulation is required in order to preserve the same style of running
commands as has been use... |
5a709b60492bc8d420fe7cb65dc3d5678af8eedd79677cb14e00e2bdc30317dd | Python | 1,002 | 39 | ##
# \file installation_test_monaifbs.py
# \brief Class to test installation of MONAIfbs
# (https://github.com/gift-surg/MONAIfbs)
#
# \author Marta Ranzini (marta.ranzini@kcl.ac.uk)
# \date December 2020
#
import os
import unittest
import pysitk.python_helper as ph
from niftymic.definitio... |
78f1fbf454bcfb944f478f43cc460c02457a8cca50154a39bc3d30262c11fc45 | Python | 1,002 | 36 | from __future__ import annotations
import pytest
jf = pytest.importorskip("jobflow")
from pathlib import Path
from quacc import get_settings, job, redecorate, strip_decorator
def test_strip_decorators():
@job
def add(a, b):
return a + b
stripped_add = strip_decorator(add)
assert stripped_a... |
93f2bca36034933d035e5f6d34af6a0c2fd844e9dd118ed5fea766f6439c5472 | Python | 1,002 | 27 | from monai.transforms import Transform
import numpy as np
class LoadNumpyd(Transform):
# load a numpy file
def __init__(self, keys):
self.keys = keys
def __call__(self, data):
for key in self.keys:
data[key] = np.load(data[key])
return data
class BifNP2Dict... |
01cab2a3e47af04c47962bcf19e278d46d0dd6c21eed53bd5e65a6ca51f927d5 | Python | 1,003 | 42 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward.suites import suite_optimal_with_ipc11
from downward.configs import default_configs_optimal
import common_setup
REVS = ["issue385-base", "issue385-v1", "issue385-v2"]
CONFIGS = default_configs_optimal()
# remove config that is disabled in this branch
del... |
31b1c5b1480a0acfed722da9a3ab81fa809eee7d8c1492d993db91928bebe60a | Python | 1,003 | 39 | from __future__ import annotations
from pathlib import Path
import pytest
FILE_DIR = Path(__file__).parent
GAUSSIAN_DIR = Path(FILE_DIR, "gaussian_run")
def mock_execute(self, *args, **kwargs):
from shutil import copy
copy(GAUSSIAN_DIR / "Gaussian.log.gz", Path(self.directory, "Gaussian.log.gz"))
@pytes... |
585c48767a739bffeee3c75beb831f8c6a4236aceaa790949a6fa8bda3190e30 | Python | 1,003 | 48 | import matplotlib.pyplot as plt
import autograd.numpy as np
from autograd import grad
def fun(x):
return np.sin(x)
d_fun = grad(fun) # First derivative
dd_fun = grad(d_fun) # Second derivative
x = np.linspace(-10, 10, 100)
plt.plot(x, list(map(fun, x)), x, list(map(d_fun, x)), x, list(map(dd_fun, x)))
plt.... |
ce36a9f270af490ebe79d188cc771c2cd07deb2a54d6139b31e212ee9d52443c | Python | 1,003 | 49 | import numpy as np
from abc import ABC, abstractmethod
class KernelBase(ABC):
def __init__(self):
super().__init__()
@abstractmethod
def apply(self, x, y):
pass
class CovKernel(KernelBase):
def __init__(self, factor):
super().__init__()
self.factor=factor
d... |
2a68a2fe5132dd3bd720801ef052d363fb5a33749b0e48ba033b11dd2aabe198 | Python | 1,004 | 33 | import unittest
import os
import random
import shutil
from torcheeg.model_selection import KFoldCrossTrial
from torcheeg.datasets import DEAPDataset
class TestKFoldCrossTrial(unittest.TestCase):
def setUp(self):
shutil.rmtree('./tmp_out/')
os.mkdir('./tmp_out/')
def test_k_fold(self):
... |
61408b750351e5fb11180e82e2d7879ae8a88ceaad90965212000cedd9262923 | Python | 1,005 | 27 | import numpy as np
import networkx as nx
###################################
#
#Get node names, create mapping
#
###################################
all_nodes = open("all_nodes.txt", "r").read().splitlines()
node_mapping = {i:n for i,n in enumerate(all_nodes)}
###################################
#
#Load adjacency ma... |
67ad44aaf835c5d7d8fdb8e23ec9c0c67e9b1d830d40ab8d874d6884f3feac5c | Python | 1,005 | 28 |
from sklearn.linear_model import LinearRegression
#from ..tools import regression
import numpy as np
def corrcoefconn(activity_matrix, target_ts=None):
"""
activity_matrix: Activity matrix should be nodes X time
target_ts: Optional, used when only a single target time series (returns 1 X nn... |
fff0e320e720009b9c9cc4362aa032b818992e967e380c608cc55fb86db3326b | Python | 1,005 | 41 | import os
OBSTACLES = ['floor']
SURFACES = ['table', 'tray', 'stove', 'button', 'placemat'] # TODO(caelan): refactor
NAME_TEMPLATE = '{}#{}'
##################################################
def is_surface(name):
return any(surface_type in name for surface_type in SURFACES)
def is_fixed(name):
return an... |
44ad8b8705e16590d48b901ac1240cf358ae215c0568d26c65566333a9bab125 | Python | 1,006 | 29 | import logging
from utils import rigid_registration, apply_affine, getSubjectID
def process_image_segmentation(image, segmentation, atlas):
print(getSubjectID(image))
print(getSubjectID(segmentation))
assert getSubjectID(image) == getSubjectID(segmentation), 'different subjects, aborting!'
processe... |
63ae6692a37783b904cd495e6518e3f1eab029b7183b4b65ad336b59b3a97578 | Python | 1,007 | 27 | import torch
from PIL import Image
from transformers import AutoImageProcessor, ResNetForImageClassification
from cog import BaseRunner, Input, Path
WEIGHTS_DIR = "/src/weights/resnet50"
class Runner(BaseRunner):
def setup(self) -> None:
self.device = torch.device("cuda" if torch.cuda.is_available() els... |
7bddf6d5324a727a996b59460a911383124ebced0d7adc0c91c66cc9f786d366 | Python | 1,007 | 42 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward.suites import suite_satisficing_with_ipc11
from downward.configs import default_configs_satisficing
import common_setup
REVS = ["issue385-v3-base", "issue385-v3"]
CONFIGS = default_configs_satisficing()
# remove config that is disabled in this branch
del... |
ae2d23b938291d144b8a9509d470a063d98448be91e02290f987a96df5c6eca2 | Python | 1,008 | 33 | import os
from pathlib import Path
import tensorflow as tf
import shutil
# old function for segmentation before pathlib and using os.chdir
def vesicle_segmentation(path_to_folder):
os.chdir('../../..')
dataset_dir = os.getcwd()
unet_weigth_path = dataset_dir + '/weights/weights.h5'
os.chdir('./data/'+p... |
b5bbbdd7420ab4ec9c95841cf10091132393c3d6db8ade0e8d39f6c3ccde7c35 | Python | 1,008 | 21 | """
toposampling - Topology-assisted sampling and analysis of activity data
Copyright (C) 2020 Blue Brain Project / EPFL & University of Aberdeen
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation... |
c9e39dcf65c6fa98787565553695933700eb78bc61faa3e1c50cf3fccec9c6e3 | Python | 1,008 | 31 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed 10 Nov 2021
@author: hugwei
"""
import os
import pandas as pd
DATA_PATH = '../data/meg/' # This relative path works if the notebook is ran from the notebook folder, use absolute path if ran from another folder
STIM_PATH = '../data/stim/' # same com... |
54120deee47002fb39b44517837941b37b8d4dea55b9440c93b110f397a4b4b1 | Python | 1,009 | 35 | extensions = dict(
set_required_params="""
parms$training_frame <- training_frame
args <- .verify_dataxy(training_frame, x, y)
parms$ignored_columns <- args$x_ignore
parms$response_column <- args$y
"""
)
doc = dict(
preamble="""
Trains a Support Vector Machine model on an H2O dataset
Alpha version. Supports o... |
b0a606385edf4e50efa58d2a9147f982411e8a20ec011f1315c25d1a46bdc611 | Python | 1,009 | 36 | import unittest
import torch
import torch.nn.functional as F
from torcheeg.models import BCGlow, BGlow
class TestFlow(unittest.TestCase):
def test_bglow(self):
model = BGlow()
# forward to calculate loss function
mock_eeg = torch.randn(2, 4, 32, 32)
z, nll_loss = model(mock_eeg)
... |
034b871eab99c2be24758cd028416e7695549fb842f984d960c1fa94ce505e1d | Python | 1,010 | 31 | import random
from pandas._typing import FilePath
from ord.data.data_llm import prompt_to_procedure
from ord.utils import json_load, json_dump
BASE_DATASET = "datasets/USPTO-n100k-t2048_exp1"
def create_dataset_for_cot(base_dataset: FilePath, size: int = 500):
test_ids = json_load(f"{base_dataset}/meta.json")[... |
2fd0552efe1aea5055b8a6ae59d9ffe31c5710fd3dfa55655733cca8eb64db73 | Python | 1,010 | 43 | """
Standalone GUI launcher for the Neuroglancer Viewer.
"""
import os
import sys
from regtools import get_project_root
_project_root = get_project_root()
if _project_root not in sys.path:
sys.path.insert(0, _project_root)
from regtools.gui.app_scaffold import AppScaffold
from regtools.ng_viewer.g... |
55eb7487851320e6dc928f030a5bcb0612da10e3e11fed1b1fbb66ed7ae29b59 | Python | 1,010 | 41 | #!/usr/bin/env python3
import os
import h5py
from tiffile import imsave
def writeTIFF(data, output_dir, file_name):
'''
Write a TIFF file
args: data -> data to be written
output_dir -> output directory of h5 file
file_name -> name of the h5 file
'''
os.chdir(outpu... |
b30b1c009dd3a99ebff25dbcbdc4d01b9d109b651a913701e318d5af9b1f8775 | Python | 1,010 | 37 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from downward import configs, suites
import common_setup
SEARCH_REVS = ["issue512-base", "issue512-v1"]
LIMITS = {"search_time": 1800}
SUITE = suites.suite_satisficing_with_ipc11()
configs_satisficing_core = configs.configs_satisficing_core()
CONFIGS = {}
for name in ... |
b6b20b7130d19628765e8143b84c81a81b27218089fcc39fa186ba8c18046a5a | Python | 1,010 | 31 | from typing import Protocol
from .fxp_converter import FxpConverter
from .fxp_params import FxpParams
def int_converter(total_bits: int, signed: bool) -> "IntConverter":
return FxpConverter(FxpParams(total_bits=total_bits, frac_bits=0, signed=signed))
class IntConverter(Protocol):
@property
def total_b... |
2506ac7c09a189158c8e17baa71e4662c82c1513bf5a38491a98d519024cc8f2 | Python | 1,011 | 36 | # -*- coding: utf-8 -*-
"""
Created on Wed Nov 10 23:33:33 2021
@author: arefk
"""
from __future__ import print_function # print('me') instead of print 'me'
from __future__ import division # 1/2 == 0.5, not 0
# - import common modules
import numpy as np # the Python array package
def mutualInfo(Im1,Im2):
... |
30163a890b5e698c6202f6ffe7eb35706a13ebfb0946a556664d248923a33d4e | Python | 1,011 | 15 | """CHECK_CLAIMS.py — every number MAIN.md states must be printed by a script in an output file.
Reads 04-NOTES/CLAIMS.csv (claim -> script -> output -> regex) and checks each one. Run it before sending any text out.
Exit code 1 if any claim is unsupported."""
import csv, os, re, sys
R = 'D:/eucys'; bad = 0
for c in csv... |
5ea2dab3fd91bd56fb86bccefc24fc18b17ac9e968d90970abcf7b210711e253 | Python | 1,011 | 37 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
from common_setup import IssueConfig, IssueExperiment
from relativescatter import RelativeScatterPlotReport
import suites
configs = [
IssueConfig(
"cegar-900s",
["--search", "astar(cegar(subtasks=[landmarks(),goals()],max_time=900))"]),
]
revisions =... |
6b485ad3ae5c9a9d69dec9c8243c06575f0f090d19a7e8a3125e67d0c462a460 | Python | 1,011 | 34 | from elasticai.creator.file_generation.on_disk_path import OnDiskPath
from elasticai.creator.nn import Sequential
from elasticai.creator.nn.fixed_point import Linear, ReLU
from elasticai.creator.vhdl.system_integrations.firmware_env5 import FirmwareENv5
if __name__ == "__main__":
inputs = 2
outputs = 2
tot... |
8bf6f9f821d3b656775d6e6a135cf3c10dba6f559d5a1b713880c6a550f3b5d9 | Python | 1,012 | 30 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
requirements = ["numpy", "scipy", "sklearn", "nibabel", "gdist"]
setuptools.setup(
name="Connectome_Spatial_Smoothing",
version="0.1.1",
author="Sina Mansour L.",
author_email="sina.mansour.lakoura... |
97ca13e86702c5d12bf75f535e6b91dff8cca7f4b79a0ca4288ce5d05ba31a45 | Python | 1,012 | 30 | import pandas as pd
from cuppa.components.preprocessing import MaxScaler, Log1pTransformer
from cuppa.compose.column_transformer import ColumnTransformer
class TestColumnTransformer:
def test_column_transformer_outputs_correct_values(self):
X = pd.DataFrame([
[0, 0, 0, 2, 2],
[1,... |
d7010292b7bdc18b25390360b21e96010a665907e897c2cb3ef3a943b50324d7 | Python | 1,012 | 33 | import os
import torch
from torchvision.datasets.folder import pil_loader
from torch.utils.data import Dataset
NORM_CHANNEL_MEAN = [0.806, 0.621, 0.592]
NORM_CHANNEL_STD = [0.151, 0.177, 0.203]
class ISIC2020TorchDataset(Dataset):
def __init__(self, data_files, isic_image_dir, targets=None, transform=None):
... |
d90273564d62e1c559ded065d190da32de5437d6a59e469da6c3494fe62a76ed | Python | 1,012 | 28 | import torch
from ase.data import chemical_symbols, atomic_numbers
def main(*args, model="model.pt", device="cpu", output="infer.pt", symbols=None, **kwargs):
model = torch.load(model, map_location=torch.device(device))
# change embedding layer
if symbols is not None:
all_elements = [atomic_number... |
3718edd5743cd127251ec1baafd82fa0e2c12d8f4303f4364377cc281a8f106b | Python | 1,013 | 33 | """Photoreceptor Linearization - Light Adaptation Clamp (LaC) Tool.
A Python implementation of the biophysical photoreceptor model and model
inversion tools for designing light stimuli that modulate phototransduction
currents while accounting for light adaptation and nonlinearities.
"""
from .biophys_model import Bio... |
c2780b417e867510ac279c98d85a0c7975b115231b6f24521050e04aa73eea32 | Python | 1,013 | 40 | from typing import Any
import numpy as np
class EarlyStop:
def __init__(self, patience) -> None:
self.best_loss = np.inf
self.best_epoch = 0
self.best_model = None
self.patience = patience
self.counter = 0
def __call__(self, model, loss, epoch):
if loss < se... |
ed08d70481d6422cc6b98154c41af4d338a5975d0299ccb86702d6325e0c7367 | Python | 1,013 | 46 |
# imports
from sklearn.svm import LinearSVR, SVR
from func.utils import heuristic_C
# Define classes that use heruristics for hyperparameters
# SVR + C heuristic
# inherit class from SVR
class LinearSVRHeuristicC(LinearSVR):
# Overwrite fit method to use heuristic C as HP
def fit(self, X, y, sample_weight... |
359c68940dd48fb1f27f73284bdedadf734e2fcf0afed9aad340e9dfdba9ff00 | Python | 1,014 | 25 | """Persistence-round-trip tests for ViewerSettings (additive - supplements
any existing tests in this file)."""
from regtools.ccf_boundary_editor.settings import ViewerSettings
class TestLastAtlasField:
def test_default_last_atlas_is_allen_ccf(self):
s = ViewerSettings()
assert s.last_at... |
453d6e363a93511f9646f3e819feb58a8357320c33d2575935c8752de1feb4e4 | Python | 1,014 | 42 | import numpy as np
from mne.io import read_raw_eeglab
from mne import events_from_annotations
from scipy.ndimage import gaussian_filter1d
from string import ascii_uppercase
def smoothing(data, sigma):
if sigma>0:
return gaussian_filter1d(data, sigma, axis=1)
else:
return data
def back_fitting(... |
5235456fe9e5a792d3f730fb89a3c9617c18e68f3eb0e9f642116cc6eb6414fc | Python | 1,014 | 24 | # 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
#
# ht... |
900c6262d90c9941209cd1ff173cbd1d32020fdf146d7d68b41ac1e62f9d671d | Python | 1,014 | 24 | import numpy as np
import pandas as pd
from glob import glob
outpath = r'dir/' # Specify output directory for the raw calcium response CSV files
cd D:\dir\ # change directory to the directory containing raw data
filenames = glob('*.csv') # Get list of all CSV files in the specified data directory
frame_rate = 10 # ... |
461a9d895e536f4363f363abecba13b62a22bfee89baae6737277de11a1efac4 | Python | 1,015 | 45 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 12:38:33 2020
@author: usingh
This script takes n fasta files as input and check whether all sequences are same in all files
This script is quick and not memory efficient; written to test small fasta files.
Example:
python compare_fasta_files.py... |
4626b219c622b20bbdeda255d7b80a0a89269d90407c14bebbabad8314b39aed | Python | 1,015 | 41 | from sklearn.base import BaseEstimator
"""
This module contains sklearn estimators that do nothing. These are useful as 'bypass' estimators amongst a collection
of actual estimators, specifically when a polymorphic method e.g. transform() needs to be called from all estimators.
"""
class PassthroughTransformer(BaseEs... |
cd13894661d3656ac1b7d58e6e8d1115297be8f6076dae8eb6b3e03ff1ceb7f4 | Python | 1,015 | 38 | from collections.abc import Iterable
from datetime import datetime
from elasticai.creator.file_generation.resource_utils import read_text
from elasticai.creator.hdl_ir import DataGraph
from elasticai.creator.ir2verilog import (
Code,
Registry,
TemplateDirector,
type_handler_iterable,
)
@type_handler_... |
3bf5a62148bba092ae3f8a742c0a6ae62f8e4881c1fda113e5eef97362e317cf | Python | 1,016 | 33 | import unittest
import os
import random
import shutil
from torcheeg.model_selection import KFoldGroupbyTrial
from torcheeg.datasets import DEAPDataset
class TestKFoldGroupbyTrial(unittest.TestCase):
def setUp(self):
shutil.rmtree('./tmp_out/')
os.mkdir('./tmp_out/')
def test_k_fold_trial(sel... |
7355c02984282100f0e2df4806291e2ef845dd95963670e638c7c620a86a75f4 | Python | 1,016 | 44 | import argparse
import matplotlib.image
import nibabel as nib
import numpy as np
def find_center_of_image(image):
vox_center = (np.array(image.shape) - 1) / 2
aff = image.affine
M = image.affine[:3, :3]
abc = image.affine[:3, 3]
f = M.dot([vox_center[0], vox_center[1], vox_center[2]]) + abc
r =... |
890627a330f795d2687e031c416f956966fdfb74c597b890f36945e4d847e350 | Python | 1,017 | 33 | from analyse import *
import os
import subprocess
import shutil
from jinja2 import Template
proteins = initProteins()
proteins.to_csv('proteins.csv')
submission = Template("""#!/bin/bash
#SBATCH --job-name={{name}}_{{replica}}
#SBATCH --nodes=1
#SBATCH --partition=qgpu
#SBATCH --gres=gpu:1
#SBATCH --cpus-per-task=18
... |
a21655cf5bf91a8c9485a73c71adf39c3a0f3a8f2ff1a3aa49b7d1904c6cda5d | Python | 1,017 | 36 | from typing import Protocol
import torch
from torch import Tensor, nn
from elasticai.creator.base_modules.math_operations import (
ParamExponent,
Quantize,
TwosScale,
)
class MathOperations(Quantize, TwosScale, ParamExponent, Protocol): ...
class LeakyReLU2(torch.nn.LeakyReLU):
def __init__(
... |
c37b30ae6c7b05e0de15d4bffd0f7a3c1639915d90f7842ef2605467da7be53a | Python | 1,017 | 30 | import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
requirements = ["numpy", "scipy", "scikit-learn", "nibabel", "gdist"]
setuptools.setup(
name="Connectome_Spatial_Smoothing",
version="0.1.6",
author="Sina Mansour L.",
author_email="sina.mansour.la... |
c5ade5a09c09656a05980ea71c8786bf3632ec4b94ba6c41c36a7b662fc0d01e | Python | 1,017 | 38 | from __future__ import print_function,division
import os
import sys
import numpy as np
import pandas as pd
def parse_args():
import argparse
parser = argparse.ArgumentParser('Script for subsampling particles from a coordinates table')
parser.add_argument('file', help='path to particle coordinates file')
... |
3e67b0a84b906a3f56f9ee942b07b8e427aca0be8faaddf1b3cb318d3f04aa99 | Python | 1,018 | 27 | # Plots effect sizes for preferential parameters for Fig 6
from os.path import join
from get_paths import *
from TVATPlotting import TVATPlotting
import matplotlib.pyplot as plt
if __name__ == "__main__":
save_flag = 0
## Load data
fname_regressions = "data_tvat_polynomialregressions.pic... |
83f13a68378392e75f7006982738f5763a00102e97d70028c08a6e15193236b7 | Python | 1,018 | 38 | # Parameters for evolution
import sys
sys.path.append("..")
params = {}
# States to be simulated
params["states"] = ["resting"]
# Objectives used to evaluate fitness - pso_comp.py
params["objective_names"] = [
"peaks_iwave",
"minima_iwave",
"tpeaks_iwave",
"tminima_iwave",
"postmin_iwave",
"f... |
a9a7c1c6d3dffca5a099f82889591e079fcbc8a8aca202d4e37ad8eb4ff0b50b | Python | 1,019 | 38 | """A script for running the regression analysis on the marged data set."""
import imp
import pandas as pd
import statsmodels.api as sm
plot = imp.load_source("plot", "src/plot.py")
df = pd.read_csv('data/merged_3_processed.csv')
features = [
"CC_to_C_rate",
"CD_to_C_rate",
"DC_to_C_rate",
"SSE",
... |
1ab9f22d801b44b8a7f0be55e057c02c52c8eb40fdff3a71bbdef51924c2ff48 | Python | 1,020 | 31 | import sys
import json
from typing import Union
from utils.common import *
from utils.param_process import *
from train_icon_noise import Trainer
def main(config_path: Union[Path, dict]):
for run_no in range(5):
trainer = Trainer(config_path)
print(trainer.params.gat_shapes)
if t... |
6597fdabdff62be98da806640a8a7d753f8bc914ed1e375b9e875924e789534f | Python | 1,020 | 37 | from .pddl_types import Type
from .pddl_types import TypedObject
from .tasks import Task
from .tasks import Requirements
from .predicates import Predicate
from .functions import Function
from .actions import Action
from .actions import PropositionalAction
from .axioms import Axiom
from .axioms import Propositional... |
c61cdb26aa160ce9b12776b052da32d95fbcb3a2894bafa07946df4648c2550c | Python | 1,020 | 32 | #!/bin/env python3
'''
Define a history, i.e. a list of steps, each of which capture a point in
time.
'''
from typing import Union
from .pool import ParticlePool
from .reaction import Reaction
from .yamlrepr import YAML_Sequence_Representer
class ReactionHistory(YAML_Sequence_Representer):
@property
def pool(s... |
cc78b051f8260feb3208a984e9ab60011dd9873db841bffb456cc0c43155ce7c | Python | 1,020 | 42 | import torch.nn as nn
from abc import ABC, abstractmethod
# nn.Conv2d default values:
# self,
# in_channels: int,
# out_channels: int,
# kernel_size: _size_2_t,
# stride: _size_2_t = 1,
# padding: Union[str, _size_2_t] = 0,
# dilation: _size_2_t = 1,
# groups: int = 1,
# bias: bool = True,
# padding_mode: str = 'zero... |
e501afdf842a4487bbf515ec8537b1d79c7533263ead1021bd7e36500ca4f1d1 | Python | 1,020 | 35 | import os
from torchdrug import data, utils
from torchdrug.core import Registry as R
@R.register("datasets.CiteSeer")
class CiteSeer(data.NodeClassificationDataset):
"""
A citation network of scientific publications with binary word features.
Statistics:
- #Node: 3,327
- #Edge: 8,059
... |
fb05f89468184138a577be1b25a68106acb05d96cd90b5248c305e2bf555d726 | Python | 1,020 | 32 | import sys
fn=sys.argv[1]
dfh=open(fn,'r')
dfh.readline()
rfh=open(fn+'_rmdup.txt','w')
pre=''
duplicate=0
total=0
First_aligned=0
Second_aligned=0
Used_Frag=0
for i in dfh:
line=i.split()
total+=1
# if line[1]!='na':
# First_aligned+=1
# if line[-1]!='na':
# First_aligned+=1
# for a in line[2:-1]:
# if a!='na':
... |
07e070feee05dcc4bbbb9565f72b02bf70c8e9b25da51ae9f5146f85327688bf | Python | 1,021 | 31 | from Patient import PatientDataBase
# mods: gaussian, rectangle, noise, noise_gauss
mods = 'noise_gauss'
DATA_PATH_IN = "../../data/input_data"
DATA_PATH_OUT = "../data/output_data/" + mods
ct_data_out = "../data/output_data/png_org"
if __name__ == '__main__':
print('start initialization')
data_base = Patien... |
095b78527b6c062c8aa7b9a08a5982b4caf4f4b3e6753ae5e38519d38ae6f21c | Python | 1,021 | 31 | # SPDX-FileCopyrightText: 2024 Blue Brain Project / EPFL
#
# SPDX-License-Identifier: AGPL-3.0-or-later
import os
import pandas as pd
import h5py
import numpy as np
dir_path = './topological_sampling/working_dir/data/other/classifier/Parameter'
names = os.listdir(dir_path)
def get_scores(address):
with h5py.File(... |
63f27bca7c4f4a81454d3ec7d1f3206c195512bc320c670e6e099ee4c06ecf9f | Python | 1,021 | 30 | from __future__ import annotations
from pathlib import Path
from ..wheelfile import WheelFile
def unpack(path: str, dest: str = ".") -> None:
"""Unpack a wheel.
Wheel content will be unpacked to {dest}/{name}-{ver}, where {name}
is the package name and {ver} its version.
:param path: The path to t... |
c725470a63862f561df70ae36c71672f0c4c5689020b17f3153da79ea1a99d08 | Python | 1,021 | 31 | import os
import re
# for IDE test
from codex.configuration import APP_ENVIRONMENT
from codex.data.local_data_loader import DATA_ROOT_PATH
from codex.data.neuron_data_factory import NeuronDataFactory
from codex.data.versions import TESTING_DATA_SNAPSHOT_VERSION
TEST_DATA_ROOT_PATH = re.sub(r"tests.*", DATA_ROOT_PATH,... |
256831379a82fd2b6adc24900623910903d3503851234010de167858e88ca045 | Python | 1,022 | 31 | r"""Example test that uses the OpenBabel Python bindings
On Windows or Linux, you can run these tests at the commandline
in the build folder with:
"C:\Program Files\CMake 2.6\bin\ctest.exe" -C CTestTestfile.cmake
-R pybindtest -VV
You could also "chdir" into build/test and r... |
c44efc264bc10772ef530bf585453b874c8fd151e3bf55bc6335d62ca9cbaa21 | Python | 1,022 | 36 | import os
os.environ["HF_HUB_CACHE"] = "./.cache"
os.environ["HF_XET_HIGH_PERFORMANCE"] = "1"
import tempfile
import torch
from diffusers import ZImagePipeline
from cog import BaseRunner, Path
class Runner(BaseRunner):
def setup(self) -> None:
self.model = ZImagePipeline.from_pretrained(
... |
efbe18d66f2499c718507eea0c38edadab13575f82bd0714a2d12658a1536197 | Python | 1,022 | 43 | # built-in
from math import isclose
# external
import hypothesis
import pytest
# project
import textdistance
ALG = textdistance.Sorensen
@pytest.mark.parametrize('left, right, expected', [
('test', 'text', 2.0 * 3 / 8),
])
def test_distance(left, right, expected):
actual = ALG(external=False)(left, right)... |
f8d93483bec6767d6265f87f19b46db24ff7058db773cedbbf5a9f4ab5328d6f | Python | 1,022 | 44 | from unittest import TestCase
from codex.utils.pathway_vis import sort_layers
from tests import get_testing_neuron_db
class Test(TestCase):
@classmethod
def setUpClass(cls):
cls.neuron_db = get_testing_neuron_db()
def test_sort_layers(self):
layers = {1: 0, 2: 1, 3: 1, 4: 1, 5: 2, 6: 2, ... |
666edde1d9c34df04c1017758a0a331cadebd88d62371d893c143b6ae712c22e | Python | 1,023 | 25 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2024 Clinic for Diagnositic and Interventional Radiology, University Hospital Bonn, 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 ... |
77a125fd9fb21f702f6071a3b483aece9a93f33e2fdc29a4950098429c9a78b2 | Python | 1,023 | 30 | import torch
import torch.nn as nn
import math
class PositionalEncoding(nn.Module):
'''
positional encoding module changed around for the tensor shapes and order
required for our special type of "Transformer"
Needed to do a special version as the way we flatten at the end requires
[batch, ... |
8c6a7f9c7aae049a9d0022976f9302172d1caadef00bb3ffaa663b619ef86a47 | Python | 1,023 | 36 | from Bio import SeqIO
from torch.utils.data import Dataset
from utils import encode_seq, reverse_complement
class FastaDataset(Dataset):
def __init__(self,
file_path: str,
reverse: bool = False):
super().__init__()
self.file_path = file_path
self.seqs = li... |
2ab0c8438843859fa05798b1b0f2d3a0ed15e5129408b7e9fec7156fc40b5ac7 | Python | 1,024 | 41 | import networkx as nx
import pytest
from skymap.metrics import SkyMapMetrics
@pytest.fixture
def graph_1():
g = nx.wheel_graph(5)
nodes = [0, 1, 2, 3, 4]
classes = [0, 0, 1, 1, 1]
features = [
[0, 0, 1, 0],
[0, 0, 1, 0],
[0, 1, 0, 0],
[0, 1, 1, 0],
[1, 0, 0, 1]
... |
beedc78d25f1145fb02de3d310fa1246efe657e159dad82c53705979f6921096 | Python | 1,024 | 28 | from cloudvolume import CloudVolume
import numpy as np
from scipy import ndimage
mip = 6
src = CloudVolume('gs://neuroglancer/pinky100_v0/son_of_alignment_v8', mip=mip)
dst = CloudVolume('gs://neuroglancer/pinky100_v0/son_of_alignment_v8/roicc', mip=mip, cdn_cache=False)
# Get bounding box of a total slice
offset = s... |
2740c0844774f45da0aeff3c684b0ceb82de5c77e16e6c99590346a400692be0 | Python | 1,025 | 29 | from models.mlp import MLP
from models.mlp_kan import MLP_KAN
from models.hu1dcnn import Hu1DCNN
from models.hu1dcnn_kan import Hu1DCNN_KAN
from models.hu1dcnn_full_kan import Hu1DCNN_KAN as Hu1DCNN_FULL_KAN
from models.m1dcnn import M1DCNN
from models.m1dcnn_kan import M1DCNN_KAN
from models.m1dcnn_full_kan import M... |
ca7eb5bb40075e837d4ff0d38d697d09c03fff6fffd15cdd4b88446464eebcbd | Python | 1,025 | 32 | import sys
sys.path.append("../../../../pylib")
from pathlib import Path
import os
import numpy as np
import pickle
if __name__ == '__main__':
all = Path("../230k/stage2_app2/all.txt")
coords_pik='coords.pickle'
with open(coords_pik, 'rb') as fp:
brains = pickle.load(fp)
mtx_pik = "mtx.... |
d0ae16c007cc1b521d77dc9364100d32124f9560339600aa3019d960d32ff9b2 | Python | 1,025 | 39 | from __future__ import annotations
import pytest
ray = pytest.importorskip("ray")
from pathlib import Path
from quacc import flow, job
from quacc.utils.files import copy_decompress_files
def test_copy_files(tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path)
@job
def create_file(name: str, copy: list... |
b2eba496f702dfb1214d2b5240933909dcfd356eb986a8163cbca1e61b33c7c7 | Python | 1,026 | 39 | from elasticai.creator.graph.name_generation import NameRegistry
def test_can_generate_unique_name():
reg = NameRegistry()
reg.prepopulate(["a", "b", "c"])
assert reg.get_unique_name("a") == "a_1"
assert reg.get_unique_name("a") == "a_2"
def test_name_is_not_altered_if_already_unique():
reg = Na... |
e8e7eef8ca4e1d84adde5bc679dc07563a329b3d796a18f7d9e5b3b7b9f04442 | Python | 1,026 | 33 | from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="PRiMeR",
version="0.1",
author="Daniel Sens & Francesco Paolo Casale",
author_email="daniel.sens@helmholtz-munich.de",
description="Genetics-driven Risk Pr... |
d744946429f5d118a96c77f34e9d60eb8ae20bb5b7367673928f32fb173b90ff | Python | 1,027 | 37 | from logging import getLogger, WARNING
lg = getLogger(__name__)
def write_mnefiff(data, filename):
"""Export data to MNE using FIFF format.
Parameters
----------
data : instance of ChanTime
data with only one trial
filename : path to file
file to export to (include '.mat')
No... |
e3a27113ef8089f3177d6241ef117ea76e5dd2c3632ca14b3387239e32d45b95 | Python | 1,028 | 33 | import unittest
import os
import random
import shutil
from torcheeg.model_selection import LeaveOneSubjectOut
from torcheeg.datasets import DEAPDataset
class TestLeaveOneSubjectOut(unittest.TestCase):
def setUp(self):
shutil.rmtree('./tmp_out/')
os.mkdir('./tmp_out/')
def test_leave_one_subj... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.