sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
795b45a92d382b3ca2887d48fe2618512c7dd62de8870a6e446bd3fc844ee507 | Python | 3,071 | 58 | """ Some useful constants used throughout codebase """
DATASETS = {"avgfp": {"ds_name": "avgfp",
"ds_dir": "data/avgfp",
"ds_fn": "data/avgfp/avgfp.tsv",
"wt_aa": "SKGEELFTGVVPILVELDGDVNGHKFSVSGEGEGDATYGKLTLKFICTTGKLPVPWPTL"
... |
5141f7f9eef06038c0357da05396de15ae1c6ecfbea4cd802308214291e51318 | Python | 3,072 | 94 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import json
from types import SimpleNamespace
from cvat_sdk.api_client import ApiClient, Configuration
from cvat_sdk.api_client.api.tasks_api import TasksApi
from shared.utils.config import BASE_URL, make_api_client
def test_can_make_custom_requ... |
c602f99438b9a8b5bbab9cf2aef1f27f8df47528ef7762ebb889058bb410b916 | Python | 3,072 | 79 | from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, confusion_matrix, precision_score, recall_score, f1_score
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import time
import torch
class DecisionTreeClassification:
def __init__(self, train_dataload... |
dfd07e7f873e2cfd0959c8dce67b918bcafe8359df50622b6666b63e40aab650 | Python | 3,072 | 107 | # Copyright (c) DP Technology.
# 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 logging
import numpy as np
import torch.utils.data
logger = logging.getLogger(__name__)
class EpochLi... |
5a147988ffc7f6eb8f8ae640645cbe08efa79b3acf8a187ec4509eb390f186d4 | Python | 3,073 | 94 | #!/usr/bin/env python
# author: Jannes Spangenberg
# e-mail: jannes.spangenberg@uni-jena.de
# github: https://github.com/JannesSP
# website: https://jannessp.github.io
from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser, Namespace
import os
from pathlib import Path
from collections import defaultdict
fr... |
1455b7582258dc1dba7edde20eb4a49c9721951a5b8aa9a95bfde4cb7cf87eef | Python | 3,074 | 99 | # -*- coding: utf-8 -*-
import sys
import os
def setup(app):
app.add_css_file('custom.css')
extensions = [
'sphinx.ext.todo',
'sphinx.ext.mathjax',
'sphinx.ext.ifconfig',
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
# The suffix of source ... |
8129a243ce80bd45769e304e095d62f2ed6223fd1f7ed6ae94d02e79243ef5ab | Python | 3,075 | 92 | # %% ### import modules
from pathlib import Path
import pandas as pd
# %% read results table
results_dir = Path(__file__).resolve().parents[1] / "results"
# %% data
df = pd.read_excel(results_dir / "long_c_results_cox.xlsx")
# %% round intercept and coef to 3 decimal places. same for intercept_ste and coef_ste
df["h... |
fe88e7cad7055028cd757b14396cb81dad0d7282326f821918ba70ac736da22c | Python | 3,075 | 81 | import torch
import torch.nn as nn
import torch.nn.functional as F
# Ensure the resize_to_match function correctly matches the spatial dimensions of tensors
def resize_to_match(source, target):
target_size = target.size()[2:] # Extract spatial dimensions of target
source_resized = F.interpolate(source,... |
03fd944c83bd9e057f33722937e294abfbae0d7166b772f1bbd061efe05563c1 | Python | 3,076 | 74 | """Confirmation dialogs that look the same on every platform.
Qt lays dialog buttons out the way the host platform does, and the platforms
disagree about which end the affirmative button belongs on: Windows and most
Linux desktops put it first, macOS puts it last and focuses the other one. Left
to itself, "Reset all p... |
ae622e302cc0d4ca793bbdad6b32e12b7fe127da684976beaed63d406acba2cd | Python | 3,077 | 112 | import numpy as np
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.layers import (
Conv1D, Conv2D, MaxPooling1D, MaxPooling2D, Flatten,
Dense, Dropout, Activation
)
from tensorflow.keras.models import Model
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint
import m... |
0188c8188186593f622dab7a48817c8fc5343fa1edc16333012d63de984ec6b8 | Python | 3,078 | 93 | import json,time
import numpy as np
import pandas as pd
import os, subprocess
import argparse
from collections import OrderedDict
import operator
parser = argparse.ArgumentParser(description='Shape the answer')
parser.add_argument('--nbest_path', type=str, help='location of nbest_predictions.json')
parser.add_argumen... |
427b7dd7d0e29b16170198715579565941835a5d89657160c21347d8f0aa2f89 | Python | 3,078 | 122 | #!/usr/bin/env python3
#
# compare_config.py
#
# compare two by two all the provided files and print the one with fewer differences than the cutoff
#
# Copyright F. Nedelec, 2011 - 2016
"""
Compare two by two all the provided files and print the one with fewer differences
Syntax:
compare_config.py THRESHOLD ... |
7fb820c366e4542ba076fdc86ea58acb5ae5654296c342c0f4b8451b1224af51 | Python | 3,078 | 61 | import numpy as np
import os
import json
import tempfile
from ivim.io.base import read_im, write_im, write_bval
from ivim.preproc.signal_drift import temporal, spatiotemporal
# Paths to data
temp_folder = tempfile.gettempdir()
im_file = os.path.join(temp_folder, 'drift.nii.gz')
bval_file = os.path.join(temp_folder, 'd... |
9e0d13a9ce811eaad47bf5c6c024f79e66f71879824d3db0cbee14cecdd049ec | Python | 3,078 | 74 | from src.wrappers.OsipiBase import OsipiBase
from src.original.fitting.PvH_KB_NKI.DWI_functions_standalone import generate_IVIMmaps_standalone, generate_ADC_standalone
import numpy as np
import warnings
warnings.simplefilter('once', UserWarning)
class PvH_KB_NKI_IVIMfit(OsipiBase):
"""
Bi-exponential fitting a... |
10f9cb93d3bc8ca905c636877a82b9265543925c9736e2a160c3391c520e1edf | Python | 3,079 | 78 | # Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
from drf_spectacular.utils import extend_schema_serializer
from rest_framework import serializers
class SublabelMappingEntrySerializer(serializers.Serializer):
name = serializers.CharField()
attributes = serializers.DictField(child=serializ... |
8c28019104d6320f93cd53c8a1aaabf88c1313b28570528dc0194bdda62ce5f5 | Python | 3,079 | 65 | from zigzag.utils import pickle_deepcopy
from zigzag.classes.stages.Stage import Stage
# from zigzag.classes.stages.MainInputParserStages import WorkloadParserStage
# from zigzag.classes.stages.WorkloadStage import WorkloadStage
from zigzag.classes.stages.MPISaveStage import MPISimpleSaveStage
import logging
import co... |
bbd9f94dd71a4b2975fcf162f4b8f2a28f76626f2a4807651c03a4cf9432d44e | Python | 3,079 | 86 | """Consensus-clustering modularity, port of ``mod_consensus_cluster_iterate.m``.
Runs Louvain community detection (``louvain.py``) many times, builds a
consensus co-classification matrix (Lancichinetti & Fortunato 2012), and
repeats on the thresholded consensus matrix until it becomes block-diagonal
(stable partition)... |
8ca25e08e219d07108547e977f6c077cd84cca4dd66283803d9a9e811be13ba2 | Python | 3,080 | 79 | import numpy as np
from . import data_handling as dh
def make_stimfunc_lines(stimdict,styledict,horizontal=True):
if horizontal:
spanfn = 'axvspan'
linefn = 'axvline'
else:
spanfn = 'axhspan'
linefn = 'axhline'
def plot_stims(axarr,zord=-10,markpos=0.5):
for key,subd... |
7d64eb034033d8ac4e4a1d805d603e55e2d7108b214ca17bd00015ef8553f1ef | Python | 3,081 | 74 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['tractometry.zip'])
tmp_dir = tempfile.... |
b955adf13a082885b895159265ac8238b0e3e7b3002f88e7bb626bae78fa1da5 | Python | 3,081 | 106 | # coding=utf-8
"""
Tests for deepreg/train.py
pytest style
"""
import os
import shutil
import pytest
from deepreg.predict import main as predict_main
from deepreg.train import build_config
from deepreg.train import main as train_main
class TestBuildConfig:
# in the config, epochs = save_period = 2
config_... |
2939ddfd24b5cce03eed743c864d6883d432446831c1de242eeef76c40d20bd7 | Python | 3,082 | 91 | """
BlurPool layer inspired by
- Kornia's Max_BlurPool2d
- Making Convolutional Networks Shift-Invariant Again :cite:`zhang2019shiftinvar`
Hacked together by Chris Ha and Ross Wightman
"""
from functools import partial
from typing import Optional, Type
import torch
import torch.nn as nn
import torch.nn.functional a... |
e924068a9a76d3ca93bea9b3b6cdaaf146d46fa38b61e48138ab046a921c2b77 | Python | 3,082 | 88 | import os
import numpy as np
parallel_starts = 16
# args dict
args_dict = {'device': 1, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'epochs': 1000,
'eval_ste... |
5289d038b8833d293f89a85b03a835f2351c6042fcddea9438f5eee2f7345838 | Python | 3,084 | 64 | import os
from PIL import Image
from tqdm import tqdm
from deeplab import DeeplabV3
from utils.utils_metrics import compute_mIoU, show_results
os.environ["CUDA_VISIBLE_DEVICES"]='3'
'''
进行指标评估需要注意以下几点:
1、该文件生成的图为灰度图,因为值比较小,按照PNG形式的图看是没有显示效果的,所以看到近似全黑的图是正常的。
2、该文件计算的是验证集的miou,当前该库将测试集当作验证集使用,不单独划分测试集
'''
if __name__ =... |
c33b1ae36d95430ed3f167fa74d656347fd959ba8e674b6b92577283671c2ac2 | Python | 3,084 | 90 | import scanpy as sc
import pandas as pd
import numpy as np
import anndata
import warnings
from tqdm import tqdm
from scipy.sparse import csr_matrix
from sklearn.neighbors import BallTree
def get_activity_dataframe(adata):
obs_names = list(adata.obs)
activity_names = [v for v in obs_names if "activity_" in v]... |
cc6f3d3a6a784c7df3b48e8690f257c85db3e3392c5fb3509cb54dc4cff759e6 | Python | 3,084 | 75 | # -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'add_behavior_dialog.ui'
##
## Created by: Qt User Interface Compiler version 6.4.2
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
#######... |
45fe6cbed1dfff9162a899eb12c79b58ab5d48f2ae1ab3fd3e9c3eaefea51158 | Python | 3,085 | 89 | #!/usr/bin/env python3
import pandas as pd
import numpy as np
import os
import argparse
def get_header_size(pir_file):
"""
Get size of header (lines)
"""
with open (pir_file, 'r') as f:
line = f.readline()
return int(line.split(' ')[1])+1
def get_header(pir_file):
"""
Get header ... |
8b7bdaeb1c40891b0869c302bd4279b833d9987426160bd4d322f8d570f441bd | Python | 3,086 | 79 | import torch
import opt_einsum
import tensorly as tl
from tensorly.plugins import use_opt_einsum
tl.set_backend('pytorch')
use_opt_einsum('optimal')
def einsum_complexhalf_two_input(eq, a, b):
"""
Compute (two-input) einsum for complexhalf tensors.
Because torch.einsum currently does not support complex32... |
d2c2fb0c097bc4ee4c4dd15133d1346ad22277edcb30ad87a3c79fec74cac327 | Python | 3,086 | 92 | import numpy as np
import numpy.typing as npt
def cartesian_to_spherical(cartesian_vecs: npt.ArrayLike) -> npt.NDArray[np.float_]:
"""Calculates spherical coordinates in degree from cartesian coordinates
Parameters
----------
vec : npt.ArrayLike (N x 3)
Cartesian coordinates in the format [x,... |
ba88fe39e659ee5bd24055675e05b9dc619d62edf085954549c1e44e93976eb7 | Python | 3,087 | 71 | ################## PURPOSE #################
# This script is to restructure the 4th(start pos), 5th(end pos), 6th(copy number), and 7th(seg.mean) columns of the input file
# Because these columns hold the "raw" coordinates of the CNV after filtering out for IGLL, telomerics, centromeric
# and segup regions, we want to... |
b03019898d9fedab9d311cbca54aa2ce58b756189f0574274d2517c20e932a77 | Python | 3,089 | 58 | import os
from nipype.interfaces.base import (CommandLineInputSpec, CommandLine, traits, TraitedSpec, BaseInterface, BaseInterfaceInputSpec, File)
from traits.api import Directory, Str, List, Bool, Enum, Int, Float, TraitError, Either
# ***************************************************
# The following COMPULSORY opt... |
da3c418787ac89c207299658e49a57ffcad9864ce9a5c3f05deca758ce73d156 | Python | 3,089 | 93 | from dataclasses import dataclass
import numpy as np
from sklearn.preprocessing import KBinsDiscretizer
from eir.data_load.label_setup import (
al_label_transformers,
al_target_columns,
merge_target_columns,
)
from eir.setup import schemas
from eir.setup.schema_modules.output_schemas_survival import Survi... |
7f047893c21e92e225cc41503e2b966f36416564c4b94e191c9ebd3ad1fb7c8f | Python | 3,090 | 77 | from torch.utils.data import DataLoader
from geoseg.losses import *
from geoseg.datasets.cvc_clinic import CVC_Dataset
from geoseg.models.Unet import UNet
from catalyst.contrib.nn import Lookahead
from catalyst import utils
CLASSES=('background', 'foreground')
# training hparam
max_epoch = 100
ignore_index = len(CLA... |
66623d40f08e7b3a74ef162c440cbe4d28a69b6c00a342672de27ef6b93d7702 | Python | 3,091 | 66 | # 生成残基间相互作用的矩阵
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
import argparse
parser = argparse.ArgumentParser(
'Visualize the distribution of learned edges between residues.')
parser.add_argument('--num-residue... |
7e5ee0d8d9ecd923fb9acb28499d44554d57091f5f81375e1a731d8624d928b0 | Python | 3,092 | 86 | '''MobileNetV2 in PyTorch.
See the paper "Inverted Residuals and Linear Bottlenecks:
Mobile Networks for Classification, Detection and Segmentation" for more details.
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
class Block(nn.Module):
'''expand + depthwise + pointwise'''
def __init... |
0b7124974e2d05436efc6e9d72508030255d30aea3a65dc3fe059ec0074c2ff2 | Python | 3,093 | 89 | from collections.abc import Sequence
from dataclasses import dataclass
from typing import Literal
@dataclass
class ArrayOutputTypeConfig:
"""
:param normalization:
Which type of normalization to apply to the array data. If ``element``, will
normalize each element in the array independently. If... |
1d35ee10e7a97df37dbca95340d7e56d5a63ed4c37494a8546aee47160b97402 | Python | 3,095 | 77 | # !/usr/bin/env python
# coding: utf-8
# @Time : 2022/7/17 13:54
# @Author : Z.-H. G.
# @Email_0 : guozhenhao17@mails.ucas.ac.cn
# @Email_1 : guozhenhao@tongji.edu.cn
# @File : params.py
# @IDE : PyCharm
import pandas as pd
# TODO yaml
PARAMS = \
{'preprocess':
{
'path': './dataset/... |
92373a6fae735771001e119afe6990b123da982253f2ce906e62c5ea8d637070 | Python | 3,095 | 126 | """Example script for running HMM inference on simulated HMM-MVN data.
This script should take less than a couple minutes to run and
achieve a dice coefficient of ~0.99.
"""
print("Importing packages")
import os
import pickle
import numpy as np
from osl_dynamics.simulation import HMM_MVN
from osl_dynamics.data impo... |
1af2e71ddbb2a315032d1a06b7b52474aef5dad3eafabaa7849002b84a4bf9c0 | Python | 3,097 | 104 | import argparse
import logging
import os
from concurrent.futures import ThreadPoolExecutor
from preprocess_with_antspynet import preprocess_with_antspynet
from tqdm import tqdm
from pyment.utils.strip_extension import strip_extension
logging.basicConfig(
format='%(asctime)s - %(levelname)s - %(name)s: %(message)... |
2f5a92171244569270c7f653e6e860d01592fa9a0d9d889370450d8d2e525eda | Python | 3,097 | 86 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Compute distance map between two binary masks. The distance map is the
Euclidean distance from each voxel of the first mask to the closest
voxel of the second mask.
Slowest scenarios are 1) two very large masks that are far appart or 2) a very
small mask completely in... |
644559bb040c8bd71b8a992b72ba7fdf5fff8a75e69e34a003524a2a4ed6a26d | Python | 3,098 | 84 | import numpy as np
import tifffile
from matplotlib import pyplot as plt
from matplotlib.axes import Axes
from argclz import AbstractParser, argument
from neuralib.persistence.cli_persistence import get_options_and_cache
from neuralib.plot import plot_figure
from neuralib.plot.colormap import insert_cyclic_colorbar
fro... |
8b12151e37258e98270a2c5ffba5b4dc0a4471011ea154bb2ffd07001724cad7 | Python | 3,098 | 90 | """Caching utilities."""
import os
from collections.abc import Callable
from typing import Any
import numpy as np
import torch
from mcmlnet.utils.env import require_env
from mcmlnet.utils.logging import setup_logging
logger = setup_logging(level="info", logger_name=__name__)
def torch_to_np(
data: torch.Tenso... |
d8a0ebb059c1214b00c68fc1f32843702cab669f43c01e83c7f3562105b4c444 | Python | 3,098 | 106 | """
Tools for fusing contiguous alignment blocks together.
"""
from copy import deepcopy
def fuse_list(mafs):
"""
Try to fuse a list of blocks by progressively fusing each adjacent pair.
"""
last = None
for m in mafs:
if last is None:
last = m
else:
fused =... |
f560771338df7e05aac2ed159619f5f240a3ea6cdd268d0b75a82d90df306539 | Python | 3,098 | 84 | import warnings
warnings.filterwarnings("ignore", message="It is not recommended to directly access")
import torch
import numpy as np
from itertools import compress
from rdkit.Chem.Scaffolds import MurckoScaffold
from collections import defaultdict
def generate_scaffold(smiles, include_chirality=False):
"""
O... |
b7db13062247269c2aa76c01f98a2ab76c4e8cd8adff866fb87b0f0cd68e88b9 | Python | 3,099 | 114 | import json
import pandas as pd
with open('results/tables/mechanistic_benchmark.json', 'r') as f:
mech_results = json.load(f)
with open('results/tables/drl_vrfb_results.json', 'r') as f:
drl_results = json.load(f)
table_data = {
'Approach': [
'Mechanistic Solver',
'ANN (PEMFC) [2]',
... |
c43d116fcefb5200d82dbf02ca0eabc34bc90be564dd5e97aee4be033fb94fc4 | Python | 3,099 | 60 | import logging
import os
import click
import pandas as pd
from atom3.database import get_pdb_name, get_pdb_code
from parallel import submit_jobs
from project.utils.deepinteract_utils import check_percent_identity, construct_filenames_frame_txt_filenames
# -------------------------------------------------------------... |
cf4af2da6a991160546925e0ced48378041017228c591c1192549cdeff72ca47 | Python | 3,099 | 104 | # %%
from pathlib import Path
import pandas as pd
from scipy.stats import pearsonr
import statsmodels.api as sm
import numpy as _np
# %% load data
data_dir = Path(__file__).resolve().parents[1] / "data"
results_dir = Path(__file__).resolve().parents[1] / "results"
df = pd.read_excel(data_dir / "cs_baseline.xlsx")
# %... |
8b86aafbb9796f8f3060fdf13334d01883f833088da37ce2383b8461a143f597 | Python | 3,100 | 100 | from collections import OrderedDict
import mmcv
import numpy as np
import torch
def calculate(gt, pred):
if gt.shape[0] == 0:
return np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan, np.nan
thresh = np.maximum((gt / pred), (pred / gt))
a1 = (thresh < 1.25).mean()
a2 = (thresh < ... |
9f354ff904b10879742d11dfaba7802dde379b3c078480711dac3f1e5cf12463 | Python | 3,100 | 67 | from typing import Generator, Callable, List
from zigzag.utils import pickle_deepcopy
class Stage:
"""Abstract superclass for Runnables"""
def __init__(self, list_of_callables: List[Callable], **kwargs):
"""
:param list_of_callables: a list of callables, that must have a signature compatible ... |
052e071bdf2cd313fb20e17b0b310c4273d5086f755af2f1af376a32d701cc46 | Python | 3,101 | 106 | # -*- coding: utf-8 -*-
# external inputs
import numpy as np
def match_vertex_number(vtx_white, vtx_pial, fac, ind_white, ind_pial):
"""Match vertex number.
This function takes arrays of white and pial surface vertices as input and
matches the vertex numbers of both surfaces. The match is based... |
37740b79e4d5f1927b47aa120ef521fb6f48863e2505b446c828b9b8a8af75db | Python | 3,101 | 83 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
import os
import numpy as np
import pandas as pd
import pytest
import re
from bluepysnap import Circuit
from mock import Mock, patch
from numpy.testing import assert_array_equal
from sci... |
c0a9d50754040e2d6e6db6754b8a40d9d59eb80ab58d05eb4740219b632115f9 | Python | 3,101 | 88 | """Render a compact, four-view PNG preview of a labelled GIFTI surface."""
from __future__ import annotations
import argparse
from pathlib import Path
import nibabel as nib
import numpy as np
import vtk
def actor_for_label(points, faces, colour):
poly = vtk.vtkPolyData()
vtk_points = vtk.vtkPoints()
vt... |
d31fa0f13da153a0da9344a6ad495c501119fc1cea3deaf089881042fb2462f4 | Python | 3,101 | 78 | from nipype import IdentityInterface, Function
from nipype.interfaces.fsl import Reorient2Std
from PUMI.pipelines.anat.anat_proc import anat_proc
from PUMI.engine import NestedWorkflow as Workflow
from PUMI.engine import NestedNode as Node
from PUMI.pipelines.anat.func_to_anat import func2anat
from nipype.interfaces im... |
73af3a79ca2dfe2691a42e217ac6b641ecef4145f0b6de1b43fb0506cbc12356 | Python | 3,102 | 79 | import sys
from torch.utils.data import DataLoader
from geoseg.losses import *
from geoseg.datasets.segpc import SegPCDataset
from geoseg.models.deepunet.DeepUnet import Model
from catalyst.contrib.nn import Lookahead
from catalyst import utils
from torchinfo import summary
CLASSES=('background', 'foreground')
# tra... |
f2266ace19fd8256e0601559d06015e4bb2665514687df3fd23f6a955813babf | Python | 3,102 | 116 | # The ImpedanceFitter is a package to fit impedance spectra to
# equivalent-circuit models using open-source software.
#
# Copyright (C) 2018, 2019 Leonard Thiele, leonard.thiele[AT]uni-rostock.de
# Copyright (C) 2018, 2019, 2020 Julius Zimmermann,
# julius.zimmermann[AT]un... |
6a00827e6de56aa4f42d2100f2168bd33048740d0643a41502278822a0103794 | Python | 3,103 | 88 | """Custom TensorFlow optimizers."""
from typing import List, Tuple
from packaging import version
import tensorflow as tf
if version.parse(tf.__version__) < version.parse("2.12"):
from keras.optimizers.optimizer_v2.optimizer_v2 import OptimizerV2 as Optimizer
elif version.parse(tf.__version__) < version.parse("2... |
db3ac3858ba267b76792e2c7c2adf9c53ad52a99cb4def93007f6a3ebc042a68 | Python | 3,103 | 90 | #!/usr/bin/python
#
## @file
#
# A generic wrapper class for a spinning disk without a UI. All parameters are controlled from the Hal parameters editor.
#
# Jeff Moffitt 5/16
#
import storm_control.hal4000.qtWidgets.qtAppIcon as qtAppIcon
import storm_control.hal4000.halLib.halModule as halModule
import storm_control... |
69b8299fc34d3f0905f5c2ade63f85c8751075066060b93b4d4dd03241e591a7 | Python | 3,104 | 72 | #@ String (label="Image", choices={"Current image", "Image from path specified below", "None. Use demo image"}, style="listBox") choice
#@ File (label="Image file", required=false) impFile
#@ boolean (label="Skeletonize image") skeletonizeImp
#@ String(visibility="MESSAGE", value="<html><b>Disconnected Components:",per... |
c4e2e6d9e2012a58d6b8e5390c9d9f5d537a9bfbd934a2382cdb72cd3d957d9a | Python | 3,104 | 81 | import os
import numpy as np
import SimpleITK as sitk
from skimage.measure import regionprops_table
def get_mci_image(folder_path, core_name, sigma, percentage_removal):
file_path_mask = os.path.join(folder_path,core_name,'mask', f'{core_name}.nhdr') # mask
file_path_raw = os.path.join(folder_path,core_name,... |
1e5bef015bd0c684d930111f3d1f916422464119b50acce9c256b2e20d199ad7 | Python | 3,105 | 33 | from testsetclass import TestsetClass
class PNICO23(TestsetClass):
def __init__(self):
self.weak = 1.0
self.molecules = ['18b', '13a', '22a', '3b', '4b', '20', '18', '6a', '5b', '7a', '19a', '2', '3a', '23a', '11a', '17', '22', '17b', '9', '14a', '10b', '4a', '9b', '23', '14', '21', '12b', '12', '... |
795e02a7bc42a8c7800a396cd009955dc4b32300d851c1524facda15d5ae8d0e | Python | 3,105 | 79 | """The chunk-size seam.
``_load_and_sort_paths`` and ``_path_lookup_chunked`` read the volume lookup in
chunks to keep peak memory down. That chunking is where the most recent
regression happened, and with the size hardcoded at 1000 it is unreachable
below roughly a thousand view rows -- so a miniature fixture could n... |
b9f1f6a4f5b746590ff158f963a346dd26eeb9d865c4e58cee9e3faf425bf56c | Python | 3,105 | 107 | from collections.abc import MutableMapping
from typing import (
TYPE_CHECKING,
Literal,
NewType,
Protocol,
Union,
)
import torch
if TYPE_CHECKING:
from eir.models.fusion.fusion import al_fused_features, al_fusion_model_configs
from eir.models.fusion.fusion_default import al_features
fr... |
093d9f5985eda9680c2ce9b5f0933282ee095ed36dc9473d5bcccfc8b233bf32 | Python | 3,106 | 100 | from psychopy import prefs # noqa
prefs.hardware['audioLib'] = ['PTB', 'sounddevice', 'pyo', 'pygame'] # noqa
from psychopy import visual, core, event, sound, __version__, monitors
import os
from psychopy.hardware import keyboard
import random
# stop the script by pressing escape
def prepare_audio_stim(categories=... |
bc0dcc3c01b98c0906db68d0186fda28fbcacd567af6fcbf7098a646679096e0 | Python | 3,106 | 122 | '''
nd segmentation (label map) utilities
Contact: adalca@csail.mit.edu
'''
import numpy as np
from . import ndutils as nd
def seg2contour(seg, exclude_zero=True, contour_type='inner', thickness=1):
'''
transform nd segmentation (label maps) to contour maps
Parameters
----------
seg : nd array
... |
f802cdd811ed777079874d33c7977376f0903a147e85bda807646a4206d4ae5a | Python | 3,106 | 99 | import h5py
import os
import torch
import yaml
import numpy as np
from deepdwi import prep, util
from deepdwi.models import bloch, prox
from deepdwi.models import autoencoder as ae
from deepdwi.recons import linsub
DIR = os.path.dirname(os.path.realpath(__file__))
HOME_DIR = DIR.rsplit('/', 1)[0]
HOME_DIR = HOME_DI... |
6035e4447676abefd2473d3ce550f005aa4a8d6f9f6b9704080a2b80bc979dc2 | Python | 3,107 | 84 | # This file is part of connectome-manipulator.
#
# SPDX-License-Identifier: Apache-2.0
# Copyright (c) 2024 Blue Brain Project/EPFL
import json
import numpy as np
import os
import pytest
from bluepysnap import Circuit
from utils import TEST_DATA_DIR
from connectome_manipulator.connectome_manipulation.manipulation im... |
a7d4dbf5bdb77f21bd4d899b867530ae56cab77fb47577ebb2297b5d74773ed0 | Python | 3,107 | 85 | # This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
b4fcdc655fc0d143367cf759571d0d9a65332affed755dfa526b00124c859c20 | Python | 3,107 | 96 | # -*- coding: utf-8 -*-
from collections import namedtuple
from collections.abc import Iterable
from flair.parser.utils.field import Field
from flair.parser.utils.fn import isprojective
CoNLL = namedtuple(typename='CoNLL',
field_names=['ID', 'FORM', 'LEMMA', 'CPOS', 'POS',
... |
27428649ca29f3eba46f321a283cbcda74081bf5556d466ebbe5f5f3f8f7c689 | Python | 3,108 | 87 | import os.path as op
from typing import Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import AutoMinorLocator
def plot(input: str, output: str, voxel: Union[Tuple[float], None] = None) -> None:
"""Plots subject motion from eddy_qc output file.
Parameters
--------... |
391bac711616c9c85d17b77bab01e5f0295bb328ff975d88d838fdff95698b34 | Python | 3,108 | 80 | import torch
import torch.nn as nn
import torch.nn.functional as F
# Ensure the resize_to_match function correctly matches the spatial dimensions of tensors
def resize_to_match(source, target):
target_size = target.size()[2:] # Extract spatial dimensions of target
source_resized = F.interpolate(source,... |
29457cc3e4a57ef702963f5f3798ba54fbf955098eba5dd501632fa591f1e0f0 | Python | 3,109 | 98 | #-*- coding : utf-8-*-
import os
import csv
import pandas as pd
import time
import content_features as cf
from tqdm import tqdm
def caculate_feature(all_text, all_text_like, all_text_retweet):
vec = {
"id":'u',
"characters":cf.count_characters(all_text),
"hashtags":cf.count_hashtags(a... |
a89562c0d606045caa2fb9d30546680ff04d734bf9c01f52a6437a3d4ff1ad7f | Python | 3,109 | 73 | """Packaged skill protocol and broken-distribution regressions."""
import asyncio
import pytest
from chemgraph.skills.backend import BundledSkillsBackend
@pytest.mark.parametrize("asynchronous", [False, True])
def test_bundled_file_protocol(asynchronous):
backend = BundledSkillsBackend()
def call(name, *a... |
c221c36f3c5b35fb32bbbc156e3a7eefb22eb43fb591938a836de335407e5187 | Python | 3,109 | 72 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import tempfile
from scilpy import SCILPY_HOME
from scilpy.io.fetcher import fetch_data, get_testing_files_dict
# If they already exist, this only takes 5 seconds (check md5sum)
fetch_data(get_testing_files_dict(), keys=['atlas.zip'])
tmp_dir = tempfile.Tempor... |
45d55ac4a125c30e4a2db32162a70e13da12364f667bb89d38a774cb07b3687d | Python | 3,110 | 148 | import numpy as np
from impedancefitter.single_shell_wall import (
eps_cell_single_shell_wall,
single_shell_wall_model,
)
from impedancefitter.single_shell_wall_ellipsoid import (
eps_cell_single_shell_wall_ellipsoid,
single_shell_wall_ellipsoid_model,
)
# for single_shell_wall_model
c0 = 1.0
em = 10... |
883bc977747c1490cd94e32d1e2bb95e836d6014486e90c07997e00497bb40b2 | Python | 3,111 | 88 | import re
import os
import requests
def parse_a2m(file_content):
sequences = {}
seq_id = None
seq = ""
for line in file_content.split('\n'):
if line.startswith('>'):
if seq_id:
sequences[seq_id] = seq
match = re.search(r"\w+\|(\w+)", line)
i... |
99bd3130d8062e50603bb774842888957038314384c2b882a39721be42863268 | Python | 3,112 | 123 | import sys
def forwarddiff(y, h):
n = len(y)
res = []
for i in range(1, n):
res.append((y[i] - y[i-1]) / h)
return res
def slope_start(data, start=0, epsilon=0.0001, h=1.0):
d = data[start:]
n = len(d)
for i in range(1,n):
if abs(d[i] - d[i-1]/h) > epsilon:
... |
107c45057b50314840ab0cd6eb0665fb08962a328e3e315d8587f0dd07f330f7 | Python | 3,113 | 77 | from torch.utils.data import DataLoader
from geoseg.losses import *
from geoseg.datasets.ham10000 import HAM10000_Dataset
from geoseg.models.Unet import UNet
from catalyst.contrib.nn import Lookahead
from catalyst import utils
CLASSES=('background', 'foreground')
# training hparam
max_epoch = 100
ignore_index = len(... |
ccedd1e6f7c3530acb2b76f7c7b538f08e2a5757e6c9179db7ee62ff04386c2b | Python | 3,113 | 92 | # -*- coding: utf-8 -*-
"""
Vessel distance map
This scripts calculates a distance map to vessels found as ridge structures in a
GRE. If multiple inputs images are set, the geometric mean of all inputs is
computed.
"""
# python standard library inputs
import os
# external inputs
import numpy as np
import nibabel as... |
05ed54bfbbaf25226aa34a171b80f5a0ec6e473216036f30ede645b8c2af7458 | Python | 3,114 | 116 | from typing import Optional, List, Union
import skimage.io
import skimage.measure
import torch
import torch.nn
from fvcore.nn import FlopCountAnalysis
from fvcore.nn.parameter_count import parameter_count
from torch import Tensor
def get_volume(
x: Tensor, spacing: Optional[Union[List[float], Tensor]] = None
) -... |
50fcb4280ac5551a5f239e683c358ddc3a3fa224f2eb5d65a3cee18e7d40963c | Python | 3,114 | 85 | #!/usr/bin/env python3
# -*- coding: utf-8
"""
Script that runs embedding algorithms on simulated data.
Created on 2020/02/03
@author romain_lopez
"""
import os
import click
import numpy as np
import scanpy as sc
import matplotlib.pyplot as plt
from scipy.sparse import data
import seaborn as sns
import pandas as pd... |
a42aa40ecec188c4af1bb97e38389a90fc0bf1da5a59a45b12ce890d08582a08 | Python | 3,114 | 88 | #############################################################################
# Copyright (C) 2020-2026 MEmilio
#
# Authors: Patrick Lenz
#
# Contact: Martin J. Kuehn <Martin.Kuehn@DLR.de>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licen... |
40d8f059ccd8131675c111819a9baa61b9fab41ecd0b8054f83120ce385c66ac | Python | 3,115 | 97 | import math
import torch
from torch import Tensor
class PositionalEncoding(torch.nn.Module):
r"""The positional encoding scheme from the `"Attention Is All You Need"
<https://arxiv.org/abs/1706.03762>`_ paper.
.. math::
PE(x)_{2 \cdot i} &= \sin(x / 10000^{2 \cdot i / d})
PE(x)_{2 \cdo... |
5d1de00cb5e95a40d50da38da569e84a4f72d83befd8697085ed677b3f70e1ed | Python | 3,115 | 100 | import attrs
import numpy as np
import polars as pl
from typing import final, get_args
from typing_extensions import Self
from neuralib.registration import FieldOfView
from rscvp.util.util_gspread import USAGE_TYPE
__all__ = ['RSCObjectiveFOV']
COORDINATES_FIELD = ['medial_anterior', 'medial_posterior', 'lateral_ant... |
d3a5b179562ac25c2ffa1b43f4c257d8026ec1feb3e0ee01915c730c6ec694f6 | Python | 3,115 | 83 | import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
cmap_states = ListedColormap(["k","b","r"]) # custom colormap for the 3 states : 'forward', 'left' or 'right'
def plot_transition_matrix(ax, T, labels=["forward", "left", "right"]):
"""Routine to plot transition matric... |
71439a84fff6356245a5c2ea4c94ca6baa7604a6353f8f40ea9038cf6558ae2d | Python | 3,116 | 83 | #!/usr/bin/env python
"""
Emulated DAQ functionality.
Hazen 04/17
"""
import storm_control.hal4000.halLib.halMessage as halMessage
import storm_control.sc_hardware.baseClasses.daqModule as daqModule
import storm_control.sc_library.halExceptions as halExceptions
class NoneDaqModuleException(halExceptions.HardwareE... |
7d8590c5e0d01f4aba36534ed1e81d9b09900a3a6d87484eeaf3a2ad8a5083aa | Python | 3,116 | 81 | from pathlib import Path
from brainscore_core.supported_data_standards.brainio.stimuli import StimulusSet
from brainscore_core.supported_data_standards.brainio.packaging import package_stimulus_set
stimuli = []
image_paths = {}
stimuli_directory = '../datasets/colour/dnn/session-1'
'''
Dataset Meta Info (from https:... |
f6322a9a2ba451f4acf6b1941ba33d039329e116548461b7ae31d0f27f69588b | Python | 3,116 | 82 | from pathlib import Path
from diagrams import Diagram, Cluster
from diagrams.custom import Custom
from diagrams.programming.flowchart import StartEnd, Action, Database, StoredData
from diagrams.programming.language import Python, Sql, Matlab
def physiology_workflow():
with Diagram("Physiological Data Analysis Wo... |
689a55ecfb232cc22e1816db0dccbf2f9507cae665d360fd2299af590bba6599 | Python | 3,117 | 90 | """
Register functional resting state data to anatomical images
"""
import nibabel as nb
import numpy as np
import subprocess
import os
import glob
ROOT = '/Users/sebastiandresbach/data/s1Anfunco/Nifti'
# Set subjects to work on
subs = ['sub-12']
for sub in subs:
print(f'Processing {sub}')
funcDir = f'{R... |
0cf2cefdf20900950e7929008d5441fe1bf3afd083ff1b6bc8698cbefab25a8c | Python | 3,118 | 82 | import numpy as np
from dipy.core.gradients import gradient_table
from src.wrappers.OsipiBase import OsipiBase
from src.original.fitting.IAR_LundUniversity.ivim_fit_method_linear import IvimModelLinear
class IAR_LU_linear(OsipiBase):
"""
Bi-exponential fitting algorithm by Ivan A. Rashid, Lund University
... |
8f0ce1afb26df2d30c38c5e7a550377cfa23c334cb0effba6927672779335c3e | Python | 3,118 | 66 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
from __future__ import annotations
from ultralytics.models.yolo.detect.predict import DetectionPredictor
from ultralytics.utils import DEFAULT_CFG, ops
class PosePredictor(DetectionPredictor):
"""A class extending the DetectionPredictor class f... |
9bfce2622a1a8996f53c0c4310fd5ecb41a15cf93c5c16adf7646088d32a1e98 | Python | 3,118 | 84 | # Copyright (C) 2021-2022 Intel Corporation
# Copyright (C) CVAT.ai Corporation
#
# SPDX-License-Identifier: MIT
import json
from pathlib import Path
import pytest
from deepdiff import DeepDiff
from shared.utils import config
@pytest.mark.usefixtures("restore_db_per_class")
class TestGetResources:
@pytest.mark... |
9ca35ba4f813e555541e6530b3375bb612f91c8b1d30ab6ac31e63532c107155 | Python | 3,118 | 76 | import os
from cath_imem_2nd import Cath_imem,dataset_argument
from torch.optim import Adam
from torch_geometric.data import Batch,Data
from utils import NormalizeProtein
from Bio.PDB import PDBParser
from Bio.PDB.DSSP import DSSP
import torch.nn.functional as F
import torch
from tqdm import tqdm
import argparse
amin... |
c60b9825f510721a791bb899949445334481eb4d940f1f1bc80e2d1226ec2086 | Python | 3,118 | 91 | """
Joint angle computation from COCO-17 keypoint coordinates.
Ported from utils/kinematics.py (Chambers et al. 2020 pipeline).
Updated to use COCO-17 keypoint naming.
"""
import numpy as np
import pandas as pd
from kinescope.skeleton import JOINT_ANGLE_TRIPLETS, NECK
def get_joint_angles(df: pd.DataFrame) -> pd.D... |
a4ab668dc1079a461ccec3b5c8a7dc745195bb267d3abb16783f05928334c381 | Python | 3,119 | 72 | import torch
import torch.nn.functional as F
from tqdm import tqdm
import numpy as np
from utils.dice_score import multiclass_dice_coeff, dice_coeff
def evaluate(net, dataloader, device):
net.eval()
num_val_batches = len(dataloader)
dice_score = 0
iou_mean_score = 0
# iterate over the validation s... |
d052d7f87f8615ac7a92f24e6ced6b6a44b500a03bd6d2b3b8be7845575ce93f | Python | 3,119 | 99 | # Copyright (c) DP Technology.
# 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 Dict, Optional
import torch
import torch.nn.functional as F
from unicore import utils
from ... |
01b6778144d1d8272a4e365e76438bbbd4891cf7e51632617bc3fbd688c38554 | Python | 3,120 | 120 | #!/usr/bin/env python
#
## @file
#
# The HoloeyeThumbnail class.
#
# Hazen 07/14
#
from PyQt5 import QtCore, QtWidgets
## HoloeyeThumbnail
#
# This is used to show a reduced version of what is being shown
# on the Holoeye device.
#
class HoloeyeThumbnail(QtWidgets.QWidget):
changeScreen = QtCore.pyqtSignal(int)
... |
3271ede8365bd82a688fa82ac1cfc4af5fab37eccc494eb0b1079618d86ac545 | Python | 3,120 | 114 | import pytest
import numpy as np
import xdas
import seisbench.models as sbm
@pytest.mark.parametrize("model", [sbm.PhaseNet, sbm.EQTransformer])
@pytest.mark.parametrize("blinding", [(0, 0), (100, 100)])
@pytest.mark.parametrize("transpose", [False, True])
def test_das_wrapper_annotate(model, blinding, transpose):
... |
37e71a690893c3e119c516aed3911975fda16b8ed605de792f7c351eacbe3d59 | Python | 3,120 | 101 | """Chase/avoid task with predators, prey and an occluder.
The predators (red circles) chase the agent. The agent receives reward for
catching prey (yellow circles), which disappear upon capture. There is an
occluder (gray rectangle) in the arena.
"""
import collections
import numpy as np
import os
from moog import a... |
9e630e382f2b77804b1eb50fbb2058c8cdbbc93a4aa3099c0facc31489718b9d | Python | 3,120 | 102 | import sys
import cebra
import os
import tempfile
import torch
import pandas as pd
import numpy as np
import pickle as pkl
import matplotlib
import cebra.models
import cebra.models
import cebra.data
from cebra.models.model import _OffsetModel, ConvolutionalModelMixin
from torch import nn
from scipy import stats
from ce... |
07b0d962cfecc144d7b305748c0c7bfcd57172206f718801d11248f35f1dd72d | Python | 3,121 | 97 | import numpy as np
def tuning_curve_discrete(angle, signal):
"""Compute the tuning curve and tuning factor of a signal
given a discrete experimental parameter.
Parameters :
------------
:angle: 1D array
discrete experimental parameter in time.
:signal: 1D array
signal in time... |
0800afee283a96a218ab0b8a8a95633971dcade99b3db2a6f37f56adbda1d566 | Python | 3,121 | 90 | import os
import numpy as np
parallel_starts = 8
# args dict
args_dict = {'device': 6, # gpu
'log_steps': 1,
'num_layers': 3,
'hidden_channels': 256,
'dropout': 0.0,
'batch_size': 64 * 1024,
'lr': 1.e-03,
'epochs': 1000,
'eval_ste... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.