sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
d9413e3336fe444c96994778180c7682243b1aaf29689f4e1c2bb884626ea45d | Python | 11,896 | 270 | """
API for functions used in the sct_deepseg_lesion CLI script
Copyright (c) 2022 Polytechnique Montreal <www.neuro.polymtl.ca>
License: see the file LICENSE
"""
import os
import logging
import numpy as np
from scipy.interpolate import interp1d
from spinalcordtoolbox.image import Image, add_suffix, zeros_like, emp... |
68dfbd3c7087d8d8e887ae5e02b080e9cc54501dde2c9b1396e1164888ea7790 | Python | 11,904 | 350 | """Unit tests for Storage, Composite, and Redis result backends."""
import asyncio
from unittest.mock import AsyncMock
import pytest
import pytest_asyncio
from redis.asyncio import Redis
from zndraw.result_backends import (
CompositeResultBackend,
RedisResultBackend,
StorageResultBackend,
)
# ==========... |
46aa37b98f036a90129f1528cfe243e68db6d71d2efad9a20a8b24a55416e941 | Python | 11,906 | 363 | # create transforms for training, validation and test dataset
## TODO: Make Transforms more dynamic by directly building from config args
## Maybe like this
## TFM_NAME=config.transforms.keys()[0]
## tfm_fun=getattr(monai.transforms, TFM_NAME)
## tmfs+=[tfms_fun(keys=image+cols, **config.transforms[TFM_NAME], prob=pro... |
055f23be28f03b2222436fda6d6d38dfa47ce5e47635c867847a569bc5877bad | Python | 11,914 | 335 | import logging
import os
from pyalfe.data_structure import PipelineDataDir, Modality
from pyalfe.image_processing import ImageProcessor
from pyalfe.image_registration import ImageRegistration
from pyalfe.roi import roi_dict
class CrossModalityRegistration:
"""This task registers all the modalities to target moda... |
33bb040558c2b56014a7e0e447873993f8f54ad1c23b5492d9b378a6e7342f24 | Python | 11,915 | 487 | # -*- coding: utf-8 -*-
import numpy as np
from plotly.graph_objs import Bar, Box, Figure
import plotly.offline as off
def graph_mean_median(title, column_names, summary, online=False):
"""
Compute plotly graph with mean and median stats
Parameters
----------
title : string
Title of the ... |
1a9d9d5f9dc4686989e1577b37b2bf7b479f1a492a3e476742d6419a34952ce7 | Python | 11,934 | 298 | '''
Unit test for the low level vds interface for eiger
https://support.hdfgroup.org/HDF5/docNewFeatures/VDS/HDF5-VDS-requirements-use-cases-2014-12-10.pdf
'''
import os.path as osp
import tempfile
import numpy as np
import h5py as h5
from ..common import ut, make_name
class TestEigerLowLevel(ut.TestCase):
def... |
d4f70d107ccff35bc076d86dd3f868eba316d90fa555edfc668c5c59d0100dcf | Python | 11,946 | 358 | """Trajectory REST API endpoints for file download and upload.
Provides browser-downloadable trajectory files with format selection,
drag-and-drop upload from the frontend, and temporary download tokens
for browser/wget downloads without Authorization headers.
"""
import io
import re
import uuid as _uuid_mod
from typ... |
57733c6de7460cdc44d20a4ebbc7e43164c348fc1ffc97abb8a88ad2799dcc50 | Python | 11,947 | 287 | import numpy as np
import pandas as pd
from gph import ripser_parallel
from grid_cell.manifold_fitter import GP_Fitter, Avg_Fitter, label_mesh
from scipy import stats
from grid_cell.util import Shuffled_Matrix
from ripser import Rips
from sklearn.metrics.pairwise import pairwise_distances
from scipy.spatial.distance im... |
00416d1a255ce6a3e22d6bac9d243afd7ce9b564f5317120178d12c6c16f21dc | Python | 11,958 | 299 |
# MIT License
# Copyright (c) 2017 Sriram Ravindran
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, me... |
9e98cb428a35f241a18696ee380230eff4203a32a56dd68b93a383194ab474eb | Python | 11,979 | 259 | import logging
import multiprocessing as mp
import numpy as np
from guppy.extractors import (
CsvRecordingExtractor,
DandiNwbRecordingExtractor,
DoricRecordingExtractor,
NpmRecordingExtractor,
NwbRecordingExtractor,
PyPhotometryRecordingExtractor,
TdtRecordingExtractor,
detect_acquisit... |
e0d7a5a415fa2a250fbe8df5dfc0098acd7947f29d09ccf42043e0803cbed323 | Python | 11,980 | 290 | # 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... |
110a874f7497a53973f968c41d4f0659a57aa5645af10f21b1bae2436a2ad0a4 | Python | 11,981 | 337 | """
Entrypoint for training nanopore classification models
"""
import argparse
import pandas as pd
from sklearn.metrics import confusion_matrix
from tqdm import tqdm
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchsummary import summary
from resnet1d imp... |
86afc7c88d983d209b14edf0d89eea348525d4042ebbb14c09fa5a377472e312 | Python | 11,988 | 339 | # I may be missing import statements, so add if you find something I missed
import os
import pandas as pd
import numpy as np
# from tqdm import tqdm
from sklearn.decomposition import PCA
from sklearn.cross_decomposition import PLSCanonical, CCA
from sklearn.preprocessing import StandardScaler
from scipy.stats import p... |
cfbd9bf5e3aa24150db93d340451060e12a2d4ffbf0125f12f77832aee0c0fd8 | Python | 11,988 | 322 | from __future__ import annotations
from gymnasium import Space, spaces
from CybORG import CybORG
from CybORG.Simulator import State
from CybORG.Simulator.Actions import Action
from CybORG.Simulator.Scenarios.EnterpriseScenarioGenerator import (
EnterpriseScenarioGenerator,
)
from typing import Any
import numpy a... |
8fb6e238dfa113f1b397053d9620ff7264df06e92f6517904eb7ea410b119181 | Python | 11,990 | 322 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
def writeHTMLHeader(filename, title=''):
with open(filename, 'w') as f:
f.write('<!DOCTYPE html>\n<html>\n<body>\n')
f.write('<h1>'+title+'</h1>\n')
def writeHTMLFooter(filename):
with open(filename, 'a') as f:
f.wr... |
113c1df6e53725c97dbd50354eb3efd929c6fa89eb127ac39505b17ffff93093 | Python | 11,999 | 280 | from ml_training.dataset_hidden import (TrainDataset, TestDataset, ValDataset, extract_data)
from ml_training.model import GRU_Hidden, LSTM, BasicTransformer, LocalTransformer
from ml_training import config
from torch.nn import BCEWithLogitsLoss
from torch.optim import Adam
from torch.utils.data import DataLoader
from ... |
5a85d2c9acd055eb26f3c6230946b5f677d73301a9bbf6b98da7a55183a8ca2d | Python | 12,017 | 337 | import math
import numpy as np
import torch
import torch.nn as nn
# from einops import rearrange
import torch.nn.functional as F
from .model_Transformer import GPTDecoderLayer, GPTDecoder
from MCMG_utils.utils import Variable
device = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')
class decoderTrans... |
17e27cdfef99d742657c233459286b057b4321972fcff3436b30059a4fc2a454 | Python | 12,024 | 295 | #!/usr/bin/env python3
"""
Prepare dimer XYZ files for SO3LR calculations.
This script takes an XYZ file containing a dimer structure that contains
charge=0 charge_a=0 charge_b=0 selection_a=1-2 selection_b=3-4 benchmark_Eint=-0.090
(like this one: https://github.com/Honza-R/NCIAtlas/blob/main/geometries/NCIA_D1200/... |
abbe22d51001c226200d9e70e1be6c425418e777279462c1c3d6753f99fcb967 | Python | 12,033 | 386 | # -*- coding: utf-8 -*-
#
# mytest documentation build configuration file, created by
# sphinx-quickstart on Sat Dec 19 19:34:52 2015.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# Al... |
f264935cc19421d7414f09420635561fca99327140e6b7845cbf8efd85996d3d | Python | 12,040 | 383 | import tempfile
import pandas as pd
import numpy as np
import itertools
from statistics import stdev
from statistics import NormalDist
# from fdr_plotting import hist_feature
import matplotlib.pyplot as plt
import math
import re
from sklearn.model_selection import train_test_split
from sklearn.model_selection impo... |
49304927e59dd9a35f3c89c7a639e9f62f1a709a48402ebd6f2d85dcb4786755 | Python | 12,079 | 323 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import imageio
import os
import sys
import numpy as np
import SimpleITK as sitk
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.nets import inception
from geomstats.special_or... |
71ff536eecf9baeb878c871920489edbf310ffdbd7ab65a4f13f214f17c29f8b | Python | 12,081 | 293 | import os
import shutil
import yaml
from pathlib import Path
import subprocess
from typing import Dict, Any, Optional, Union, List
from ..logger import logger
import contextlib
import pkg_resources
class WorkflowError(Exception):
"""Custom exception for workflow errors"""
pass
@contextlib.contextmanager
def w... |
daf24dda648c6294805ad3e02f63361a9843fbab59637c9f5902e885c5c00338 | Python | 12,095 | 284 | ##
## CPCantalapiedra 2020
import gzip, os, sys
CLEAN_OVERLAPS_ALL = "all"
CLEAN_OVERLAPS_CLANS = "clans"
CLEAN_OVERLAPS_NONE = "none"
CLEAN_OVERLAPS_HMMSEARCH_ALL = "hmmsearch_all"
CLEAN_OVERLAPS_HMMSEARCH_CLANS = "hmmsearch_clans"
##
def process_overlaps(hits, clean_overlaps, CLANS_FILE, idmap_idx = None):
if ... |
b469afe91867a4cf971e0dc4ee0bbf0e9880254a1bb509a20b20256dc01b1017 | Python | 12,097 | 397 | """Unit tests for GIF export CLI module."""
from __future__ import annotations
import io
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, PropertyMock, patch
import pytest
from zndraw.cli_agent.gif import _assemble_gif, _build_schedule, _get_session
if TYPE_CHECKING:
from pathlib import Pa... |
2dd50f328f2d516f317d33b8c936b21e1d6db5c66fccce2f70f4893ca11c4398 | Python | 12,098 | 294 |
# The following was copied and modified from the source:
# https://github.com/kaapana/kaapana/blob/26d71920d53c3110e2494cbb2ddb0cbb996b880a/data-processing/base-images/base-nnunet/files/patched/run_training.py#L213
# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Hei... |
f4d15976e63275dcb1a077c424762e4c3ad01f782ed2ebc29f45e71d1a0d2cb2 | Python | 12,098 | 207 | #!/usr/bin/python
"""
This file to run ABC-DLS for parameter estimation of a given model
"""
import argparse
import os
import sys
from Classes import ABC
from Classes import Misc
from _version import __version__
# input argument is done
parser = argparse.ArgumentParser(description='This file will run Parameter estim... |
f0b78489c757b9fe8acf7addf3f98aedd4fe9c0a857701ef58749855db38dfcb | Python | 12,099 | 299 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def get_first_trigger(df_row, t_first_trigger):
if (df_row['trial_block'] == 1) and (df_row['countdown_response.keys'] == 't'):
# start of the countdown display and response screen should happen simulatenously:
countdown_display_started = df_row['count... |
e6a5994650a2bee29ff6b725919be5a9852c2536d89beb06537f65b77d1650a3 | Python | 12,100 | 283 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from sklearn.neighbors import KDTree
from sklearn.metrics.pairwise import euclidean_distances
def cluster_label(dbscan_centers_df):
label_dict = {'index': [], 'coordinates': [], 'label': []}
for idx, row... |
188cc2f220ef362b288cf8e7481c73a7c9c6d743c98b93c21875fb771c149d69 | Python | 12,101 | 299 | import numpy as np
import pytest
import torch
from mace.calculators import mace_off
from mace.tools.scatter import scatter_sum
from simgen.calculators import MaceSimilarityCalculator
from simgen.utils import get_system_torch_device_str, initialize_mol
torch.set_default_dtype(torch.float64)
DEVICE = get_system_torch_... |
a3df4600bd0e9af99367acf139af233af8c49cb497d819328837215c1c216e16 | Python | 12,103 | 377 | """Simulator classes"""
# pylint: disable=W0511
import os
import logging
import imp
import ctypes
import platform
import warnings
import pathlib
from bluepyopt.ephys.acc import arbor
logger = logging.getLogger(__name__)
class NrnSimulator(object):
"""Neuron simulator"""
def __init__(self, dt=None, cvod... |
1c191a42b54b4f604c27699ff46dbe911873f6bafda8bf9ffa5fc1fbf716b2aa | Python | 12,109 | 213 | from generateHTML import *
from weightAnalysis import *
from getActivity import *
import argparse
def writeActivitySection(reportFile, simTag, objFolder, calcDistance=False, epoch=-1):
# this section generates the metrics that cover the activity of the network
# each metric is often broken down by excitatory (... |
4759ee4f4e46f7f563d624d3fb3d08f5a1c43e3174646ea74ad2f4a2a3cb8c2d | Python | 12,111 | 279 | '''
Joint training of VGAE and MLP models for feature reconstruction and graph-level prediction.
Both models are newly initialised, no pre-trained model loading.
Authors: Hanna M. Tolle
Date: 2025-01-08
License: BSD 3-Clause
'''
import sys
sys.path.append('graphTRIP/')
from sacred import Experiment
from experiments.... |
c75f607ec4e0918029d6d03ab508a78b339c224e9a77b2bbf70ab4713055c73c | Python | 12,114 | 407 | """Screenshot REST API endpoints for room screenshots."""
import base64
import json
from pathlib import Path
from typing import Annotated
from fastapi import APIRouter, Form, Query, Response, UploadFile, status
from sqlalchemy import func
from sqlmodel import col, select
from zndraw.dependencies import (
AccessE... |
8600511530c3b1c25a4675e6a4ab72e3f8d1ff587a08a6b6c96e06554ab5d9e4 | Python | 12,116 | 384 | from rest_framework import status
from medperf.tests import MedPerfTest
from parameterized import parameterized, parameterized_class
class MlCubeTest(MedPerfTest):
def generic_setup(self):
# setup users
mlcube_owner = "mlcube_owner"
other_user = "other_user"
self.create_user(mlc... |
98f5967f23c70712dd895bcfc496875457daf80171fa4a171615d4fb6337d91a | Python | 12,116 | 281 | from transformers import AutoTokenizer, BartForConditionalGeneration, BartConfig
from pytorch_lightning import (
LightningModule,
Trainer,
)
from pytorch_lightning.callbacks import LearningRateMonitor
from dataclasses import dataclass
import os
import argparse
import torch
import math
import time
from torch.uti... |
60e0d72ee72546dc5fd6de0f213bc46d6b8ed64466498c65c58236d165438111 | Python | 12,118 | 336 | import os
import subprocess
import pandas as pd
import numpy as np
from pathlib import Path
from typing import Dict, Any, List, Optional
from concurrent.futures import ThreadPoolExecutor
from ..logger import logger
class SegmentationError(Exception):
"""Custom exception for segmentation errors"""
pass
def val... |
72cafb32b91ccc4be9e9bd1fbb38c603cf37ad3d3fd42a9b8c46bc83d2e0a313 | Python | 12,122 | 361 | """bluepyopt.ephys.simulators tests"""
"""
Copyright (c) 2016-2022, 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 publis... |
e66ee08ea85a7072626ad5a20ba941f08611cd85051bbcd37d35a625a472c598 | Python | 12,127 | 387 | import argparse
import os
import time
import numpy as np
import open3d as o3d
from feater import io
from matplotlib import colormaps
from pytraj import Trajectory
from siesta.scripts import view_obj
element_color_map = {
# BASIC ELEMENTS
12: [0.5, 0.5, 0.5],
1: [1, 1, 1],
14: [0, 0, 1],
15: [
... |
a9af30d159e28db6f9f4a9aeffe8e564e8787feb56a9cdb524115ca384dbebc7 | Python | 12,131 | 370 | import pytest
import numpy as np
from numpy.testing import assert_allclose
from keras import backend as K
from keras import layers
from keras.models import Model
from keras.models import Sequential
from keras.utils.test_utils import layer_test
from keras import regularizers
from keras import constraints
from keras.lay... |
d8db5a4094231e5d138691775a026d212b01319d95107093e5875c0ab5d92f55 | Python | 12,139 | 307 | import dgl
import copy
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from utils import get_func
from dgl import function as fn
from functools import partial
from torch.nn import Sequential, Linear, ReLU, BatchNorm1d
# dgl graph utils
def reverse_edge(tensor):
""" Implement edge rev... |
cff6e5d0667f5cbe9390c652dde01d536974e1e18769d809841d4ecb8bc665e8 | Python | 12,140 | 258 | from freesurfer.samseg import initVisualizer, requireNumpyArray, gems
from freesurfer.samseg.io import GMMparameter, kvlReadCompressionLookupTable, \
kvlWriteCompressionLookupTable, kvlWriteSharedGMMParameters
from freesurfer.samseg.merge_alphas import kvlGetMergingFractionsTable, kvlMe... |
3f8fde07301be4ce76293db9b52df9422e4dd5dcfa431555f8b3ee93ed73f5bf | Python | 12,145 | 388 | """Simulator classes"""
# pylint: disable=W0511
import ctypes
import importlib.util
import logging
import os
import pathlib
import platform
import warnings
from bluepyopt.ephys.acc import arbor
logger = logging.getLogger(__name__)
class NrnSimulator(object):
"""Neuron simulator"""
def __init__(
s... |
0fde0055489944806388bcd05a91b46c9f64c8a24b523c0c0b9082673d72e836 | Python | 12,147 | 376 | # -*- coding: utf-8 -*-
# encodermap/misc/xarray_save_wrong_hdf5.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Sawade, Tobias Lemke
#
# E... |
63e329f51d545fe33212265a224575f4ef9b25931ec977958c3684580dd82d2d | Python | 12,149 | 260 | import numpy as np
from collections import Counter, defaultdict
from time import time
import re
from glob import glob
from sklearn.base import clone as CLONE
import warnings
from sklearn.exceptions import ConvergenceWarning
import sklearn.metrics as metrics
# Imputation
from sklearn.experimental import enable_iterativ... |
fbf23c920fbcd2c3f062e78d994b6249ff6efe84ea45f2705016b07e53d8c52d | Python | 12,150 | 287 | import unittest
from unittest.mock import patch
import numpy as np
import pandas as pd
import torch
from DiastereomericResolutions.main import ModelTask
from DiastereomericResolutions.main.data_loading import (
MolecularRepresentation,
ReactionRep,
_load_reps,
_node_name,
_rep_name,
compress_r... |
77a58fdb359e39eb05dd5355d79c71d53e7513ba38783de48feeaf2ec9018038 | Python | 12,151 | 291 | import logging
import math
import numpy as np
logger = logging.getLogger(__name__)
def compute_psth(
z_score: np.ndarray,
event: str,
filepath: str,
nSecPrev: float,
nSecPost: float,
timeInterval: float,
bin_psth_trials: float,
use_time_or_trials: str,
baselineStart: float,
b... |
43483d173216d8193c2e9f097cd8315c7c1db2a031843ee8e230b5b3600f14b0 | Python | 12,154 | 331 | """
Base class for Riemannian metrics.
"""
import logging
import numpy as np
import geomstats.vectorization as vectorization
EPSILON = 1e-5
class RiemannianMetric(object):
"""
Base class for Riemannian metrics.
Note: this class includes sub- and pseudo- Riemannian metrics.
"""
def __init__(sel... |
3ab0efc2d83b5eae05cbe73ae84e0bad7d0363a750440ee96216f8a727c58810 | Python | 12,156 | 240 | # pytest unit tests for sct_process_segmentation
import pytest
import logging
import numpy as np
import tempfile
import nibabel
import csv
from spinalcordtoolbox.scripts import sct_process_segmentation, sct_image
from spinalcordtoolbox.utils.sys import sct_test_path
from spinalcordtoolbox.image import add_suffix
log... |
7e32cd9e1551075ef87507c479f9a0f69738bda27338b67253e6ed7df830f7b0 | Python | 12,157 | 338 | from typing import Dict, List, Optional, Tuple
import numpy as np
import torch
from torch import nn, Tensor
from torch_scatter import scatter_mean
from oa_reactdiff.model import EGNN
from oa_reactdiff.utils._graph_tools import get_subgraph_mask
from oa_reactdiff.model.util_funcs import radius_graph_pbc, get_pbc_dista... |
a6bbb2096213f104ce9bbe6a29b8fc3d54dd59cf193df2c0549c9d59d64412d0 | Python | 12,157 | 236 | # 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... |
c0c6642246ac0936ed23703a56b4a4abdde4d1d4afe61863001901ef5b40fe29 | Python | 12,161 | 389 | #!/usr/bin/env python
"""
MetaWIBELE: ddi_DOMINE_SIFTS module
Based on SIFTS DBs, divide DDIs into known human+bacterial DDIs vs. interologs
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation f... |
82317c15494717285d9ffffcd42add488fe5b4bbacc88d8d6d779ec92922e51a | Python | 12,162 | 366 | from typing import Dict, Union, Optional
from kgx.error_detection import ErrorType, MessageLevel
from kgx.utils.infores import InfoResContext
from kgx.prefix_manager import PrefixManager
from kgx.config import get_logger
log = get_logger()
DEFAULT_NODE_CATEGORY = "biolink:NamedThing"
DEFAULT_EDGE_PREDICATE = "biolin... |
419736a801a7dc5ec4adcce183d89d4fb90281631c305038f49edb9172247047 | Python | 12,163 | 395 | # #############################
#
# Copyright (C) 2018
# Jennifer Dreiling (dreiling@gfz-potsdam.de)
#
#
# #############################
import zmq
import pickle
import numpy as np
import os.path as op
from configobj import ConfigObj
import matplotlib.pyplot as plt
from scipy.optimize import least_squares
rstate = ... |
715ab24745b2b29cdcc4a3d545e02bda8ad076ed65a2d5757e615d767f5b046a | Python | 12,163 | 279 | import numpy as np
import nibabel as nib
import skimage
import tensorflow.keras.backend as K
from tensorflow.keras.losses import mean_squared_error as mse
import tensorflow as tf
from .. import wm_peak_normalize
def dice_coef_loss2(y_true, y_pred):
area_reg = 0.1
y_true /= K.sum(y_true, axis=-1, keepdims=Tr... |
cb6993a86ef4e681d251bdc13368ea6dabd6449b171e6c1537640af89fd573e6 | Python | 12,178 | 330 | # Copyright (c) OpenMMLab. All rights reserved.
import math
from typing import Sequence
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import build_conv_layer, build_norm_layer
from mmengine.model import BaseModule
from mmengine.utils import to_2tuple
class AdaptivePadding(nn.Module):
"""App... |
139b3778a26aa3d3c04c459b1c90700c9e61c7079cf8188344caf6e0edc5d16c | Python | 12,182 | 339 | import torch
import numpy as np
import dgl
import os
import math
import pickle
import json
import copy
import torch.utils.data as data
from collections import defaultdict, Counter
from tqdm import tqdm
from utils import get_enc_len, int2onehot, \
batch_convert_tensor_to_tensor, batch_convert_array_to_array
INF = f... |
40bec5b9e3b74a8800a6636c0655c59aee4129179bf540c5e0974e46eb35a32d | Python | 12,185 | 382 | """
Calculate everything to do with travel and outcome grids.
"""
# Import packages
import numpy as np
import pandas as pd
import copy
# For keeping track of files:
import os
from dataclasses import dataclass
# Custom packages:
from stroke_outcome.continuous_outcome import Continuous_outcome
def main(fixed_times, pa... |
c3704bc5f73ca5fb31fbe9ce2cb427c4d49d03373c37a79b76ad427b03b9479d | Python | 12,186 | 344 | import torch
import itertools
import json
import hashlib
import os
from matplotlib.ticker import FormatStrFormatter, StrMethodFormatter
import umap
from matplotlib import pyplot as plt
import torch.nn as nn
import torch.optim as optim
import torch_geometric
import torch_scatter
import torch.multiprocessing as mp
from ... |
d210d2e051efe2698241ec865f01be4a254bb6ed578b5f9848274cf30da1710d | Python | 12,188 | 350 |
"""
Implements a new custom setuptools command for handling library
configuration.
The "configure" command exists to provide a set of attributes that are
used by the build_ext replacement in setup_build.py.
Options from the command line and environment variables are stored
between invocations... |
4f4f8a14a456d2a58f9c5573ab5da22fea2a02db72187960479bb5fb55fd11bf | Python | 12,196 | 320 | import argparse
import datetime
import logging
import math
import random
import time
import torch
from os import path as osp
from basicsr.data import create_dataloader, create_dataset
from basicsr.data.data_sampler import EnlargedSampler
from basicsr.data.prefetch_dataloader import CPUPrefetcher, CUDAPrefetcher
from b... |
89a6df82c2b7753f52f88b5e4b7ee56bf1ab6ab53661c23f3c323cb943a93dfa | Python | 12,201 | 269 | import pandas as pd
import numpy as np
import processing.impute_fncs as impute_fncs
from nilearn.signal import clean
import time
expt_type_dict = {
"Av_Vol" : lambda R_Side, L_Side : (R_Side + L_Side) / 2 ,
"Tot_Vol" : lambda R_Side, L_Side : (R_Side + L_Side) ,
"Vol_R_side" : lambda R_Side, ... |
976db93be2bf5fbcfd8a519e86acd8fc3c5aa880a3034f37d8cffaccd5f10ca2 | Python | 12,201 | 284 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import cm
from sklearn.neighbors import KDTree
from sklearn.metrics.pairwise import euclidean_distances
def cluster_label(dbscan_centers_df):
label_dict = {'index': [], 'coordinates': [], 'label': []}
for idx, row... |
53040a831528a8e445228ae858049978e6ebb5a2ae06a6517a658568028aca2d | Python | 12,208 | 294 | import pytorch_lightning as pl
import torch.nn as nn
import torch.nn.functional as F
import torch
import timm
from torchvision import transforms as T
import open_clip
import sys
import torch
import json
from transformers import BertModel, BertTokenizer
from PIL import Image
from diffusers import StableDiffusionPipeline... |
f6e829e34338e069a2b6bad830ed0106d6f7126b5884740986f02c9cae32495c | Python | 12,209 | 274 | # 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... |
6bdc98d8990dfeb61855e6a8ce6980a97828be9f62ddce0a507e59aac9e5405e | Python | 12,216 | 264 | import gzip
import pytest
from src.datahandlers.ncbigene import (
GENE_INFO_HEADER,
pull_ncbigene_labels_synonyms_and_taxa,
split_ncbigene_synonym_field,
)
from src.predicates import HAS_SYNONYM
from tests.conftest import (
assert_descriptions_file_valid,
assert_labels_file_valid,
assert_synon... |
57604b4a8d5a43f988b58a1975e993cd8322252bf4a4d1dc59800996109c65a2 | Python | 12,218 | 317 | # coding=utf-8
# Copyright 2021 The IDEA 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 a... |
9e320a2009d92b571b22cda970de8b8c4b6d9dfaed6c0cd8f2cc280ed24a4f73 | Python | 12,218 | 340 | """Tests for the users router endpoints (/users/*)."""
import uuid
import pytest
from httpx import AsyncClient
from zndraw_auth import TokenResponse, UserCreate, UserRead, UserUpdate
async def _register_and_login(
client: AsyncClient, email: str, password: str, login_form_class: type
) -> tuple[UserRead, dict[... |
76b2bbc9b1497bda2ec4f9f47c24c35903be2b6ec9d8a5baed59e1d41882a465 | Python | 12,225 | 232 | 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_orig = []
times_orig = []
for i in range(len... |
9b0dc554bb2c0e8255ccb75d11afdafb6f53ef520198cf8187f7ed4fbf579468 | Python | 12,227 | 216 | # 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... |
21b6d16e21ee3e7ac1b9668fecd32f4b883d442a8231f6236fee08158397c6c3 | Python | 12,228 | 238 | # 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... |
6d3116ea3c0ff71cc5c9fad5874fecdb32b476b4aa660c0393512b6513ff64ab | Python | 12,233 | 323 | # Copyright (c) OpenMMLab. All rights reserved.
"""Modified from https://github.com/bermanmaxim/LovaszSoftmax/blob/master/pytor
ch/lovasz_losses.py Lovasz-Softmax and Jaccard hinge loss in PyTorch Maxim
Berman 2018 ESAT-PSI KU Leuven (MIT License)"""
import torch
import torch.nn as nn
import torch.nn.functional as F
f... |
e5648467bc0a039305873073371ca8e3f4dd614e3709fffd0c6701689cad0302 | Python | 12,233 | 214 | from generateHTML import *
from weightAnalysis import *
from getActivity import *
import argparse
def writeActivitySection(reportFile, simTag, objFolder, calcDistance=False, epoch=-1):
# this section generates the metrics that cover the activity of the network
# each metric is often broken down by excitatory (... |
e484aee1d3c3b1d9e7fb5c9b7ec69e342f390fe87a00a50b4014e41bc8b1f355 | Python | 12,235 | 348 | import argparse
import json
import os
import time
from collections import OrderedDict
import numpy as np
import nearl.features
import nearl.featurizer
from nearl.io.traj import MisatoTraj, Trajectory
# Define the way to generate labels for the database-indexed trajectories
class _PreserveNewlinesHelpFormatter(argp... |
c4c5c32019d37c276a71209d3754509b9aa5189f5a4b05fd1e0da6dab97658fa | Python | 12,239 | 373 | """Tests of the experimental MPI extension."""
import json
import os.path
import sys
from collections.abc import Generator, MutableMapping
from importlib.resources import files
from io import StringIO
from pathlib import Path
from typing import Any, cast
import pytest
from ruamel.yaml.comments import CommentedMap, Co... |
9c7a9fc5a0f4127f83d6242e4856e74233f4b90fd5f121cf53963bba4f134319 | Python | 12,240 | 231 | import argparse
import os
import platform
import sys
from pathlib import Path
import torch
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLO root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from mod... |
8570c4c27e4539e7f4c990f14aff24fd758b512a1cc36cb07790a565917d4057 | Python | 12,243 | 266 | #!/usr/bin/env python
#
# This program takes as input an anatomic image and the centerline or segmentation of its spinal cord (that you can get
# using sct_get_centerline.py or sct_segmentation_propagation) and returns the anatomic image where the spinal
# cord was straightened.
#
# Copyright (c) 2013 Polytechnique Mon... |
9db1242b36e3df0078bf9516c48614b5e80a92a33e62a3c976f158e2655a5efb | Python | 12,256 | 350 | import os
from configparser import ConfigParser
from functools import cached_property
from types import SimpleNamespace
from pyalfe.data_structure import (
DefaultALFEDataDir,
BIDSDataDir,
PatientDicomDataDir,
Modality,
)
from pyalfe.image_processing import Convert3DProcessor, NilearnProcessor
from pya... |
2be7bcf7196c565e693e5ba860484ca39a682acb51704c36c904a6dd00db452e | Python | 12,259 | 340 | #!/usr/bin/env python
#
# Copyright 2008, Google Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list... |
572d9cd557aa41e920cd55a434852c32ccd62ccd46b8ecef3e124934a8ee21f3 | Python | 12,261 | 393 | """
Simple script for managing Python, R, and source release packages.
tqdm, sh, and build are required to run this script.
"""
import argparse
import shutil
import subprocess
import tarfile
import tempfile
from pathlib import Path
from typing import Dict, List, Optional, Tuple
from urllib.request import urlretrieve
... |
0a25442321ef1592e0e9686632af63bad85748d1c1e80844c8698091481e52e1 | Python | 12,267 | 312 | from pathlib import Path
from typing import Optional
import torch
import numpy as np
import mrcfile
from ..data.handlers.particle_image_preprocessor import ParticleImagePreprocessor
from ..data.dataloaders.relion import RelionDataset
from torch.utils.data import DataLoader
from ..utils.utils_new import pdb2points
from ... |
10b94fb2b375addbbe65d07d1907da96352d116be9d90cf25299731e7d71e295 | Python | 12,269 | 296 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This script will create a new CATMAID release based on the current branch and
# date. Specifically, it does the following:
#
# 1. Determines release name from date and prompts for confirmation
# 2. Creates release branch
# 3. Creates release commit updating CHANGELOG.md... |
bab07ba11cc4a272f079dbaa6823ef7eba640e4edda23c3c6787a966da6bc35d | Python | 12,270 | 232 | import argparse
import os
import platform
import sys
from pathlib import Path
import torch
FILE = Path(__file__).resolve()
ROOT = FILE.parents[0] # YOLO root directory
if str(ROOT) not in sys.path:
sys.path.append(str(ROOT)) # add ROOT to PATH
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
from mod... |
67f13af1a6f536686051f25f9fdce2cff323f3b02e7e01ad390e339e88bde125 | Python | 12,271 | 269 | # pytest unit tests for sct_compute_snr
import numpy as np
import pytest
import logging
import skimage
import tempfile
import nibabel
from spinalcordtoolbox.scripts import sct_compute_snr
logger = logging.getLogger(__name__)
# Declare the signal intensity in the object created in the dummy_*() functions. This obje... |
f2f68cd584c1a869fd4a447e1aae41c1443339f4ffb335078c0ad2806a26aba8 | Python | 12,275 | 382 | #!/usr/bin/env python
import os
import sys
import re
import subprocess
import csv
import gzip
import bz2
# ---------------------------------------------------------------
# utilities used by MetaWIBELE-tools
# ---------------------------------------------------------------
# indicator of a comment line or the heade... |
46a4865f902517cbc6e28ffd060a746ca48ec9b47bf4b3c51934973ea5eab92e | Python | 12,285 | 306 | # pytest unit tests for sct_maths
import os
import pytest
import traceback as tb
import logging
import numpy as np
from spinalcordtoolbox.image import Image, compute_dice
from spinalcordtoolbox.utils.sys import sct_test_path
from spinalcordtoolbox.scripts import sct_maths
logger = logging.getLogger(__name__)
@pyt... |
600c095d1005bd42ea47dd8ea83c7610886a19115905ade19ebddc40a7dc5dea | Python | 12,293 | 370 | """bluepyopt.ephys.simulators tests"""
"""
Copyright (c) 2016-2022, 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 publis... |
2ca43665e813d8d45aad09db86bd0440bc38d56419d8c7121fae00c6fe270948 | Python | 12,296 | 401 | # SPDX-License-Identifier: Apache-2.0
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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/licen... |
f15a2bbac69619df96f73ce5ddfda87ebdcb1112aa54255a8b635f7d1662381a | Python | 12,296 | 362 | """Tests for ASE constraint serialization through encode/decode, storage, and client."""
import uuid
import ase
import numpy as np
import pytest
import pytest_asyncio
from ase.calculators.singlepoint import SinglePointCalculator
from ase.constraints import FixAtoms, FixBondLengths, FixedLine, FixedPlane
from asebytes... |
86bb33b4a2d2613cdb752515f64130b8502f9ac810f645e3d82590816cbd2eed | Python | 12,298 | 327 | import importlib
import torch
from collections import OrderedDict
from copy import deepcopy
from os import path as osp
from tqdm import tqdm
from basicsr.models.archs import define_network
from basicsr.models.base_model import BaseModel
from basicsr.utils import get_root_logger, imwrite, tensor2img
loss_module = impo... |
01691b8c4d8c3d3d19b9a79e324c78ebb73a1aa013502145698f21ea96abf04f | Python | 12,301 | 356 | import torch
import math
def _mel_to_hertz(mel, htk):
"""
Converting mel values into frequency
"""
mel = torch.as_tensor(mel).type(torch.get_default_dtype())
if htk:
return 700. * (10 ** (mel / 2595.) - 1.)
f_min = 0.0
f_sp = 200.0 / 3
hz = f_min + f_sp * mel
min_log_hz ... |
d2b36218051a741a96b0bff01e19072689bad4a4480b6d811e18be7b062dc0e6 | Python | 12,302 | 349 | # -*- coding: utf-8 -*-
# encodermap/loss_functions/loss_classes.py
################################################################################
# EncoderMap: A python library for dimensionality reduction.
#
# Copyright 2019-2024 University of Konstanz and the Authors
#
# Authors:
# Kevin Sawade, Tobias Lemke
#
# E... |
38217907b4273fb113cc9816f3b606c5467e424bbfe07bc644bcc6c6193813a5 | Python | 12,303 | 388 | import typer
import time
from typing import Optional
import medperf.config as config
from medperf.decorators import clean_except
from medperf.entities.cube import Cube
from medperf.commands.list import EntityList
from medperf.commands.view import EntityView
from medperf.commands.mlcube.create import CreateCube
from med... |
d2f244c826a1c0ada9439f762ec1d90c63755ee4a056477623047bc588984bfe | Python | 12,307 | 356 | import torch
import numpy as np
from sklearn.cluster import KMeans
from sklearn.metrics import (
normalized_mutual_info_score,
adjusted_mutual_info_score,
silhouette_score,
davies_bouldin_score,
calinski_harabasz_score,
)
from sklearn.decomposition import (
PCA,
NMF,
... |
fa9b88e9e92793f18023204977119b0308841d69eda9bb5898f502d2998271ae | Python | 12,311 | 306 | import os
import dgl
import csv
import torch
import numpy as np
import pandas as pd
from rdkit import Chem
from rdkit import RDConfig
from rdkit import RDLogger
from rdkit.Chem import MACCSkeys
from rdkit.Chem import ChemicalFeatures
from rdkit.Chem.BRICS import FindBRICSBonds
from const import *
from dataset import *... |
8bcc7647a8d886ae007428fafd1c3703622ff310e6e2975a2958686d88858761 | Python | 12,346 | 303 | # -*- coding:utf-8 -*-
'''
Author: MrZQAQ
Date: 2022-03-29 14:06
LastEditTime: 2023-03-01 22:24
LastEditors: MrZQAQ
Description: turely model execute file
FilePath: /MCANet/RunModel.py
'''
import os
import random
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim ... |
57ffadf10524e87242c0b5fba5c8d48dfc5433ff02aa2d88899dae9e923ec869 | Python | 12,347 | 298 | import argparse
import json
import re
import stat
import sys
from pathlib import Path
HEADER_RE = re.compile(r'^\s*#\s*(?P<title>.+?)\s*$')
SEPARATOR_RE = re.compile(r'^\s*#\s*={5,}\s*$')
DATASET_IN_TITLE_RE = re.compile(r'\s*\(dataset:\s*(?P<dataset>[^)]+?)\s*\)')
# FIXME: List of dataset zip assets published on th... |
c6544f34f113d6fe921cf03992607b45c93e99f16ff9f5b6b1d5df5b77e2b2c6 | Python | 12,348 | 320 | ## The following code contains work of the United States Government and is not subject to domestic copyright protection under 17 USC § 105.
## Additionally, we waive copyright and related rights in the utilized code worldwide through the CC0 1.0 Universal public domain dedication.
"""
Pertaining to actions that establi... |
db73104c1ab76a7d2c5167a66f0ebbdd10b5ed936aeebabe19439d6a42f91d77 | Python | 12,350 | 309 | # %%
#example usage: python synthetic_generator3T.py --Dw 0.12 --rho 0.05 --RatioDw_Dg 20 --gm_path "/path/to/gm_file.npy" --wm_path "/path/to/wm_file.npy" --out_dir "/path/to/output_directory"
import argparse
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.co... |
34c10e4f09782bfd60b57052dc35a63fd47c0889761970bec6706320355fd2cc | Python | 12,360 | 312 | # 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... |
d4ac3eee8bbe2cd3a55c00fb46cb538ffadca884ed67238f5db62b376dc990ca | Python | 12,367 | 254 | import pandas as pd
import numpy as np
import diffrax
import jax
import jax.numpy as jnp
from models.manual_implementations.glycolysis.glycolysis_model import glycolysis,NeuralODE
def overwrite_y0_dict(y0_dict, dataset):
"""Overwrites the y0 dictionary with the values from the dataset"""
ynew_dict = y0_dict.c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.