sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
5ea84e404d1f77acd41283d30c175fa1e5efdd7192623719c1c0f70d6d95bb81 | Python | 2,088 | 63 | """
Helper functions for setting up probability variation with time.
find_mrs_constants - find a,b,A constants.
find_mrs_bins_t - find bins at time t.
"""
# ###############################
# ########### IMPORTS ###########
# ###############################
import numpy as np
# ###############################
# ##... |
f2eb32ec796d87eb4d16242365c33329115b5d7edc57fa0207f069438668f647 | Python | 2,088 | 51 | import pandas as pd
import pickle
from pathlib import Path
from glob import glob
from sys import exit
from logging import getLogger
logger = getLogger(__name__)
def setup_checkpoint_folder():
# Create checkpoint
Path("checkpoint").mkdir(parents=True, exist_ok=True)
existing_checkpoints = glob('checkpoint/... |
ddf74746112a1c5bc617f722baca37decceadee9d191e72eb31ac0aa5090df13 | Python | 2,090 | 52 | import nibabel as nib
import numpy as np
import matplotlib.pyplot as plt
def load_nifti(file_path):
"""Load a NIfTI file and return the image data."""
img = nib.load(file_path)
return img.get_fdata()
def dice_coefficient(seg1, seg2):
"""Compute the Dice coefficient between two binary phantom... |
cef5a1053e130d633df2643f0777abfe59dd17141964f1ef131aea1b37b42626 | Python | 2,091 | 59 | #!/usr/bin/env python3
import os
import sys
import csv
import pydicom
from pydicom.tag import Tag
from pydicom.errors import InvalidDicomError
def is_dicom_file(path):
# Checks first 132 bytes for 'DICM' header
try:
with open(path, 'rb') as f:
return f.read(132)[128:132] == b'DICM'
exce... |
af49b7bbce5cf35d04105f590d8adc9fd33c58b6dab9e50a69aaec2834d6401a | Python | 2,093 | 68 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmseg.models.decode_heads import LRASPPHead
def test_lraspp_head():
with pytest.raises(ValueError):
# check invalid input_transform
LRASPPHead(
in_channels=(4, 4, 123),
in_index=(0, 1, 2),
... |
c28a41a5c72f0f8da8bfc8bb3d8ccc2c24a40aafbde9b8ddde1beedb0195368b | Python | 2,096 | 45 | # pytest unit tests for spinalcordtoolbox.deepseg.models
import json
import pytest
import spinalcordtoolbox.deepseg.models as deepseg_models
def test_load_crop_metadata(tmp_path, monkeypatch):
"""
`load_crop_metadata()` should: skip the disk entirely for non-crop models; require an
explicit, complete `... |
6595ffee98b45d7570df523f82a84c38a793d3f24cdd003c66b46c37206d8f6b | Python | 2,097 | 65 | # -*- coding: utf-8 -*-
import django.core.validators
from django.db import migrations, models
forward_history = """
SELECT disable_history_tracking_for_table('catmaid_sampler'::regclass,
get_history_table_name('catmaid_sampler'::regclass));
SELECT drop_history_view_for_table('catmaid_sampler'::reg... |
55906ce23816a429d763ddd42e558559a40d0e14c97de71e5cdc23ee4f5f1aff | Python | 2,101 | 61 | import argparse
import os
import re
from prov.model import ProvDocument
from provdbconnector import ProvDb
from provdbconnector import Neo4jAdapter
from neo4j import GraphDatabase
NEO4J_USER = os.environ.get('NEO4J_USERNAME', 'neo4j')
NEO4J_PASS = os.environ.get('NEO4J_PASSWORD', 'neo4jneo4j')
NEO4J_HOST = os.environ.... |
83522cf91c4ba29e80790db16645a1d15a55172f568b910264864744e58cde93 | Python | 2,101 | 93 | """ZnDraw Auth - Shared authentication for ZnDraw ecosystem.
Example usage:
from zndraw_auth import (
current_active_user,
current_superuser,
fastapi_users,
auth_backend,
get_session,
User,
UserRead,
UserCreate,
)
# In your FastAPI app:
a... |
d75bfcdad5df22858347d40335f68b5c57f7285f66ac5bde621446e62b40d7fe | Python | 2,102 | 65 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
e0d042e00e87485123dfbe1d6f3b9561cb9d206f42d0a330b437d3b4d29cdf1d | Python | 2,102 | 62 | '''GAE models'''
import torch
import torch.nn as nn
import torch.nn.functional as F
from gae.layers import GraphConvolution
class GCNModelVAE(nn.Module):
def __init__(self, input_feat_dim, hidden_dim1, hidden_dim2, dropout):
super(GCNModelVAE, self).__init__()
self.gc1 = GraphConvolution(input_fe... |
e37857f42f3d7e79b539d6c30d07e57ce30e0b84487442a61c886a10814a1c4a | Python | 2,103 | 71 | """Numpy-related utilities."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
def to_categorical(y, num_classes=None, dtype='float32'):
"""Converts a class vector (integers) to binary class matrix.
E.g. for use with categorical... |
46fb027507ad68e44bca2219e9c3a92f691b075d55db6da4a2505700586ed113 | Python | 2,104 | 65 | """Regression: RoomRenamed fans out to every previous group member (review #3)."""
import pytest
from helpers import (
MockSioServer,
auth_header,
create_test_user_in_db,
)
from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from zndraw.access import GroupRole, Visibility
from zn... |
a998fd0ea5dfa8e353da9272d7f3a65102fc10c446bc595165923fe32fbd145e | Python | 2,104 | 66 | # -*- coding: utf-8 -*-
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
forward = """
CREATE OR REPLACE FUNCTION on_edit_treenode_connector_update_edges() RETURNS trigger
LANGUAGE plpgsql
AS $$BEGIN
IF OLD.treenode_id IS DISTINCT FROM NEW.tr... |
e7b62cc54c81c6b0676043cd88242a1560f09d21566791a2d542dac933525458 | Python | 2,105 | 68 | from setuptools import setup, find_packages
from torch.utils import cpp_extension
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
from pathlib import Path
import subprocess
def _get_cuda_bare_metal_version(cuda_dir):
raw_output = subprocess.check_output(
[cuda_dir + "/bin/nvcc", "-V"],... |
f4029274256ef59caec7dcaf006b81b7af67bbfb5167ac9dd0326920ddc0ce89 | Python | 2,105 | 61 | import torch
from torch import Tensor
from torch import nn
from torch.nn import functional as F
class SigmoidFocalLoss(nn.Module):
""" Focal Loss, as described in https://arxiv.org/abs/1708.02002.
It is essentially an enhancement to cross entropy loss and is
useful for classification tasks when there is a... |
7a12eeca8412cb4dc36a4bf3e83db7446c41acd02984147598c6082ae4b76232 | Python | 2,108 | 63 | """Custom build hook to build the frontend before packaging."""
import os
import shutil
import subprocess
from pathlib import Path
from hatchling.builders.hooks.plugin.interface import BuildHookInterface
class FrontendBuildHook(BuildHookInterface):
"""Build the frontend using bun/npm before packaging."""
P... |
88fdd47a755bbdabdffcd95e66cedb9922722f86f6d523197f1e34e7ca2101e6 | Python | 2,108 | 65 | # Generated by Django 4.2.11 on 2024-04-29 13:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("dataset", "0004_auto_20231211_1827"),
migrations.swappable_dep... |
3d21e3064a8ef8e16a5304809514014794e3ee167d720af7e1ae3c724c3ef363 | Python | 2,110 | 67 | """GET /v1/rooms emits composed addresses and resolved owner labels."""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
if TYPE_CHECKING:
from httpx import AsyncClient
async def _register_and_login(client: AsyncClient, email: str) -> tuple[str, str]:
r = await client.post... |
f494b67baec7c83727cab4e1cc3b5015ad01279e912236a032d06f3aac6d9810 | Python | 2,110 | 49 | """Unit tests for the NWB form styling helpers (label humanizing + HTML chrome builders)."""
import panel as pn
from guppy.frontend import nwb_form_style as style
class TestHumanize:
def test_capitalizes_first_word_only(self):
assert style.humanize("optical_fiber") == "Optical fiber"
assert styl... |
57c0d28be52e7dc3da19dc9b789c005079644c94cf39af4987ca49705f58e724 | Python | 2,111 | 76 | #!/usr/bin/env python
#
# Compute magnetization transfer ratio (MTR)
#
# Copyright (c) 2014 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
import os
from typing import Sequence
from spinalcordtoolbox.utils.sys import init_sct, printv, set_loglevel
from spinalcordtoolbox.utils... |
b6c8d89a8e537b4384bd32f1dd15417b3565923587ce58d9a0a71b7c3e95ccc8 | Python | 2,111 | 65 | # Generated by Django 4.2.11 on 2024-04-29 13:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
("aggregator", "0001_initial"),
migrations.swappable_dependency(... |
d42bee52e3d1ef7c85eec47d0ec25e5f21d018e523bd5d84094f3640c48c7f54 | Python | 2,112 | 55 | from __future__ import print_function
from caffe import layers as L, params as P, to_proto
from caffe.proto import caffe_pb2
# helper function for common structures
def conv_relu(bottom, ks, nout, stride=1, pad=0, group=1):
conv = L.Convolution(bottom, kernel_size=ks, stride=stride,
... |
ca708589ccb1afacfd015d0f99bb3ae9af0c9801b86080fd52f8ee2569d73566 | Python | 2,113 | 74 | from rest_framework.permissions import BasePermission
from benchmark.models import Benchmark
from model.models import Model
class IsAdmin(BasePermission):
def has_permission(self, request, view):
return request.user.is_superuser
class IsModelOwner(BasePermission):
def get_object(self, pk):
t... |
f90c4c524c7f6f46fc4a78223ca2ef3e40f789520c26711f25e44ec911fdd4c2 | Python | 2,113 | 77 | """CHECK-constraint tests for Room ownership invariants."""
from uuid import uuid4
import pytest
from sqlalchemy.exc import IntegrityError
from sqlmodel.ext.asyncio.session import AsyncSession
from zndraw.access import Visibility
from zndraw.models import Group, Room
@pytest.mark.asyncio
async def test_room_requir... |
6728db9b0d7c22c0ba8be57fe0fa3beb5f39d199e603d70fb57e911c1cca2263 | Python | 2,116 | 63 | import torch
from torch import Tensor
from typing import Optional
from torch_scatter import scatter_mean
def zeros(tensor): # fills tensor with 0s
if tensor is not None:
tensor.data.fill_(0)
def ones(tensor): # fills tensor with 1s
if tensor is not None:
tensor.data.fill_(1)
class GraphNorm(t... |
437649fe5301e2d6b5e2cba351958343bddeea140228f29e949315e75be41bcd | Python | 2,119 | 72 | import h5py
import os
from scipy.io import loadmat
import cv2
from tqdm import tqdm
import numpy as np
nyu_root = "/data/nyu_depth_processed"
train_path = "./data/depth_train_big_new.h5"
test_path = "./data/depth_test_big_new.h5"
if not path.isdir(nyu_root):
raise ValueError("Please download the Apolloscape datas... |
85faf0fed92a3f14fa1b60fc9c523ac1dd07aff39f4dfa320e97ebc118e89b4c | Python | 2,119 | 74 | from rest_framework.permissions import BasePermission
from benchmark.models import Benchmark
from dataset.models import Dataset
class IsAdmin(BasePermission):
def has_permission(self, request, view):
return request.user.is_superuser
class IsDatasetOwner(BasePermission):
def get_object(self, pk):
... |
c954fc72a4ebac0a2ce31b175786f674689d9069ba7d912609362852c0998d17 | Python | 2,119 | 48 | from batchgenerators.utilities.file_and_folder_operations import *
import shutil
from nnunet_mednext.paths import nnUNet_raw_data
from nnunet_mednext.dataset_conversion.utils import generate_dataset_json
if __name__ == '__main__':
# this is the data folder from the kits21 github repository, see https://github.com... |
27122b525a9c8ac1eafc67b090d734a3fa76022f6fe01e6272e8470f43818936 | Python | 2,120 | 69 | # -*- coding: utf-8 -*-
from django.db.models import JSONField
from django.db import models
from django.utils import timezone
class TestView(models.Model):
"""
Represents a views that should be tested. It expects 'GET' or 'POST'
as method, a URL and optionally a data dictionary.
"""
method = mode... |
67eb8744dde7ee473cae69bacb48b703c47affd688d04354eb9e95d0e16df109 | Python | 2,120 | 55 |
import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self,patience=7, verbose=False, delta=0):
"""
Args:
patience (int): How long to wait after last time validation loss improve... |
020e2a687fa69f6c0051b41bc92d3f2ba941512d2b7e2081a11866090fe1c916 | Python | 2,124 | 81 | import numpy as np
import statsmodels.api as sm
__author__ = "Albert Qü"
__version__ = "0.0.1"
__email__ = "albert_qu@berkeley.edu"
__status__ = "Dev"
def regularize(x, lb, ub, eps=1e-15):
return np.clip(x, lb+eps, ub-eps)
class Task:
def __init__(self):
self.k_action = 0
class Probswitch_2ABT(T... |
35c8539e9d2d77a770fd16bd55ce253dbd87e00b50370172a6597b204fb6312d | Python | 2,124 | 70 | import math
import requests
from tqdm import tqdm
from .misc import sizeof_fmt
def download_file_from_google_drive(file_id, save_path):
"""Download files from google drive.
Ref:
https://stackoverflow.com/questions/25010369/wget-curl-large-file-from-google-drive # noqa E501
Args:
file_id (s... |
38c0234d399ab07e4532e6b8610c6b03ce86626a479bbfb04a54ab62c586e163 | Python | 2,124 | 57 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Linear
from torch_geometric.nn import GATConv, GINConv, HGTConv
from torch_geometric.data import DataLoader, Data
from torch_geometric.nn import global_mean_pool
from torch_geometric.nn import DataParallel
from to... |
b66f46294a4e4abe0f8564e7e6c6a3a82bb88859a628368d2b33cc30322131c9 | Python | 2,124 | 54 | """Tonic Analysis step: an interactive page served by the persistent main app.
Clicking its sidebar button opens a browser tab on the
main app's ``/tonic-analysis`` route (served by :data:`build_tonic_analysis_view`),
composed from the Step-3 outputs already on disk. Averaging those traces over the windows is
a read-o... |
2bc5559a90944553fd47d07e1aa67cc7b9a23edfc3aa955cd409545171b9d7a0 | Python | 2,126 | 58 | import torch
from unsloth import FastLanguageModel
from datasets import load_dataset
import sys
import argparse
import torch
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--model", type=str, required=True)
args = parser.parse_args()
layers = [0, 10, 20, 30, 40] # c... |
f1c714accf6d3992caf174bedb64d9f94f56a6b51a1408e162018c43877d8df6 | Python | 2,126 | 74 | """selIBEA tests"""
import deap
import numpy
import bluepyopt.deapext
from bluepyopt.deapext.tools.selIBEA \
import (_calc_fitness_components, _mating_selection,)
from .deapext_test_utils import make_mock_population
import pytest
@pytest.mark.unit
def test_calc_fitness_components():
"""deapext.selIBEA: te... |
3ea2ce1f13dd7b0d868779cf5f6beb817574b3e2b33a89a7adcc7aa366840b31 | Python | 2,127 | 67 | # -*- coding: utf-8 -*-
import django.core.validators
from django.db import migrations, models
forward_history = """
SELECT disable_history_tracking_for_table('catmaid_sampler'::regclass,
get_history_table_name('catmaid_sampler'::regclass));
SELECT drop_history_view_for_table('catmaid_sampler'::re... |
43fe3f3e9a07a1f078730249564c0dbb39570ed663639fc40616b6b217c45e0d | Python | 2,128 | 69 | """
=======================================================
Blind source separation using preconditioned ICA on EEG
=======================================================
The example runs the Picard-O algorithm proposed in:
Pierre Ablin, Jean-François Cardoso, Alexandre Gramfort
"Faster ICA under orthogonal constrai... |
ff49910a4590adbe2f07d929aeb7c599a9fd3060c8406eea1f1257e1453475c9 | Python | 2,129 | 70 | # Copyright (c) OpenMMLab. All rights reserved.
import argparse
import os.path as osp
from collections import OrderedDict
import mmengine
import torch
from mmengine.runner import CheckpointLoader
def convert_vit(ckpt):
new_ckpt = OrderedDict()
for k, v in ckpt.items():
if k.startswith('head'):
... |
3554dce6d42dc612252110437f7792f7af2548ec530ea3cd059bc1470173d6be | Python | 2,130 | 66 | import os
import numpy as np
from PIL import Image
root_path = 'data/'
img_suffix = '.png'
seg_map_suffix = '.png'
save_img_suffix = '.png'
save_seg_map_suffix = '.png'
tgt_img_dir = os.path.join(root_path, 'images/train/')
tgt_mask_dir = os.path.join(root_path, 'masks/train/')
os.system('mkdir -p ' + tgt_img_dir)
os... |
c86a19f208e9360813f3d7ed52643b742ee1d77d2a828e35eea4fab3bd2b081e | Python | 2,130 | 57 | import panel as pn
import pytest
from guppy import app
@pytest.fixture
def served(monkeypatch):
"""Capture the route map instead of starting a real Bokeh server.
``pn.serve`` binds a port and opens a browser tab, so it is stubbed here; everything
downstream of it (the route factories themselves) runs fo... |
44086e85fd97cf869079660b2ef602f55a74efb6393720bd16f31ed475b8760b | Python | 2,131 | 56 | '''
get example grid cell tuning by averaging spike count
'''
import numpy as np
import matplotlib.pyplot as plt
from grid_cell.util import select_arr_by_t
import grid_cell.tuning as gct
from scipy.ndimage import gaussian_filter # for smoothing grid cell tuning
import os
from global_setting import *
########## Hyperpa... |
b35b7f3c09cba1257e5a65d86c6549e211aef30c833c66588c3fc73e3514b2eb | Python | 2,131 | 59 | import numpy as np
import xgboost as xgb
import json
rng = np.random.RandomState(1994)
class TestSYCLTrainingContinuation:
def run_training_continuation(self, use_json):
kRows = 64
kCols = 32
X = np.random.randn(kRows, kCols)
y = np.random.randn(kRows)
dtrain = xgb.DMatrix... |
999a902f361db2715aa49d382f77d2a9579fcce3b69b41a2ebb09a669213de32 | Python | 2,132 | 58 | """
Code is modified from https://github.com/lm-sys/FastChat/blob/main/fastchat/model/make_delta.py.
Make the delta weights by subtracting base weights.
Usage:
python3 -m make_delta --base ~/model_weights/llama-13b --target ~/model_weights/ziya-13b --delta ~/model_weights/ziya-13b-delta
"""
import argparse
import to... |
58ea54b02c787d9bf8451e16871ad681ad3efa8844079dab384c63d9fd91d507 | Python | 2,135 | 65 | """Helpers for testing monotone constraints."""
from typing import Optional
import numpy as np
from .._typing import FeatureNames
from ..core import Booster, DMatrix
def is_increasing(v: np.ndarray) -> bool:
"""Whether is v increasing."""
return np.count_nonzero(np.diff(v) < 0.0) == 0
def is_decreasing(v... |
7a3f0c9e0e78cb048098b8aee137a02808d182af14304efafcea74739c9cdb48 | Python | 2,135 | 69 | # sbatch 9_2_batch2
import sys
import os
import time
import random
import anndata as ad
import pickle
import pandas as pd
from datetime import datetime
pwd = os.getcwd()
# Print all command line arguments
for i, arg in enumerate(sys.argv):
print(f"Argument {i}: {arg}",flush = True)
# Print all command line argume... |
d7e8aa22bfc23678cf8260ed4f7654c981b36e79f2e875526b1ef2b201429fab | Python | 2,137 | 79 | """ephys.parameters tests"""
import json
import pytest
import numpy
from . import utils
from bluepyopt import ephys
from bluepyopt.ephys.serializer import instantiator
import bluepyopt.ephys.examples.simplecell
@pytest.mark.unit
def test_pprocessparam_instantiate():
"""ephys.parameters: Testing point process... |
986a4f86ba4c3867a4396523765e7ddca0a15f45bd1eb12ebd6358fee913b213 | Python | 2,138 | 51 | ##################################################################
# Plotting histogram of coefficient and survival p-val in size 2,3,4 motifs
# Reproducibility for Figure.3MNO
##################################################################
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
impo... |
d29fab510df5aa385ab73f55c28500b0be6f7470970a38b038ba410c7c2f9db4 | Python | 2,138 | 83 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue May 2 08:59:45 2023
@author: george
"""
import numpy as np
import pandas as pd
import glob
from tqdm import tqdm
import skimage.io as skio
def getIntensity(A,locsDF, frames=[0], pixelSize=108):
#convert frames to zero start
locsDF['frame'] = ... |
19f082bae92fce6c1ef8600376e68b26afeb2085eaa295970106dc60a84ceeca | Python | 2,141 | 80 | """Extensions requiring the molify package."""
import typing as t
from pydantic import BaseModel, Field
from zndraw.extensions.abc import Category, Extension
class AddFromSMILES(Extension):
"""Add a molecule from SMILES notation."""
category: t.ClassVar[Category] = Category.MODIFIER
smiles: str = Fiel... |
94c34b24509a5bcfcae8c472e4cbf734185ef96430a56b2f20645947b4f9d56f | Python | 2,141 | 53 | import numpy as np
import pytest
from guppy.analysis.filtering import filterSignal, validate_chunk_lengths_for_filtering
# ── validate_chunk_lengths_for_filtering ──────────────────────────────────────
def test_validate_chunk_lengths_raises_on_short_chunk():
# filter_window=100 -> padlen=300, so a chunk must ha... |
edfc062bee55d404abdfd4e37928a0e37d3547d48b65519314362e5391072bde | Python | 2,141 | 68 | import pytest
import torch
import torch.nn as nn
import numpy as np
import os
from Adversarial_Observation.Swarm import PSO
@pytest.fixture
def simple_model():
return nn.Sequential(
nn.Conv2d(1, 4, 3),
nn.Flatten(),
nn.Linear(4 * 26 * 26, 10)
)
def dummy_cost_func(model, position):
... |
7c3ad0067c1c9c0249f08d65106cfe6a14bde242e8457cfdcd4ebd0c8210749c | Python | 2,142 | 88 | """Built-in regularizers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import six
from . import backend as K
from .utils.generic_utils import serialize_keras_object
from .utils.generic_utils import deserialize_keras_object
class Regularizer(object):... |
8e81eb39ecee9adc188c56a71e4560df7bb891b15e99d06e0b2b096d9ae0337e | Python | 2,142 | 60 | import argparse
import cv2
import h5py
import numpy as np
import os
import time
import tensorflow as tf
import edl
import data_loader
import models
import trainers
parser = argparse.ArgumentParser()
parser.add_argument("--model", default="evidential", type=str,
choices=["evidential", "dropout", "... |
0c212c3aa4e1d1a6021d77064863359bc35fc6765bc82340226a6150c5295448 | Python | 2,143 | 70 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 25 04:01:07 2024
@author: max
"""
#%% Can use this to get any feature map from neuromaps and average in parcels from .annot files
#%% Load T1w/T2w data
import sys
import numpy as np
from neuromaps.datasets import available_annotations
import pand... |
e845b93aa0f5c9981393d7cd2cef8410c1ea6994ccb1c88664b858d7c85568a0 | Python | 2,143 | 64 | # Copyright (c) OpenMMLab. All rights reserved.
from copy import deepcopy
from os.path import dirname, join
from unittest import TestCase
import torch
from mmengine import Config, ConfigDict
from mmengine.structures import PixelData
import mmseg
from mmseg.models.segmentors import DepthEstimator
from mmseg.structures... |
50f854f5bc74bd7386cdb22045a9af70f8e4f5082e16afc24e1371cfbff815d1 | Python | 2,146 | 73 | """
The Euclidean space.
"""
import numpy as np
from geomstats.manifold import Manifold
from geomstats.riemannian_metric import RiemannianMetric
import geomstats.vectorization as vectorization
class EuclideanSpace(Manifold):
"""The Euclidean space."""
def __init__(self, dimension):
self.dimension =... |
21f4636336c2cf85b1e2ecb0dffb1bbd38ef66fb66237d793bc44597dee56d30 | Python | 2,148 | 56 | # -*- coding: utf-8 -*-
import subprocess
import os
import sys
import re
import errno
# This variable contains a reference version of the current code-base. It is
# updated by release and dev-cycle scripts.
BASE_VERSION = '2026.05.06'
# This commit is the reference commit of the BASE_VERSION above. Technically, it
#... |
843d85939e42a40a41b230a92fdf37cbae4b152b05aa2a5a2e91ec5414bf7c96 | Python | 2,148 | 77 | #!/usr/bin/env python
#
# Transpose bvecs file (if necessary) to get nx3 structure
#
# Copyright (c) 2013 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
from spinalcordtoolbox.utils.fs import extract_fname
from spinalcordtoolbox.utils.sys import in... |
17c8b00ea556d1ccbe24d732c72985fb8d9a43800bcd78baeeda318643432256 | Python | 2,149 | 66 | import pandas as pd
import matplotlib.pyplot as plt
import numpy
try:
import cPickle as pickle
except:
import pickle
import gzip
steps = ['Step-0.25', 'Step-0.2', 'Step-0.15', 'Step-0.1', 'Step-0.05', 'Step0.05', 'Step0.1', 'Step0.15', 'Step0.2', 'Step0.25']
traces = []
times = []
for i in range(len(steps)):
... |
21329d5ac26146ec7d993805701452baeadc8970ba141fcbd0820fe9a5149b41 | Python | 2,149 | 70 | #!/usr/bin/env python3
"""Generate golden annotation outputs for the self-test dataset.
Runs emapper once per ``--itype`` against ``test_datasets/data`` and stores the
resulting ``.annotations`` as ``test_datasets/golden/<itype>.annotations``.
Re-run this only when the expected output legitimately changes; the pytest
... |
4c682f59ca8f9812aec8d9c40e6431c0e097aaf5bd523d0a4edf5b559d8818ec | Python | 2,149 | 66 | import numpy as np
from h5py import h5s
from h5py._selector import Selector
class Helper:
def __init__(self, shape: tuple):
self.shape = shape
def __getitem__(self, item) -> h5s.SpaceID:
if not isinstance(item, tuple):
item = (item,)
space = h5s.create_simple(self.shape)
... |
2d36635f0cb246a43a9f01cfb78dcdd034743e965df85f95b74bacd046c188bf | Python | 2,150 | 83 | # -*- coding: utf-8 -*-
"""
Created on Mon Aug 15 18:38:58 2022
@author: milan
"""
import sys
import pandas as pd
import uuid
from sklearn.preprocessing import MinMaxScaler
import numpy as np
from sklearn.naive_bayes import GaussianNB
import fdr_utils
def get_scores(df, features, y):
X = df[ features ].... |
4972f7f3a610b3491839bce9a52c724ac6ebc2d83c56ca11e872b96acb18b93b | Python | 2,151 | 41 | import deepchem as dc
def generate_model_feature(m_name, n_tasks, args):
op_dir = f"{args.model_dir}/{args.split}/{args.mode}"
mode = args.mode
if mode == 'soft':
mode = 'classification'
batch_size = args.batch_size
if m_name == 'GCN':
feat = dc.feat.MolGraphConvFeaturizer()
... |
cdb9b6eefeeb0a3b8fede3dfcd8e6c93aaef0c182e4a4f5ed189e4d6656f30a8 | Python | 2,152 | 62 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import Upsample
from .decode_head import BaseDecodeHead
@MODELS.register_module()
class SETRMLAHead(BaseDecodeHead):
"""Multi level feature aggretation... |
ac56f8f64a501169b8622e196d37b726b4663703943deb4c3a949e4c31b18103 | Python | 2,153 | 59 | import os
os.environ['DDE_BACKEND'] = 'pytorch'
import deepxde as dde
import torch
import numpy as np
from model_GP import FourierDeepONet
from data_GP import dataset
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
class Dataset(dde.data.Data):
def __init__(self, X_train, y_train, X_test, y_... |
c4d2fc9a6f3ee2441b6fc344d4d100c0011d196b826569199886da34c8743bc4 | Python | 2,153 | 59 | import logging
import torch
from . import ModelTask
from .ae_network import AENetwork
from .network import SeparationNetworkClassifier, SeparationNetworkRegressor
def create_compressor(
pretrained_path: str | None, device: str | torch.device, use_best: bool = False, old_version: bool = False
) -> AENetwork:
... |
5997d3cf49f5886473790fadba2faaaccd969fc438b1a428df817c440d08bea4 | Python | 2,154 | 72 | _base_ = './catseg_vitb-r101_4xb2-warmcoslr2e-4-adamw-80k_coco-stuff164k-384x384.py' # noqa
pretrained = 'https://download.openmmlab.com/mmsegmentation/v0.5/pretrain/swin/swin_base_patch4_window12_384_20220317-55b0104a.pth' # noqa
crop_size = (384, 384)
data_preprocessor = dict(size=crop_size)
model = dict(
back... |
a798017884afac5362e1650b67f70d2727d1c548fa4d293983fad97c9d025d4c | Python | 2,154 | 66 | # the change of rate map with speed
import numpy as np
import matplotlib.pyplot as plt
from grid_cell.grid_cell_processor import Grid_Cell_Processor, Speed_Processor
from mpl_toolkits.axes_grid1 import make_axes_locatable
import os
from global_setting import *
#################### Hyperparameters ####################
... |
ea677a006f5e45df7b9a700dcf9b2aae9060d18e401031e465dd3101a03a5f89 | Python | 2,154 | 70 | import csv
import numpy as np
import tqdm
import glob
def generate_csv(img_path, output_path, dataset_name):
"""
Generate Splits and csv from a folder with images
@param: img_path: str
path to images
@param: output_path: str
path to output train csv
"""
train_path = output_path... |
6798242658f79a15bf82f5f4220b4289b40cc9d029ba643a76d90d5f8fd5946f | Python | 2,155 | 68 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
# pyre-strict
import logging
import os
import tempfile
from typing import Optional
from iopath.common.file_io import ( # noqa, unused import required by some deps
file_lock,
HTTPURLHandler,
LazyPath,
NativePathHandler,
OneDr... |
b3390f92ca28212245b2e8d887677c2771406f69607eaa0603cf27143ad0a4e9 | Python | 2,155 | 71 | import cv2
import torch
import numpy as np
from glob import glob
from natsort import natsorted
import os
from tqdm import tqdm
from pdb import set_trace as stx
src = 'Datasets/Downloads/SIDD'
tar = 'Datasets/train/SIDD'
lr_tar = os.path.join(tar, 'input_crops')
hr_tar = os.path.join(tar, 'target_crops')
os.makedirs... |
174f10242458f714737058a5a49dd765f7eeea63f022fdc12ed901b126238ed5 | Python | 2,156 | 61 | import torch
import pytest
import numpy as np
from Adversarial_Observation.Attacks import fgsm_attack, gradient_ascent, gradient_map
from Adversarial_Observation.utils import load_MNIST_model, compute_success_rate
@pytest.fixture
def sample_data():
model = load_MNIST_model()
device = torch.device("cuda" if tor... |
196295eaa8457f3bb839944ee9aacf8c21a8714026030547ddb5b50915aef0f2 | Python | 2,156 | 74 | import codecs
from typing import Generator
from rdflib.plugins.parsers.ntriples import W3CNTriplesParser, ParseError
from rdflib.plugins.parsers.ntriples import r_wspace, r_wspaces, r_tail
class CustomNTriplesParser(W3CNTriplesParser):
"""
This class is an extension to ``rdflib.plugins.parsers.ntriples.W3CNT... |
342d415173aa6fda7bcf3a3b6158983756307bbe4ba2ce0b0510ad9dd2610325 | Python | 2,156 | 69 | import os
import shutil
import argparse
import json
import urllib.request
import hashlib
from typing import Union
from tqdm import tqdm
def main(cfg):
with open(cfg.filelist, 'r') as f:
filelist = json.load(f)
target = filelist[cfg.target]
for fl in target['files']:
output = os.path.joi... |
586f1480099df861c04c90377bda39351ec047703ee6f66cb669d4b83cec1bac | Python | 2,156 | 79 | #!/usr/bin/env python
"""
sa.py
Parse and possibly sanity-check a .sa file output by bowtie2-build in --sa
mode. These files have a very simple format: first is a uint32_t containing
the length of the suffix array, the rest is an array of that many uint32_ts
containing the suffix array.
"""
import sys
import struct... |
9584f946bbc8ad48902a44eaa621f5283f952d62b7c839199eb7de5d8d9dd4a4 | Python | 2,159 | 81 | # utils file for simulation
import numpy as np
def id_mapping(IDs1, IDs2):
"""
Mapping IDs2 to IDs1, both of which should only contain unique ids.
Parameters
----------
IDs1 : array_like or list
ids for reference.
IDs2 : array_like or list
ids waiting to map.
... |
165792156ba00b46d191388d5970cda94e2baf653a7d3c898d6eae9b12669edd | Python | 2,160 | 59 | # coding utf-8
"""
Code for obtaining input for non stationary temporal MIIC.
Author: Tiziana Tocci
"""
"""
### Set working directory
"""
import os
script_dir = r"spheroid_morpho_ML/MIIC" # adjust your own path
os.chdir(script_dir)
"""
### Libraries
"""
import pandas as pd
from modules.functions_st... |
284903931231c571548d59d18618c0587540ce595c1b4dcbc9778f5c9af38ed1 | Python | 2,160 | 74 | # Authors: Pierre Ablin <pierre.ablin@inria.fr>
# Alexandre Gramfort <alexandre.gramfort@inria.fr>
# Jean-Francois Cardoso <cardoso@iap.fr>
#
# License: BSD (3-clause)
import numpy as np
import numexpr as ne
from scipy.optimize import check_grad
from numpy.testing import assert_allclose
def check_... |
90ffba71e78a4fb17fd37ace5501d6c320df665a466de3e40e8ba5a047a23edd | Python | 2,160 | 58 | # Copyright (c) OpenMMLab. All rights reserved.
import torch.nn as nn
from mmcv.cnn import ConvModule
from mmengine.utils import is_tuple_of
from .make_divisible import make_divisible
class SELayer(nn.Module):
"""Squeeze-and-Excitation Module.
Args:
channels (int): The input (and output) channels of... |
d97b34a8f51973bb5b508d9a39ee49ba39418543c85c657f32adeca693bcee22 | Python | 2,160 | 60 | import numpy as np
import pandas as pd
# import torch
# device = torch.device("cuda")
def gen_data(i,j):
### i means index of inlet velocities; j means index of different topology structure
filename = "dataset/v"+str(i)+"N"+str(j)+".csv"
df=pd.DataFrame(pd.read_csv(filename))
df.columns = df.colu... |
1c46dcffa45f932a45a4b099f197bcd906fad6a35661ab0ac703e9fbd4840b2e | Python | 2,162 | 67 | #!/usr/bin/env python
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the Heudiconv package for the
# copyright and license terms.
#
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
def main():
import o... |
2a8cd36b027a749817299ab4721343f198a131dc1feda3a953f529236ae44904 | Python | 2,162 | 76 | # tests/test_schemas.py
from datetime import UTC, datetime
from uuid import UUID
from zndraw_joblib.models import TaskStatus
from zndraw_joblib.schemas import (
JobRegisterRequest,
JobResponse,
TaskClaimResponse,
TaskResponse,
TaskSubmitRequest,
TaskUpdateRequest,
)
def test_job_register_requ... |
2fc9dd29ed77c787908bfde92aae0d937caffc387d23736303476ff14f976f65 | Python | 2,162 | 78 | import torch
import torch.nn.functional as F
from torch import nn
from torch.optim import Adam
from einops import rearrange, repeat
import sidechainnet as scn
from egnn_pytorch.egnn_pytorch import EGNN_Network
torch.set_default_dtype(torch.float64)
BATCH_SIZE = 1
GRADIENT_ACCUMULATE_EVERY = 16
def cycle(loader, le... |
ba92ca31261aaafa00aa8439ddc15c5909bf0d5f46d95193d7d8d931b8d877bc | Python | 2,163 | 71 |
import torch
from torch.utils import tensorboard
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal
import matplotlib.pyplot as plt
class TensorBoardLogger:
def __init__(
self,
writer: tensorboard.writer.SummaryWriter,
mode: Literal["classif... |
f094417fdffdf34d4d89511d69e9141582ebce9526c46c594dfb634d3f80bcfc | Python | 2,164 | 61 | # tests/test_models.py
from datetime import UTC, datetime, timedelta
from uuid import UUID
from zndraw_joblib.models import (
Job,
Task,
TaskStatus,
Worker,
)
def test_task_status_enum():
assert TaskStatus.PENDING.value == "pending"
assert TaskStatus.CLAIMED.value == "claimed"
assert Task... |
96307b4c3c06ba6431687420821f87010bfbc4df3dc34fbe9fe1c43ec0eb189c | Python | 2,165 | 65 | # allertrans/model.py
import torch
import torch.nn as nn
import torch.nn.functional as F
class NeuralNet(nn.Module):
def __init__(self, input_size, hidden_size1, hidden_size2, hidden_size3, num_classes):
super(NeuralNet, self).__init__()
self.fc1 = nn.Linear(input_size, hidden_size1)
... |
0ab43bc2717152026805fb20e0b04f555aae853a895949d505836d56111b6ec2 | Python | 2,167 | 61 | """Shared h5py-native HDF5 read/write helpers.
These helpers implement GuPPy's "one file per event, multiple keyed datasets
per file" convention. Used by both the extractor layer (raw store dumps) and
the analysis layer (preprocessing, z-score, transients, etc.).
"""
import logging
from pathlib import Path
import h5... |
811f89bc66df485378177e06bd3a22f650f50baee289c911a4f865e444bbe55c | Python | 2,167 | 68 | import os
num_to_modality = {
"_0000": "_brain_t1n.nii.gz",
"_0001": "_brain_t2w.nii.gz",
"_0002": "_brain_t2f.nii.gz",
"_0003": "_brain_t1c.nii.gz",
}
def get_subdirs(parent_directory):
subjects = os.listdir(parent_directory)
subjects = [
p
for p in subjects
if os.pat... |
d7d34d1e8f968894099bef1703fae3d457cab80b758789580f1d0ab9488dca6f | Python | 2,167 | 63 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import pandas as pd
import nest_asyncio
from zoo_bids.functions import setup, log_event
from zoo_bids.functions import input_exlusions
from zoo_bids.data import get_trial_data, get_first_trigger
nest_asyncio.apply()
paths = setup()
try:
__file__
ex... |
eb93a441ebfb2247820118057f7656a6e11d94c1c37ba2a3f753313bd3d6acd1 | Python | 2,168 | 68 | from functools import partial
from typing import List
import ase
import numpy as np
import torch
from mace.data.atomic_data import AtomicData, get_data_loader
from mace.data.utils import config_from_atoms
from mace.tools import AtomicNumberTable
from .model import HydroMACE
from .tools import get_model_dtype
# From... |
203098053949925022a6b4d9ee9425349aea0660ab053e62861e84a89b7b165f | Python | 2,170 | 83 | import pytest
from cwl_utils.sandboxjs import code_fragment_to_js
from schema_salad.avro.schema import Names
from schema_salad.utils import yaml_no_ts
from cwltool import process, validate_js
TEST_CWL = """
cwlVersion: v1.0
class: CommandLineTool
baseCommand: echo
requirements:
- class: InlineJavascriptRequirement... |
51d02ea88c085c1dc7c91cec5b4fa3f67bf473bb3f787e346b71fe43aff476b1 | Python | 2,170 | 70 | from ipaddress import IPv4Address
from typing import List
from CybORG.Shared.Enums import TransportProtocol
class HostEvents():
"""Object that holds 'events'/alerts that have happened on a specific host.
Attributes
----------
network_connections : List[NetworkConnection]
current network... |
35135526dbcbc5fdb834ecd7a5e98a1c944a7ed66ad85033ea578e11c1c88a96 | Python | 2,171 | 71 | import numpy as np
def gen_weighted_rdf(
distance_matrix: np.ndarray,
bond_properties: np.ndarray,
nbins: int = 30,
min_d: float = 1.0,
max_d: float = 8.0,
four_body_term: bool = False,
) -> np.ndarray:
if four_body_term:
raise NotImplementedError(
"Four body term was n... |
d206bdaeb777703e4c19c300b8715ad50a54f16f9e2526d9a49a2fe829ce70eb | Python | 2,171 | 59 | import h5py
import pandas as pd
from experiment import *
import numpy as np
from matplotlib import pyplot as plt
import matplotlib as mpl
def trajectory_to_tail(x, components, mean, std):
y = np.dot(x, components)
angles = (y * std) + mean
# convert into dx, dy vectors
ps = np.concatenate([np.cos(an... |
38ed9dd0e0c541ca845f46e509b2a32c7a8b8b4dea3df6b45850ae87c3dce07d | Python | 2,174 | 74 | """
End-to-end AllerTrans pipeline:
1. Generate ProtT5 embeddings (HDF5)
2. Generate ESM-2 embeddings (.pt per protein)
3. Run ensemble prediction
4. Save CSV results
"""
import subprocess
import os
import torch
import pandas as pd
from pathlib import Path
from allertrans.model import load_models, predict... |
e58a4ac9b19085738767c9e2c5c03306f1d0d2378452b42fd1298d6bede6bfc6 | Python | 2,174 | 65 | #!/usr/bin/env python3
#
# Calculates statistics about the standard deviations reported in the midpoints
# data.
#
import numpy as np
import base
nooocytes = True
if nooocytes:
w = 'where cell != "Oocyte"'
a = 'and cell != "Oocyte"'
else:
w = a = ''
with base.connect() as con:
c = con.cursor()
... |
a5dca4c05ef6783e8056a77d2005f52e489554908da3a15bf74dc87a5fc8235b | Python | 2,175 | 64 | # please run fit_gp_torus_speed.py first to obtain the gp model
import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
import os
from grid_cell.speed_partition_processor import Speed_Partition_Processor
from grid_cell.manifold_fitter import GP_Fitter
import grid_cell.ploter as ploter
import grid_cell.t... |
cf226c3f5d3c08d95e70e6ca735c2f72a2785d591d1812de0f292f0580c0a1d7 | Python | 2,177 | 42 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.