sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
e77cfe9f00a78dc4535389e4fa2c99e09a67eb7473b2d7560211e90f5cc90358 | Python | 5,396 | 163 | """Created on Mon Jan 27 11:00:26 2020.
@author: martafradera
"""
import warnings
import numpy as np
from neurogym.core import TrialEnv
from neurogym.utils import spaces
from neurogym.utils.ngym_random import TruncExp
class Detection(TrialEnv):
"""The agent has to GO if a stimulus is presented.
Args:
... |
153f241ae7df13b98be5a1568ef2d51a6aaf35f0b5393f80226c8a053ffceeef | Python | 5,397 | 148 | import rclpy
from rclpy.node import Node
from rclpy.parameter import Parameter
from std_msgs.msg import Bool, Int32, Float32MultiArray
import numpy as np
from saccade_code import SaccadeGenerator
class SaccadeROS2Node(Node):
def __init__(self):
'''
Initialize the SaccadeROS2Node.
Creates ... |
3eae674f469b3c6d0c6c99833a93ffdf0a4ed866a1b9aa8d25d2ca16147aa33b | Python | 5,398 | 164 | """Visual search task."""
import numpy as np
from psychopy import visual
from neurogym.utils import spaces
from .psychopy_env import PsychopyEnv
class VisualSearch(PsychopyEnv):
"""Visual search task.
Args:
target_centers: list of tuples, centers of target stimuli
length: float, length of ... |
d9f51f7b9edce3646b05e1480d0d6c483538d6b6aadf0d0a1415ab5bc3b9dcc0 | Python | 5,398 | 164 | from interpretability.generate_residues_of_interests_with_attn import (
score_on_residue_with_attn_map,
score_on_residue_with_attn_map_multiprocess,
)
from interpretability.generate_residues_of_interests_with_integreted_gradients import (
score_on_residue_with_integreted_gradients,
)
from interpretability... |
2ee8606519555b70ac3ce8b83aa7d5410b79b78a19336e89dca4841c01410b68 | Python | 5,399 | 148 | """
References:
- https://arxiv.org/pdf/1708.03888.pdf
- https://github.com/pytorch/pytorch/blob/1.6/torch/optim/sgd.py
"""
import torch
from torch.optim.optimizer import Optimizer, required
class LARS(Optimizer):
"""Extends SGD in PyTorch with LARS scaling from the paper
`Large batch training of Conv... |
f4e909f2810e595093f064bf88cc753f14f8155662c2fee3c692e27fffc56506 | Python | 5,399 | 128 | import argparse, time, logging, os, math
import numpy as np
import mxnet as mx
from mxnet import gluon, nd
from mxnet import autograd as ag
from mxnet.gluon import nn
from mxnet.gluon.data.vision import transforms
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from gluoncv.data import mscoco
from gluoncv.mode... |
0a2fd39d3ccbc83292dc91d157b9dd42cab68ae092539c2b25e59c085d1a3b41 | Python | 5,400 | 170 | # a/b will always return float
from .Picker_ import Picker, color_walker
from .plots import group_maps, group_plots, plot_coll
#--- old ui.py ---
import numpy as np
from .. import io
from ..core import ifnot
from .plots import guess_gridshape
from matplotlib import pyplot as plt
from matplotlib import animatio... |
56d77629836cbcd1f060fe0c83abd866a501605fa1e2d117b442fb9bfb3e5d90 | Python | 5,400 | 152 | import os
import numpy as np
import pandas as pd
import pymannkendall as mk
from os.path import join as pjoin
from magicbox.io.io import CiftiReader, save2cifti
from cxy_visual_dev.lib.predefine import Atlas, LR_count_32k,\
mmp_map_file, proj_dir, get_rois
anal_dir = pjoin(proj_dir, 'analysis')
work_dir = pjoin(an... |
0f2a965f6cbf9dbb9e8911919dd8c72c07b7b670ae3c5bc109b6d644cf0456ed | Python | 5,402 | 184 | from functools import lru_cache
import io
from types import SimpleNamespace
import numpy as np
import scipy.io as sio
from permacache import permacache
from modular_splicing.utils.download import read_gzip
def read_mrs(name):
"""
Read the MRS data from my public fork of the paper's data.
"""
prefix... |
1c2d140e678d5e8a1e712598c4560696543990d1b4b0ac022aa54671159ec4a6 | Python | 5,403 | 148 | import warnings
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
from mirp._images.generic_image import GenericImage
from mirp._images.mask_image import MaskImage
from mirp._masks.base_mask import BaseMask
class InteractivePlot: # pragma: no cover
def __... |
3181ba57a365da0d99661678ed6f11e9638c3cdb316e8a76cd6566c8b7cad579 | Python | 5,404 | 151 | # This is a wrapper for JAMM to use it in Galaxy
# It will be accompanied with a jamm.xml file, which specifies the interface that Galaxy is showing to the user
# as well as the JAMM software including JAMM.sh, the bash script that is actually called.
# This wrapper does the following things:
# map the files (from Gal... |
ab0c4d7163f6a997be5d73c8d35017ac2b8a81144e1c77f8124782bca4631d4c | Python | 5,404 | 124 | import numpy as np
import itertools as itools
from ridge_utils.interpdata import sincinterp2D, gabor_xfm2D, lanczosinterp2D
class DataSequence(object):
"""DataSequence class provides a nice interface for handling data that is both continuous
and discretely chunked. For example, semantic projections of speech s... |
de71f94719517f5cf4bf7336c5f3ca06a7cc29bfe2aa9d39a92e2f542b6ebe91 | Python | 5,404 | 155 | from scipy.spatial import distance
from scipy.stats import zscore
from sklearn.model_selection import LeavePOut
from sklearn.linear_model import RidgeCV as RidgeGCV
import numpy as np
from scipy.spatial.distance import cdist
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition ... |
8953b5eb78a25b6226be89eb5d6b8af13b6530bf8d84283d2afd3c7d244889ae | Python | 5,405 | 161 | import copy
import numpy as np
import pandas as pd
from mirp._features.texture_matrix import DirectionalMatrix
class MatrixRLM(DirectionalMatrix):
def __init__(self, **kwargs):
super().__init__(**kwargs)
# Placeholders for derivative values computed using set_values_from_matrix
# Run-l... |
fa07c0458ab4c9e91021f50e2aa3c21eb66a98522e5a8fc991a8af648f297cfa | Python | 5,405 | 142 | """Behavioral tests for the SAE splice-experiment bridge helper.
The splice experiment composes fork + push + ``tl.splice_module``: these
tests pin the causal contract (site actually replaced, downstream actually
recomputed), the fidelity metrics, the latent-edit knob, and the typed
refusals -- all against an in-test ... |
9334c5edca865a006b24f7ae08532f344d4dc059b624a1870acb77515f29e623 | Python | 5,407 | 144 | import numpy as np
import scipy.signal
from keras.src import backend
from keras.src import initializers
from keras.src import testing
class ConstantInitializersTest(testing.TestCase):
def test_zeros_initializer(self):
shape = (3, 3)
initializer = initializers.Zeros()
values = initializer... |
a89eb42f479be76d53ae096b828768ed77bc20429460ebc0f38d6d79e6bc6651 | Python | 5,407 | 167 | '''
Copyright 2023 Douglas Feitosa Tomé
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hop... |
ddf4ba1e02af7f6a12c1e3f48c26835c56bbf96efa2f218de1c88463500f2184 | Python | 5,407 | 144 | """F12 pins: RenderIR answer keys and the naive-battery harness.
Keys are GENERATED (hand keys prohibited); packets are seed-deterministic
with the memo's fixed question-phase order; honesty classes are
zero-tolerance in scoring; threshold freezing follows the anchor-midpoint
procedure and refuses on overlapping bound... |
e1c375175d98505fc686a3217f4bb0f3efe317100d36bcefb1240193b070f295 | Python | 5,407 | 153 | import contextlib
import os
import typing
import rpy2.rinterface as rinterface
import rpy2.rinterface_lib.sexp as sexp
from rpy2.robjects.robject import RObjectMixin
from rpy2.robjects import conversion
_new_env = rinterface.baseenv["new.env"]
class Environment(RObjectMixin, sexp.SexpEnvironment):
""" An R envir... |
1d464b38ec3de6b83b93a565c0aab894b714a1a16e7f024bffb93b30afde634f | Python | 5,408 | 103 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
0d8e4be33d4ac0237668a001d72b55749db084c1a00cf09883bfa326cd57c630 | Python | 5,409 | 167 | # SOURCE: vendored from samsledje/ConPLex @ ccd8c804a76dff41649e58f692293b55c8907129 (conplex_dti/model/architectures.py)
# https://github.com/samsledje/ConPLex/blob/ccd8c804a76dff41649e58f692293b55c8907129/conplex_dti/model/architectures.py
#
# ConPLex: contrastive coembedding model for drug-target interaction (DTI)
#... |
2fe614cfe60bf08042700ffa773e7c24860fde29adecc2aa4d91cc388961a69a | Python | 5,410 | 152 | """A save predicate matching ZERO sites must warn, never pass silently.
TF is fail-closed on selector reachability, but the shared non-torch
selective-save resolver accepted a predicate matching nothing with status
COMPLETE and no diagnostic: a typo'd label or function name silently produced
a trace with zero saved ac... |
540f5cc1e3b64437cfea025cb1e8be40af75c04537b4f50d27af7126ee357ada | Python | 5,411 | 156 | import re
from dataclasses import dataclass
from typing import (
Generic,
Protocol,
TypeVar,
)
from .auto_identifiers import filename_to_element_identifier
class HasName(Protocol):
name: str
T = TypeVar("T", bound=HasName)
# matches pairing.ts in the client
COMMON_FILTERS: dict[str, tuple[str, str... |
c661b1bd795291e2f792c36e5fda665bc5053222f34e5b081df02367ed57740e | Python | 5,411 | 157 | """Shared pytest configuration for the pyrosm test suite."""
import http.client
import os
from urllib.error import URLError
import pytest
pytest_plugins = ["pytester"]
def pytest_configure(config):
config.addinivalue_line(
"markers",
"live_download: downloads from an outside service (Geofabrik,... |
1d55db648ee9c72fdf8d41c174054e2aa8054a4cd2ba58207ff120d32697a5e7 | Python | 5,414 | 150 | # type: ignore[override]
import os
from typing import Any, Callable, Optional
from pytorch_lightning import LightningDataModule
from torch.utils.data import DataLoader
from pl_bolts.datasets import UnlabeledImagenet
from pl_bolts.transforms.dataset_normalizations import imagenet_normalization
from pl_bolts.utils impo... |
06f7a66377270424faa4562f22a41e6f4e3422d1bba3bef17e3b5ffffee7397b | Python | 5,415 | 159 | # Copyright 2019 Image Analysis Lab, German Center for Neurodegenerative Diseases (DZNE), Bonn
#
# 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... |
4c89331e9a8a78665c03ffb7c7705cc687f90f86af1ff850090ad2ab4a508812 | Python | 5,417 | 172 | import os
import numpy as np
import nibabel as nib
from nilearn import image, datasets, maskers
from nilearn.image import math_img, resample_to_img
from irnlm.utils import read_yaml, save_yaml, check_folder
def masks_overlap(mask1, mask2):
"""Return the percentage of overlap between two mask.
Args:
-... |
5ed8aec0da6773c5d0d9a8c03fd521c7261e179ade53ab4379589cb4cd4ec443 | Python | 5,417 | 154 | """
Signal processing
=================
This is a local fork of the required components of the :mod:`scipy.signal` module.
Scipy is a heavy install, requiring Fortran to compile. As we only fit two kinds of waveform in Bream, it would be
unreasonable to depend on the entire library.
These methods are reproduced in a... |
773507812e9c2b43bf46df6f6e546c2a56034b20c37a6cf3c0f2b79927bb0eee | Python | 5,418 | 156 | """Vizmech wave-3 item 20: usability-envelope metrics, calibrated both ways.
The collision oracle is structurally blind to a legend that triples page
width, 877 fused arrowheads, and a caption 15 inches from its members (each
demonstrated on a real render this sprint) -- the envelope is the second
oracle (memo D2). Ev... |
0c3e41886dc9bf8a4822cd931ded7e656155c578bfd7acc93d225831501ed48c | Python | 5,419 | 177 | import os
import numpy as np
from itertools import combinations
import pre_process
import pandas as pd
from seqtools import SequenceTools
DATA_DIR = "../data/counts/"
def calculate_enrichment_scores(n_pre, n_post, N_pre, N_post):
"""
Calculates the mean and approximate variance
of enrichment scores. The... |
84110673cc479915122dedfbca53ec4b34cbec8fd64561dc6560ea522056792b | Python | 5,419 | 163 | #!/usr/bin/env python3
"""
Creates HIC pileup plots using hic data, and a list of feature files.
"""
import bioframe
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import pandas as pd
import cooler
import cooltools
import cooltools.expected
import cooltools.snipping
import os
import multipro... |
34a40ead0e58a69f974b5f1615104c93c78e3c15973367991c70aaae2cc50a94 | Python | 5,422 | 157 | """F12 pins: the item-11 encoding honesty fixes and the rank transform (N5
slice).
Composition-test row 16: a degenerate (min == max) domain renders UNENCODED
with the note, never mid-ramp; a per-pass field on a rolled multi-pass node
unencodes with its own note, never resolves to pass 1. Plus the rank
transform's ord... |
e8b167f124c932fbe7ad8672108aebff5a89b4f29f987a8f6b3832a95bfb113b | Python | 5,422 | 212 | # --- THIS FILE IS AUTO-GENERATED ---
# Modifications will be overwitten the next time code generation run.
from plotly.basedatatypes import BaseLayoutHierarchyType as _BaseLayoutHierarchyType
import copy as _copy
class Margin(_BaseLayoutHierarchyType):
_parent_path_str = "layout"
_path_str... |
ec0cd3684cf73d03bb874812eb383b2809849c91dcb95ab410ac6f85150e5633 | Python | 5,422 | 138 | from sklearn.metrics import confusion_matrix
import numpy as np
import tensorflow as tf
import os, argparse
from data import (
process_image_file,
process_image_file_medusa,
)
# To remove TF Warnings
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
def... |
04dec9b5eb73106d06cbfab452b6a9194d9eaaa7d1195ec4ef20111e33320ab2 | Python | 5,423 | 137 | """Intervention honesty: ``mean_ablate(over=)`` fails closed and
``batch_independent`` is DERIVED (edits memo rows 0a/0b, decisions D16/D18/D19).
Pins, in both failure directions of the one line that shipped wrong:
- A1b: an unknown ``over=`` token refuses typed at construction, so no typo can
flip ``batch_independ... |
7a41d9eba4a56576557156f20d182cf984e0862eac122f66a64432bf12b79f3c | Python | 5,423 | 139 | #!/usr/bin/env python3
"""
Dx AK resume — finish the 2026-04-25 17:04 run.
The first run completed 5 of 6 cohorts (brainlat, ds006036, ds003775,
lemon, figshare) but ds004504 had a tuple-unpack bug. K-files for the
other five live in epoch_sweep_all_cohort/. Re-run only ds004504, then
run the Dx AA pipeline at each K ... |
84f0f80606688f247fd895a3c58533d92707610355275eb4e5c3e1a9300178cc | Python | 5,424 | 137 | import inspect
from argparse import ArgumentParser, Namespace
from dataclasses import dataclass
from typing import Any, Dict, List, Optional
from pytorch_lightning import LightningDataModule, LightningModule
@dataclass(frozen=True)
class LitArg:
"""Dataclass to represent init args of an object."""
name: str... |
d89cc0e6fc01067967ba83b2c24559fd5ecff938c71784f403a8f5b52b81507c | Python | 5,425 | 107 | #==============================================================================#
# Author: Dominik Müller #
# Copyright: 2024 IT-Infrastructure for Translational Medical Research, #
# University of Augsburg ... |
5dc9d57a4ef930aefbaf8ab7b7a283a8dbe5470982e2475e749175c16ba1a7e6 | Python | 5,426 | 291 | #!/usr/bin/env python
'''Generate models for affinity predictions'''
# variables:
# RESOLUTION(0.5)
# CONVKERNEL(3)
# BALANCED(true)
# POSEPREDICT
# RECEPTOR(false)
# AFFMIN(0)
# AFFMAX(0)
# AFFSTEP(0)
# GAP(0)
basemodel = '''layer {
name: "data"
type: "MolGridData"
top: "data"
top: "label"
top: "affinity... |
27adea552fc104e61e8f56c4430d8e048fc86b471b40d4052b2e7183a2fa709d | Python | 5,428 | 143 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Get summaries of head movement in scanner per group.
@author: mikkel
For information about NatMEG-PD please refer to the data descriptor:
Vinding, M. C., Eriksson, A., Comarovschii, I., Waldthaler, J., Manting, C. L.,
Oostenveld, R., Ingvar, M., Svenningsson, P.,... |
c4016146fb40a86de4726f9abab14a63170deff35cd01c7c9a2cf12aad6142a1 | Python | 5,429 | 159 | #!/usr/bin/env python
'''Connects to sql database.
Checks atomically to see if there are an configurations that should be run
because they are requested (R). If so, runs one
'''
#https://hyperopt-186617.appspot.com
import sys, re, MySQLdb, argparse, socket, tempfile
import pandas as pd
import numpy as np
i... |
37a53299fe569888e7dc54b5b2e253c705a063828a4bdd61df70b0017bdb701e | Python | 5,431 | 190 | from pip.utils import logging
__author__ = 'quentin'
import cv2
import time
import logging
import os
from ethoscope.utils.debug import EthoscopeException
from ethoscope.tracking.cameras import BaseCamera
import multiprocessing
try:
from picamera.array import PiRGBArray
from picamera import PiCamera
except:
... |
113589a80a7f3dfc6e6e8bc7374cfbcb5801c34a6f4db09f487262117e7b1f78 | Python | 5,433 | 122 | from __future__ import division
from __future__ import print_function
import argparse
import logging
logging.basicConfig(level=logging.INFO)
import time
import numpy as np
import mxnet as mx
from tqdm import tqdm
from mxnet import nd
from mxnet import gluon
import gluoncv as gcv
gcv.utils.check_version('0.6.0')
from g... |
574cb0fb8973801d6039d9c14e2a5b15e2a341a26cdcb09d8543e38369a836c7 | Python | 5,433 | 182 | import argparse
import numpy as np
import numba as nb
from numba import int32, float32, float64, boolean
import math
from pyteomics import mgf, mass
import tensorflow as tf
import tensorflow.keras as keras
import tensorflow.keras as k
class config(dict):
def __init__(self, *args, **kwargs):
s... |
c4cff19eebe83ae785d3cdc4dc34b0dca52955d33284060ed9c6842d2ebe6e94 | Python | 5,433 | 146 | import math
from typing import List, Tuple
import torch
from pytorch_lightning import LightningModule
from torch import Tensor
from torch.nn import Identity
from torchvision.models import resnet50
from lightly.loss.ntx_ent_loss import NTXentLoss
from lightly.models.modules import SimCLRProjectionHead
from lightly.mod... |
fb37c25c8776ec9bf9a39741b73f22644cf81816fb3162802b914cd771f63e35 | Python | 5,433 | 159 | """
This script updates the CPU power data by reading from Intel and AMD CPU data file,
cleaning the CPU names, and merging the data into an existing CPU power CSV file.
It ensures that the TDP values are numeric and updates existing entries or adds new ones.
cd codecarbon/data/hardware/cpu_dataset_builder
uv run pyth... |
b72edb34225a7cbd9c2f03d21861da47ee1a5d866c38d62bda5f98d9c075d2ee | Python | 5,434 | 148 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import torch
def pad_1d_unsqueeze(x, padlen):
x = x + 1 # pad id = 0
xlen = x.size(0)
if xlen < padlen:
new_x = x.new_zeros([padlen], dtype=x.dtype)
new_x[:xlen] = x
x = new_x
return x.unsqueeze(0)
def... |
da17f1e27243951bb9ae6757839d328804c6287a9efe63846a93d2b3c4ce9eb5 | Python | 5,434 | 206 | # -*- coding: utf-8 -*-
"""
> :warning: **DEPRECATED**: This will be removed in version 1.0.0. Check [nwbmatic](https://github.com/pynapple-org/nwbmatic) or [neuroconv](https://github.com/catalystneuro/neuroconv) instead.
Loaders for calcium imaging data with miniscope.
Support CNMF-E in matlab, inscopix-cnmfe and min... |
872351ae1c9427e9141ddf477a12d54ced349c10506c2fd9580ca158f5b369c0 | Python | 5,436 | 135 | import os
import sys
import unittest
from unittest.mock import MagicMock, patch
import pandas as pd
from codecarbon import EmissionsTracker
class TestUnsupportedGPU(unittest.TestCase):
def setUp(self):
self.output_csv = "emissions_unsupported_gpu.csv"
self.NVMLError_NotSupported = type("NVMLErr... |
16a0d07f596bb6908cd03ad29bf0e8d74978cdf56786e5d84b7ff9559b7f5ee9 | Python | 5,438 | 149 | import tensorflow as tf
import tensorflow.keras as keras
import numpy as np
from copy import deepcopy
from sklearn.model_selection import StratifiedKFold
import numpy as np
brightness_offset_neg = 40
# THIS OFFSET IS SUBTRACTED
brightness_offset_pos = 10.4 #10
# THIS OFFSET IS ADDED
def load_local_emnist(path, dat... |
c05899e7872f7a9f674b5d931ac009b5e82db3d062ccfa6cfd98eec1f964b2c8 | Python | 5,439 | 196 | #!/usr/bin/env python
import re
import sys
import tempfile
# from rpy import *
import rpy2.robjects as robjects
from rpy2.robjects.vectors import DataFrame
r = robjects.r
assert sys.version_info[:2] >= (2, 4)
def stop_err(msg):
sys.stderr.write(msg)
sys.exit()
def S3_METHODS(all="key"):
Group_Math =... |
e7fbc8ae85c6a6e95134a6970fe8a5ad164df5c01393f5f3cbaf5f0183fe3f36 | Python | 5,439 | 142 | import paddle
from paddle import nn
from paddle.nn import functional as F
import pgl
import pgl.math as math
from layers import GVP, RR_VPConv, Linear
class PTHL(nn.Layer):
def __init__(self, args):
super().__init__()
self.n_h_dim = args.n_h_dim
self.v_n_feats = args.v_n_feats
s... |
dd964b8b5f807f1deb8b365c2096113f6ebbcb4970267bbdf10ef14a17875cb3 | Python | 5,441 | 145 | """Round-11 F5 regression: forward-modifying interventions must not lie.
A forward-modifying (value-override) intervention makes the captured forward diverge
from the recorded sparse DAG (which stores only the original op recipe). A runnable
replay could only recompute the un-intervened value, so since deephunt F1 the... |
609da694762f9e211a1a40623ec73a92f88f06e8b445e99ae7fdb12da50ab45a | Python | 5,442 | 155 | import numpy as np
from scipy.ndimage.interpolation import map_coordinates
from .imref import imref3d
try:
from numba import njit
except ImportError:
def njit(f):
return f
def imwarp(inputImage, tform, R_A=None, outputRef=None):
"""transform input image with provided tform matrix"""
# chec... |
a3e17cf4be2b1e6448ae5c78b588c965dddf689a1682f40153e2e2f28a66f356 | Python | 5,442 | 123 | import numpy as np
import torch as ch
import sys
from .helpers import erb_filters as erb
class CochlearFilter:
"""
Filterbanks designed to model the processing in the human cochlea.
"""
def __init__(self, signal_size, sr, apply_in_fourier=True,
use_rfft=True, pad_factor=None, filter... |
571854d28c80aa8f7b0bda639c890e7bb8f2f4301ff8d2effb12444777541463 | Python | 5,443 | 122 | """
Scripts for plotting the BrainScore results vs. the metamer
recognition for the analyzed layer.
Moved here to clean up the notebook.
See BrainscoreResultsVsMetamerRecognition.ipynb for usage
"""
import numpy as np
import pandas as pd
import os
import glob
import math
import json
import scipy
import scipy.stats
... |
225843ba1b4b618befe63896031080707b74c74bfefcf5086249260e3948febc | Python | 5,444 | 148 | """Tests for the xcp_d.workflows.anatomical.surface module."""
import os
import shutil
import pytest
from xcp_d import config
from xcp_d.tests.tests import mock_config
from xcp_d.tests.utils import get_nodes
from xcp_d.workflows import anatomical
from xcp_d.workflows.base import clean_datasinks
@pytest.fixture
def... |
e696ea37306d54aad3b2f147485cf76ec6344115c5a66262d1ff11eb3ded3d9c | Python | 5,444 | 174 | """JSON utilities for legacy saving formats (h5 and SavedModel)"""
import collections
import enum
import json
import numpy as np
from keras.src.legacy.saving import serialization
from keras.src.utils.module_utils import tensorflow as tf
_EXTENSION_TYPE_SPEC = "_EXTENSION_TYPE_SPEC"
class Encoder(json.JSONEncoder)... |
88ecf258f86fe4eeb5aa88f663c08858f7b01e1391b912d02bd24420941169d3 | Python | 5,445 | 186 | # %%
import os
import torch
import random
import shutil
# %%
def del_folder(path, *args):
'''
delete the folder which path/version
Args:
path (str): path
version (str): version
'''
if os.path.exists(os.path.join(path, *args)):
shutil.rmtree(os.path.join(path, *args))
def... |
bd3fbcb9858d4f9b486234db6474797c4771652067673c84edc5be4f7096cf3e | Python | 5,446 | 151 | import os
import pandas as pd
import pytest
from mirp.extract_image_parameters import extract_image_parameters
CURRENT_DIR = os.path.dirname(os.path.abspath(__file__))
@pytest.mark.ci
def test_extract_image_parameters_default():
# Read single image.
image_parameters = extract_image_parameters(
imag... |
c203af8dc866ec61e0b380394261b2a1505927d4de755986a5d3662f037955b9 | Python | 5,446 | 171 | import os
import logging.config
import pandas as pd
import torch
import yaml
from lib.utils.log import LOG_CONFIG
logging.config.dictConfig(LOG_CONFIG)
from argparse import ArgumentParser
import pytorch_lightning as pl
from torch.utils.data import DataLoader
from lib.datasets import InferenceDataset
from lib.model... |
8abf5e36bd7ec3fc36ab3e961d5851d780781ea4c83f2538f5b4dbf89bc0ab17 | Python | 5,447 | 149 | # This example requires the following dependencies to be installed:
# pip install lightly
# Note: The model and training settings do not follow the reference settings
# from the paper. The settings are chosen such that the example can easily be
# run on a small dataset with a single GPU.
import copy
import pytorch_l... |
d8178e4e1abebb972128678c21ffbf4f9c906ce5d0a4f9b8b36f5ea33a7d6dfb | Python | 5,447 | 180 | """Data for tests."""
import numpy as np
from specparam.bands import Bands
from specparam.modes.modes import Modes
from specparam.data.data import Data, Data2D, Data2DT, Data3D
from specparam.data.stores import FitResults
from specparam.models import (SpectralModel, SpectralGroupModel,
S... |
5498e97f7cdf8e522025441f95fa841be3ce9d3c607f1fabc6aa1dab8c5c0db5 | Python | 5,450 | 155 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 app... |
8bc8ad74ebd4ce63b6323fbc71ef2d198ebe3bc15b9214d3ba685d92536f23e5 | Python | 5,450 | 115 | import torch
from torch import nn
from torch.nn.init import xavier_uniform_, orthogonal_
from schnetpack import Properties
from schnetpack.nn.base import Dense
from schnetpack.nn.cutoff import HardCutoff, CosineCutoff
from moinn.nn.activations import softmax, swish
from moinn.nn.neighbors import AdjMatrix, PairwiseDis... |
68fb392da6dd165bd86f7016e5087d8f74fb90d906a9fcc8f3c90ac69693d266 | Python | 5,451 | 122 | import numpy as np
import imodelsx.augtree.data
import imodelsx.augtree.llm
import imodelsx.augtree.augtree
import random
import imodelsx.data
import imodelsx.augtree.ensemble
def seed_and_get_tiny_data(seed=1, classification_or_regression='classification'):
np.random.seed(seed)
random.seed(seed)
if class... |
6bff0292d09f4b7542f7a2930d76e077bf646da3342fd80fc3f768aa9a3d4b64 | Python | 5,451 | 175 | import torch
import torch.distributed as dist
import torch.nn.functional as F
from torch import Tensor
from lightly.utils.dist import gather
class VICRegLoss(torch.nn.Module):
"""Implementation of the VICReg loss [0].
This implementation is based on the code published by the authors [1].
- [0] VICReg, ... |
b5f44cd0b322ae06ffc05901051f2379ee17d34fd9227072f55b7ec6a0655ab5 | Python | 5,453 | 163 | import numpy as np
from modular_splicing.data_for_experiments.standardized_sample import (
eclip_motifs_on_standardized_sample,
standardized_sample,
)
from modular_splicing.utils.intron_exon_annotation import (
ANNOTATION_EXON,
ANNOTATION_INTRON,
)
from .eclip_peaks import eclips_from_onehot
def extr... |
3350af0c5ab3c847a795ce9fca48cf03e0a0b9cabc0bc9bae8f89f2719655749 | Python | 5,455 | 207 | import torch
import numpy as np
from sklearn.metrics import average_precision_score
import itertools
import re
IN_MAP = np.asarray(
[[0, 0, 0, 0], [1, 0, 0, 0], [0, 1, 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]
)
# One-hot encoding of the inputs: 0 is for padding, and 1, 2, 3, 4 correspond
# to A, C, G, T respectively.
... |
44d0d4674c805fe766c59019a0a18eab9d9462cdee8a6a3ad382ee69c1040419 | Python | 5,455 | 111 | # Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com)
# PLUS
import os
import sys
import argparse
import torch
import plus.config as config
from plus.data.alphabets import Protein
import plus.data.dataset as dataset
import plus.model.plus_rnn as plus_rnn
import plus.model.plus_tfm as plus_tfm
impor... |
6bed11dcdfe3b493e2ef5e2316cd34a29272d042dc8ff3b57810cb47669b87cc | Python | 5,455 | 132 | """Checkpoint live-ref guard, real-model legs (A-CKPT; foldB MEMO s4.2 tests 1-2).
Leg 2 (zero-network): torchvision resnet18 + the real IMAGENET1K_V1 checkpoint
plus one deterministic SGD step between two captures -- the exact measured
repro of the defect (weight_norm_diff false zero, diff_pair "identical",
aggregate... |
5a1158bbd897cb5c7e82d3e06a2fd751b5533b3e40d3e3345659302dfe66aeb0 | Python | 5,456 | 141 | """The absence-claim adjudicator (testing MEMO D2 ladder #2, D7 class 2).
Every ``structurally_absent`` claim in a facet-coverage report is a FACTUAL
ASSERTION about the user's model. The adjudicator checks each claim against
the module tree: a classified module of the required kind present in the
tree makes the claim... |
7043c83ef107b009de8054dfd590ccaffb9cbe369d55ed1c56dfc00f63c97646 | Python | 5,456 | 165 | import logging
from logging import LogRecord
import os
import sys
import pathlib
import datetime
import importlib_metadata as metadata
from carbontracker import constants
from typing import Union
def convert_to_timestring(seconds: int, add_milliseconds=False) -> str:
negative = False
if seconds < 0:
n... |
749ad70d9cd86c3af44e8993c3ce896ad26337bb65a07fb89039b0352ca04ee7 | Python | 5,456 | 122 | """b5 R50-2: the scrub runtime-only allowance must not shadow declared policy.
``_io/scrub.py`` decides what leaves a Trace on the way into a portable
artifact through TWO authorities, in this order (``scrub.py:612``)::
if owner_is_trace and _is_runtime_only_trace_field(field_name):
continue ... |
728b9242712da4b2f27cfd9fbd8d952a75b41d5868ce876fe4b8d9edc49fb4b5 | Python | 5,457 | 139 | from unittest import TestCase
import numpy as np
from drug_interactions.reader.dal import Drug, DrugBank
from drug_interactions.training.train import Trainer
from drug_interactions.datasets.dataset_builder import ColdStartDrugDataset
class ColdStartDrugDatasetTestCase(TestCase):
def setUp(self):
self.O... |
11928c32e0c05f8386f722ef530c16b0c4a929030155b5175586708fa5f57639 | Python | 5,460 | 155 | from .augument import random_noise, random_flip, random_brightness
import numpy as np
import tensorflow as tf
from copy import deepcopy
from random import sample
import glob, os
class BaseGenerator(tf.keras.utils.Sequence):
def __init__(self, patches_path, patch_shape, batch_size=8, num_classes=2, shuffle=True):
... |
2ff1d07a32d4d405420ef6b550f0e4c8c071096baba3dde105d05b83c09efb59 | Python | 5,460 | 169 | # Written by Seonwoo Min, Seoul National University (mswzeus@gmail.com)
# Some parts of the code were referenced from or inspired by below
# - Tristan Bepler's code (https://github.com/tbepler/protein-sequence-embedding-iclr2019)
# PLUS
""" Transmembrane 3line file loading functions """
import numpy as np
import tor... |
00048d956e059655a44c0ce25f9b049f711e0cb9fe540693e0c4dd2a74bfcf90 | Python | 5,463 | 168 | '''
This code creates the model described in 'Convolutional neural networks for reconstruction of undersampled optical projection tomography data applied to in vivo imaging of zebrafish' and derived from https://github.com/imperial-photonics/CNOPT
author: obanmarcos
'''
import torch
import torch.nn as nn
import nump... |
beab541198b3af37b737b22baa61fc6aff388e1c1d8804202d2e769f81a6f267 | Python | 5,464 | 127 | """
Computes theoretical quantiles or mean of the distribution of r^2.
Run on the command line with pyrho compute_r2 -h or --help to see
a list of options and their description.
"""
from __future__ import division
import sys
import numpy as np
from pandas import read_hdf, DataFrame
from numba import njit
from pyrho... |
e3f99230d538ae1a07b9958ae69004b385b296f0ee8df9566896d7e05c35e53c | Python | 5,465 | 180 | import copy
import attr
import numpy as np
import torch
import torch.nn as nn
from modular_splicing.utils.arrays import run_length_encoding
@attr.s
class HSMM:
initial = attr.ib()
distance_distributions = attr.ib()
transition_distributions = attr.ib()
@property
def states(self):
return s... |
d42cef503d70c346cfc8057a3f01d010489e5e1c7d81660f85760b894ae08abf | Python | 5,467 | 175 | """Tests for the portal landing page."""
from __future__ import annotations
from pathlib import Path
import panel as pn
import pytest
from larvaworld.portal.landing_app import landing_app
from larvaworld.portal.landing_registry import ITEMS, LANES, QUICK_START_MODES
from larvaworld.portal.panel_components import PO... |
0ae00a5e6fc5a58ef32ea2eedf2bdd449a76dcfca1c43fd1e9b12f6ea415eba8 | Python | 5,468 | 118 | import glob
import pandas as pd
from nilearn.glm import compute_fixed_effects
from nilearn.glm.second_level import SecondLevelModel
def fixed_effect(sub, task_type, contrasts, input_path, output_path,
save_beta=True, save_var=True, save_tstat=True):
"""
This function takes in a subject, task ... |
8793a38a5e0ddb9932700cc390944b4f2dfcc37f09ec33d54d32a24e44235871 | Python | 5,468 | 150 | import os
import numpy as np
import pandas as pd
import nibabel as nib
from os.path import join as pjoin
from magicbox.algorithm.array import summary_across_col_by_mask
from cxy_visual_dev.lib.predefine import proj_dir, Atlas, s1200_avg_RFsize,\
s1200_avg_eccentricity, s1200_avg_angle, LR_count_32k, get_rois
from m... |
3f5dc3563cbfafc6b984a0be1676e556e6decf086d7dc7f5630156e50827dc7b | Python | 5,471 | 167 | import math
import numpy as np
import torch
import torch.nn.functional as F
from scipy import ndimage
from scipy.ndimage import measurements
from skimage import morphology as morph
import matplotlib.pyplot as plt
from misc.utils import center_pad_to_shape, cropping_center, get_bounding_box
from dataloader.augs impor... |
ad8867bca31c4a3748e6894668ba33cb102c6731c2bfe85464ede251418cafac | Python | 5,472 | 153 | """Tests that ``restrict`` dispatches to the intended implementation.
``_Base.restrict`` chooses between:
- ``_restrict_ranges`` (searchsorted boundaries + contiguous copy) for few
intervals over numpy data, and
- ``_restrict`` (the numba merge scan) for many intervals or non-numpy data.
These tests spy on th... |
72997596d148f25fc7033fddaf3d208a43e58be6a63d7e2259786baa6d7de1c9 | Python | 5,474 | 198 | """Render a small smart-collapse visual review set to /tmp."""
from __future__ import annotations
import sys
from pathlib import Path
import torch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import torchlens as tl
OUT_DIR = Path("/tmp/autocollapse/sample_renders")
class ConvBlock(torch.nn.Modul... |
7bb370d4957471a1aa8107bcae7c379051705e063aa5d669c5b5de70874b7f23 | Python | 5,474 | 161 | import numpy as np
from neurogym.core import TrialEnv
from neurogym.utils import spaces
class DualDelayMatchSample(TrialEnv):
"""Two-item Delay-match-to-sample.
The trial starts with a fixation period. Then during the sample period,
two sample stimuli are shown simultaneously. Followed by the first dela... |
7f497076b61ceffb0b4d30666afb5fa0f2246bdb645a673ae8c0b64152f37038 | Python | 5,474 | 147 | import numpy as np
from mitochondria import Mito
from gates import get_ros
from utils import Recorder, Q_nak
def ret_run_sim(mito_baseline, spike_quanta, psi_fac=1e-3, refrac=6, theta_ret=0.025, tau_rise=5):
print('Baseline : ', mito_baseline, 'Quanta :', spike_quanta)
print('Psi factor: ', psi_fac, 'Refrac ... |
83ad303c1228a80b17fd1ca7be520f82c45aadabf2c4413eae5f77ec51edd548 | Python | 5,475 | 144 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import pycuda.gpuarray as gpuarray
from pycuda.compiler import SourceModule
def best_rotation_gpu(verts1, verts2, arr1, arr2, centroid1, centroid2):
code = """
__global__ void Funktion(int *match, float *verts1, float *verts2, int *arr1, int *arr2, int... |
c375b3f77d2f78d74a95624f0a78afcdeb8366c01f918a8ada9899cd07177ffa | Python | 5,475 | 148 | from tensorflow import keras
from tensorflow.keras import layers
import tensorflow as tf
class Capsule_Mul(layers.Layer):
def __init__(self, num_classes):
super(Capsule_Mul, self).__init__()
self.num_classes = num_classes
def build(self, input_shape):
# -*- batch_size use 1... |
0b4079a0a3b7ed89aa1a4a3f84597180f27a2d203ee23cd78b0e050d1aaa129e | Python | 5,476 | 173 | # coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# 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 applicab... |
7b5baa46c91bf576134a0521b640cfd2d3482bb10f1fe076d8dc9647ed50eb3d | Python | 5,478 | 109 | import sys
import os
# setting path
sys.path.append('../TM2_segmentation')
import numpy as np
import pandas as pd
import nibabel as nib
from skimage.transform import resize, rescale
from scipy.ndimage import zoom
from settings import target_size_unet, scaling_factor
import matplotlib.pyplot as plt
from scripts.prep... |
085b77d74705085757704c428142fdfe9163a711eef16ea6a2452f3455f4873a | Python | 5,481 | 140 | #!/usr/bin/env python
# =============================================================================
# MODULE DOCSTRING
# =============================================================================
"""
Loss functions to train PyTorch normalizing flows for reweighting.
"""
# =====================================... |
7e93b9d8c09adf0e714a55c8057c37f410d31b33fc1b8e7bd045b7e2156f20a4 | Python | 5,481 | 144 | from __future__ import absolute_import
import io
import os
from pip._vendor import pytoml, six
from pip._internal.exceptions import InstallationError
def _is_list_of_str(obj):
return (
isinstance(obj, list) and
all(isinstance(item, six.string_types) for item in obj)
)
def load_pyproject_t... |
321dca2831c10f89870ba63c27095665ea4fcafbc0f2db1c37163fdc63548cf9 | Python | 5,482 | 148 | """Adapted from: https://github.com/https-deeplearning-ai/GANs-Public."""
from argparse import ArgumentParser
from typing import Any, Tuple
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
from pl_bolts.callbacks import SRImageLoggerCallback
from pl_bolts.datamodules import TVTDataModule
fr... |
396a3ae9fd6c822c152c000e9730737d989cc68cb73eb05e0f7eebf67bb5a6d0 | Python | 5,482 | 145 | # -------------------
# train a model
# -------------------
import os
import sys
import time
import random
import numpy as np
import pandas as pd
import tensorflow as tf
from DePTH import _utils
def train(hla_class, data_dir, model_dir, enc_method,
lr, n_dense, n_units_str, dropout_flag, p_dropout,
... |
8ccbb006275ff916e454f481c33a05072814e7547c2e649c79aa97ef81daf270 | Python | 5,483 | 163 | """Embedding Strategies"""
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
from __future__ import annotations
import time
from typing import TYPE_CHECKING, List, Optional, Tuple
import numpy as np
import torch
from torch.nn import Module
from torch.optim import Optimizer
from torch.optim.... |
309f17065bf7ec36405fe2d81a541dc431f68c6ffa72237905ab4f49377785e3 | Python | 5,484 | 146 | import itertools
import numpy as np
import torch
from torch.nn import functional as F
from torch_scatter import scatter_add
from torch import nn
class UnsignedMSELoss(nn.Module):
def __init__(self, reduction="sum"):
"""Since eigenvectors are accurate only upto a sign change, we need to
make s... |
9220df9b88f49a21ddd2e83be49c53e40918335e91b8bd09194bdb509bf6a955 | Python | 5,484 | 168 | # Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# 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 app... |
f1349363ce11c4bb5d0075a08b4f449a958bba1c5adbf01cab93388985f87441 | Python | 5,484 | 145 | """Regression tests for capture-time short/friendly label selector matching.
These lock the fix for the class of capture-time ``save=`` selectors that resolve
through the capture label universe (``tl.label``, ``tl.contains``, ``tl.regex``). At capture
time the base ``RecordContext`` only carries the RAW label (e.g. ``... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.