sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
f1c0742da3da6ce31ab1f2b6fa3f685e9722db5ecdfe03bbc00339b00e4c4d38 | Python | 1,361 | 65 | import torch
import tonic
import norse
import nir
import lightning.pytorch as pl
# %%
g = nir.read("cnn_sinabs.nir")
# %%
model = norse.torch.from_nir(g)
# %%
to_frame = tonic.transforms.ToFrame(
sensor_size=tonic.datasets.NMNIST.sensor_size, time_window=1e3
)
dataset = tonic.datasets.NMNIST(".", transform=to_fr... |
7eeabfb914adab4447616183e066d3467c8bac4316176146d746752fac3ea6e3 | Python | 1,362 | 29 | from projectmetis.python.models.model_dataset import ModelDataset
class LearnerEvaluator(object):
def __init__(self, model_ops_fn, model_pb):
"""
We apply the model weights one-time during the initialization of the Evaluator constructor
because applying the weights on per evaluation or in... |
27733d8735b5120bc67b014a355a60b8d7090007d82464e14c18336751c473a6 | Python | 1,363 | 45 | from typing import Any, Dict, List, Tuple, Union
import ray
from ray.dag import DAGNode
from ray.dag.format_utils import get_dag_node_str
from ray.util.annotations import DeveloperAPI
@DeveloperAPI
class MultiOutputNode(DAGNode):
"""Ray dag node used in DAG building API to mark the endpoint of DAG"""
def __... |
7c05897711f8626bc11c57c63db3a2070b737bdbac284c9cef3b2be0c14b8e5b | Python | 1,363 | 40 | import gym
import numpy as np
class RandomizeAction(gym.ActionWrapper):
"""Apply a random action instead of the one sent by the agent.
This wrapper can be used to make a stochastic env. The common use is
for evaluation in Atari environments, where actions are replaced with
random ones with a low prob... |
c4182fa7d25f32c0066e00be33ce858b41acbcd769430cb21fa4197bfc8e1fb2 | Python | 1,363 | 53 | import numpy as np
from .basic_distributions import Distribution
from ... import config
class Bernoulli(Distribution):
"""
Class to define Bernoulli distributions
Equations:
"""
def __init__(self, dim, theta, E=None):
Distribution.__init__(self, dim)
# Initialise parameters
... |
1248b7ead906b902719e591cc1b33b8c671aa0d5810948e7603663bb5dfb1fa1 | Python | 1,364 | 46 | import os
from pcntoolkit.normative_parallel import execute_nm, collect_nm, delete_nm
# globals
root_dir = '/project_cephfs/3022017.02/projects/hansav/'
proc_dir = os.path.join(root_dir,'Run8_f')
w_dir = os.path.join(proc_dir,'vox/')
os.makedirs(w_dir, exist_ok=True)
py_path = '/home/preclineu/hansav/.conda/envs/py38... |
2ee5f7d1dec99c4c665ab7ecf9adfa8d2b26ee139c018721d7f9856d374381cd | Python | 1,364 | 42 | """UMAP a/b curve-parameter fitting — bit-faithful to umap-learn 0.5.7.
``find_ab_params`` fits the smooth low-dimensional membership curve
``1 / (1 + a * x^(2b))`` to an offset exponential decay parameterised by
``spread`` and ``min_dist``. We reproduce umap-learn's exact ``curve_fit``
so the attractive/repulsive gra... |
f765cd3b50e4f8a5700b23884eb43b3e7f8cdbcae5972ffb2c0f838950d3df99 | Python | 1,364 | 57 | def context():
"""
Infers the context in which the current program is being executed.
https://stackoverflow.com/a/47428575
Returns
-------
str
The context, either 'colab', 'jupyter', 'ipython', or 'terminal'.
"""
try:
ipy_str = str(type(get_ipython()))
if 'colab... |
558b37557b7af55e05147cea46fa9dc5665ae28891e7e00df0e2d34eed0bd6ed | Python | 1,365 | 36 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion):
# --------------------------------------------------------------------------------... |
78f9f6c2e9bfe392effb5aacdac8b329d716737d6d895ba9006447d716e0a879 | Python | 1,365 | 55 | # -*- coding: utf-8 -*-
"""Test mesh plotting."""
import numpy as np
import pytest
import vtkplotlib as vpl
from tests._common import numpy_stl
path = vpl.data.get_rabbit_stl()
pytestmark = pytest.mark.order(7)
def test_type_normalise():
mesh = numpy_stl().Mesh.from_file(path)
vectors = mesh.vectors
... |
0cd45695b7b9a4173aec182640433e1fd3d9916cbce04b9c18217793da2e773d | Python | 1,366 | 48 | """Utilities for condensing dialogue into structured project briefs."""
from __future__ import annotations
from dataclasses import dataclass
from typing import List, Sequence
@dataclass
class ProjectBrief:
"""Structured representation of a project's requirements."""
title: str
objectives: List[str]
... |
739e89e36cfba111adc90068b1527b4ea266d70611085afa391a1fe1a413e8e7 | Python | 1,368 | 46 | # Vendored from `decoupler` (https://github.com/scverse/decoupler) by
# omicverse for in-tree GPU acceleration work. Original copyright by
# the decoupler authors, redistributed under decoupler's GPL-3.0
# license. Cross-module imports rewritten from `decoupler.*` to
# `omicverse.es.*` (see scripts/vendor_decoupler.py)... |
b7a8be6846fb8b51059a2dc5a1625f0e8c94cbc8f86c7778c31c4e7371ee0223 | Python | 1,368 | 59 | """ Wave generator from fiducial data. Fast script for generating masks from re-annotated data"""
from sak.data_structures import load_data
from os.path import join
import pandas
import glob
import numpy as np
path = '/media/guille/DADES/DADES/PhysioNet/QTDB/manual0'
maxSize = 225000
################ P wave #######... |
41eec4fd4c23ff34999a1e3fdedff9d075dab34df10b931052ca6a72ea3ac7b1 | Python | 1,369 | 37 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter, MaxNLocator
plt.rc('font',size=15)
TestLength=450
L=50
Actual=np.load('actualTrajectory.npy')
predict=np.load('avgTrajectory.npy')
total=np.load('totalTrajectory.npy')
actual=np.zeros((1,TestLength))
actual[0,... |
a5e1c36a2350c79bb804ffae5803c47859c1a5b91fb76598682dfff3eadd90a0 | Python | 1,369 | 46 | import os
from pcntoolkit.normative_parallel import execute_nm, collect_nm, delete_nm
# globals
root_dir = '/project_cephfs/3022017.02/projects/hansav/'
proc_dir = os.path.join(root_dir,'Run8_fs')
w_dir = os.path.join(proc_dir,'vox/')
os.makedirs(w_dir, exist_ok=True)
py_path = '/home/preclineu/hansav/.conda/envs/py3... |
62caa17381dbae270490314230e34c27c021b954d0919740cfb4f9abe4d51c89 | Python | 1,370 | 38 | import torch
from ..utils import loss_and_miner_utils as lmu
from ..losses.base_metric_loss_function import BaseMetricLossFunction
class GenericPairLoss(BaseMetricLossFunction):
def __init__(self, mat_based_loss, **kwargs):
super().__init__(**kwargs)
self.loss_method = (
self.mat_base... |
aa204f5d43b39550804ca51e3e391a897d29073032c108cb184f9ff64cc8cd1c | Python | 1,370 | 39 | import torch
def extract_model_state_dict(ckpt_path, model_name='model', prefixes_to_ignore=[]):
checkpoint = torch.load(ckpt_path, map_location='cpu')
checkpoint_ = {}
if 'state_dict' in checkpoint: # if it's a pytorch-lightning checkpoint
checkpoint = checkpoint['state_dict']
for k, v in chec... |
ea92da0fb70b7ab91c5f1d8e583ceb43e8160a7160bebd266ccd6ac3104168ed | Python | 1,370 | 39 | # Copyright 2022 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
095de4aac0ac1e2dfd698be3e29cfd7164fbf49274e751de016ac24ce7ade3a3 | Python | 1,371 | 52 | from typing import List, Tuple, Union
import numpy as np
from torch import nn
ArrayLike = Union[np.ndarray, List, Tuple]
class Cropping2dLayer(nn.Module):
"""Crop input image by.
Args:
cropping: ((top, bottom), (left, right))
"""
def __init__(
self,
cropping: ArrayLike = ((... |
151206436f3973e939824ccfe6915b6d0f8c51ed74811a69a065e57759f22149 | Python | 1,371 | 41 | import os
import pytest
from sv_utils import fix_vcf, genomics_io
class Default:
resources_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
small_needs_fix_vcf = os.path.join(resources_dir, "small_needs_fix.vcf.gz")
def gatk_installed() -> bool:
return os.system("gatk") == 0
... |
a0aa199adbb0bd6430fbe4649f7f98e1be77265f55f257200be37bf3d4bdb3ce | Python | 1,371 | 65 | #!/usr/bin/env python3
import rospy
from std_msgs.msg import MultiArrayDimension,Int8MultiArray
import os
import shutil
import cv2
from cv_bridge import CvBridge
import ros_numpy
import numpy as np
import PIL.Image
import io
from torch2trt import torch2trt
from torch2trt import TRTModule
import torch
from torchvisio... |
d4a100acb9460e68c73d03a6c5faab6dd3d3ca73942282bd911e7f475955273b | Python | 1,371 | 44 | import pandas as pd
import numpy as np
from scipy.stats import truncnorm
import json
import pathlib
from pathlib import Path
import glob
import os
import cv2
import nmrglue as ng
import plotly
from basicsr.utils import FileClient, imfrombytes, img2tensor
import plotly.express as px
from scipy.ndimage import gaussian_fi... |
4299da741f8b6448e8969e084a320d639f2a4bd29501a59bb3bc5ef718909d28 | Python | 1,372 | 48 | import unittest
from spinnaker2 import hardware
from spinnaker2.neuron_models.application import PEMemory, NamedMemoryRegion, MemoryRegionType
from spinnaker2.configuration import MemoryRegion
from spinnaker2.coordinates import WordAddr
import pprint
pe_mem = PEMemory()
pe_mem.instruction_memory()
pe_mem.insert(Memor... |
c266115148c917d287c223a2c1181cd172ee55493e434851f55fd4fadef4511e | Python | 1,372 | 47 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 12 08:40:51 2022
Development.
Trying to figure out the SNR of the invivo data
Adding noise and re-evaluating
@author: pbolan
"""
from utility_functions import *
from inference import get_inference_dataloader
#%%
ds_name = 'INVIVO_SET1_NOISE_3'
loa... |
70cd34a3d37fd073329992ddabfe6b07bd53061e2868876e6619a5aa27783e57 | Python | 1,373 | 35 | """
Module for class used to format loop table in STAGG Settings Editor
***
built as part of the Russell Ray Lab Breathing And Physiology Analysis Pipeline
***
Breathe Easy - an automated waveform analysis pipeline
Copyright (C) 2022
Savannah Lusk, Andersen Chang,
Avery Twitchell-Heyne, Shaun Fattig,
Christopher S... |
7325485a7f179a31906b13959bfd64c77f695b3bf59365b635ad2aa15151e5e7 | Python | 1,373 | 37 | import unittest
import torch
from rising.transforms.functional import to_device_dtype
class TestSpatialFunctional(unittest.TestCase):
def setUp(self) -> None:
self.device = "cuda:0"
self.batch_2d = torch.arange(1, 10).reshape(3, 3)[None, None]
@unittest.skipUnless(torch.cuda.is_available(),... |
bdafd4734fac54c7a4f9aa7844f5595bbd02fe70904d0bb37d4f4c9daf38b428 | Python | 1,373 | 48 | """
Copyright (c) Meta Platforms, Inc. and affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import os
import ase.io
from ase.build import add_adsorbate, fcc100, molecule
from ase.constraints import FixAtoms
def main():
"""
... |
fd4c14d0e1454d78c6b62f38db96dab332e442314e9c831396bd4b5dd0ac315d | Python | 1,373 | 38 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter, MaxNLocator
plt.rc('font',size=15)
TestLength=400
L=50
Actual=np.load('actualTrajectory.npy')
predict=np.load('avgTrajectory.npy')
total=np.load('totalTrajectory.npy')
actual=np.zeros((1,TestLength))
actual[0,... |
3a2c01c22d17eab9c2064e6bbaf810c5e2d171635d053709838a175dd487bd98 | Python | 1,374 | 53 | """
This file serves as a documentation example for aggregated tokenization.
"""
import ray
from ray.data.llm import (
vLLMEngineProcessorConfig,
build_processor,
TokenizerStageConfig,
DetokenizeStageConfig,
)
# __aggregated_tokenization_start__
config = vLLMEngineProcessorConfig(
model_source="u... |
e4463efa5f8789ea26517dbcac9904ed7250bbc0056f179b4f31d23146f52b92 | Python | 1,375 | 45 | import random
import unittest
import pytest
import torch
import pfrl
class TestSetRandomSeed(unittest.TestCase):
def test_random(self):
pfrl.utils.set_random_seed(0)
seed0_0 = random.random()
pfrl.utils.set_random_seed(1)
seed1_0 = random.random()
pfrl.utils.set_random_se... |
53003628bc43f16e311f582f81800477cf01174ee3582ce7efff21d31177372d | Python | 1,376 | 45 | import os
import sys
if True:
folder = 'E:\\1photon-small\\added_refined_masks\\DeepWonder_scale_full'
list_Exp_ID = [ 'c25_59_228','c27_12_326','c28_83_210',\
'c25_163_267','c27_114_176','c28_161_149',\
'c25_123_348','c27_122_121','c28_163_244']
for Exp_ID in list_Exp_ID:
os.sy... |
662b1cf3794421034205fae0346105a42a6405c64b6a71c92906331724686b0d | Python | 1,376 | 64 | """
HTML flavour mapping
"""
from data_profiling.report.presentation.core import (
HTML,
Alerts,
Collapse,
Container,
CorrelationTable,
Dropdown,
Duplicate,
FrequencyTable,
FrequencyTableSmall,
Image,
Root,
Sample,
Scores,
Table,
ToggleButton,
Variable... |
818d3a4a1073c62ff4eddba9f0aee6689301d93062356a0b3224ac5e5b20f5e3 | Python | 1,377 | 54 | import pdb
import torch
import torch.nn as nn
from latent_time_stepping.AE_models.encoder_decoder import Encoder
class VAEEncoder(nn.Module):
def __init__(
self,
num_channels: list = None,
kernel_size: list = None,
latent_dim: int = 16
) -> None:
super().__init__... |
aec2db365683d43e40b383cefbd04755620d1e37d4accf6ef10363c2c265204e | Python | 1,377 | 39 | #!/usr/bin/env python3
# Copyright 2004-present Facebook. All Rights Reserved.
import numpy as np
from scipy.spatial import cKDTree as KDTree
import trimesh
def compute_trimesh_chamfer(gt_points, gen_mesh, offset, scale, num_mesh_samples=30000):
"""
This function computes a symmetric chamfer distance, i.e. t... |
3401b891a842f509940f8b51ccaffdd2e8ef1f5bad026db3d2a907c58f969c03 | Python | 1,378 | 44 | # Copyright 2026 Google LLC.
#
# 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 in writing, ... |
614dfc8e4b4ea16dca27eddfd26914d7cff9e1ab9e3b89fcbabc23db6f0f91e1 | Python | 1,378 | 33 | import os
import glob
import pytest
from typing import Iterable
from sv_utils import get_genome_track_overlaps, genomics_io
class Default:
resources_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources")
small_vcfs_dir = os.path.join(resources_dir, "small_vcfs")
small_vcfs = tuple(so... |
7a707cb8d7acbbd93a00da5363e6d25493b9615521a214efa769b8e905c4b610 | Python | 1,379 | 41 | import glob
import yaml
import pandas as pd
import pdb
from parameterized import parameterized
yaml_files = glob.glob('datasets/*/*.yaml')
all_yfs = [(yf,) for yf in yaml_files]
@parameterized.expand(all_yfs)
def test_all_yaml_files(yf):
"Check basic information in yaml files."
print("\nTesting {}".format(yf))... |
2b3c16825c73ba3e6973539f7558fb4a515c222ce8d0865ddf799027038abbde | Python | 1,381 | 54 | from typing import Optional, Type
import pytest
from ray.air.execution._internal.barrier import Barrier
def _raise(exception_type: Type[Exception] = RuntimeError, msg: Optional[str] = None):
def _raise_exception(*args, **kwargs):
raise exception_type(msg)
return _raise_exception
def test_barrier_... |
32390fe39325341a046e455cf7242d0be361137bfbfd5f3f78a9efd91588da00 | Python | 1,381 | 66 | from enum import Enum
class AugmentationStrengthScalers(Enum):
# This is needed since some augmentation might need sub/super-linear scaling
AFFINEROTATE = 0.2
AFFINETRANSLATE = 1
AFFINESCALE = 0.01
ADJUSTCONTRASTGAMMA = 0.01
SHIFTINTENSITYOFFSET = 0.025
GAUSSIANNOISESTD = 0.01
class VQVA... |
5973e3bc7a3fec11f18ebb59ac59e159e246a411f5922f3290b4afb5aac90578 | Python | 1,382 | 41 | import argparse
import gtfparse
import pickle
from collections import defaultdict
def parse_argument():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', help='Input GTF file.', required=True)
parser.add_argument('-o', '--output', help='Output ensg2tss pickle file.', required=True)
... |
663223c790283317d2b6803694de6969a5fe90081751326b91a227458fa867ae | Python | 1,383 | 52 | """
script to test synchronous start of all PEs
"""
import os
from spinnaker2 import hardware, snn
def test_routing_all_pes():
n_stim = 1
n_tgt_pes = 151
spike_times = {0: [1, 5, 10]}
stim = snn.Population(n_stim, "spike_list", params=spike_times, name="stim")
lif_params = {
"threshold":... |
6a7e0f7a90fea752102c1d09f95c6089f067edce080318ad7bd8ab865b7dc907 | Python | 1,383 | 32 | from torch_pgn.train.train_utils import predict
from scipy.stats import pearsonr
from sklearn.metrics import r2_score
import numpy as np
def evaluate(model, data_loader, args, metrics, mean=0, std=1, remove_norm=True):
"""
Function used to evaluate the model performance on a given dataset.
:param model: T... |
3d2be787fc7d92dd9cc77c42b1ecaa102efaa6161dadef1cb842eaf8790713ba | Python | 1,385 | 45 | # Copyright 2023 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
5106b361a52acb4614b3c989be0d2ec7f4536e3594438d67d2630e074becdcc6 | Python | 1,386 | 41 | from pathlib2 import Path
import pathlib2
import os
from datetime import datetime
import numpy as np
PROJECT_DIR = Path(__file__).resolve().parents[1]
PACKAGE_DIR = Path(__file__).resolve().parent
DATA_DIR = PROJECT_DIR / "data"
def ensure_dir(file_path):
"""create a safely nested folder"""
if type(file_path... |
b499d1a06c902f4c9ada76115977e4d2307a433b2ced8f873b4bd7a24cc0d73d | Python | 1,386 | 45 | from typing import List
from ipywidgets import HTML, Button, widgets
from data_profiling.report.presentation.core import Alerts
from data_profiling.report.presentation.flavours.html import templates
from data_profiling.utils.styles import get_alert_styles
def get_row(items: List[widgets.Widget]) -> widgets.GridBox:... |
fee25a2e85b2673fd2edd7071b21add4ae7fef4d0abcadbfce26b33cc19fecce | Python | 1,386 | 42 | """
An app script for running calibration of a camera from the command line.
Copyright (C) Microsoft Corporation. All rights reserved.
"""
# Standard Libraries.
import argparse
# Calibration tools.
from camera_tools import calibrate_camera
# --------------------------------------------------------------------------... |
468a8a34b62eaabff6807206d4fbea22647d77ae7ff2a65b4cf2c2bc16a80d94 | Python | 1,387 | 42 | # 3rd party dependencies
import pytest
# project dependencies
from deepface.modules import streaming
from deepface.commons.logger import Logger
logger = Logger()
class ValidationPassed(Exception):
pass
def test_streaming_requires_opencv_python(monkeypatch):
def distribution(name):
raise streaming.... |
0db7cea14ceeb0ad3970c4671290ed204b8f9c31319f200eed82b8d8f7c559c5 | Python | 1,388 | 45 | """
test for setting individual parameters for the LIF neuron
"""
from spinnaker2 import snn, hardware, brian2_sim
import numpy as np
rng = np.random.default_rng()
def test_lif_neuron_individual_params():
n_neurons = 300 # larger than max neurons per core
params = {
"threshold":rng.uniform(0.8, 1.2... |
6be61cbfb0b502756a3331aef76fb12a6c508fc19e94742c52a896f8bf97e29a | Python | 1,388 | 52 | """Vendored MetaQ (Li et al., Nat Commun 2025).
Original repo: https://github.com/XLearning-SCU/MetaQ (MIT License).
Vendored verbatim with the following modifications:
- ``engine.py``: ``from model import reconstruction_loss`` →
``from .model import reconstruction_loss`` so the package works without
being added ... |
a970c42b726ca98cdcad1d00f7d48e70c4a815ba487ea6541cb8b5568d036f80 | Python | 1,388 | 32 | import sys
import h5py
def merge_hdf5_files(file_list, output_file):
with h5py.File(output_file, 'w') as merged_h5:
for file_name in file_list:
with h5py.File(file_name, 'r') as file:
for group_name in file.keys():
group = file[group_name]
... |
1513d9a1f26b7c7d10dba67c4c0d50c12c1c6cc47f1e782a9ed351c8da4b6d87 | Python | 1,390 | 61 | """
Flavour widget
"""
from data_profiling.report.presentation.core import (
HTML,
Alerts,
Collapse,
Container,
CorrelationTable,
Dropdown,
Duplicate,
FrequencyTable,
FrequencyTableSmall,
Image,
Root,
Sample,
Table,
ToggleButton,
Variable,
VariableInfo... |
522d018f71dbb10d77e6c391db1bebe6b505ec767916721aa034e845f4f041bf | Python | 1,390 | 63 | import os
import subprocess
from pathlib import Path
NSIGHT_FAKE_DIR = str(
Path(os.path.realpath(__file__)).parents[4]
/ "python"
/ "ray"
/ "tests"
/ "nsight_fake"
)
subprocess.check_call(
["pip", "install", NSIGHT_FAKE_DIR],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
... |
7b8523570b2e0cfd033259baffc5d9c70230e07f2b5e1cff29f9797a409d654f | Python | 1,390 | 44 | import numpy as np
from siapy.entities import Pixels, SpectralImage
from siapy.utils.plots import InteractiveButtonsEnum, display_multiple_images_with_areas
# Create two mock spectral images (e.g., simulating VNIR and SWIR)
rng = np.random.default_rng(seed=42)
# VNIR-like image (4 bands)
vnir_array = rng.random((50,... |
cc38e7871f81abfff5de2f6f7b24b3e3d37aa7f96987c31e72ec5b10e52041d9 | Python | 1,391 | 35 | from pathlib import Path
from siapy.entities import SpectralImage
from siapy.transformations import corregistrator
from siapy.utils.plots import pixels_select_click
# Set the path to the directory containing the data
# !! ADJUST THIS PATH TO YOUR DATA DIRECTORY !!
data_dir = "./docs/examples/data"
# Get first image
... |
351122593a61ae7ce94a18ed67a38089206f60f7ebaaf168b51a4d3052b487d9 | Python | 1,392 | 40 | import json
import os
# Define paths
bidsdir = "/ZPOOL/data/projects/rf1-datapaper-dev/bids"
func_dir = "func" # Directory containing the functional images
# Find all subject directories in the BIDS directory
subs = [d for d in os.listdir(bidsdir) if os.path.isdir(os.path.join(bidsdir, d)) and d.startswith('sub-1036... |
7e56ec5dcf686aca7a1a0deabb16cfb22595d914149e5c2dbffb489a67c0a2fb | Python | 1,392 | 39 | import os
import sys
sys.path.append('.')
import cv2
import math
import torch
import argparse
import numpy as np
from torch.nn import functional as F
from model.pytorch_msssim import ssim_matlab
from model.RIFE import Model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = Model()
model.loa... |
57acfb61878ecbdf375d782ec0a6471556f0985ecb3caac47dcd94afcec12498 | Python | 1,395 | 44 | import random
import unittest
import torch
from rising.transforms import GaussianSmoothing, KernelTransform
class TestKernelTransforms(unittest.TestCase):
def setUp(self) -> None:
torch.manual_seed(0)
random.seed(0)
self.batch_dict = {
"data": torch.zeros(1, 1, 3, 3).float(),... |
6c62f780c706f71a83f771f21a0283e9495c390ecc3461e5970c507d65426f59 | Python | 1,395 | 46 | from dataclasses import dataclass
from typing import Optional
@dataclass
class MembraneReset:
"""Reset the membrane potential v_mem to a given value after it spiked.
Args:
reset_value: fixed value that a neuron should be reset to. Defaults to zero.
Example:
>>> layer = sinabs.layers.LIF(... |
b6a6525b811b5526beb5725cbd0b9563632082c4de227ea8e0efd06e8c58ad65 | Python | 1,396 | 51 | from scipy.signal import argrelextrema
import numpy as np
import logging
log = logging.getLogger(__name__)
# measure change in dimensionality, %sv, loading sim, across jackknifes
def get_dim(LL):
if 0:
return argrelextrema(LL, np.greater)[0][0]+1
else:
# log.info("No relative LL max, choosing... |
9127139275ca98217c3f480b01a43f1625cbc8699a0619f619724e27e14c60f8 | Python | 1,398 | 42 | import torch
from torch import fft
def fft_3d(tomo, norm="ortho"):
"""
3D Fourier transform with fftshift.
"""
fft_dim = (-1, -2, -3)
return fft.fftshift(fft.fftn(tomo, dim=fft_dim, norm=norm), dim=fft_dim)
def ifft_3d(tomo, norm="ortho"):
"""
Inverse 3D Fourier transform with fftshift.
... |
ff4a45e0f1ffa1a8bf1c80afda176cb75fc31ca4ed55b243bda51babdc087e50 | Python | 1,399 | 65 | import numpy as np
import matplotlib.pyplot as plt
def getDists(Xs,Ys):
dists = [0]
previousPoint = None
initialized = 0
for (x,y) in zip(Xs,Ys):
#print (x,y)
if initialized == 0:
previousPoint = (x,y)
initialized = 1
else:
dist = ((x-previou... |
71f999b1382cd8e5e59e4cd204245913ddc42ad5eaa3d6ce79c68e329beaf99b | Python | 1,401 | 48 | #!/usr/bin/env python3
# coding=utf-8
# Copyright 2023 The HuggingFace Inc. team.
#
# 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
#
# Unles... |
a101fcf80304d35d6bc462a00f31e75c0a70c3b319a629e9fa5515b9f8f949d4 | Python | 1,401 | 43 | """Combine for flow artifact mitigated average (composite) image."""
import os
import numpy as np
import nibabel as nb
# FOLDER = '/home/faruk/data2/temp-seb_data/megre'
FOLDER = '/Users/sebastiandresbach/data/neurovascularCouplingVASO/Nifti/derivatives/sub-08/ses-04/anat/megre'
NII_NAMES = [
f'{FOLDER}/08_avera... |
e5bd9382f51dc273f626773fe4d209b6bf4cfe443adfe65e20ae312dab74382b | Python | 1,402 | 55 | """
OmicVerse Skills Verifier
A verification system that tests skill selection and ordering using LLM reasoning,
mimicking how Claude Code autonomously selects skills based on task descriptions.
"""
from .data_structures import (
SkillDescription,
NotebookTask,
LLMSelectionResult,
VerificationResult,
... |
f691a97fccabb91192f874798d98e9fd665884b6fff55071ad7548abb6ee9286 | Python | 1,402 | 51 | import click
from ci.ray_ci.automation.docker_tags_lib import generate_index, list_image_tags
from ci.ray_ci.docker_container import (
ARCHITECTURES_RAY,
ARCHITECTURES_RAY_LLM,
PLATFORMS_RAY,
PLATFORMS_RAY_LLM,
PYTHON_VERSIONS_RAY,
PYTHON_VERSIONS_RAY_LLM,
RayType,
)
INDEX_IMAGE_CONFIGS = ... |
dfa8f61674a41759e4c0a75513c3b7c263a3762d070693a9f516622b3f38157a | Python | 1,403 | 44 | import unittest
import numpy as np
import torch
import pfrl
def count_actions_selected_by_boltzmann(T, q_values):
def greedy_action_func():
raise RuntimeError("Must not be called")
explorer = pfrl.explorers.Boltzmann(T=T)
action_value = pfrl.action_value.DiscreteActionValue(q_values)
actio... |
345f4c9ceae917d5b99d49c6d521d1bf88adf650e9891b6f1afd594472208616 | Python | 1,404 | 40 | import numpy as np
import torch
from .dnd_sf import DND_SF
class SFNEC(torch.nn.Module):
"""
Implementation of succesor neural episodic control architecture as introduced in
Successor Feature Neural Episodic Control
"""
def __init__(self, embedding_net, n_actions, config=None):
super().__... |
2664e33f86cb55c2051d71ff8e19834efc98928ef3af9babcbf0cadb165960b8 | Python | 1,405 | 40 | from dataclasses import asdict, dataclass
from typing import Any, Dict
@dataclass(eq=False)
class NIRNode:
"""Base superclass of Neural Intermediate Representation Unit (NIR).
All NIR primitives inherit from this class, but NIRNodes should never be
instantiated.
"""
# Note: Adding input/output t... |
6acb0a582cbc38df0eba59570087539549278dbff184fe617fc2bdebf1f1739d | Python | 1,406 | 47 | # Copyright 2024 Google LLC
# 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
# https://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, sof... |
7affefec0be07aa276d68d78055cf476a99de3ac57383765d6155aa9f67eaba3 | Python | 1,406 | 42 | from typing import Callable
import numpy as np
import jax.numpy as jnp
from .modules import Linear, Conv, Sequential
from .activation import ScaleFn, Prod
from .nqs_layers import ReshapeConv
from ..global_defs import get_sites, get_lattice, is_params_cpl, get_subkeys
def SingleDense(
features: int, actfn: Callabl... |
980feaa6aa57030b4cf7fdc6dc2016977d11223b31780088cd17e80761cdc971 | Python | 1,406 | 55 | import os
from itertools import repeat
import torch
from torch_geometric.data import Data, InMemoryDataset
class Molecule3DDataset(InMemoryDataset):
def __init__(
self,
root,
dataset="zinc250k",
transform=None,
pre_transform=None,
pre_filter=None,
empty=Fal... |
11d427aacc1d50b6cf449dc6e1c6e9c1af0058fcf41ecd08f042f91ef1d5db42 | Python | 1,407 | 57 | '''
Animation for the OpenAI Gym problem.
'''
import os
import pickle
import gymnasium as gym
import numpy as np
def isDiscreteActions(env):
return 'Discrete' in str(type(env.action_space))
# --- OpenAI Gym settings. --- #
# Only supports environments with the following state and action spaces:
# env.observat... |
d25dba435408f763e3743658a750388010a2c7c8a35c0c478830e4402b949bc9 | Python | 1,408 | 50 | import sys
import time
from unittest import mock
import pytest
from ci.ray_ci.bisect.generic_validator import WAIT, GenericValidator
from ray_release.bazel import bazel_runfile
from ray_release.configs.global_config import init_global_config
from ray_release.test import Test
init_global_config(bazel_runfile("releas... |
0a2a8870ac4b1dda0418ae53bad0fa32153a2d4f1cdddfd2027b20065e535235 | Python | 1,409 | 38 | import inspect
from typer_config.loaders import yaml_loader
def load_function_args_from_yaml_config(
function, yaml_config_file, shared_field_name="shared"
):
"""
This function is used to make the command line interface compatible with the .yaml config files.
"""
if yaml_config_file is None:
... |
d763f70bc1e6b77929fdd5b83faf3dbcf928cfc0bbce3abafa705a303841952e | Python | 1,409 | 39 | from typing import List
import matplotlib
def pal(palette_name:str, n:int) -> List[str]:
"""
API to retrieve palettes hex code from Scientific Colour Map (SCM) by Crameri et al.'s work, or dittoSeq colors.
Reference:
Crameri, F. (2018). Scientific colour maps. Zenodo. http://doi.org/10.5281/zenodo.1... |
7ac588495e938cbeb54656a66ecfa9d0acc3df06e101dc6f6e98264c243a4bde | Python | 1,410 | 38 | # -------------------------------------------------------------------------------------------------------------------------------------
# Following code curated for Bio-Diffusion (https://github.com/BioinfoMachineLearning/bio-diffusion):
# --------------------------------------------------------------------------------... |
e0771a3df308d737badbb147d66572ff75ec207c8ed81999d83e7f7e7b956585 | Python | 1,410 | 45 | import pdb
import torch
import torch.nn as nn
from STPN.Scripts.STPLayers import (
STPNr, STPNBase,
)
from torch import Tensor, no_grad
from STPN.Scripts import utils
"""
Networks for Maze are descirbed in Maze/Scripts/maze_nets.py , instead of here
"""
class SimpleNetSTPN(nn.Module):
""" Used in Pong RLLi... |
2eae09d0ec62fa8f5040930d9aeb4d169bac51a94ee4f17fb4d2537e69cf5aad | Python | 1,411 | 43 | import numpy as np
from sklearn.cluster import KMeans
from sklearn.mixture import GaussianMixture
# %%
def binarize_sparse_matrix(
A,
method = None,
cutoff = 0,
random_state = 1,
append_zeros = 'full'
):
# A is a scipy sparse csr_matrix
# Anything smaller than or equal to the cutoff is set... |
3a713a565f2554262dd17f88e2d3f75c35132a03e5d8eeb5cc6afd921a760fb2 | Python | 1,411 | 39 | import ray
from ray.util.dask import enable_dask_on_ray
import dask
import dask.array as da
# Start Ray.
# Tip: If connecting to an existing cluster, use ray.init(address="auto").
ray.init()
# Use our Dask config helper to set the scheduler to ray_dask_get globally,
# without having to specify it on each compute call... |
6a9c14921b90dada5a01fe42f98012b67d7b4eda2e74720ff112058f3bd94c14 | Python | 1,411 | 54 | """
This file should only be imported from Python 3.
It will raise SyntaxError when importing from Python 2.
"""
import asyncio
import inspect
from functools import lru_cache
from ray._private.ray_constants import env_bool
try:
import uvloop
except ImportError:
uvloop = None
def get_new_event_loop():
""... |
6ade3454a141387948aa5cfd81b5caef3d73d1f42ac1a0a6ee761365bf5a2b8d | Python | 1,411 | 54 | import logging
from dataclasses import dataclass, field
from typing import Any, Optional
from pokeformer.config_wrapper import ConfigWrapper, load_class
from pokeformer.datasets.dataset_builder_factory import DatasetBuilderFactory
from pokeformer.models.predictor_factory import PredictorFactory
from pokeformer.utils i... |
c564a2374deec701d4bc6a0696af8548e6d341364030068142dda3abae27351b | Python | 1,411 | 58 | #!/bin/python
#------------------- Description & Notes --------------------#
#------------------- Dependencies ---------------------------#
# Standard imports
import gzip
import itertools
from pathlib import Path
# Third-party imports
from Bio import SeqIO
# Internal imports
from .common import isZFile
from .commo... |
3ccc2e06a2c2176c898381f886a40c007e299a0a67b1869052459e91bc8a33a5 | Python | 1,412 | 42 | # __sglang_multinode_start__
from ray.llm._internal.serve.engines.sglang import SGLangServer
from ray import serve
from ray.serve.llm import LLMConfig, build_openai_app
llm_config = LLMConfig(
model_loading_config={
"model_id": "Llama-3.1-70B-Instruct",
"model_source": "meta-llama/Llama-3.1-70B-In... |
c00e8ab7bbaa4dacece5b3b7367717d5bda3da86b26fce246817bbfa090c1c0f | Python | 1,412 | 47 | """Backend implementations for ``ov.single.MetaCell``.
Each backend wraps one upstream metacell algorithm (or a baseline) behind
the :class:`~omicverse.single._metacell_backends.base.MetaCellBackend`
Protocol so that :class:`ov.single.MetaCell` can dispatch on
``method=...`` without leaking backend-specific kwargs int... |
f7914914672e7ec3768e4373b35e0323aadf2c551d20ce756b2aae12ece4df2b | Python | 1,412 | 53 | from collections.abc import Generator, Iterable
from itertools import islice
from typing import TypeVar
from django.db import migrations
_T = TypeVar("_T")
def take_by(iterable: Iterable[_T], chunk_size: int) -> Generator[list[_T], None, None]:
"""
Returns elements from the input iterable by batches of N it... |
ffc7442c078e45de67132bc9de73454e00166c87930e2928b99c56a5a65f6b3d | Python | 1,412 | 53 | # usage ./gen-preset
import itertools
import sys
minlen = int(sys.argv[1])#7
maxlen = int(sys.argv[1])#7
maxnnode = 99
maxsibl = 99
def enum_recu(dfs):
if maxnnode<len(dfs)-1 or maxlen<2*len(dfs): return
print_dfs(dfs)
parent = len(dfs)-1
while -1 != parent:
enum_recu(dfs + [parent])
p... |
43fcabe26592c3b944bd18e2125281fb9387c88e46823cbe9c6747cfe37014ab | Python | 1,414 | 40 | from model import (Net, Trainer, Tester)
from utils import (
load_configuration,
initialize_logging,
set_random_seed,
get_computation_device,
initialize_scheduler,
train_and_validate_model
)
def main():
# --- Pre-Training Setup ---
# Load configs. Use config file to change hyperparamete... |
655e71afa7c3a396dcbf43fb2c7183cdec289f0669fd5bfb232140ed64fc3f2f | Python | 1,414 | 44 | import h5py
import os
import numpy as np
import argparse
# to run, type in the command line:
# python /home/groups/ravnica/src/sciMET/sciMET_cellCalls2h5.py [input folder path] [output prefix]
# Define and parse command line arguments
parser = argparse.ArgumentParser()
parser.add_argument("input_folder")
parser.add_a... |
b430fefdb2ed550bfe57a8055ebcb17440ad789cd82765c5f2401039c354b764 | Python | 1,414 | 48 | # Copyright 2023 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
e7fb52a86866fb9b41545efd9d0ad2531a5e38e57f11c7c1fecff1523cd7aa8e | Python | 1,414 | 37 | # -*- coding: utf-8 -*-
# (C) Copyright 2026 IBM. All Rights Reserved.
#
# Licensed under the MIT license. See LICENSE file in the project root for details.
"""Compound configurations presets for resistive processing units."""
# pylint: disable=too-many-instance-attributes
from typing import List
from dataclasses im... |
25a023064005d6cc7582bd155b5dca9317a6d5d08b3f523c44f8519e56acfef9 | Python | 1,415 | 53 | import basetest_dqn_like
from basetest_training import _TestBatchTrainingMixin
from pfrl.agents.double_dqn import DoubleDQN
class TestDoubleDQNOnDiscreteABC(
_TestBatchTrainingMixin, basetest_dqn_like._TestDQNOnDiscreteABC
):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return Dou... |
e6a9505f7db2f042309823aadd6df6d9c3635bf887fdb30b6657a69e6f64220e | Python | 1,415 | 53 | import basetest_dqn_like
from basetest_training import _TestBatchTrainingMixin
from pfrl.agents.double_pal import DoublePAL
class TestDoublePALOnDiscreteABC(
_TestBatchTrainingMixin, basetest_dqn_like._TestDQNOnDiscreteABC
):
def make_dqn_agent(self, env, q_func, opt, explorer, rbuf, gpu):
return Dou... |
f6d850b8fcb40576c5ac6d55b6153f8d792b327dad42f793814bc6a57bc40dc9 | Python | 1,415 | 54 | import click
from ci.ray_ci.pipeline.gap_filling_scheduler import GapFillingScheduler
from ci.ray_ci.utils import ci_init, logger
from ray_release.aws import get_secret_token
from ray_release.configs.global_config import get_global_config
@click.command()
@click.argument("buildkite_organization", type=str)
@click.a... |
16c189cd13d627f91b2e60ca48bfc14f428a0e8246ceb99ff4da554634c3cbe4 | Python | 1,417 | 41 | """ example script for parallelized simulation """
# select the pattern
from examples.HorizontalCell import pattern as HC
from examples.HorizontalCell import scope, h_func
features = ["NN", "VD"]
# set output files
save_prefix = "examples/simulated/HC/W1"
# chose a random seed
seed = 89375
# print the optimize process... |
6317b8b28ae457f27fb8409982118674c96e4516c035c2e84ae5b4078bf269a4 | Python | 1,417 | 56 | import tensorflow as tf
class StepCounter(tf.keras.callbacks.Callback):
def __init__(self, total_steps):
super(StepCounter, self).__init__()
self.total_steps = total_steps
self.steps_counter = 0
self.epochs_counter = 0
def on_train_begin(self, logs=None):
pass
de... |
a1c6e7f8d2677349442d5e1d17dff437b039a474a6320f17847f803e4d61b638 | Python | 1,417 | 37 | import mmcv
import mmengine
import mmeval
from mmengine.utils import digit_version
from .version import __version__, version_info
mmcv_minimum_version = '2.0.0'
mmcv_maximum_version = '2.1.0'
mmcv_version = digit_version(mmcv.__version__)
assert (mmcv_version >= digit_version(mmcv_minimum_version)
and mmcv_v... |
1848b1b4569b11459499398e3b4a490fbb0c530d9c021028f1a89ff5d4084c93 | Python | 1,418 | 61 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def test_activity_timecourse_with_inlay():
import pandas as pd
import matplotlib.pyplot as plt
import samri.plotting.maps as maps
import seaborn as sns
from os import path
# Style elements
palette=["#56B4E9", "#E69F00"]
data_dir = path.join(path.dirname(path.real... |
64c8dafc4163b2a5725953f2f55105da448861c37299aba522314465e89e4e32 | Python | 1,418 | 53 | import pathlib
path = pathlib.Path.cwd()
if path.stem == 'tmb_survival':
cwd = path
else:
cwd = list(path.parents)[::-1][path.parts.index('tmb_survival')]
import sys
sys.path.append(str(cwd))
from model import utils
from matplotlib import pyplot as plt
from lifelines import KaplanMeierFitter
from sklearn.model_... |
fbcaa95c36f591a5463843e524424cd2bcde226c084c44c57d46f4d5f0530225 | Python | 1,418 | 38 | import os
import nibabel as nib
import numpy as np
import IVIMNET.deep as deep
from hyperparams import hyperparams as hp
root = '/tmp'
sub = 'phantom'
for i in range(2):
bval_file = os.path.join(root,sub,'{}_validation-{}.bval'.format(sub,i+1))
cval_file = bval_file.replace('bval','cval')
outbase_dl = os.... |
23d8f211f746d235df2bf760b63a023eaf8e0d0ba0691c898fd9d9382d8eb00a | Python | 1,419 | 37 | # --8<-- [start:init]
import numpy as np
from rich import print
from siapy.entities import Shape, SpectralImage
from siapy.entities.shapes import GeometricShapes
# Create a mock spectral image
rng = np.random.default_rng(seed=42)
array = rng.random((100, 100, 10)) # height, width, bands
image = SpectralImage.from_nu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.