sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
08ae109ae28b9f53a7609fc8cd9f822e39ac077c8aec3fb7d166ab9a8bf2a890 | Python | 3,411 | 66 | def set_inference_options(parser):
parser.add_argument('-o', '--output_folder', default=None, type=str) # if None, will not write the images to disk
parser.add_argument('--dataset_name', default='reconstruction', type=str)
parser.add_argument('--use_gpu', dest='use_gpu', action='store_true')
parser.s... |
b0655fa4a04399839dbe6b68e787d160248e07edd2c272ad9501aaf04656993a | Python | 3,411 | 81 | """ Binary Cross Entropy w/ a few extras
Hacked together by / Copyright 2021 Ross Wightman
"""
from typing import Optional, Union
import torch
import torch.nn as nn
import torch.nn.functional as F
class BinaryCrossEntropy(nn.Module):
""" BCE with optional one-hot from dense targets, label smoothing, thresholdin... |
40bb976e0a5d789ac3996e6c824bb67f5427e10d0042d0924de2ba250063067a | Python | 3,414 | 92 | from pydantic import BaseModel, ConfigDict, Field
from typing_extensions import Literal, Union
from GANDLF.schedulers import global_schedulers_dict
TYPE_OPTIONS = Literal[tuple(global_schedulers_dict.keys())]
class BaseTriangleConfig(BaseModel):
min_lr: float = Field(default=(10**-3))
max_lr: float = Field(d... |
fdff284d8adfc98f403ec88d0208438e791738e419d7e4c8671bfa587bc08722 | Python | 3,418 | 124 | import module.predict as p
import pandas as pd
import numpy as np
from tqdm import tqdm
import math
import matplotlib.pyplot as plt
def predict(plots_path, tables_path, cutoff_ls, shot_ls, file_name):
RMSE = []
miss = []
RMSE_shot = []
RMSE_mix = []
r2_shot = []
r2_cutoff = []
fh = []
... |
3e103c6fd18e87609a5914da0f11ff15a809c75da51137e66cf25136516376c3 | Python | 3,424 | 92 | from __future__ import annotations
import importlib.util
import sys
import tarfile
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parents[3]
SPEC = importlib.util.spec_from_file_location(
"dm_rust_sources", ROOT / "tools/dm_rust_sources.py"
)
assert SPEC is not None and SPEC.loader is not... |
db27538c7b8c17b5da0663d94b52382d560a02679d2937e16754abbfd744c0e0 | Python | 3,424 | 91 | import torch
from torch.optim.lr_scheduler import _LRScheduler
from typing import List
class WarmupLinearDecayLR(_LRScheduler):
def __init__(
self,
optimizer: torch.optim.Optimizer,
warmup_factor: float = 0.001,
warmup_iters: int = 10,
warmup_method: str = "linear",
... |
1415a2dcdad373709831a2b92529feeb38419216f989e65960b239684d49d10e | Python | 3,425 | 106 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
70f221653f7194985d5c585fe5b2fad52616a4a9b1e2e76fc79a86a89ff5d8ed | Python | 3,427 | 99 | # -*- coding: utf-8 -*-
#
# comparison_schemes.py
#
"""
Features selection and classifications
"""
__author__ = "Ahmed Albuni"
__email__ = "ahmed.albuni@gmail.com"
from lightgbm.sklearn import LGBMClassifier
from scipy.stats import randint as sp_randint
from sklearn.ensemble import ExtraTreesClassifier
from sklearn... |
08e93624557513ad6af5820258eb3eda4435c9e4d6ca2932dbd1d7c8d0f0e34e | Python | 3,429 | 87 | from nidm.core import Constants
from nidm.experiment import (
AssessmentAcquisition,
AssessmentObject,
DemographicsObject,
MRAcquisition,
MRObject,
Project,
Session,
)
# dj TODO: adding more tests; I only put the Dave's pipeline to a function
def main():
# create new nidm-experiment do... |
ee7276fc9e2fbb913e0123fd1777d21dce3bc1c43fe6bfb172823d5e3b6122ab | Python | 3,432 | 101 | import numpy as np
from netCDF4 import Dataset
import os, pathlib
from scipy import stats
#==========================================================
# Set main directory
#==========================================================
hdir = '/home/jhkim/model/deep_detection'
i_name_list = [
'DD_ERA5_prcp_... |
9c406503630c392b248c59a944b54eab5297eef29989791460e90cc304a3bbef | Python | 3,434 | 99 | # Inheritaed from open-mmlab/mmclassification
# Modified by Hangyu LIN
import os
import os.path as osp
from pathlib import Path
from .misc import is_str
def is_filepath(x):
return is_str(x) or isinstance(x, Path)
def fopen(filepath, *args, **kwargs):
if is_str(filepath):
return open(filepath, *arg... |
815afac6a9f397e0c6f3a47f694bdbb41e112f5017b8e05478269f03e0f48646 | Python | 3,435 | 88 | import pandas as pd
import zipfile
from os.path import splitext
import numpy as np
from .timers import Timer
class FixedSizeEventReader:
"""
Reads events from a '.txt' or '.zip' file, and packages the events into
non-overlapping event windows, each containing a fixed number of events.
"""
def __i... |
80b927c4374ef5674d89f8757b0cd766c9779250f15ddba506d3109e919277b6 | Python | 3,437 | 83 | import os
from PIL import Image
import torchvision
from torch.utils.data import Dataset
from util.io_handler import SampleIoHandler
class CIFAR10_selected(Dataset):
def __init__(self, args, root: str, transform: torchvision.transforms.Compose, train: bool) -> None:
super().__init__()
self.root =... |
f17c03811c9dfd5673e75f4febd3d1158429ed454aef8529a7c3f80072b7596f | Python | 3,438 | 107 | # All the mapping used in the code
REDCAP_COLUMN_MAP = {
"Variable / Field Name": "item_name", # column A
"Form Name": "activity_name", # column B
"Section Header": "preamble", # column C
"Field Type": "inputType", # column D
"Field Label": "question", # column E
"Choices, Calculations, OR ... |
9b3064c3f9108a04834f1691eeda2385d238102210eb98bfaa20ab35a6660472 | Python | 3,442 | 105 | # -*- coding: utf-8 -*-
"""
Implementation of MSDNet
This module contains the implementation of MSDNet, a mixed-scale dense convolutional neural network
for image analysis, as described in the paper "A mixed-scale dense convolutional neural network for image analysis" by Daniel et al.
References
Daniël M. Pelt an... |
1eb8909da8ef54bff4ad13a436096470349f95aed8a330887c75fe66b6e71258 | Python | 3,443 | 95 | # This file is part of pyunicorn.
# Copyright (C) 2008--2026 Jonathan F. Donges and pyunicorn authors
# URL: <https://www.pik-potsdam.de/members/donges/software-2/software>
# License: BSD (3-clause)
#
# Please acknowledge and cite the use of this software and its authors
# when results are used in publications or publi... |
ac04aa21d03d96c4273b779ff9de0956cd37d073d93cfcf1e1f92e9bb5f17b20 | Python | 3,446 | 124 | '''Some helper functions for PyTorch, including:
- get_mean_and_std: calculate the mean and std value of dataset.
- msr_init: net parameter initialization.
- progress_bar: progress bar mimic xlua.progress.
'''
import os
import sys
import time
import math
import torch.nn as nn
import torch.nn.init as init
... |
a547547855067a4fd5cce1edef6072203d72f304514efec7aa29605ad82b16de | Python | 3,449 | 84 | """Module for pixel-based classifiers."""
from __future__ import annotations
from typing import Any, Protocol
import numpy as np
from lightgbm import Booster
class ClassifierType(Protocol):
"""Defines the necessary classifier interface."""
def predict(self, X: np.ndarray) -> np.ndarray: # pylint: disable... |
682a0421d4f4518aaa8d9036d84d45c161e21bd55a5731629c5027ce5073e3d3 | Python | 3,453 | 108 | import numpy as np
def convert_strtoseclist(cell, location):
if location.lower() == 'soma':
location = cell.soma
elif location.lower() == 'axon':
location = cell.axon
elif location.lower() == 'all':
location = cell.allsec
elif location.lower() == 'alldend':
location = c... |
c3bdb05d53a08ded2e9f8daea0cc58f5a9c6191ee2537b01fa3ec58f91a4fbed | Python | 3,457 | 103 | """
MatchTemplate
=============
The **MatchTemplate** module uses `normalized cross-correlation`_ to
match a template to a single-channel two-or-three dimensional image or
multi-channel two-dimensional image. The output of the module is an
image where each pixel corresponds to the `Pearson product-moment
correlation c... |
a492a4d7e05dd552aee6ff5b2481fe2b7a255c89aba515b3b873d9960867c9bd | Python | 3,459 | 110 | """
validation.py
=============
Contains utils for validating the filetype and existence of manifest-defined files/folders
"""
import logging
import os
import sys
from distutils.spawn import find_executable
logger = logging.getLogger('root')
def exists(filepath):
if not os.path.isfile(filepath):
logge... |
9c77249c20e90893b1d2c2ba2d23188589159985a34289cda5e22f8b84d64e6c | Python | 3,463 | 102 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
File related util functions for megsim.
"""
import sys
import pickle
import pathlib
from math import isclose, inf
from pathlib import Path
import subprocess
import platform
import os
import tempfile
import numpy as np
from megsimutils.utils import subsample
def _nam... |
47755870188da0dd02747d74966f56ddca6188cb9a30eaa40ec0efbc2ab025f2 | Python | 3,464 | 101 | import os
import json
import pickle
import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import *
from tensorflow.keras.regularizers import l1,l2
from pymatgen.core.composition import Composition
os.environ["CUDA_VISIBLE_DEVICES"]='0'
import argparse
def output(targets, model, pr... |
907c792b7a403465f23cb798d6ac6599140d1a7f023bd46d44605dae4c24168c | Python | 3,464 | 97 | # -*- coding: utf-8 -*-
"""
pysteps.noise.interface
=======================
Interface for the noise module.
.. autosummary::
:toctree: ../generated/
get_method
"""
from pysteps.noise.fftgenerators import (
initialize_param_2d_fft_filter,
generate_noise_2d_fft_filter,
initialize_nonparam_2d_fft_f... |
c1c3d5f8a3c8687ebe37be9afb1e3b315398fe15b14694af96c9ac1862e03bb6 | Python | 3,467 | 98 | import nibabel as nib
import numpy as np
from traitlets import Bool, Dict, Integer
from mrHARDI.base.application import (mrHARDIBaseApplication,
output_prefix_argument,
required_file)
_aliases = {
"in": "DWIValidation.dwi",
"bvals": ... |
06bdbf6bfceb50684c4e17b04e07f406461e08b0812ed7daf87b9de1de20b6d7 | Python | 3,468 | 101 | ''' adapted from https://github.com/all-umass/ManifoldWarping '''
import numpy as np
import scipy as sp
from sklearn.manifold import Isomap,LocallyLinearEmbedding
from neighborhood import neighbor_graph,laplacian
def lapeig(W=None, L=None, num_vecs=None, return_vals=False):
tmp_L = (L is None) # we can overwrite ... |
524709daa337da19a707febccb28ca99d6aeb3bf0e5dca568bb1393b0473f51f | Python | 3,469 | 55 | from cellprofiler_library.functions.image_processing import enhance_speckles, enhance_neurites, enhance_circles, enhance_texture, enhance_dark_holes, enhance_dic, suppress
from pydantic import Field, ConfigDict, validate_call
from typing import Annotated
from cellprofiler_library.types import ImageGrayscale, ImageGrays... |
cc1cd536d3115c6aa35e3792185cfa1840b9fbb93d19866dac1f980e8c13bf17 | Python | 3,470 | 98 | # Pytorch Tabular
# Author: Manu Joseph <manujoseph@gmail.com>
# For license information, see LICENSE.TXT
"""Category Embedding Model"""
import logging
from typing import Dict
import pytorch_lightning as pl
import torch
import torch.nn as nn
from omegaconf import DictConfig
from src.models.tabular.pytorch_tabular.rep... |
868816a2ef430357d9a8d54f963ed4ad1a5f557f77cc3806bd5c21433a34b47a | Python | 3,471 | 128 | from abc import abstractmethod
from typing import Generator
import nibabel as nib
from numpy import loadtxt, ones, ubyte, sign, array
from numpy.linalg import eigh
from mrHARDI.compute.math.linalg import color
from mrHARDI.compute.math.tensor import compute_eigenvalues
def load_from_cache(cache, keys, alternative=N... |
ed3a083809391e23acf0aa623f3aa935023c5221901c86f0596931927367219a | Python | 3,471 | 87 | """ Padding Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
import math
from typing import List, Tuple, Union
import torch
import torch.nn.functional as F
from .helpers import to_2tuple
# Calculate symmetric padding for a convolution
def get_padding(kernel_size: int, stride: int = 1, dilation: int = ... |
5ed04e9ce6ecb7ce987544a12f772ac98009614cee909a6fdffdf7be09d0e12c | Python | 3,474 | 102 | import re
from ._setting import Setting
from ._validation_error import ValidationError
class TreeChoice(Setting):
"""A tree choice chooses one path to a leaf in a tree
Trees are represented as collections of two-tuples. The first element is
the name of the node and the second is either None if a leaf or... |
e9d8dfb6562874c8c89d9cc0d83435301fe9f99ae13c7b41738d30bd4ab96579 | Python | 3,474 | 93 | import numpy as np
from configuration import default_lower_bounds, default_upper_bounds
def sample_scale(alpha=1.0, beta=25.0, rng=None):
"""Generates 3 random draws from a beta prior over the
scale of the random walk.
Parameters:
-----------
alpha : float, optional, default: 1.0
The alph... |
18871b6c153f0f5fc1f7ada0c4ce56b5b31a99cf1d3a205d76299987fa662875 | Python | 3,477 | 72 | # -*- coding: utf-8 -*-
import argparse
import train
import setup
import os
import torch
import numpy as np
import time
import utils
def mkd(args):
try:
os.makedirs('output/' + args.codename)
except FileExistsError:
print('file already exists')
def main():
parser = arg... |
51441e9638926f9574f8c72f75615d61e3082e7115a4752164ccb523cc91a121 | Python | 3,478 | 94 | import numpy as np
import matplotlib.pyplot as plt
import sys
sys.path.append("/home/diego/Dropbox/hold_noise/iclamp-glm/")
from icglm.iclamp import IClamp
from fun_signals import get_arg, mask_thres_sustained_crossings, shift_array, extend_trues
class HoldNoise(IClamp):
# def __init__(self, t, v, stim=None... |
3247dca9f235079e969eb528a7cd2839fecc44308536a6f1234cc007e354d0b8 | Python | 3,479 | 117 | """ Layer/Module Helpers
Hacked together by / Copyright 2020 Ross Wightman
"""
from itertools import repeat
import collections.abc
import torch
_HAS_COMPILER_IS_EXPORTING = hasattr(torch, 'compiler') and hasattr(torch.compiler, 'is_exporting') # PyTorch >= 2.7
# From PyTorch internals
def _ntuple(n):
"""Retur... |
67aeb19138db33b0bee4efa20e4a18fda5824b4fdd6dd925c2ef14c92028c111 | Python | 3,479 | 101 |
from .lifneuron import LIFNeuron
from .synapse import Synapse
class Cluster():
'''
classdocs
'''
def __init__(self, neutype='LIF', neunum=10):
'''
Constructor
'''
self.id = 0 # starting with 1
self.name = '' # name of this group
self.neutype = neutyp... |
7c4208f4ff83e0c51aa4faad4a429e59438c5e044748bdea0d12cf84c5f2e285 | Python | 3,481 | 106 | import pandas as pd
import numpy as np
import argparse
import matplotlib.pylab as plt
from rdkit import Chem
import rdkit.Chem.Descriptors
import os
def pref_split(smiles_string):
"""
splits a string on '|' into a list with two elements, starting from the right
the prefix token must be in '<pref... |
e34ca55b000b42d72e628663f75afd6d842c4e11163b5298c9ffdd41354f693f | Python | 3,482 | 87 | """
ClinicalASL - Clinical Arterial Spin Labeling processing pipeline
NIfTI saving utility module.
Repository: https://github.com/JSIERO/ClinicalASL
Author: Jeroen Siero
Institution: UMCU (University Medical Center Utrecht), The Netherlands
Contact: j.c.w.siero@umcutrecht.nl
Description:
Utility fun... |
5f7dd567f7bb13f38685394373ac524ded056307365a8c79ded5af0be9fa8c44 | Python | 3,483 | 112 | import cv2 as cv
import numpy as np
from scipy import ndimage as nd
from skimage.filters import sobel
class PreProcess(object):
def __init__(self, size=(128, 128), preprocess="basic", interpolation=cv.INTER_CUBIC):
"""
:param size:
:param preprocess:
:param interpolation:
... |
bc0884495dbce3ec831e9a0072fb6df0b07eaa937cf95c232483c0c760ace202 | Python | 3,486 | 91 | import glob
import logging
import zipfile
from pathlib import Path
from tempfile import TemporaryDirectory
from typing import Union
from imctools.io.imc.imcwriter import ImcWriter
from imctools.io.mcd.mcdparser import McdParser
from imctools.io.txt.txtparser import TXT_FILE_EXTENSION, TxtParser
from imctools.io.utils ... |
64fba8b0d6808a1074f9bc98542a04f8f66ab9ccecfe3c4c6fcfe7de5678c92e | Python | 3,498 | 102 | """Tests for the shared -nl file-list resolver used by query / queryai."""
from __future__ import annotations
from pathlib import Path
from nidm.experiment.tools.nidm_file_utils import (
bundled_cde_files,
expand_nidm_file_list,
)
def _make_study(root: Path) -> None:
"""Two subjects, each with a canonica... |
c65ced2d9a520c03887f23bb21cc46dd3d831f3387848b0fa4b5bb55a4df8afa | Python | 3,500 | 101 | import json
import csv
import gudhi
import matplotlib.pyplot as plt
def draw_barcode_and_matrix(data, matrix, output_filename):
plt.rcdefaults()
fig, ax = plt.subplots(1, 2)
max_xaxis = sorted([i[1] for i in data], reverse=True)[0]
y_pos = [i for i in range(len(data))]
values = [pair[1] for pair i... |
eeb3743e2af85505d70f536e7ece7bf052084bf1081fc796b43b114deee50b27 | Python | 3,500 | 122 | #
# nate berry
# 2023-04-01
#
#
# ---------------------------
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.graphics.tsaplots import plot_acf
from pyrqa.time_series import TimeSeries
from pyrqa.analysis_type import Cross
from pyrqa.settings import Settin... |
8a16900c041d956eb501d3831be6ab5e7a37d36a135d6b6611356e080c7ba62c | Python | 3,503 | 103 | import logging
from .._text import Text
from ..._validation_error import ValidationError
LOGGER = logging.getLogger(__name__)
class Number(Text):
"""A setting that allows only numeric input
"""
def __init__(self, text, value=0, minval=None, maxval=None, *args, **kwargs):
if isinstance(value, st... |
e27a9e874cad6b90c638bdce7333af033d4910012a364b6dc3818ad6fcfa5778 | Python | 3,504 | 112 | from os import getcwd
from os.path import basename, join
from traitlets import Bool, Dict, Instance
from mrHARDI.base.application import (mrHARDIBaseApplication,
mask_arg,
output_prefix_argument,
... |
0aa0b08e67698fddc71b800c4c57b040decdfd35b5396eaf920324d50db64b88 | Python | 3,508 | 99 | """ A dataset reader that extracts images from folders
Folders are scanned recursively to find image files. Labels are based
on the folder hierarchy, just leaf folders by default.
Hacked together by / Copyright 2020 Ross Wightman
"""
import os
from typing import Dict, List, Optional, Set, Tuple, Union
from timm.util... |
cfaaa56e5aa166e4af68ba8cee9ea2f48e315272292c1e80e35000c9fdb21ca1 | Python | 3,511 | 109 | """
@author: Johanna Rahm
Research group Heilemann
Institute for Physical and Theoretical Chemistry, Goethe University Frankfurt a.M.
Handle widgets of VisualizeDeepSTORM2DLocs Jupyter Notebook.
"""
import tkinter as tk
import os
from ipywidgets import widgets
import tkinter.filedialog as fd
from IPython.display impo... |
b55832437250e9899a2e02d16c7b5b46d16e69d612e6e361ff71f4fbb64a3858 | Python | 3,513 | 105 | import numpy as np
import scipy.sparse as sp
from .distortion import filter_adj
try:
from torch_sparse import coalesce
from torch_geometric.data import Data
from torch_geometric.utils.grid import grid_pos
except Exception as e:
print('Warning: torch geometric not installed error importing. ' + str(e))
... |
db296093fda0096072df7f134300d932f3a1acda6e59923e661f903f3cb6c055 | Python | 3,513 | 88 | from tqdm import tqdm
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import torch
from sklearn.metrics import balanced_accuracy_score, roc_auc_score, roc_curve, f1_score
from sklearn.metrics import auc,precision_recall_curve, r2_score
from sklearn.linear_model import LinearRegression, Thei... |
442cb55548cee7f5db619190d7f259519b8fee46075dc8f5c3fad27fb1020454 | Python | 3,516 | 160 | import numpy
import pytest
import cellprofiler_core.measurement
from cellprofiler_core.constants.measurement import COLTYPE_INTEGER
import cellprofiler.modules.measureimageskeleton
instance = cellprofiler.modules.measureimageskeleton.MeasureImageSkeleton()
@pytest.fixture(scope="module")
def image_skeleton():
... |
57bd0e33e0910aea16ff75f454e617f657a6f281ad5262b8c9a6d1c4cafb6834 | Python | 3,519 | 98 | """
Visualization routines for the final generated sRVE
--> Routines work with the DAMASK-Output!
Author: Niklas Fehlemann
Phases:
1: IPF
2: Black
3: Brown
4: Grey
5: IPF with edges
6: Black with edges
7: white
"""
import pyvista as pv
import numpy as np
from dragen.utilities.InputInfo import RveInfo
def plot_srve... |
d7efe850a957619564f1a73ea0612928e2f5141b0997dd61fb1117a0326e3e44 | Python | 3,520 | 142 | # -*- coding: utf-8 -*-
"""
pysteps.utils.tapering
======================
Implementations of window functions for computing of the FFT.
.. autosummary::
:toctree: ../generated/
compute_mask_window_function
compute_window_function
"""
import numpy as np
from scipy.spatial import cKDTree
def compute_mas... |
626fe1d94044c584c5ac0150b47b8aa2a9f5462131d7fc6b9d1fd8ebb2ce5a70 | Python | 3,521 | 105 | '''
JHK
Python script for calculating the linear trend of 7x7 occlusion sensitivity.
'''
import numpy as np
from netCDF4 import Dataset
import os, pathlib
from scipy import stats
#==========================================================
# Set main directory
#==========================================================... |
2d07a8e9f87e3285eef8239e685ac1804ed0e43e65cc6f43c1265ca52e7564af | Python | 3,523 | 130 | import torch
import torch.nn as nn
from DT_for_WDN_leak_localization.model_architectures.transformers import EncoderLayer, PositionalEmbedding
class CategoricalEmbeddingLayer(nn.Module):
""" Embedding layer for categorical parameters"""
def __init__(
self,
pars_dims: int,
embed_dim: in... |
b84f39bf33413cb651de20543f2af0a346e1de9b60e24a179f9c6e68d2fbfe35 | Python | 3,523 | 99 | import torch
from torch import nn as nn
try:
from inplace_abn.functions import inplace_abn, inplace_abn_sync
has_iabn = True
except ImportError:
has_iabn = False
def inplace_abn(x, weight, bias, running_mean, running_var,
training=True, momentum=0.1, eps=1e-05, activation="leaky_re... |
cc308868504ac1b42c94e3fecf33262bcf2f8213b4985a202fe98fcfd2fbcf23 | Python | 3,523 | 123 | """
Calculating the output of a model circuit
where the connections weights are proportional to the connection counts
from the connectome
@author: Nikolai M Chapochnikov
"""
#%%
import numpy as np
import pandas as pd
import functions.olfactory as FO
import params.act3 as par_act
import scipy.linalg as LA
import funct... |
e73cc76fdee7f801eb9c9cbf55c235aa579fcc60afb6acd5a7138368d08acacf | Python | 3,525 | 96 | from glob import glob
import os
from pdb2sql import pdb2sql
import numpy
import h5py
from deeprank.config import logger
from deeprank.features.FeatureClass import FeatureClass
from deeprank.config.chemicals import AA_codes, AA_codes_3to1, AA_codes_1to3
from deeprank.operate.pdb import get_residue_contact_atom_pairs, ... |
72b805d1e7bcc5dc3b0c64749d0501fadf1a4fcb3527f01a542376dace0b943c | Python | 3,531 | 133 | """ Depthwise Separable Conv Modules
Basic DWS convs. Other variations of DWS exist with batch norm or activations between the
DW and PW convs such as the Depthwise modules in MobileNetV2 / EfficientNet and Xception.
Hacked together by / Copyright 2020 Ross Wightman
"""
from typing import Optional, Type, Union
from ... |
8390b4a9449ee29aad0dd5d60269d628e4259b4c49a6ee2e0785ed833bae522c | Python | 3,534 | 93 | from http.server import BaseHTTPRequestHandler, HTTPServer
import json
import onnxruntime as rt
import os
import sys
# Installer:
# pyinstaller --onefile --clean --hidden-import numpy --hidden-import onnxruntime --add-data "models/ic_intellevent.onnx;models" --add-data "models/fo_intellevent.onnx;models" vicon_... |
2995eca5f406b8667d864b1051502001778730630dca71e2dc66e9925c211ab8 | Python | 3,535 | 89 | """
File name: create_table_for_performance_results.py
Author: Esra Zihni
Date created: 21.05.2018
This script creates a table of the overall performance results. It reads the
implementation and path options from the config.yml script. It reads the training and
test performance results calculated using the specified... |
91feef53adeb5bc02e32d7783bead8324d64d46efe581d1e92512ee71a449f79 | Python | 3,536 | 99 | from math import ceil, log2
import torch.nn as nn
import torch.nn.functional as F
from torchgan.models import Discriminator, Generator
class DCGANUpGenerator(Generator):
"""Deep Convolutional Generator with resize convolution
"""
def __init__(
self,
encoding_dims=100,
out_size=32,... |
e2fc25f7b18e4f17d6dbc02b467ff8b5cd87f81a8c3686be70189660d35320d9 | Python | 3,538 | 107 | import glob
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
from neuron import h
import Functions.globalFunctions.ExtracellularField as EcF
import Functions.globalFunctions.morphology_v2 as mphv2
from Model import Cells
cmap_contour = sns.color_palette("mako", as_cma... |
505b7979026b7d44325a71363ec4ea479017db29d031d6672ad02e9383c11c05 | Python | 3,540 | 135 | import pytest
import numpy as np
from pysteps.motion import farneback
from pysteps.exceptions import MissingOptionalDependency
from pysteps.tests.helpers import get_precipitation_fields
fb_arg_names = (
"pyr_scale",
"levels",
"winsize",
"iterations",
"poly_n",
"poly_sigma",
"flags",
"s... |
9118acdbc212230603b80570a3dd68cee89df41f7ed27e24f17a4ad3182f3bf7 | Python | 3,545 | 100 | import prov.model as pm
from .Core import Core, getUUID
from ..core import Constants
class Acquisition(pm.ProvActivity, Core):
"""Class for NIDM-Experiment Acquisition-Level Objects.
Default constructor uses empty graph with namespaces added from NIDM/Scripts/Constants.py.
Additional alternate constructo... |
732fe7ee12e2f6265e14c3e7c73476587ddb1b1647823dd5f2772f5907d82b42 | Python | 3,547 | 142 | import os
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from allensdk.brain_observatory.ecephys.ecephys_project_cache import EcephysProjectCache
from allensdk.brain_observatory.ecephys.ecephys_session import EcephysSession
from allensdk.brain_observatory.ecephys.stimulus_analysis import Recep... |
a54422ebef1eacb7515ea30b12b7efb020e2590ca88e3df5937343cd35f1c97e | Python | 3,549 | 137 | '''
Created on Nov 3, 2014
@author: noampeled
'''
import numpy as np
import traceback
try:
import tables
DEF_TABLES = True
except:
print('no pytables!')
DEF_TABLES = False
# http://stackoverflow.com/questions/9002433/how-should-python-dictionaries-be-stored-in-pytables
tables_dict = {
'key': tab... |
07f6d15e91575b1a077989e961b6aaae0a3e7057db30994a1e019a3db876679f | Python | 3,554 | 104 | """
Alphabet maps objects to integer ids. It provides two way mapping from the index to the objects.
"""
import json
import os
class Alphabet:
def __init__(self, name, label = False, keep_growing=True):
self.__name = name
self.instance2index = {}
self.instances = []
self.keep_growi... |
df446905f8e9c04f462d14920fb251ab0a079e011240bd1e3add3d9ffe6bd7c4 | Python | 3,555 | 95 | import os, warnings
from typing import Optional, Union
from functools import partial
from pathlib import Path
from PIL import Image
from GANDLF.data.patch_miner.opm.patch_manager import PatchManager
from GANDLF.data.patch_miner.opm.utils import (
alpha_rgb_2d_channel_check,
patch_size_check,
parse_config,... |
b94f8e29600fb70c26fb1355f9ffb0cee90b2dcb4d1bd896698b0cad2d5f8b13 | Python | 3,558 | 80 | """ Convert PP-LCNetV2 weights from PaddleClas to timm
Checkpoints: https://github.com/PaddlePaddle/PaddleClas/blob/release/2.6/docs/en/models/PP-LCNetV2_en.md
NOTE: `paddlepaddle` is required to unpickle the .pdparams files, it is not in requirements.txt
Usage:
python convert/convert_lcnetv2_paddle.py PPLCNetV2_... |
97ecce7072ca05b1532ec04e7b885f15e07d5acab89408d45160647239e0e23b | Python | 3,560 | 110 | # import maninetcluster here
import numpy as np
import pandas as pd
from sklearn import preprocessing
from ManinetCluster_python.alignment import manifold_nonlinear
from ManinetCluster_python.correspondence import Correspondence
from ManinetCluster_python.distance import SquaredL2
from ManinetCluster_python.neighborho... |
fae54f427cbfa2ea7fceff769e2fc49d97415c064c0ee6ee7b15dbbe2aea510b | Python | 3,562 | 93 | """This package includes all the modules related to data loading and preprocessing
To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset.
You need to implement four functions:
-- <__init__>: ... |
bc71f125b150b367fb0435a35bdd50878439ad3dfc0d055fa0812bd89a792e05 | Python | 3,563 | 142 | import pdb
import torch
import torch.nn as nn
from DT_for_WDN_leak_localization.model_architectures.dense import DenseResNetLayer
from DT_for_WDN_leak_localization.model_architectures.transformers import (
DecoderLayer,
EncoderLayer,
PositionalEmbedding
)
from DT_for_WDN_leak_localization.models.paramete... |
6c4a9bb471aee97016c9fc1a64b7ef2517b161f7f498df475f11e221d9e3f0af | Python | 3,572 | 104 | import torch
import torch.nn as nn
class BatchNorm(nn.Module):
def __init__(self,num_features):
super(BatchNorm,self).__init__()
self.bn=nn.BatchNorm1d(num_features=num_features)
def forward(self,x):
x_out=torch.transpose(x,1,2)
x_out=self.bn(x_out)
x_out=torch.transpo... |
4620a22894c06b25fd5fbd8977287e47b652b54f4b47834ccc8ee0074e76f8eb | Python | 3,573 | 96 | import numpy as np
def interpolant(t):
return t*t*t*(t*(t*6 - 15) + 10)
def generate_perlin_noise_2d(
shape, res, tileable=(False, False), interpolant=interpolant
):
"""Generate a 2D numpy array of perlin noise.
Args:
shape: The shape of the generated array (tuple of two ints).
... |
9bcf45179809c2ad56f7f15d6611f46b27faaf1e87c6eb093577aa325c1c9ae8 | Python | 3,581 | 95 | ## TODO August 06 version
"""This package includes all the modules related to data loading and preprocessing
To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset.
You need to implement four functions:
-- <_... |
794fe833d66225cd536f7797ae89c35c8bbe7d06e42132564ab2c76ee418c719 | Python | 3,586 | 102 | #### for the five cross validation
import os
import numpy as np
#import SimpleITK as sitk
import nibabel as nib
import matplotlib.pyplot as plt
from PIL import Image
import csv
import shutil
img_root = "data_prepro_tmp"
sub_dir = ["data_AD/AV45","data_HC/AV45"]
csv_save = "./five_cross_valid/"
split_char... |
661e0fa3b78349129b3e32b90665becc2f5c26588a0e9f028a9ce416fffe0743 | Python | 3,588 | 99 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
0db60d70f5ce2b3edf7bfdc6b083b54e2d0884cab73ef1f48b2649dcb792752e | Python | 3,591 | 102 | import numpy as np
from keras import layers, models
from functools import partial
import config
def _after_conv(in_tensor):
norm = layers.BatchNormalization()(in_tensor)
return layers.Activation('relu')(norm)
def conv3(in_tensor, filters):
conv = layers.Conv2D(filters, kernel_size=3, strides=1, padding='... |
71aac07d5a8bb832703c513fe51eeb40c4478a58075468b7e414f9ee907754e0 | Python | 3,594 | 49 | # TODO Sept 08 version
from .base_options import BaseOptions
import os
class TestOptions(BaseOptions):
"""This class includes test options.
It also includes shared options defined in BaseOptions.
"""
def initialize(self, parser):
parser = BaseOptions.initialize(self, parser) # define shared ... |
d951bda46dd199f51d4f39f3fe48a1564c33031dbf86173526883e95871bc422 | Python | 3,594 | 118 | #
# nate berry
# 2023-04-01
#
# ---------------------------------------------------------
# NOTES:
# - this script calcualtes sample entropy for EEG and COM data
# - calulations are made across a variety of embeddings and radii
# with a fixed lag (tau)s
#
# WARNING:
# - runtime on these scripts is not in... |
263d8f9c77332e4fc30ac5d885c9060ae594b3784f87f463ebda9ca51ecf5004 | Python | 3,596 | 80 | # -*- coding: utf-8 -*-
"""
Created on Mon Oct 08 17:01:43 2018
@author: saskiad
"""
import numpy as np
import pandas as pd
import os, h5py
import core
def Speed_Tuning(session_id, binsize=900):
save_path_head = core.get_save_path()
save_path = os.path.join(save_path_head, 'SpeedTuning')
l0_events = core... |
ffb0f97d4371ae6cee1dc56901deed9f4aa344c74960157aa21029806d385ee0 | Python | 3,596 | 122 | import numpy as np
import pytest
from pysteps.feature.tstorm import detection
from pysteps.utils import to_reflectivity
from pysteps.tests.helpers import get_precipitation_fields
try:
from pandas import DataFrame
except ModuleNotFoundError:
pass
arg_names = (
"source",
"output_feat",
"dry_input",... |
92de22696ceff254e130ca7f4f6e1d00c3a3b3422eab63c044eeeba04468e392 | Python | 3,597 | 111 | import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sns
import matplotlib.cm as cm
from Helper import calcW
FD_directory = 'Paper Data Change Sigmas'
PINN_data_directory = 'Data'
linewidth = 4
fontsize = 15
font = {'family' : 'monospace',
'weight' : 'bold',
... |
624860a1437dcbaff98fbf526581bf532f1c7f18ffd6927d713acac78b6fb776 | Python | 3,599 | 101 | #!/usr/bin/env python3
"""
Makes a group mask (excluding low signal voxels) for statistical comparisons
from input cifti files.
Usage:
ciftify_groupmask [options] <output.dscalar.nii> <input.dtseries.nii>...
Arguments:
<output.dscalar.nii> Output cifti mask
<input.dtseries.nii> Input cifti files
Options:... |
1c1cdaa61699770c66bdc4b09263850aaaa2280383a78ea25e194e7a6a5d011c | Python | 3,600 | 103 | """test_nowx.py - ensure that there's no dependency on wx when headless
"""
import builtins
import sys
import tempfile
import unittest
from urllib.request import urlopen
from tests.frontend.modules import example_images_directory, get_test_resources_directory
def import_all_but_wx(
name,
globals=builtins.glo... |
70d35b63304c022da37c5278ff33760b4b871d825e9d56c35c8d3192ed425758 | Python | 3,603 | 103 | import settings
import os
import subprocess
import numpy as np
from pathlib import Path
from sklearn.metrics import balanced_accuracy_score
def get_bal_acc(y_true, y_pred, windows_per_recording):
y_true = y_true.reshape((-1, windows_per_recording))[:,0] # need only one label per subject
... |
4d18e14d0269cedd8e008b4c193140aa4e0bee39df2f477bfc0a62ecb3d325f0 | Python | 3,607 | 84 | import numbers
import os
import pickle
class _ClassMapUnpickler(pickle.Unpickler):
"""Restricted unpickler for `.pkl` class map files.
A class map is a plain ``{class_name: index}`` dict of built-in types, which never
triggers ``find_class``. Disallowing all globals therefore blocks arbitrary code
ex... |
73e34097ce329e24d68cc29e3c195fd13b022099d81ce0e996df0778493d51a7 | Python | 3,610 | 102 | import torch
from copy import deepcopy
from GANDLF.metrics import get_metrics
from abc import ABC, abstractmethod
from typing import Union
class AbstractMetricCalculator(ABC):
def __init__(self, params: dict):
super().__init__()
self.params = deepcopy(params)
self._initialize_metrics_dict(... |
2aa3d0598fe1651ad1516cee47539a5197784660d82fc65a466c678fb6876647 | Python | 3,616 | 59 | import rvt.default
import rvt.blend_func
import rvt.blend
import rvt.vis
import numpy as np
# Test color relief image map (CRIM)
dem_path = r"D:\RVT_py\test\CRIM_TEST\Skolj_dem_05m.tif"
dem_dict = rvt.default.get_raster_arr(dem_path)
dem_arr = dem_dict["array"]
dem_res = dem_dict["resolution"][0]
output_srrim_path =... |
187b7252562c5a9b9db8a7caf09bdbe74c56f9cbcda603406853fdbdc6e772d5 | Python | 3,619 | 133 | import torch
import yaml
from yaml.loader import SafeLoader
import pdb
import mlflow
import os
from DT_for_WDN_leak_localization.dataset import get_dataloader
from DT_for_WDN_leak_localization.trainers.AE_trainer import train_AE
from DT_for_WDN_leak_localization.models.dense_decoder import Decoder as DenseDecoder
fro... |
25d4a48f57ceca61ea154d0268a195a388e9dd02ad961e78ece43c9fa5698eff | Python | 3,622 | 147 | import os
from concurrent.futures import ThreadPoolExecutor
from typing import Type
import numpy as np
import pytest
import xgboost as xgb
from xgboost import testing as tm
from xgboost.testing.data import make_categorical
from xgboost.testing.ordinal import (
run_basic_predict,
run_cat_container,
run_cat... |
2ff96931cf0ba31180f352e327dc9ed2b1bb100930d564fdc1b520d9d6b2d8f0 | Python | 3,622 | 92 | """Normalize curated references without inferring citation recommendations."""
from __future__ import annotations
from collections.abc import Mapping
from typing import Any
from datamonger._errors import UnsupportedRegistryError
from datamonger._validate import require_array, require_mapping, require_string
def ci... |
ae6d5d38e817333bcdf5b327739f512b97663bd722005bf5363ea3dea4e36386 | Python | 3,623 | 96 | import copy
from collections import deque, defaultdict
from dataclasses import dataclass, field, replace, asdict
from typing import Any, Deque, Dict, Tuple, Optional, Union
__all__ = ['PretrainedCfg', 'filter_pretrained_cfg', 'DefaultCfg']
@dataclass
class PretrainedCfg:
"""
"""
# weight source location... |
29300301a73b31315f1c247d6345c0fe05ce05338d549d5f8484ddc4f7fd7863 | Python | 3,625 | 78 | # -*- coding: utf-8 -*-
import argparse
import train
import setup
import os
import torch
import numpy as np
import time
import utils
def mkd(args):
try:
os.makedirs('output/' + args.codename)
except FileExistsError:
print('file already exists')
def main():
parser = a... |
ad68bf42b316966520997c59bc3915016ce007eb21c9512a575992a45ea4ebd3 | Python | 3,625 | 64 | import numpy
from typing import Callable, Optional, List, Tuple, cast, Union, Annotated
from numpy import isscalar as _isscalar
from pydantic import validate_call, ConfigDict, Field
from cellprofiler_library.opts.imagemath import Operator, BINARY_OUTPUT_OPS, UNARY_INPUT_OPS, BINARY_INPUT_OPS
from cellprofiler_library.t... |
f4fac258bbb7295296c74ffa89a443afb1f8724735a54712a0a20e5aec8d9adc | Python | 3,630 | 108 | import logging
import time
import threading
import tensorflow as tf
class Tracker:
def __init__(self, mins_to_update=1):
self.logger = logging.getLogger(__name__)
self.speed_counter_names = set()
self.last_counters = {}
self.counters = {}
self.mins_to_update = mins_to_upda... |
27c011e2d12ac580d95c7b3358cf23469d0ffe27634ada0a8929dde7f0405845 | Python | 3,638 | 101 | """ AvgPool2d w/ Same Padding
Hacked together by / Copyright 2020 Ross Wightman
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from typing import List, Tuple, Optional, Union
from ._fx import register_notrace_module
from .helpers import to_2tuple
from .padding import pad_same, get_padding_valu... |
6da5afdaa3fbe09e2868186b253d55c9f8f36bf888214e9a6d87e867e87a8929 | Python | 3,640 | 89 | from enum import Enum
from centriole.threshold import (
TM_OTSU,
TM_MOG,
TM_METHODS,
)
from .threshold import OtsuMethod as ThreshOtsuMethod
"""Root module measurement name"""
C_IMAGE_QUALITY = "ImageQuality"
C_SCALING = "Scaling"
class Feature(str, Enum):
FOCUS_SCORE = "FocusScore"
LOCAL_FOCUS_S... |
fbe6ac800cf3ca37cb36ef33e588357f49f33ba40cee2bd1c2666069a2be6ec6 | Python | 3,642 | 122 | # -*- coding: utf-8 -*-
# (C) Copyright 2020, 2021, 2022, 2023 IBM. All Rights Reserved.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
ba74c1508ec6b129c417c2827256c533087fea5e455f13d7b7f991a7f39b7328 | Python | 3,643 | 133 | """
Image classification webpage
Date: September 2018
Author: Ignacio Heredia
Email: iheredia@ifca.unican.es
Github: ignacioheredia
Description:
This script launches a basic webpage interface to return results for image classification prediction.
To launch this webpage you can run `python serve.py`.
Tip:
To host the... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.