sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
77e617fa99e0447d2faa6c56450337cf11ec39c12b0df212f3ce3476faf55a76 | Python | 4,812 | 137 | import pandas as pd
import os
import numpy as np
import nibabel as nib
from joblib import Parallel, delayed
from . import consts
class SumNiiRois:
"""
Kinderseg helper class to summarize ROIs as mapped in sumroi_mapping.csv
Example:
>>> from kinderseg.sums import SumNiiRois
>>> sumrois = SumNi... |
5cf3054b1415b85f075d3d129abc84799e92452ab78a17ed9b041ec43cf2e99c | Python | 4,813 | 109 | from dataclasses import dataclass
from copy import deepcopy
import numpy as np
from features.BackgroundSubtraction import BackgroundSubtraction
from features.Baseline import Baseline
from features.Smoothing import Smoothing
from features.AdjustFrequency import AdjustFrequency
from features.EventDetection impor... |
1dfee86e603424357172445b974c856b03938a748ed785d3481762f199cd6a84 | Python | 4,815 | 167 | # -*- coding: utf-8 -*-
"""
@File: self_attn_pool.py
"""
import torch
import torch.nn.functional as F
from torch import nn
def squash(input_tensors, dim=2):
"""
Squashing function
Parameters
----------
input_tensors : a tensor
dim: dimensions along which to apply squashing
Returns
-... |
8e17427c1f8919ce0172bc3f39c5359327c444941b722bd63cd1f03c5be314f8 | Python | 4,816 | 137 | #!/usr/bin/env python
#
# This command-line tool is the interface for the deepseg_gm API
# that implements the model for the Spinal Cord Gray Matter Segmentation.
#
# Reference paper:
# Perone, C. S., Calabrese, E., & Cohen-Adad, J. (2017).
# Spinal cord gray matter segmentation using deep dilated convolutions.... |
be2e932ef175886a36cbcadf1482ba7ee5a6df8bb20ab47e804911462d8b1840 | Python | 4,816 | 141 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# use write-only mode for matplotlib to surpress UserWarning caused by logomaker:
# UserWarning:Starting a Matplotlib GUI outside of the main thread will likely fail.
import matplotlib
matplotlib.use('agg')
from dash import Input, Output, callback, State, html, ctx
... |
eb0905e59a814ea268a984c0755e531f8fea46744872ceb5f8b3537f1d9cb170 | Python | 4,820 | 122 | import pytorch_lightning as pl
from pytorch_lightning.loggers import CSVLogger
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
import torch
import torch.nn as nn
import torch.optim as optim
from nnunet_mednext import create_mednext_v1
import data_loader
import yaml
import argparse
import os... |
c5d441a74416284012c9a97f85c81aa3a1661ad31706002db6f17db812013c22 | Python | 4,821 | 137 | # Copyright (c) OpenMMLab. All rights reserved.
"""Modified from
https://github.com/JunMa11/SegLoss/blob/master/losses_pytorch/dice_loss.py#L333
(Apache-2.0 License)"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from ..builder import LOSSES
from .utils import get_class_weight, weighted_loss
@... |
52d5d6e53db2855f77e95de7d517a7152c0f788a20a4df708bc364997fb3506b | Python | 4,822 | 108 | # run fit_gkr_models.py first
import numpy as np
# from ripser import Rips, ripser
# import ripserplusplus as rpp_py
from gph import ripser_parallel
import hickle as hkl
from grid_cell.ploter import scatter_torus_ploter, plot_barcodes
from grid_cell.persistent_homology import find_quantile_lifetime, cloud_2_sparse_mat
... |
5a28dec6d08de46cc0ea9cec85c266f90ecb16f9145716821fa584f4c0174373 | Python | 4,823 | 155 | import numpy as np
import pytest
import torch
from e3nn import o3
from mace.modules import interaction_classes
from mace.modules.blocks import (
RealAgnosticInteractionBlock,
RealAgnosticResidualInteractionBlock,
)
from mace.modules.models import MACE, ScaleShiftMACE
from mace.tools import AtomicNumberTable
fro... |
b6daa62ea48ab275ecd51432a6ce78a95d4b365245f214edc9f66fe23b201216 | Python | 4,825 | 152 | import numpy as np
import math
def calculate_XYZ_pad_old(alignment, bounds):
"""
alignment is a quicknii alignment
bounds is the shape of the volume minus 1
"""
Ox, Oy, Oz, Ux, Uy, Uz, Vx, Vy, Vz = alignment
# bounds = np.array(volume.shape) - 1
X_size = np.sqrt(np.sum(np.square((Ux, Uy, U... |
d3d3596f170d927ce0dd3af1ecf90cc52042f7d549e616dd07dba856930e665f | Python | 4,830 | 152 | import logging
import os
import ase.io as ase_io
import numpy as np
import torch
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.generation_utils import calculate_restorative_force_strength
from simgen.integrators import IntegrationParameters
from simgen.manifolds import CirclePrior, Multiva... |
1f9abf134c3cbcc0cde0f275a53fd8cb9eade5a76f0af4bad4b16c9e7b401fc7 | Python | 4,832 | 160 | import math
import torch
import torch.nn as nn
from e3nn.o3 import Linear
from torch_geometric.data import Data
from ccdvaeplus.pl_modules.embeddings import MAX_ATOMIC_NUM
from ccdvaeplus.pl_modules.equiformer_v2.equiformer_v2 import EquiformerV2
from ccdvaeplus.pl_modules.gemnet.gemnet import GemNetT
d... |
60c597ed1ba6d3a0a331f9c6726a92f1ed1f7a4e8a8a6a26f56f6f2fa5c409e1 | Python | 4,832 | 128 | #!/usr/bin/env python3
import msgpack
import subprocess
import os.path
import random
import tempfile
import csv
sambamba = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../build/sambamba')
def referenceSequences(bam_fn):
header = subprocess.check_output([sambamba, "view", "-H", bam_fn,
... |
b6af04aa24d9ae2edf7bc97524aeb37520e6c2e164f56aa987b0ffe2f3656464 | Python | 4,833 | 136 | """
This module contains the legacy implementation for calculating the atomic representations.
Here for testing purposes, to ensure correctness of the new implementation.
"""
import numpy as np
def gen_weighted_rdf(
distance_matrix: np.ndarray,
at_props: np.ndarray,
bond_properties: np.ndarray,
all_a... |
5923f7657dc7cf1908642b3822465bed83aa38f48111a172ec9e51b01f97a6d0 | Python | 4,841 | 123 | # 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... |
09c296ba22a93fa0b39574cc3062412d7a6697e2cb645f7ce76239decb5ba0a6 | Python | 4,842 | 113 | """Tests for src/util.py helpers."""
import pytest
from src.util import Text, _biolink_ref, ensure_parent_dir
@pytest.mark.unit
class TestBiolinkRef:
"""Unit tests for _biolink_ref(), which controls the git ref in GitHub raw URLs."""
def test_version_number_gets_v_prefix(self):
assert _biolink_ref(... |
8f5dfddb848b1ca9300c952e1bd218adb38e348f1034759c2a07aac957d5462d | Python | 4,843 | 149 | import logging
from pathlib import Path
import ase.io as aio
import mace
import torch
from mace import modules
from mace.tools import (
MetricsLogger,
build_default_arg_parser,
get_atomic_number_table_from_zs,
get_tag,
set_default_dtype,
set_seeds,
setup_logger,
)
import wandb
from hydroma... |
17739ced6ad2d3432951e705780e95a0f13ffd6572b0e4934d9071ed715a6276 | Python | 4,844 | 102 | #!/usr/bin/env python
"""
extract dvars and fd info from fmriprep_confounds_timeseries
calculate mean and append it with BIDS data
"""
__author__ = "Heejung Jung, Owen Collins"
__copyright__ = "Spatial Topology Project"
__credits__ = [""] # people who reported bug fixes, made suggestions, etc. but did not actually wri... |
652af17553a0561fbe720a2314459f3e9b679e5b1ce3e282e1b2cb77015de2ac | Python | 4,844 | 153 | """Tests for create_hoc.py"""
# pylint: disable=W0212
import os
from bluepyopt.ephys.acc import ArbLabel
from bluepyopt.ephys.parameterscalers import NrnSegmentSomaDistanceScaler
from . import utils
from bluepyopt.ephys import create_acc, create_hoc
import pytest
DEFAULT_LOCATION_ORDER = [
'all',
'apical... |
909fb63ba9aba9df247894a575b13b051faf75b2676f2dcb97680b20a1a12e49 | Python | 4,844 | 120 | import shutil
from pathlib import Path
from unittest.mock import patch
import holoviews as hv
import pandas as pd
import pytest
from guppy.frontend.visualization_dashboard import VisualizationDashboard
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4, step5
from guppy_test_data import STUBB... |
5474319eec72d081f77d9f5a0204824ec16fa19e86bc4623964dbd6748a9a536 | Python | 4,845 | 131 | from __future__ import annotations
from typing import Optional
from heudiconv.utils import SeqInfo
def create_key(
template: Optional[str],
outtype: tuple[str, ...] = ("nii.gz", "dicom"),
annotation_classes: None = None,
) -> tuple[str, tuple[str, ...], None]:
if template is None or not template:
... |
ca041b561c08688e1674330bc5f27edd5c3d496f6421032d510728333a57528d | Python | 4,847 | 139 | from Utils.dataloader_RSNA_BONE import *
from Utils. config import *
from Utils.models import *
from Utils.TrainModelRSNA import *
from multiprocessing import Process
from codecarbon import EmissionsTracker
def task(lr, data_partition:float=None, run_idx:int=None, backbone: str='eff3'):
_cuda = 'cuda:0'
if backbone ... |
0b0810833ac04d0e6da4402612c04ced1417671ceb50b23c67ca9e00bb681754 | Python | 4,849 | 125 | import logging
from pathlib import Path
import panel as pn
from ..frontend.custom_events_config import CustomEventsConfig
from ..frontend.frontend_utils import scanPortsAndFind
from ..utils.custom_events import (
is_sorted,
parse_pasted_timestamps,
write_custom_event_csv,
)
logger = logging.getLogger(__n... |
723e72d066ae2c41044816baf1e8f2f6a9976b4cb8eacea5477109554958afed | Python | 4,850 | 137 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmcv.cnn import NonLocal2d
from torch import nn
from mmseg.registry import MODELS
from .fcn_head import FCNHead
class DisentangledNonLocal2d(NonLocal2d):
"""Disentangled Non-Local Blocks.
Args:
temperature (float): Temperature to adju... |
dda7f82874e546f2d48407ebab75f438549579e114b4575d81417d8cdb5c6921 | Python | 4,850 | 152 | from typing import List
import torch
import numpy as np
from oa_reactdiff.utils import bond_analyze
def write_xyz(mol, dataset_info, xyzfile="tmp.xyz"):
atom_decoder = dataset_info['atom_decoder']
n_atom = mol["atom"].size(0)
with open(xyzfile, "w") as fo:
fo.write(str(n_atom) + "\n\n")
fo... |
e84b507cdb5504bfba434464eb688edbec09cc54b674110e428dc570f852ab9e | Python | 4,857 | 108 | from dataAnalysis.data.Training import Training
from dataAnalysis.data.Validation import Validation
import pandas as pd
from dataAnalysis.data.Greifswald_Validation import GreifswaldValidation
from dataAnalysis.data.MIMIC import MIMIC
import numpy as np
from dataAnalysis.scorer.AUROC import area_under_curve
def count... |
b9abcc38af2d50b773d3ecd6005c3b9ee2596c8159cce13983c38529ad7e3bae | Python | 4,858 | 132 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_norm_layer
from mmengine.model import ModuleList
from mmengine.model.weight_init import (constant_init, trunc_normal_,
trunc_normal_init)
... |
443794420f96c155469f2157cb88df37537e2844ba892c772e2e7880ad53d522 | Python | 4,862 | 168 | import argparse
import json
from pathlib import Path
import pandas as pd
def annotation_csv_to_dict_for_images(annotation_path, hv_dir_path, split_index):
database = {}
data = pd.read_csv(annotation_path, header=0)
keys = []
subsets = []
labels = []
mri_ids = []
for hv_file in hv_dir_path... |
acc3474030a0e88546d460148c04ebd8bfd52813c5d436489209a139c0219879 | Python | 4,862 | 148 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
import argparse
import glob
import os
import numpy as np
SPLITS = {
"OC20": ["id", "ood_ads", "ood_cat", "ood_both"],
"OC22": ["id"... |
3657df69374de0fc167508bceda3ea3e1ab8fef86366d30cf32945f49f4d9194 | Python | 4,863 | 153 | import logging
import os
import ase.io as ase_io
import numpy as np
import torch
from simgen.element_swapping import SwappingAtomicNumberTable
from simgen.generation_utils import calculate_restorative_force_strength
from simgen.integrators import IntegrationParameters
from simgen.manifolds import CirclePrior, Multiva... |
0b5d904cc758a0d107a713b73ccf2329e3064f26831966db4150530c84b761a8 | Python | 4,866 | 128 | from __future__ import print_function, unicode_literals, absolute_import, division
from tensorflow.keras.layers import Input, Conv2D, Conv3D, Activation, Lambda
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Add, Concatenate
from .unet_blocks import unet_block
import tensorflow as tf
f... |
f5110ba3c7ff3441dd53292451073b1a80e811b12ea4236ce12b33e5c45eb37b | Python | 4,867 | 121 | # -*- coding: utf-8 -*-
import logging
import requests
from datetime import datetime
import os
from django import forms
from django.core.exceptions import ValidationError
from django.contrib import messages
from django.shortcuts import redirect
from formtools.wizard.views import SessionWizardView
from catmaid.models ... |
749049e570b148d82be3d5359c3560f69eff2bc4597bc968a4f42e00aaa36827 | Python | 4,868 | 169 | """
Creates LMDB files with extracted graph features from provided *.extxyz files
for the S2EF task.
"""
import argparse
import glob
import multiprocessing as mp
import os
import pickle
import ase.io
import lmdb
import numpy as np
import torch
from tqdm import tqdm
from ocpmodels.preprocessing import AtomsToGraphs
... |
f3f3ca8604002413dac22de671b48b6d5016f0e92fa2bffe14215e14961d3a37 | Python | 4,869 | 142 | from typing import Type
import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing.monotone_constraints import training_dset, x, y
dpath = "demo/data/"
def is_increasing(y):
return np.count_nonzero(np.diff(y) < 0.0) == 0
def is_decreasing(y):
return np.c... |
62d56dc1f0c8cf0cd28dc80523ae4fdfab7272719933e54e89bd5b6faef48170 | Python | 4,873 | 143 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.11 on 2016-12-19 00:02
import os
import logging
import django.contrib.postgres.fields.jsonb
from django.conf import settings
from django.db import migrations, models
from catmaid.apps import get_system_user
from catmaid.control.volume import get_volume_instance
from... |
94bfb56c798caaa186113cceafc3ca5f8debcfc5105c2f7ebbf93dbfd68a14b2 | Python | 4,873 | 97 | # 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... |
5bcfeb85816fdba6045d512b6765ee45768884680f3eb526e55a28f0afa00218 | Python | 4,878 | 146 | """
Feature engineering pipeline for categorical data
=================================================
The script showcases how to keep the categorical data encoding consistent across
training and inference. There are many ways to attain the same goal, this script can be
used as a starting point.
See Also
--------
-... |
30cdb719512edbdbf597d7e20646a9cfdc4573e45d4062457b55c755def45388 | Python | 4,880 | 114 | import hydra
from omegaconf import DictConfig
from pathlib import Path
import os
from tqdm import tqdm
def load_data(path_to_source: str, path_to_prediction: str):
path_to_source: Path = Path(path_to_source)
path_to_prediction: Path = Path(path_to_prediction)
if not path_to_source.exists():
raise F... |
ba3a64f4600c62f209206a6df3b40e3fcf133edae32fad658831bb0c2a6d1146 | Python | 4,885 | 118 | # Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import warnings
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import Nor... |
eece497b74022db5daf4e9536f6323db8c75ada231862a386c32548a01d39824 | Python | 4,889 | 124 | import io
import logging
import contextlib
import pandas as pd
import importlib.resources
import rpy2.rinterface_lib.callbacks
from rpy2.robjects import r, pandas2ri
from rpy2.rinterface_lib.callbacks import logger as rpy2_logger
pandas2ri.activate()
rpy2.rinterface_lib.callbacks.logger.setLevel(logging.ERROR)
rpy2... |
817600f0e4ad0ebfcbc1419b044c110b5e32451066451c73f87069e9f3b0b859 | Python | 4,891 | 142 | # This file is part of h5py, a Python interface to the HDF5 library.
#
# http://www.h5py.org
#
# Copyright 2008-2013 Andrew Collette and contributors
#
# License: Standard 3-clause BSD; see "license.txt" for full license terms
# and contributor agreement.
"""
Tests for the (internal) selections module
"... |
81d1021821e612366a59cbf795a791ac6ccbb57ee0f25ea1db6401c0bdd1c622 | Python | 4,892 | 104 | from CybORG.Shared import Observation
from CybORG.Simulator.Actions.Action import RemoteAction
from CybORG.Simulator.State import State
from ipaddress import IPv4Address
class DiscoverDeception(RemoteAction):
""" A Red action that probes a remote host to see if it is running any decoy services.
Attributes
... |
3b4066cda0e08e8107c4ff587b79134b03a7b20d403d375d7aa0a9f912bc55f1 | Python | 4,896 | 135 | import numpy as np
samplingRateLabjack = 1000
samplingRateNeuropoixels = 30000
def extractPulseTrains(
variableInput,
device='lj',
maximumWrapperPulseDuration=0.011,
minimumBarcodeInterval=3,
):
"""
"""
#
global samplingRateLabjack
global samplingRateNeuropoixels
# Identi... |
906988508764a567052b8781303609c19ce30503c4d30a522c143228f6d6b80c | Python | 4,896 | 144 | import pandas as pd
from itertools import combinations
from analysis import perform_and_save_analysis
from visualization import visualize_results
def apply_function_to_groups(df, group_col, func, *args, **kwargs):
"""
Applies a function to subsets of a DataFrame grouped by a specified column.
Parameters... |
2b0a61cb53f7af93252607fe4a03c95929d5db86b7aaf66facbc92066c66460b | Python | 4,897 | 166 | """Parameter classes"""
"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
This file is part of BluePyOpt <https://github.com/BlueBrain/BluePyOpt>
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License version 3.0 as published
by the Fre... |
1da7e989576d0ed78c68f87db56fa57d90b0e9cb1cb15f629d21ad8247e71a89 | Python | 4,904 | 173 | """Tests related to the `DataIter` interface."""
from typing import Callable, Optional
import numpy as np
from xgboost import testing as tm
from ..compat import import_cupy
from ..core import DataIter, DMatrix, ExtMemQuantileDMatrix, QuantileDMatrix
def run_mixed_sparsity(device: str) -> None:
"""Check QDM wi... |
b16b786453cc5bd095e1bb28ad343088ceedb9af17cf43abf134142dd3fe0330 | Python | 4,904 | 119 | import numpy as np
import matplotlib.pyplot as plt
import hickle as hkl
import os
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.linear_model import Perceptron
from grid_cell.slope_ploter import SlopeAnalysis, draw_two_li... |
ab33c3e5ca5daf8077fff5bddc3fc8ae773495fd15844f7b5eb3e8af35280ecf | Python | 4,905 | 146 | #!/usr/bin/env python
#
# Merge b=0 and dMRI data and output appropriate bvecs/bvals files
#
# Copyright (c) 2019 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
import textwrap
import numpy as np
from spinalcordtoolbox.utils.sys import init_sct, ... |
6057e008f215c84b4f4c00e1d70a86ef9bcf533c127d206dbcc5c281bfb33e97 | Python | 4,908 | 144 | """
Administration utilities for managing a neuprint server.
Using these tools requires admin privileges on the neuPrintHttp server.
"""
import re
import pandas as pd
from requests import HTTPError
from .client import inject_client
class Transaction:
"""
For admins only.
Used to batch a set of operations ... |
4b0e26ed2469c15628748fc45cdfa6b70669d27e7325cd594f46dfef5b57b777 | Python | 4,912 | 148 | from PIL import Image
import numpy as np
import pandas as pd
from tqdm import tqdm
import os
import yaml
import argparse
import inspect
import importlib
from shutil import copytree
import torchxrayvision as xrv
import torchvision
class Preprocessor:
def __init__(
self, img_path, csv_path, params_file, out... |
ce0f1e5294c29eddb34455d3616b76e017fc86fd431ebac15fbba24fc2eacc89 | Python | 4,912 | 127 | import os
import pandas as pd
from rano_monitor.constants import REVIEW_FILENAME, REVIEWED_FILENAME, MANUAL_REVIEW_STAGE, DONE_STAGE
from rano_monitor.messages import InvalidSubjectsUpdated
from rano_monitor.messages import ReportUpdated
from rano_monitor.messages import AnnotationsLoaded
from rano_monitor.utils import... |
027dd4dbb7c1de4f7a182e98a95f5c90927bccd3916747ba9791348da412c1fe | Python | 4,917 | 155 | #!/usr/bin/env python
# coding=utf-8
# Copyright 2023 Statistics and Machine Learning Research Group at HKUST. All rights reserved.
"""Alignment tuning example, such as RLHF."""
import logging
import os
import sys
sys.path.remove(os.path.abspath(os.path.dirname(sys.argv[0])))
from dataclasses import dataclass, field
f... |
00709f4a6ae02727e3461afb77bbc57601be2356663822d1d5bd1e9699bd6814 | Python | 4,920 | 113 | DOCS = """
train the model on the a dataset (gabor or mnist) and show the robustness of the model to occlusion.
currently figure 4.
"""
from dataset import GaborDatasetOrientation
from model import ShallowMLP
from experiment.utils import set_seed, init_model, Logger, Trainer, Checkpointer
from dataset.utils import Occ... |
1b87487bbfc162a6ab86f1dc794b215a1bad3038ac8a618767e4e232de507f0f | Python | 4,923 | 164 | #!/usr/bin/env python
# This script takes in a list of sequences (tab delimited) with the first row = sequence names, second row = sequences
import random
def read_file(RNAnamecheck, filename):
seqfile = open(filename, 'r')
RNAnamelist = []
RNAseqlist = []
RNAs = {}
seqID = 0
for line in s... |
a86ffcfe015eab549c4fed0f5435cbe0dc50a682dfec33125d3effbe33a96362 | Python | 4,923 | 143 | # Copyright (c) OpenMMLab. All rights reserved.
import math
import torch
import torch.nn.functional as F
from mmcv.cnn import ConvModule
from mmseg.registry import MODELS
from ..utils import SelfAttentionBlock as _SelfAttentionBlock
from .decode_head import BaseDecodeHead
class SelfAttentionBlock(_SelfAttentionBloc... |
83ca9a480559bbf3ef7f7823f87cce54c13fff3c07c00b4fde82ba8084d4409b | Python | 4,929 | 106 | # coding: utf-8
# Copyright 2019 Sinovation Ventures AI Institute
#
# 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... |
7b726655d494d7b85b5f154f16da394a66d6d1be204b9197174a2607571f23e6 | Python | 4,931 | 174 | import pytest
from kgx.sink import ArangoSink
from kgx.transformer import Transformer
from tests import print_graph
from tests.unit import (
clean_arango_database,
DEFAULT_ARANGO_URL,
DEFAULT_ARANGO_USERNAME,
DEFAULT_ARANGO_PASSWORD,
DEFAULT_ARANGO_DATABASE,
check_arango_container,
ARANGO_C... |
18c4b072ba81fd3c09962728aed128deeff6588aa9354219d097f95e414f09bd | Python | 4,932 | 144 | import jax
import jax.numpy as jnp
from functools import partial
from jax_md import partition
from jax_md.space import DisplacementOrMetricFn, Box, transform
from so3lr.graph import Graph
def neighbor_list_featurizer(displacement_fn, species, fractional_coordinates=True):
def featurize(R, neighbor, neighbor_lr,... |
1febf97aed442fee921faed2ebc864a3f837bfdadb3cc6cbbe24fe6363e57478 | Python | 4,935 | 138 | #!/usr/bin/env python
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from MCMG_utils.utils import Variable
class MultiGRU(nn.Module):
""" Implements a three layer GRU cell including an embedding layer
and an output linear layer back to the size of the vocabulary"""
... |
ebe8b72f80e878f7f3448d743234b6f4c1bed461f25f6ca80ea8491e0fcbaf58 | Python | 4,938 | 149 | import os
import logging
from medperf.entities.cube import Cube
from medperf.entities.asset import Asset
from medperf.entities.dataset import Dataset
from medperf.entities.execution import Execution
from medperf.utils import remove_path
import medperf.config as config
from medperf.exceptions import ExecutionError, Com... |
97b640a32a1f60fcb0b62c13f92f01fadcf806638d085c320e061e32c3938078 | Python | 4,939 | 167 | import numpy as np
from collections import namedtuple
from abc import ABC, abstractmethod
from collections import defaultdict
import math
import random
def create_new(tup, index, aaa, f):
flip = random.randint(0,5)
# if flip ==5:
# tup[index] += f.turn
# elif flip ==6:
# tup[index... |
37b62c8097ac6169fdbaa52ae9e4e2e3d9ed356e3150496fbb725293b0f58523 | Python | 4,941 | 126 | import numpy as np
import matplotlib.pyplot as plt
import pickle
from sklearn.decomposition import FastICA
import mne
def find_neighbors(ch_name, info):
"""
Identifies neighboring channels for a given channel name based on the EEG montage.
Parameters:
- ch_name: str, the channel name to fin... |
472befc27727ca6baef095304461e068aa9d9c17843e0efa49c1c5d82887021b | Python | 4,941 | 144 | from textwrap import indent, dedent
from ..utils import ensure_list_args, cypher_identifier
from ..client import inject_client
class MitoCriteria:
"""
Mitochondrion selection criteria.
Specifies which fields to filter by when searching for mitochondria.
This class does not send queries itself, but y... |
ce4f67202fe8744c5027ee18b8a0a7d457f67a64c6efb2554a46ef1083de82a6 | Python | 4,945 | 123 | # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# pyre-strict
import typing
from collections import defaultdict
import tabulate
from torch import nn
def parameter_count(model: nn.Module) -> typing.DefaultDict[str, int]:
"""
Count parameters of a model and its submodules.
Args:
... |
93c6ee3221ed87b62a1e93015420e8582f758ab900f345bfc9a06a97112cda63 | Python | 4,946 | 157 | # Code adapted from https://github.com/Sage-Bionetworks-Challenges/brats-dream-challenge-infra/blob/main/Docker/score.py
import argparse
import yaml
import os
import subprocess
import argparse
import sys
import pandas as pd
from normalized_surface_dice import compute_surface_dice_from_images
def run_captk(pred, go... |
99723c5252d819c373efafd80cdfba8ede35820f9314465261aa6261927f5458 | Python | 4,946 | 127 | import os
import cv2
import argparse
import pandas
import numpy as np
import scipy.io as sio
import random
import shutil
from skimage import io
random.seed(42)
# EXCLUDE_RECORD = [
# 'RP1_2T',
# 'AOOCT_113142_volume_001_threshold_05',
# 'AOOCT_144703_volume_001_averaged_volume_stack_threshold_061',
# ... |
5ed1efa5af2bec59ea70886c4c3eff6e760a91cb748f7c4cf29cd7aafeaa04a9 | Python | 4,948 | 150 | from onmf import onmf
from numpy import zeros, hstack
from warnings import filterwarnings
class iONMF:
""" Integrative orthogonal non-negative matrix factorization.
Parameters
----------
data: dictionary of array describing samples with multiple data sources.
data = {
"data_source... |
81d521406a5b465c32736544e8c776fcd1dc705cc03240588ce937969dbf4322 | Python | 4,950 | 129 | import numpy as np
import cv2
import torch
from yolov9_model import YOLOv9_GPU, YOLOv9_FPGA
from dataset_preprocessing import get_datasets, get_data_loaders
class DecisionMaker:
def __init__(self, use_fpga=False):
"""
Initialize the decision-making module for autonomous driving.
The system ... |
812b710aa5dd1ccab752006a170a2a53ec65d84ba1624f0b94c440c4c763718a | Python | 4,952 | 140 | """
Neural ODE Utilities for GNODEVAE
This module provides utility functions and classes for integrating Neural Ordinary
Differential Equations (ODEs) into the GNODEVAE framework. Neural ODEs enable
modeling of continuous-time dynamics in the latent space, which is particularly
useful for trajectory inference in singl... |
2a4462738d7631a30a66c1bf6f20d8aaa2c162763f57d13e9fed6ce69b380deb | Python | 4,954 | 124 | import sys
from pathlib import Path
import pandas as pd
import cv2
import time
from joblib import Parallel, delayed
import os
import shutil
def save_frames_as_images(src, dst, starts, ends):
dst = Path(dst)
dst.mkdir(exist_ok=True, parents=True)
cap = cv2.VideoCapture(str(src))
for start, end in zip(s... |
07285637f1d85d1893a1bc351c38a62ec3a5e79dfc5c579ac8276cb3d39e947b | Python | 4,956 | 163 | """Server settings REST API endpoints.
Manages server-wide configuration such as the default room
that new rooms copy from when no explicit `copyFrom` is provided.
"""
from fastapi import APIRouter
from pydantic import BaseModel
from sqlmodel.ext.asyncio.session import AsyncSession
from zndraw.dependencies import (
... |
b2bd1b19e928f5b78675af8616173bf386e0dd7ce2cf033d32bbfab9e38b4fd8 | Python | 4,957 | 175 | """
Copyright (c) Facebook, Inc. and its affiliates.
This source code is licensed under the MIT license found in the
LICENSE file in the root directory of this source tree.
"""
from typing import Tuple
import torch
from ..initializers import he_orthogonal_init
class EfficientInteractionDownProjection(torch.nn.Mod... |
d396d9a617cb36e9592a2d53102cd3d7288b7b212ec59836462cb1bfd33854cf | Python | 4,957 | 144 | """Tests for the OMIM data handler and the User-Agent header it sends."""
import os
from unittest.mock import MagicMock, patch
import pytest
from src.babel_utils import get_user_agent
from src.prefixes import OMIM
from tests.conftest import assert_labels_file_valid
@pytest.mark.unit
def test_get_user_agent_include... |
24553bd8f05d63bd38ed9c5b5e8c47578dc85a5e2032f4fc278dbef81649d00c | Python | 4,960 | 134 | import numpy as np
from scipy.stats import ttest_rel, wilcoxon, mannwhitneyu
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import seaborn as sns
def plot_delta_relevance_boxplot(df_all, merged_generative, merged_random):
"""
Plot boxplot of delta relevance and ... |
36201a5a7239e3876faadf549f9fafe5afba54b16bf3f89a2a1d4922ddbb0db1 | Python | 4,962 | 139 | import logging
from pathlib import Path
import numpy as np
import pandas as pd
import torch
from torch.utils import tensorboard
from typer import Typer
from .Helper_funs import training_utils as tu
from .Helper_funs.utils import configure_logging
from .main import ModelTask, data_loading
from .main import training as... |
b63dba2c23c2eb91cde85393c79cc5b347355d5d9af22815adfeed132aec4a21 | Python | 4,962 | 111 | import os
import numpy as np
import pandas as pd
from tqdm import tqdm
import sys
from unsloth import FastLanguageModel
import transformers
from datasets import load_dataset
import math
import argparse
def randomized_choice_options(num_choices):
choice_options = list(map(chr, range(65, 91)))
return np.random.c... |
fba6205bb4cb672ed331e56de32127d3c576ba2741a9d84ad0692f78fea090c5 | Python | 4,962 | 135 | import torch
import torch.nn as nn
from nnunet_mednext.utilities.to_torch import maybe_to_torch, to_cuda
from torch.cuda.amp import autocast
from nnunet_mednext.network_architecture.custom_modules.custom_networks.TransFuse.TransFuse import TransFuse_S as TransFuse_S_Orig
from nnunet_mednext.training.network_training.nn... |
20c617ae838578ed82b39b9a30c522375eb24164e5f2eeb44d908192baf7e7a1 | Python | 4,964 | 153 | import logging
import pathlib
from enum import Enum
import typer
import zntrack
from zndraw import ZnDraw
from simgen.utils import (
get_hydromace_calculator,
get_mace_similarity_calculator,
)
from simgen_zndraw import DefaultGenerationParams
from simgen_zndraw.main import SiMGen, SiMGenDemo
from .local_serv... |
7882f757361fdc813ee6e4767ec865e447c978c68dd7140a2aae509bc90c07ab | Python | 4,964 | 147 | """Display-time rendering for PSTH significance comparisons.
The estimate is drawn with its bootstrap confidence band, and the stretches whose
interval excludes zero are marked as a bar along the top of the plot. Keeping the band
rather than only the significance mask lets a reader see how close a non-significant
stre... |
e65b3147bdaf51b8793fd32fa8f4b69ba8d8cd3c15fc07071256a6c647607a30 | Python | 4,967 | 134 | import shutil
from pathlib import Path
import pytest
from guppy.testing import compare_output_folders
from guppy.testing.api import locate_run_folder, step1, step2, step3, step4
from guppy_test_data import TESTING_DATA, event_ts_offset_for
# The last field of each case is timeForLightsTurnOn. It now means "seconds o... |
7d319edcb75ac197124305e41e2dd578c5554929ec6dcacdc2a9c1ee2972bbe6 | Python | 4,969 | 138 | import requests
import os
from .ProvenanceObject import ProvenanceObject
from .dependency import Dependency
from .task_status import TaskStatus
from .dataset import DataSet
from .performance import Performance
from datetime import datetime
from .system_info import get_system_info
import json
dfa_url = os.environ.g... |
0a897238c6f4f62d1e886069ab2a63f7cc80628a9a15c7e69f23e415a13a0c18 | Python | 4,970 | 140 | import os
import pickle
import pandas as pd
import numpy as np
import pcntoolkit as ptk
from pcntoolkit.dataio.fileio import load as ptkload
from pcntoolkit.dataio.fileio import save as ptksave
from pcntoolkit.normative import predict, evaluate
from pcntoolkit.dataio.fileio import save_nifti, load_nifti
from pcntoolki... |
b6cdaedd8b00184eed82c8d760ad58e1d8822f33daa2ea8697c872e671512d5a | Python | 4,970 | 129 | # coding=utf-8
from collections import Counter
import torch
from torch import nn
# import seqeval
from .utils_ner import get_entities
class metrics_mlm_acc(nn.Module):
def __init__(self):
super().__init__()
def forward(self, logits, labels, masked_lm_metric):
# if len(list(logits.shape))==3... |
0ec2ec0da794689fdc9b3137f593d8d42921b1acff06bb38814b4c774f59a5fb | Python | 4,975 | 125 | import gmsh
from mpi4py import MPI
import numpy as np
# /home/thomas/Documents/PhD/Mouse_experiment_dolfinx/
# Code made for parallel running
mesh_comm = MPI.COMM_WORLD
model_rank = 0
gmsh.initialize()
#Characteristic length
lc = 5e-6
[Length, Width, Height] = [6e-4, 2.5e-4, 4e-5]
xc,yc,zc,dx,dy,dz, r = 6... |
b1241312af06ed3ebdef4b79216d98840973b95db6ef8e82eedbf4560122fcbc | Python | 4,980 | 148 | #!/usr/bin/env python
#
# Function to compute the Ernst Angle
#
# Copyright (c) 2015 Polytechnique Montreal <www.neuro.polymtl.ca>
# License: see the file LICENSE
import sys
from typing import Sequence
import textwrap
from spinalcordtoolbox.utils.shell import SCTArgumentParser, Metavar
from spinalcordtoolbox.utils.sy... |
e63b54d53c96378a55d5b388f34d3481617ec5c1e1c02aba1cc38db32fc0187c | Python | 4,980 | 134 | """
purity_dataset.py
This module defines the SingleCellData class for handling the single-cell RNA sequencing data used to train GBMPurity.
It includes functionalities for filtering samples with low cell counts, normalizing gene expression data,
and simulating bulk RNA-seq data from single-cell data. The class is des... |
ff21b9fb631c855e8f5ad37a90e90bfde9e9ef8bd9fc9355b951e27a161426da | Python | 4,981 | 170 | from time import sleep
import pytest
from neo4j import GraphDatabase
from kgx.sink import NeoSink
from kgx.transformer import Transformer
from tests import print_graph
from tests.unit import (
clean_database,
DEFAULT_NEO4J_URL,
DEFAULT_NEO4J_USERNAME,
DEFAULT_NEO4J_PASSWORD,
check_neo4j_container,... |
f9c23cbc967f29661a4a021b17210e95f545cf4bc7f2e667ee8e612b22744a7a | Python | 4,984 | 117 | import os
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def get_scores_by_retinal_location(model_paths):
results = {}
for model_name, model_path in model_paths.items():
results[model_name] = {
'<=4': {'cone_f1s': [], 'is_mae': [], 'os_mae': []},
... |
6e292c9a8ff639f7046201df9dba3c2c2caf7222580b888f5e18f819c33280a5 | Python | 4,986 | 127 | import os
import medperf.config as config
from medperf.entities.benchmark import Benchmark
from medperf.exceptions import InvalidEntityError
from medperf.utils import remove_path
from medperf.commands.compatibility_test.run import CompatibilityTestExecution
from medperf.comms.entity_resources import resources
class ... |
ca784cec33f0af058fcc47e1193157834a45213ca2d13db4b05c21ca9d7ad2fb | Python | 4,987 | 132 | # Bond lengths from:
# http://www.wiredchemist.com/chemistry/data/bond_energies_lengths.html
# And:
# http://chemistry-reference.com/tables/Bond%20Lengths%20and%20Enthalpies.pdf
bonds1 = {'H': {'H': 74, 'C': 109, 'N': 101, 'O': 96, 'F': 92,
'B': 119, 'Si': 148, 'P': 144, 'As': 152, 'S': 134,
... |
f41bca7197197bd6d8c2821d7e94184e71cb66b30d4406111b0bd2b82e08b4e3 | Python | 4,987 | 95 | import argparse
from fengshen import UbertPipelines
import os
os.environ["CUDA_VISIBLE_DEVICES"] = '6'
def main():
total_parser = argparse.ArgumentParser("TASK NAME")
total_parser = UbertPipelines.pipelines_args(total_parser)
args = total_parser.parse_args()
# 设置一些训练要使用到的参数
args.pretrained_model_... |
665c569f6cfa03bb57d5bb158f53df30f20949881e019606618f60ab92565d6d | Python | 4,988 | 134 | #! python3
# -*- encoding: utf-8 -*-
# ===================================
# File : test_model.py
# Time : 2024/06/04 15:32:49
# Author : Zehong Zhang
# Contact : zhang@fmp-berlin.de
# ===================================
import os
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
... |
95c9fbe50bbe91c098602f3790353610133f5ef8aeeb738cb3072a1ccb1175db | Python | 4,991 | 133 | # yapf: disable
# Inference Speed is tested on NVIDIA V100
hrnet = [
dict(
config='configs/hrnet/fcn_hr18s_4xb4-160k_ade20k-512x512.py',
checkpoint='fcn_hr18s_512x512_160k_ade20k_20200614_214413-870f65ac.pth', # noqa
eval='mIoU',
metric=dict(mIoU=33.0),
),
dict(
confi... |
861524fb1687d1d8d00a07867022449750d38e904743f8b7ea5cbd4c7de13602 | Python | 4,992 | 122 | from CybORG.Agents.SimpleAgents.FiniteStateRedAgent import FiniteStateRedAgent
""" *Creating Variant Red Agents*
```python
class MyVariant(FiniteStateRedAgent):
def __init__(self, name=None, np_random=None, agent_subnets=None):
super().__init__(name=name, np_random=np_random, agent_subnets=agent_subnets)... |
a980efc3f6fb590bd8e0d028093b02c59bd7c3b6a56daa5d3d5f25da3713e4c7 | Python | 4,992 | 124 | import argparse
from os import path as osp
from basicsr.utils import scandir
from basicsr.utils.lmdb_util import make_lmdb_from_imgs
def prepare_keys(folder_path, suffix='png'):
"""Prepare image path list and keys for DIV2K dataset.
Args:
folder_path (str): Folder path.
Returns:
list[str... |
55ea6291bda4f7d95dea87bdfbd0b2589a378a8806f4d0fb336e36af9fed8f5f | Python | 4,993 | 125 | import gmsh
from mpi4py import MPI
import numpy as np
# /home/thomas/Documents/PhD/Mouse_experiment_dolfinx/
# Code made for parallel running
mesh_comm = MPI.COMM_WORLD
model_rank = 0
gmsh.initialize()
#Characteristic length
lc = 5e-6
[Length, Width, Height] = [6e-4, 2.5e-4, 4e-5]
xc,yc,zc,dx,dy,dz, r = 6... |
d29af3b2ebcf2556b1a2628c95980f9ef24f473ad79cfeeb09161c62e278d829 | Python | 4,997 | 141 | # Copyright (c) 2021, EleutherAI
# This file is based on code by the authors denoted below and has been modified from its original version.
#
# 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
#
#... |
d68fea41a80b08b42c3262837f51c20ec56db6d752871a386c413e9a35db5624 | Python | 4,998 | 152 | import os
import numpy as np
import xgboost
kRounds = 2
kRows = 1000
kCols = 4
kForests = 2
kMaxDepth = 2
kClasses = 3
X = np.random.randn(kRows, kCols)
w = np.random.uniform(size=kRows)
version = xgboost.__version__
np.random.seed(1994)
target_dir = 'models'
def booster_bin(model):
return os.path.join(targ... |
fb76f99d11363f486bc8c2125bcc57409568aa453b149e9e75688823ba7d6e7b | Python | 4,999 | 127 | from collections import Counter
from collections import defaultdict
import matplotlib.pyplot as plt
from sklearn.preprocessing import normalize
import pdb
def draw_pseudo_heatmap_v2(adata,genelist,anno=None, clist=None, anno_list =None, gridspec_kw = {'height_ratios': [10,1]},figsize=(3,4),fontsize=12, mean_window = 1... |
2ea68fdce80186a7b5c33e642ddcbc81cb30d55494a306b472f14e097a000946 | Python | 5,000 | 178 | """Module for reading and writing nifti files using ANTsPy."""
import os
import ants
import nibabel as nb
import numpy as np
ras = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, -1.0]])
lpi = np.array([[-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0]])
class Nifti1Image:
"""Class for Nifti1Image obje... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.