sha256
stringlengths
64
64
language
stringclasses
28 values
size
int32
1
491k
lines
int32
1
23.2k
content
stringlengths
1
200k
94fceaa71a2186094a0340180b23860610a3665504b4848fc0af0a941bc61217
Python
3,015
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=['processing.zip']) tmp_dir = tempfile.T...
03b057a5bdb9a848be086af459333b172b45b7dfebf9871e351a7913c5c3adc1
Python
3,016
62
"""A module that contains unit tests for the :py:mod:`corelay.processor.affinity` module.""" import typing import numpy from scipy.sparse import csr_matrix from scipy.spatial.distance import pdist, squareform from corelay.processor.affinity import RadialBasisFunction, SparseKNN class TestSparseKNN: """Contains...
195dc80b25755e5bb0500221924a7702e5b1114e9f16d5db8ef0d6f6f28b6a3f
Python
3,016
82
import json import torch import pandas as pd import numpy as np from torch_geometric.data import Data from torch_geometric.loader import NeighborLoader def generate_graph_loader(dataset="Twibot-20", num_neighbors=40, num_layers=3, batch_size=256): # node = json.load(open(f"../../datasets/{dataset}/node.json", "r"...
b9079c3d10e9cc07c1119ebd0ba5e2aa2931efa8b89b556cfd280577e8920ea0
Python
3,017
96
# -*- coding: utf-8 -*- import numpy as np from scilpy.dwi.operations import compute_dwi_attenuation, \ detect_volume_outliers, apply_bias_field def test_apply_bias_field(): # DWI is 1 everywhere, one voxel at 0. dwi = np.ones((10, 10, 10, 5)) dwi[0, 0, 0, :] = 0 mask = np.ones((10, 10, 10), dty...
10b2a0dc08abba5429e8f7f59f336c8e7b06141830899d0944cae9c3c2cd3110
Python
3,018
70
import subprocess import torch from batchgenerators.utilities.file_and_folder_operations import save_json, join, isfile, load_json from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer from torch import distributed as dist class nnUNetTrainerBenchmark_5epochs(nnUNetTrainer): def __init__(self,...
20c77536a5db0670b6c0bd88f7de77b6c37f3945c7cf6f7b11319b556e8202e4
Python
3,018
85
import pickle import warnings warnings.filterwarnings("ignore") import argparse from nltk import ToktokTokenizer, WordNetLemmatizer if __name__ == "__main__": # please download data from https://data.stanford.edu/congress_text and place in the folder ./data/hein-daily # Reference: https://data.stanford.edu/c...
7b1fde31cfab90483ec1bad02f17773889648190171b481f4d30529d4cfe8c5b
Python
3,018
109
#!/usr/bin/python3 # import os import sys import argparse import numpy as np from sklearn.neighbors import NearestNeighbors from uac import utils # Create the parser my_parser = argparse.ArgumentParser(description="Writes vtx files for volumetric UAC") # Add the arguments my_parser.add_argument("target_path", metava...
7d10c853314955c914e02ec7b941c535f112c4aff506d4d52eab7ddc2d8492f4
Python
3,019
90
#!/usr/bin/env python3 """ Example: SMILES -> RDKit 3D conformation -> XYZ file. Requires: - RDKit (e.g. `conda install -c conda-forge rdkit`) Usage: python examples/conformation_generation/01_smiles_to_rdkit_xyz.py \ --smiles "CCO" \ --out rdkit.xyz """ from __future__ import annotations import argpars...
e70377d73cbb8203cc47ba7f71e3d240080e1f7ed4bf2bd4d1382fc240419f99
Python
3,019
104
# Copyright (c) DP Technology. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np import torch import contextlib def str_hash(text: str): hash = 0 for ch in text: hash = (hash * 281 ^ ord(ch) * 997) & 0xFFFFFF...
39554f844f8e35083c59e92cc9b18515e417e167a8c12f0f9425ccc9c33a2b95
Python
3,020
87
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT import json import base64 import io import yaml import numpy as np from PIL import Image from mmpose.apis import MMPoseInferencer def init_context(context): context.logger.info("Init detector...") det_config = ( "/opt/nuclio/mmpos...
fba7897471af61bf03a4de03007a00e020b8bfb211b7bbfc42fcb5123c510a1d
Python
3,020
72
''' Python file with the purpose of a shell script. ''' import subprocess import shlex import os ''' datasets = ['TwoCubesBlendereevee', 'TwoCubesBlender1024', 'TwoCubesBlender128'] for dataset in datasets: command = f"python3 Analysis_2Tables.py --path2outs {dataset}_IRNet_0 --nb_instances 2" args = shlex.s...
1384fc49e15e86984daa68738e37f0d9e1dbbea80bd8f542f37f13ee81d87963
Python
3,022
75
import numpy as np def find_subset_with_all_ones(matrix, row_weight=1, min_rows=5, min_cols=600): """ Finds a subset of the given binary matrix with all ones, represented as row and column indices. Args: matrix (numpy.ndarray): A binary matrix with M rows and N columns. row_weight (fl...
7128f9cba5774b7a46b7ae99fe53ddfcd7c2711e5f23e48f9820c65589483591
Python
3,022
91
import numpy as np import torch as pt import seaborn as sns import matplotlib.pyplot as plt from Functional_Fusion.dataset import DataSetMDTB import PcmPy as pcm from scipy.stats import pearsonr from OptimalBattery.global_config import data_dir,save_dir import OptimalBattery.util as ut # Constants base_dir = f'{data_di...
a51c7a4306e767b5f344e2429d65587b663e75d9a2c8246d35e38c5af08768b7
Python
3,022
80
import seaborn as sns import numpy as np def plot_cortical_cell(ax, sk, ld=None, title=None): """Plot a cortical neuron according to ivscc style plot Parameters ---------- ax : matplotlib.axes Axes object in which to put plot sk : allensdk.core.swc.Morphology Morphology object ske...
10c6c6a31a75a55f5b026d8039a6176d71a9b4f1f556a6deff42088dbc26ca01
Python
3,024
77
# 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 from numpy.testing import assert_array_equal from bluepysnap import Circuit from voxcell import VoxelData from utils import TEST_DATA_DIR import connectome_...
b7d34971ec252cee7becf120371233c9a9e32ad8c8baef9a870da1625b2a1132
Python
3,024
85
""" Read line data from a text file. This reader is very similar to sparse pointer reader. The data format is: lineseries_id,z_position,x_position,y_position\n lineseries_id,z_position,x_position,y_position\n ... No header. The loader creates a list of lists, where all points within each list are linked. All poi...
fc9117c026ad14547be67eaf754a026942a25fd290eb68faff47b6ec9af392ad
Python
3,024
86
# Copyright 2024 Google LLC # 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
3dfbb07ca560bd3b433ab8f1fe42c9d8d1ebea32773292d3740c85660e1042ab
Python
3,025
66
# -*- coding: utf-8 -*- """ Create FOV ROI This script computes a label file to include only vertices (in further analysis) which are within the intersection of multiple volumes. """ # external inputs import numpy as np import nibabel as nb # local inputs from fmri_tools.surface.mesh import Mesh from fmri_tools.sur...
0a86c164fd50bfc824d1970287caf7acc65191b67e9f2d00af65eafeeea4dac0
Python
3,026
79
#!/usr/bin/env python3 import pysam import argparse import pathlib def parse_command() -> argparse.Namespace: """Function to parse the command line input Args: None Return: Namespace: returns the args as a standard Namespace object """ parser = argparse.ArgumentParser(description='...
6b64f67fadd179344ac7676f3f7722ebfc90d311db8f61507ba5064cab1e136d
Python
3,026
85
import math import torch import torch.nn.functional as F from distances import CosineSimilarity from utils import common_functions as c_f from utils import loss_and_miner_utils as lmu from losses.base_metric_loss_function import BaseMetricLossFunction from losses.mixins import WeightRegularizerMixin ###### modified...
6e4a53721b2b334a1c6f5affa3a8d3731f511b5773941872a212bb39fa107e79
Python
3,026
116
"""Data loading and saving operations.""" import numpy as np import scipy.io as sio from typing import List, Dict, Text, Union def load_label3d_data(path: Text, key: Text): """Load Label3D data Args: path (Text): Path to Label3D file key (Text): Field to access Returns: TYPE: Dat...
b40cd9e32b03bcaa155aa48ba85263ee75e37ba2379e6e0411c8f835e50c5a49
Python
3,026
96
# Copyright 2024 Google LLC # 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 # https://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to in writing, sof...
e8c10d8e5d684913efbff905a9fbbed194b8ae1cb49b5d3dce410e68248325cd
Python
3,026
78
from brainscore_vision.model_helpers.check_submission import check_models import functools import torch import torch.nn as nn from torchvision.models import resnet18 from brainscore_core.supported_data_standards.brainio.s3 import load_weight_file from brainscore_vision.model_helpers.activations.pytorch import Pyt...
fa622b2930647a61a6bb7a31676b7d42dbe4286c380b9a7eaf6773642f20cd4e
Python
3,028
87
# Copyright 2014-2015 Numenta Inc. # # Copyright may exist in Contributors' modifications # and/or contributions to the work. # # Use of this source code is governed by the MIT # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. import os import pandas try: import simplejson ...
429b97c52df659fb572a4652aba771c067d13d33c70669917bacd3f4404e21ef
Python
3,029
89
from typing import Final, Literal import numpy as np from argclz import try_int_type, argument from neuralib.plot import diag_histplot, plot_figure from rscvp.statistic.persistence_agg.core import AbstractPersistenceAgg from rscvp.util.cli import Region from rscvp.visual.main_response import VisualPatternCache, Apply...
5b1c57de4332bce59ddce893ec1f352dbc29ee567007546a26637fc03fb977a2
Python
3,029
100
# -*- coding: utf-8 -*- # python standard library inputs import os # external inputs import numpy as np import nibabel as nb from numpy.matlib import repmat def generate_coordinate_mapping(file_in, pad, path_output=None, suffix=None, time=False, write_output=False): """Generate c...
6788c20cead60cd89a62c36dd5be81f651ef44ec87a2e3796430182685671ed0
Python
3,029
103
""" Activation functions. """ import torch import numpy as np import EIANN.external as external def set_activation(network, activation, **kwargs): # Set callable activation function if isinstance(activation, str): if activation in globals(): activation = globals()[activation] elif...
6bdad75e456d1ec20424f5e57f72287855ffdbd4bf6373020e4eeda0be989a85
Python
3,031
110
import traceback from pathlib import Path from typing import List, Optional, Tuple import click from aicsimageio import AICSImage from PIL import Image from tqdm import tqdm from brainways.utils.image import resize_image, slice_to_uint8 from brainways.utils.io_utils import ImagePath def creat_thumbnail( input: ...
d3dd5c2739074602187fee3f4be84b6607ba24d51389169be6d5cd38f5f213ec
Python
3,031
76
import os import pandas as pd import subprocess from nipype import Node, Workflow from nipype.interfaces.utility import IdentityInterface, Merge, Function from .fsl.fsl_anat_nipype import FSLANAT class FSLANATPipeline: def __init__(self, subject, session, output_path, **kwargs): """ FSL Anat Pipel...
49e1817d994456c1e4f5d5901a528b4504d3afd05f94bc458a1e2b3ee6d5db65
Python
3,032
93
#!/usr/bin/env python # author: Jannes Spangenberg # 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 from tqdm import tqdm import h5py def pars...
4cbd75f92287c457b5b6964fea466e966e464c87a61fbc0e088ec72776c56f79
Python
3,032
84
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: # # 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 License. # You may...
5970b58e06a2a328517e8eac41af063162bb248ccbeb8265c3b41752b7c453ec
Python
3,032
80
import torch from utils import common_functions as c_f from utils import loss_and_miner_utils as lmu from losses.generic_pair_loss import GenericPairLoss class LiftedStructureLoss(GenericPairLoss): def __init__(self, neg_margin=1, pos_margin=0, **kwargs): super().__init__(mat_based_loss=False, **kwargs) ...
bc33afcdc69d0576c212a46533b4101c2028d80d7e0e22356b4b7a8bc1be4f70
Python
3,032
113
from collections.abc import Callable, Generator, Iterator from pathlib import Path from typing import ( TYPE_CHECKING, ) import numpy as np import pandas as pd import polars as pl from tqdm import tqdm from eir.data_load.label_setup import get_file_path_iterator from eir.setup.input_setup_modules.setup_sequence i...
5bc7a2ad0274cb093432816f6dd59f94adb63f0ffdddfbce0eaec3427a6310c8
Python
3,033
87
import torch import torch.nn as nn import torch.nn.functional as F import sklearn import sklearn.cluster from torch.nn.modules.module import Module from torch.nn.parameter import Parameter def cluster(data, k, temp, num_iter, init, cluster_temp): cuda0 = torch.cuda.is_available() if cuda0: mu = init.c...
9527b4a746e0d9244ad705fe3dd50c8ed227317b6e49c9120871afc888ed9025
Python
3,033
77
from __future__ import print_function, absolute_import import os.path as osp import glob import re from ..utils.data import BaseImageDataset class PersonX(BaseImageDataset): """ PersonX Reference: Sun et al. Dissecting Person Re-identification from the Viewpoint of Viewpoint. CVPR 2019. Dataset ...
26cf2bd62df82888d57e5b55d67cbc9093be774cf19fdda6b3b89189f0b0717d
Python
3,034
102
import torch from torch_geometric.graphgym.register import ( register_edge_encoder, register_node_encoder, ) @register_node_encoder('Integer') class IntegerFeatureEncoder(torch.nn.Module): r"""Provides an encoder for integer node features. Args: emb_dim (int): The output embedding dimension....
c29311ab85b5bbcd786796df7fbace66d7f5e60360c65f1af56118604cdb00c8
Python
3,034
85
from torch.utils.data import Dataset import pandas as pd import numpy as np import scanpy as sc import anndata as ad def intersect(lst1, lst2): temp = set(lst2) lst3 = [value for value in lst1 if value in temp] return lst3 def combine_training_data(src, tgt, is_preprocess=True): if not is_preprocess...
f0b77fd0b541c850488b8fd76a0ae3fae69b2775f19b9802303ca5c095b34673
Python
3,036
80
"""Molecular docking graph. Reuses the single-agent graph setup, changing only the default tool list and the default system prompt so the agent is focused on molecular docking. Keeping docking tools in their own graph (rather than in the single-agent defaults) means the general single-agent workflow and its evaluation...
70e354d420b4a7c321ca234615399d0cfc3a0174614b08b35751504647e47bba
Python
3,037
81
import random import time import tensorflow as tf from .utils import multi_input from .utils import setup_ckpt_manager from .loss import loss_function_mimo from .metrics import metrics_func_mimo from .batchloader import BatchLoader #from .show_utils import subShow3 def train_model(model, train_data, val_data, config...
ec915dedb7f9f7e152895d492934805c0dfbb80c0bf1e6d61b5e49fe9ecb79bb
Python
3,037
100
# Coulomb matrix descriptor functions # Imports import json import glob import collections import numpy as np import numpy.typing as npt import ase import ase.io import dscribe.descriptors from modules.build_data.fhi_aims.descriptors.default_settings import ( DEFAULT_CM_SETTINGS, ) from modules.tools.strings im...
294ab0ecc73de75f83f3bcb5b9e384688b73f89accc2b95d94c307dccbaf3023
Python
3,038
38
from brainscore_core.supported_data_standards.brainio.assemblies import DataAssembly from brainscore_vision import data_registry, stimulus_set_registry, load_stimulus_set from brainscore_core.supported_data_standards.brainio.s3 import load_assembly_from_s3, load_stimulus_set_from_s3 BIBTEX = """@article{CICHY201912, t...
9267ef7b0982aa2f407e533c13ba7898e434012690c6092014c63dcaef72977b
Python
3,038
92
import numpy as np ALL_DEGREES = ["1", "2", "3", "4", "5"] LABELS = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4] LABEL_NAMES = ['horn', 'tiger', 'guitar', 'kangaroo'] CHANCE_LEVEL = 0.5 SUBJECTS = [ "sub01", "sub02", "sub03", "sub04", "sub05", "sub06", "sub07", "s...
619bb869b11827875c74b4507f6e6925296ffc2a8296cfd1dbc6daef9b728b5e
Python
3,039
95
import numpy as np from ccf_streamlines.projection import ISOCORTEX_LAYER_KEYS # Structure set IDs from the mouse ontology, in the same pia-to-white-matter # order as ISOCORTEX_LAYER_KEYS. The names come from that one list so a # thickness file written here is always keyed the way the projector classes # read it back...
719761590feaf906fcbcc85115531ef69bd7e5d80b9188a1d4999f5b47a32d61
Python
3,039
86
""" Copyright 1999 Illinois Institute of Technology 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, merge, publis...
9a24c8198b8493a6f4cfb96fadebf468290d87ba7c1987634fa4324c70c2faa1
Python
3,039
105
#!/usr/bin/env python import sys from PyQt5 import QtCore, QtWidgets import storm_control.sc_library.tcpClient as tcpClient import storm_control.sc_library.tcpMessage as tcpMessage import storm_control.sc_library.tcpServer as tcpServer class Client(QtCore.QObject): def __init__(self, **kwds): super()._...
3844749132372945c1c366628448c946774a497c07e880ad92bef83b6ea4261a
Python
3,040
69
import os import json import numpy as np import matplotlib.pyplot as plt import ivim fig,axes = plt.subplots(2,1,figsize=(12, 5)) deltas = [15e-3,8e-3] Deltas = [25e-3,10e-3] T = 45e-3 TE = 60e-3 titles = ['Monopolar','Bipolar'] # Pulse sequence diagrams for ax,delta,Delta,title in zip(axes,deltas,Deltas,titles): ...
6a735a144911bdcd36bdd2dc184755131fe091f9ebdecd1f7c31553f2aee6256
Python
3,040
53
"""Upsample each image to 2 times the resolution. NOTE: This is important to preserve the single voxel level fine details such as the intracortical vessels """ import os import subprocess import numpy as np import nibabel as nb # ============================================================================= NII_NAMES...
8b9a01167d8cbe73f2d23876fc4ea72afc01805a009d6e7bfbac253a158bd969
Python
3,041
104
"""Nottingham MEGUK: Source reconstruction.""" from glob import glob from pathlib import Path import matplotlib matplotlib.use("Agg") import mne from osl_dynamics.meeg import parallel, parcellation, rhino, source_recon from osl_dynamics.utils.filenames import OSLFilenames # -----------------------------------------...
fab7e6ec0507ecdd702d72f18b1284c6278a25d8e82bf8272aa59429da8a5dc5
Python
3,042
93
# by Shaoxuan Yuan at 2024/04/22 import numpy as np from PIL import Image import os from sklearn.model_selection import train_test_split import torch from torch.utils.data import Dataset, DataLoader from torchvision import transforms # 图像和掩码的文件夹路径 image_folder = 'D:/桌面/project/atomai/dataset/augmented_image...
0f4e719dde3f2fd7f0ed1819da6c54be3d9b1ec82ab85c3e888ea2b84bd1cd21
Python
3,043
95
import polars as pl from matplotlib import pyplot as plt from matplotlib.axes import Axes from argclz import as_argument from neuralib.plot import plot_figure from neuralib.typing import AxesArray, ArrayLikeStr, ArrayLike from neuralib.util.verbose import publish_annotation from rscvp.statistic.core import StatPipelin...
685249488bb19bba68f8f464031d668224326257cd482774257e58b79f79865f
Python
3,043
66
"""System prompts for the single_agent_iri and single_agent_iri_flat workflows.""" alcf_iri_prompt = """\ You are an operator assistant for ALCF (Argonne Leadership Computing Facility). You answer questions about machine state, allocations, jobs, and remote filesystems by calling the ALCF IRI Facility API through six ...
ba5f12e7a8ab276a079538c8755b3fa7ab41a65ee887b8a1443aa27a8cdf4145
Python
3,043
81
#!/usr/bin/env python """ plot_results.py ─────────────── 依据 cross_validation.py 与 apply_thresholds.py 输出, 生成期刊所需 图表:STARD 流程图、ROC、校准、PR、阈值曲线、混淆矩阵,以及表格 CSV. """ import glob, json, numpy as np import matplotlib.pyplot as plt from sklearn.metrics import ( roc_curve, auc, precision_recall_curve, confusion_mat...
0b99848f9f629fb0afee56598f63c43b7b0016c7422aa32e9f1d94c61c164658
Python
3,044
96
############################################################################# # Copyright (C) 2020-2026 MEmilio # # Authors: Henrik Zunker # # 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 Lice...
22bc7562a4f97c2295a3f9aea134fb58b5c4ba245293d63cbd85640ac7f67ebf
Python
3,044
98
#!/usr/bin/env python """ Thorlabs FW102C control. Hazen 5/12 Josh 6/26/2013 """ import traceback import storm_control.sc_hardware.baseClasses.illuminationHardware as illuminationHardware import storm_control.sc_hardware.serial.RS232 as RS232 class FW102C(RS232.RS232): """ Encapsulates comm...
6cea5ef30ec67956a16598e35fcdae8849c424036ed2fc3a7db54b49902dfee5
Python
3,044
97
#!/usr/bin/env python from sputils import * nargs=len(sys.argv) threshs=['1.0'] if nargs<2: print('Usage: '+sys.argv[0]+' BPname threshs...') BPname="B03P223" BPname="B05P160" else: BPname=sys.argv[1] iarg=2 if nargs>iarg: threshs=sys.argv[iarg:] iarg+=1 rezdir='dropping_accuracy_filtered_results' #re...
0d74f480b21e0df2fadd9d62eb7f5d755ee05baae14ca25a334a1bf92061bef8
Python
3,045
63
from SlideRunner.dataAccess.database import Database import pandas as pd import numpy as np import glob from pathlib import Path from tqdm import tqdm from slide.data_loader import SlideContainer from random import * def create_indices(files, patches): indices = [] patches_per_slide = patches//len(files) f...
1e79ed1ed0869e86fdbf9f59f217879ee79f519d3d37559cb8068301671cd7f5
Python
3,045
90
from dataclasses import dataclass from sklearn.preprocessing import StandardScaler 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_tabular import ( TabularOutputTypeConf...
a86a62650e1839bf0ba2978cf5791b9f271f537c2dbd4af63a97c58942101f64
Python
3,045
91
import math from torch_geometric.graphgym.config import cfg, set_cfg from torch_geometric.graphgym.model_builder import create_model def params_count(model): """Computes the number of parameters. Args: model (nn.Module): PyTorch model """ return sum([p.numel() for p in model.parameters()]) ...
444449c835233fda191eda5e5146c2e1cadb72151aa33782245be0a80d3183f7
Python
3,046
93
# -*- coding: utf-8 -*- """ Created on Tue Jan 17 14:58:25 2023 @author: gligorov """ import matplotlib.pyplot as plt import numpy as np def plot_history(history, what_to_plot = 'all'): """ Plot history of training what_to_plot can be set to 'acc', 'loss' or 'lr' (for learning rate) or ...
415207f965b1a062ab96934d0c9b02d9b097a29d5a081315e9e8874ed95aab47
Python
3,047
114
# 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]uni-rostock.de # # This program is free ...
6454b96e2bedcefdc457dcea80ab1e926b90ca86598203d2725865fed44d1f1a
Python
3,047
92
from typing import Any, Optional, Tuple import torch from torch import Tensor from torch_geometric.utils import scatter class SparseCrossEntropy(torch.autograd.Function): # We implement our own custom autograd function for this to avoid the # double gradient computation to `inputs`. @staticmethod de...
e7f5b8054fdea39eeed0498661f9b889fc0ac4595bb73da89fa477c3e11ecd80
Python
3,047
102
import re import subprocess from itertools import count from pathlib import Path from textwrap import dedent import mkdocs_gen_files from qtpy.QtWidgets import QApplication DOCS = Path(__file__).parent.parent CODE_BLOCK = re.compile("``` ?python\n([^`]*)```", re.DOTALL) def _set_dark_mode(dark_mode: bool): """S...
7b757e52a04c81aa0df340d586c4089880747aecc434f5d8aef72ed1421c4f5a
Python
3,050
35
from testsetclass import TestsetClass class G21EA(TestsetClass): def __init__(self): self.weak = 1.0 self.molecules = ['EA_9', 'EA_13n', 'EA_14n', 'EA_25', 'EA_si', 'EA_o-', 'EA_9n', 'EA_f-', 'EA_21', 'EA_24n', 'EA_12n', 'EA_18n', 'EA_si-', 'EA_s-', 'EA_21n', 'EA_c', 'EA_cl-', 'EA_16', 'EA_22', 'E...
447cdbb8e2dc587388c39b266379401256c26bc47dbcca6eff625b1be1199bf2
Python
3,052
107
# -*- coding: utf-8 -*- # python standard library inputs import argparse # external inputs import numpy as np from nibabel.freesurfer.io import read_label, read_geometry, write_geometry # local inputs from ..io.surf import read_mgh, write_mgh __all__ = ['clip_surface', 'clip_mgh'] def clip_surface(verts, faces, i...
b6a6739ef0c7cc396220085885e4a126205c0046803e966b9ee7bedbe56b7af5
Python
3,052
79
# Copyright (C) CVAT.ai Corporation # # SPDX-License-Identifier: MIT from typing import Any from django.contrib.auth import get_user_model from django.contrib.auth.models import Group from django.test import RequestFactory, TestCase from rest_framework.exceptions import ValidationError from cvat.apps.iam.middleware ...
ee78fd4398e1edbb91f698d3d9263823824958c610781f5dd89143b2cd9612f7
Python
3,052
91
import numpy as np from scipy import stats import os import pandas as pd from faster_bootstrap import bootstrap, load_bootstrap from bootstrap_volumes import load_results, volume_bootstrap from statsmodels.multivariate.manova import MANOVA def welch_ttest(x, y): n_classes = x.shape[1] t = np.zeros(n_classes) ...
6dc0ce113d334e13cb614edac33a7ed0845853c5d0ebd9c2c11ad454de224ead
Python
3,053
96
''' Utilities for the console. ''' import sys, time import numpy as np from typing import Any, Union, Callable def timestamp(s: float) -> str: ''' Get a timestamp from time measurement s. INPUTS: s - Measurement of time (analogous to time.time()) OUTPUTS: str - Formatt...
84bd48cda1ad468fb8c231d0c2eb83ad53386633d6e63ddaa6ed929c5521bdba
Python
3,053
95
# 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. """Some utilities for backbones, in particular for windowing""" from typing import Tuple import torch import torch.nn as...
99a0373974f4898c87dbc7724a92eee0968ccc893c8670d373a61d5883e640e0
Python
3,053
81
"""Plot voxelwise prediction accuracy for each participant. Figure 2A. """ import matplotlib.pyplot as plt import numpy as np import os from collections import defaultdict from utils import ( get_voxel_to_fsaverage_mapper, languages, load_model_results, num_fsaverage_vertices, participant_names, ...
2a1e70238d057d7e59f9ead3d908e0a31a0cefe55038de2084c9d205145bfbf6
Python
3,055
92
import os import json import pandas as pd from tqdm import tqdm dataset_path = '../../datasets' dataset_list = os.listdir(dataset_path) # dataset_list = ['Twibot-20'] class User: """Class of a User""" def __init__(self, userid: str): self.userid = str(userid) self.dna = '' def add_tweet...
8d8fc60a4b661d22e44024ef8a3cf33aec6737feff70cdb8c85c9a497b48c931
Python
3,056
93
from pydantic import BaseModel, Field from typing import Optional, Union, Dict from pathlib import Path import torch import logging try: from fairchem.core import FAIRChemCalculator from fairchem.core.units.mlip_unit.mlip_unit import MLIPPredictUnit from fairchem.core.units.mlip_unit.api.inference import ...
b4f244dd8d915cc3d4f810dea903acfa265208b77b711a407a3ebe1f1e9403f2
Python
3,056
107
from flair.data import Dictionary from flair.models import TextClassifier from flair.trainers import ModelTrainer from flair.training_utils import convert_labels_to_one_hot, Metric def test_metric_get_classes(): metric = Metric("Test") metric.add_fn("class-1") metric.add_fn("class-3") metric.add_tn("...
c0b14151d756b4481173a16d2da02868f0c9c20f4940a94fe4c26536be0bd66c
Python
3,056
73
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import tempfile import pytest 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=['others.zip', 'processin...
30cdb615252df72496a2265d9d7333d1fd69232df46f468cd688ab3166a7ed10
Python
3,057
62
from train_gtex_random_weights import * def main(): model_type = 'MultiGene' current_dir = os.path.dirname(__file__) DATA_DIR = os.path.join(current_dir,'../data') config_path = os.path.join(current_dir,"configs/multi_gene_196kb_blood.yaml") remaining_tests = [(0,0,'60pxxfdk',False,'epoch=19-s...
32c5fe8c253cb9f1330e50053684d778cb7cff1e587d4352028d77e50a954b18
Python
3,058
101
import os import sys import math import pprint import torch from torchdrug import core, models from torchdrug.utils import comm import numpy as np import random sys.path.append(os.path.dirname(os.path.dirname(__file__))) from biopathnet import dataset, layer, model, task, util def solver_load(checkpoint, load_opti...
2af5e2d7567cfc51f188465e75ffee6cb6f13e0c6c60d76e4c6105bda889c630
Python
3,059
84
from .utils import * import subprocess as sub LABDATA_SLURM_FOLDER = pjoin(os.path.expanduser('~'),'labdatatools','slurm') #TODO: get this from preferences file def has_slurm(): proc = sub.Popen('sinfo', shell=True, stdout=sub.PIPE, stderr = sub.PIPE) out,err = proc.communicate() if len(err): retu...
42572d5e1cc6065255f133df57d09d4d5a7337f2c7fc08e342b4f81a9f5cad24
Python
3,059
90
# Copyright 2014-2015 Numenta Inc. # # Copyright may exist in Contributors' modifications # and/or contributions to the work. # # Use of this source code is governed by the MIT # license that can be found in the LICENSE file or at # https://opensource.org/licenses/MIT. import os from nab.sweeper import Sweeper from na...
dbdbba8c8c2d4d9309ca9ba9a10e10095466805957d08486abd6eb31e817b134
Python
3,059
86
""" A sparse encoder """ import torch from torch import nn import MinkowskiEngine as ME class Encoder(nn.Module): """ Encoder with sparse convolution """ def __init__(self): super().__init__() self.model = nn.Sequential( ME.MinkowskiConvolution(in_channels = 1, ...
df0e3e7820d762ef4b38212f88e7c38cca3d68f37e1e3faa7510592d31a5ec31
Python
3,059
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...
185679f451109ba66cb96a2c0f0336e5a3ac8fdb4e38ef4377f6af06953c60ee
Python
3,060
104
import os import os.path as osp import numpy as np import torch from torch.utils.data import Dataset import cv2 import matplotlib.pyplot as plt import albumentations as A from PIL import Image from albumentations.pytorch import ToTensorV2 def get_training_transform(): return A.Compose( [ A.RandomCro...
2c695994a1b8b7c0f3cff292d627e4bf9de0f6e7c057118a61667f4444f66703
Python
3,060
108
""" utils/metrics_ci.py 基于 Bootstrap 的多指标置信区间计算: - AUC-macro : ROC-AUC 的宏平均 - MCC-macro : Matthews Correlation Coefficient 的宏平均 - F1-macro : F1-score 的宏平均 - SubsetAcc : 样本级 Exact-match(所有标签均正确)的平均 """ import numpy as np from sklearn.metrics import ( roc_auc_score, matthews_corrcoe...
cd07dadd6e0b9635bc44a6c73ac5a0ba3aa6ebec8a7092563a33b5873462cf6a
Python
3,060
75
from typing import List, Tuple, Dict, Any import monai from monai import transforms import torch class Subsampled(transforms.MapTransform): """Transform that subsamples input data and pads to a specified size. Args: keys (list): List of keys to apply transform to spatial_size (tuple): Targ...
db712eb36ba7710d45e168a6d33b87870854378d4e4c93ce40169bd2775848a5
Python
3,060
93
import user_features as uf import csv import ijson import pandas as pd import time import sys import os def get_user_vector(user): user_vector = { "id": uf.get_user_id(user), "screen_name_length": uf.get_screen_name_length(user), "description_length": uf.get_description_length(user), ...
0de4b6caa53a0d6c84fd1586216fac9b160245d7c14f96a671a89dba3bdb0f23
Python
3,061
86
import numpy as np from skimage import io import getopt import sys def chop_paste_usage(): print(""" Usage : chop_paste.py -i [the img which you input, if you input one, default chop] -m [paste/chop] -f [the chop or paste model, x or y] -n [the numb...
9b9cb8ea02afada8e004ea38547d3982d65aea2f31f65b594909528d38294173
Python
3,061
102
from langgraph.graph import StateGraph, START, END from langchain_openai import ChatOpenAI from langgraph.checkpoint.memory import MemorySaver from chemgraph.tools.ase_tools import ( run_ase, save_atomsdata_to_file, file_to_atomsdata, ) from chemgraph.tools.cheminformatics_tools import ( molecule_name_t...
07372bb8dcfc33ff73ccf08f4813d14c936b0ec59c8cd39dbf5169016b2bb2c7
Python
3,063
73
from typing import Optional import torch import torch.nn.functional as F from torch_geometric.explain import Explainer, Explanation from torch_geometric.explain.config import MaskType, ModelMode, ModelReturnType def unfaithfulness( explainer: Explainer, explanation: Explanation, top_k: Optional[int] = N...
5df4b267b58cd8b10c6704259ac060e87923096691b3b241068cb0e5cbbeb5df
Python
3,063
128
#!/usr/bin/env python3 """ A reader of SAM format. import samreader # ... # Attach it to stdin and print the header. sam_reader = SamReader(sys.stdin) print sam_reader.header # ... # Open a SAM file and store each read starting position. with fopen(myfile) as fp: sr = ...
6fefeaef1ba22f44856caf2bd26242fbc4465653299fe7a59157ca1ccd05c342
Python
3,063
98
""" Settings for DataJoint. """ import json from collections import OrderedDict from .exceptions import PipelineException import collections from pprint import pformat LOCALCONFIG = 'pipeline_config.json' GLOBALCONFIG = '.pipeline_config.json' validators = collections.defaultdict(lambda: lambda value: True) default =...
2395bebb4a54c3a3fa096f3b86f1500d9649b2a39e861434cf96454ced0aaba0
Python
3,064
88
import logging import sys import warnings _LOG_FORMAT = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" def setup_logger(name=None, level=logging.INFO): """Set up a logger with consistent formatting. This function configures a logger with a standard format that includes timestamp, logger name, lo...
70fbeea60595b577a4b293a0d693d38dbd4d48264e15bec5648186f00d00bd67
Python
3,064
109
import pytest from pyment.cli.predict import _detect_format, _parse_folder_name, predict @pytest.mark.parametrize( 'name, expected', [ ( 'sub-S001_ses-01_run-1_T1w', ('S001', '01', '1', 'T1w'), ), ( 'sub-S001_ses-01_run-1', ('S001', '01'...
785d94fd8ffc39e3cd4701cfd8415c440788f2fb33473a7d8ab62cf73c013047
Python
3,066
68
"""Streamlit session-state initialisation for the ChemGraph UI.""" import logging import streamlit as st from ui.config import load_config logger = logging.getLogger(__name__) def init_session_state() -> None: """Ensure all required session-state keys exist with sensible defaults. This function is idempo...
7f8bc8397a0d339fc2788e231511bc3dd5d635d8d05fc1fca0be1329a0c20fc0
Python
3,066
96
import argparse import io import math import os import pandas as pd import requests from tqdm import tqdm DATASET_URL = 'https://s3.amazonaws.com/openneuro.org/ds000030' PARTICIPANTS_URL = f'{DATASET_URL}/participants.tsv' DEFAULT_DESTINATION = os.path.join(os.path.expanduser('~'), 'data', 'ds000030') def _download...
30a2cd43d32684092c3af0e81645c1617580810b963e486444ebf444bad76961
Python
3,067
78
""" Determine amount of each interval in one set covered by the intervals of another set. Adds two columns to the first input, giving number of bases covered and percent coverage on the second input. """ from bx.intervals.io import ( BitsetSafeReaderWrapper, GenomicInterval, ) from bx.tabular.io import ( C...
a5cc790956043df165928bb115631907ac146db7217b3a4367ec4bafe7c34d13
Python
3,067
76
import numpy as np import matplotlib.pyplot as plt import brainpy.math as bm #set default ramndom seed for reproducibility bm.random.seed(1) #set backend to cpu bm.set_platform('cpu') # Levy exponent v.s. adaptation strength; Levy exponent v.s. noise strength ticksize = 14 labelsize = 18 linewidth = 2 color = ['#F18...
e2da7f4875fa9de734d18c115b27a84e88482d65bcdc24742aea7c60a73c5cf3
Python
3,068
102
#!/usr/bin/env python3 """ Example: run xTB optimization from an input XYZ. Equivalent to: {xtb_binary} {input_struct_filename} {' '.join(run_flags)} > xtb.log Default flags correspond to: xtb_flags: ["--gfn","2","--opt"] Usage: python examples/conformation_generation/02_optimize_xtb_from_xyz.py \ --input ...
24826a78e446d6895b83585a990d233421a7c121035dfb298667f194f13c8d7d
Python
3,069
101
# -*- coding: utf-8 -*- # python standard library inputs import argparse # external inputs import numpy as np import nibabel as nb from nipype.interfaces.ants import N4BiasFieldCorrection def calc_t1w(file_bold, file_vaso, file_out, apply_bias): """Compute a T1-weighted image from nulled and not-nulled time ser...
2d925c502a6a9989d8783dce90583c4fc3ce93c5fca0bdb45a29f3046dac53da
Python
3,069
118
import numpy as np import numpy.testing as npt import torch from brainways.utils.atlas.slice_atlas import ( get_slice_coordinates, homog_center_at_zero, homog_indices, rotate, slice_atlas, translate, ) def test_homog_indices(): idxs = homog_indices(1, 2, 2) expected = [[0, 0, 0, 0], [...
52f7ee6853446f27d44565af988dfc9a78a427415658495ee49a44c2552f06cf
Python
3,070
110
import pickle as stdlib_pickle import dill import pytest import nelpy as nel from nelpy import formatters SERIALIZERS = [stdlib_pickle, dill] def _roundtrip_without_attrs(obj, attrs, serializer): for attr in attrs: obj.__dict__.pop(attr, None) return serializer.loads(serializer.dumps(obj)) @pyte...
69a612135a92d4491c2466401cb9417a7a6b655d4db9929b925216b1fa968161
Python
3,070
121
import numpy as np from impedancefitter.single_shell import eps_cell_single_shell, single_shell_model from impedancefitter.single_shell_ellipsoid import ( eps_cell_single_shell_ellipsoid, single_shell_ellipsoid_model, ) from impedancefitter.suspensionmodels import Lk, eps_sus_ellipsoid_MW # for single_shell_m...
7c258a97fce26071b26d5b12824ec292df61bafbce6a2d82b014f48b4509a6ae
Python
3,070
83
# -*- coding: utf-8 -*- """ Analyses of the EMPRISE data set by Joram Soch <soch@cbs.mpg.de> """ # import modules import os import time import EMPRISE import NumpRF import numpy as np import scipy as sp import pandas as pd import nibabel as nib import matplotlib.pyplot as plt ### Simulation C: NumpRF, 07,21/09/2023...