sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
97caad0e0e6a50a2e152c4d237000fde4f356918a92ee5142921b543b569a6d3 | Python | 8,536 | 237 | import numbers
import random
from typing import Any
from typing import Dict
from typing import Tuple
from typing import Union
import numpy as np
import torch
import functional as func
from base import BaseTransform
class ImageOnlyTransform(BaseTransform):
"""
Transform applying on only image semantic types,... |
77eee4332255bda070fabb7d9100927a6d9bb79b691dfa34fedec9b8c9d6dfed | Python | 8,542 | 197 | """End-to-end tests of train.py's stop/milestone/in-place resume behaviour and YAML config validation."""
import csv
from pathlib import Path
import pytest
import torch
import yaml
from PIL import Image
from torch import nn
from timm.utils import load_checkpoint_metadata
# torch < 2.5 (no safe_globals) can't load tr... |
57b9147efe8475a21be53ac2ee6137fd97323a1ad5b31a9a6e6482302cd7cd74 | Python | 8,546 | 197 | """
Author: "Keitaro Yamashita, Garib N. Murshudov"
MRC Laboratory of Molecular Biology
This software is released under the
Mozilla Public License, version 2.0; see LICENSE.
"""
from __future__ import absolute_import, division, print_function, generators
import gemmi
import numpy
import pandas
import os
import jso... |
43f8715112436be6b7abb8c86b96fa83a5512d9b80d9beb2e5c3434156ed1b72 | Python | 8,565 | 187 | """
Author: "Keitaro Yamashita, Garib N. Murshudov"
MRC Laboratory of Molecular Biology
This software is released under the
Mozilla Public License, version 2.0; see LICENSE.
"""
from __future__ import absolute_import, division, print_function, generators
import gemmi
import numpy
import json
import os
import shuti... |
f86ef71f6f9df65a82211ed63cca3bfb0fceee796d1122c7ff913bff714d7d3c | Python | 8,577 | 268 | import torch
import torch.nn as nn
import torch.nn.functional as F
from rdkit.Chem import AllChem
import pandas as pd
from rdkit import DataStructs
from rdkit import Chem
import numpy as np
import matplotlib.pyplot as plt
import math
import random
import os
from torch.utils.data import DataLoader
from matplotlib import... |
1423b953268d8b1ad6460d3f1afec157b46127505cc4e50eb28cb4f7798c236b | Python | 8,580 | 201 | # -*- coding: utf-8 -*-
import collections
import gffutils
import warnings
from .utilities import InputError
import logging
FORMAT = "[%(levelname)s:%(filename)s:%(lineno)s - %(funcName)20s()] %(message)s"
logging.basicConfig(format=FORMAT)
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
warnings.filt... |
2f494af15e81b84e448c423f58d2773ead45eab0245d1461edf0e0a10ed9026b | Python | 8,581 | 201 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 15:58:38 2021
@author: filtsem
"""
from pathlib import Path
import numpy as np
import eelbrain
import re
import os
import mne
import pandas as pd
from mne.stats import (spatio_temporal_cluster_test, f_threshold_mway_rm, f_mway_rm)
from mne impo... |
9c0c4e5594caf5c05b92e9f8ef9b525e1d515e93f37b7af548d04738ed36611a | Python | 8,582 | 230 | import os
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
from rdkit.Chem import AllChem
from rdkit import Chem
from multiprocessing import Pool
from multiprocessing import cpu_count
from spektral.data import Dataset,Graph
from spektral.layers import GlobalSumPool,ECCConv
from spektral.data import BatchLoader
from pandas... |
4ab170de271cfd173894100428d3f2b35ce09e7f8747a73c873f65ac41e1fbfb | Python | 8,586 | 228 | #!/usr/bin/env python3
# Copyright 2019 Christian Henning
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... |
c89f03c848591bfedf1fc37730228b132c33ca2130b9b5aa0eca99b60a97c7e0 | Python | 8,586 | 149 | # The Small_network example from the Random Growth notebook.
from neurodevsim.simulator import *
from neurodevsim.processing import nds_plot,nds_movie
import numpy as np
class BRandomFront(Front): # the large one
def manage_front(self,constellation):
if self.order == 0: # soma: make 5 dendrite roots... |
6410b279a8e42d7aad268a1416591dc7cbe5d82138b93df35a9a8d68c1a14b75 | Python | 8,602 | 284 | #!/usr/bin/env python3
import argparse
import os
import math
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
from torchdiffeq import odeint, odeint_event
from bouncing_ball import BouncingBallExample
class HamiltonianDynamics(nn.Module):
def __init__(self):
super().__init__()
... |
c79bc19448c7a7feb357ee03af71cc4451bfcb9a8d89bef3a0d754bf1d19e3fc | Python | 8,607 | 204 | import torch
import torch.nn as nn
import torchvision.models as models
import torch.nn.functional as f
from models.submodules import InterpolationLayer
class SemSegE2VID(nn.Module):
def __init__(self, input_c, output_c, skip_connect=False, skip_type='sum', input_index_map=False):
super(SemSegE2VID, self)... |
20e15219f3cb158604cdf99c6c9e5a5021590a47930df98b5c7d39a2497fd1bf | Python | 8,608 | 244 | #!/usr/bin/env python3
""" Bulk Model Script Runner
Run validation or benchmark script in separate process for each model
Benchmark all 'vit*' models:
python bulk_runner.py --model-list 'vit*' --results-file vit_bench.csv benchmark.py --amp -b 512
Validate all models:
python bulk_runner.py --model-list all --resul... |
39b4f596c8200fd41ded4e1d8790c812e47be08eb43f05b8283125a9e293b987 | Python | 8,614 | 194 | import sys
import math
import numpy as np
import csv
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from dragen.utilities.Helpers import HelperFunctions
from dragen.generation.DiscreteRsa2D import DiscreteRsa2D
from dragen.generation.DescreteTesselation2D import Tesselation2D
from dragen.ge... |
797ef6e36a5d6fa2b38c6cf69d2a5895be852c9321b3b72527a0631a3dd43d71 | Python | 8,628 | 269 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jan 13 13:45:49 2021
@author: andrey
"""
import time
import pickle
from abc import ABC, abstractmethod
import numpy as np
from mne.preprocessing.maxwell import _sss_basis, _get_n_moments
from megsimutils.utils import _prep_mf_coils_pointlike
MU0 = 1e-... |
3b5960a329a865c842952b5e4ea6b036ad55bbc040af3f232be44c446a559e10 | Python | 8,630 | 150 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 15:58:38 2021
@author: filtsem
"""
from pathlib import Path
import numpy as np
import eelbrain
import re
import utils
import os
ANOVA_results_path = '/project/3027007.02/Scripts_for_publication/TRFs/Weights_ANOVA/Dutch_part2/'
language = 'Fr... |
b54fd01c6badd888a833ae4f7e75992d15091aa206d052434efe550f7e14c2a7 | Python | 8,630 | 219 | import io
import os
import tempfile
import cellprofiler_core.constants.modules.images
import cellprofiler_core.measurement
import cellprofiler_core.pipeline
import cellprofiler_core.pipeline.event._load_exception
import cellprofiler_core.workspace
import cellprofiler_core.modules.images
import cellprofiler_core.module... |
92511c0343c6cbf1eae4599c597a16a2c366960994861ae62e0b084b7fb43d68 | Python | 8,633 | 153 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 15:58:38 2021
@author: filtsem
"""
from pathlib import Path
import numpy as np
import eelbrain
import re
import utils
import os
ANOVA_results_path = '/project/3027007.02/Scripts_for_publication/TRFs/Weights_ANOVA/Dutch_part2/'
language = 'F... |
f6c11b466d9a8cc6600f30fe3b902c5d55e07847f66477b6bb03ff046c141be4 | Python | 8,634 | 252 | # coding: utf-8
# https://github.com/cfobel/si-prefix
from __future__ import division
import math
import re
# from ._version import get_versions
# __version__ = get_versions()['version']
# del get_versions
# Print a floating-point number in engineering notation.
# Ported from [C version][1] written by
# Jukka “Yucca” K... |
bf3410908e08f647a13782bd8b0d9aaa383bfdd469c2592cde29b0e63458cd1c | Python | 8,636 | 224 | """Alignment against a prebuilt large (.bt2l) index of more than 2^32 bases.
The rest of the suite checks the large-index code path on small genomes
forced into the .bt2l format with --large-index. Only an index whose joined
reference really exceeds 2^32 bases exercises offsets that do not fit in 32
bits, and building... |
9760b52d478a69b8b11302eb51ffcc663284e9354288a5f0dcdac7b90c4621b6 | Python | 8,641 | 193 | from .synapse import Synapse
class SequenceMemory():
'''
classdocs
'''
def __init__(self, neutype):
'''
Constructor
'''
self.neutype = neutype
self.sequenceLayers = {}
def createActionSequenceMem(self, layernum, neutype, neunumpergroup):
pass
... |
8ca7aaa73e222eef057b03b350c319fa2967442013f279557400a30802a629f5 | Python | 8,642 | 191 | from pathlib import Path
from shutil import copyfile
import logging
import sys
import numpy as np
import torch
import torchio as tio
import SimpleITK as sitk
from monai.metrics import compute_meandice
from breaststudies.augmentation.augmentations import Resample2, ZNormalization, ToOrientation, RandomDisableChan... |
ad0ec888db7acdd78f1d77ee77778e8e60c9e001bab23b37ea683e846df1e30c | Python | 8,649 | 217 | #!/usr/bin/python
'''
This script parses an input PDB file and FASTA sequence and maps the sequence
to the PDB file using mafft. The script produces a CSV with columns for with
PDB residue numbering, corresponding FASTA sequence numbering, and the amino
acid. The map produced will have gaps because not all amino acids... |
1ba1467d7ddfcaaf9f91c5b847daade2617929a74df6ccd55d3ec6967ee38ef0 | Python | 8,651 | 208 | """
Computes backward model scores.
@author: JingyiGF
"""
from .toolkits import *
from .family import *
from .metrics import *
from .solver import Solver
import scipy.io
def calc_xpr(y, yhat, nt):
tpath = np.linspace(0, 1, nt)
tp = np.zeros(nt)
tn = np.zeros(nt)
fp = np.zeros(nt)
fn = np.zeros(nt... |
ddfafc0ba0a5a7dc2fb919dff6289cc608d06c49c22dc85cef878ba39bca66f4 | Python | 8,653 | 255 | from rdkit import Chem
from rdkit.Chem import AllChem,Draw,Descriptors
import json
import pandas as pd
from lib.DrawingMolecules import drawSmilesRxn
import numpy as np
from rdkit.Chem.Draw import IPythonConsole, ReactionToImage
import os
import re
from lib.Reaction_Library_Mother import *
def match_with_smiles(rxn_d... |
7092c1f91ffd20e8ec2675fd9daa89ef0210a504025322aa22812cfe5247aa2a | Python | 8,667 | 238 | import os
from glob import glob
import argparse
from itertools import product
from datetime import datetime
import numpy as np
import SimpleITK as sitk
from tqdm import tqdm
from dice_score import mean_dice_np
from helpers import *
from dbx import *
import wetransfer
from tensorflow.keras.utils import... |
7851e78f4cbd91bef5e6e42f42a0fd19c442e688e6ac046021828b932ff8a888 | Python | 8,672 | 232 | """ Convolution with Weight Standardization (StdConv and ScaledStdConv)
StdConv:
@article{weightstandardization,
author = {Siyuan Qiao and Huiyu Wang and Chenxi Liu and Wei Shen and Alan Yuille},
title = {Weight Standardization},
journal = {arXiv preprint arXiv:1903.10520},
year = {2019},
}
Code:... |
ecbeaf26b53f10239c463bf63c1f67357f03f37682cf2dc8cd1957191bf3a863 | Python | 8,676 | 266 | """
Tests for nbdc2reproschema converter.
Tests support both Parquet (preferred) and legacy RDS formats.
"""
import os
import shutil
from pathlib import Path
import pytest
import yaml
from click.testing import CliRunner
from ..cli import main
from ..nbdc2reproschema import detect_input_format, load_nbdc_data_csv
Y... |
3c5c498056a3d7cb827d23ce54d0dfea809b0bf9dd9288d75bd00f40765f0130 | Python | 8,684 | 289 | from enum import Enum as BaseEnum
from traitlets import Float, Integer
from traitlets.config import Bool, List, Unicode, default
from mrHARDI.base.application import (BoundedInt,
DictInstantiatingInstance,
mrHARDIConfigurable,
... |
aeaf414cfac3813754a711f394784cfcef6484910fc8bb9ebb774729ffd98e85 | Python | 8,688 | 201 | import warnings
from typing import Dict, Optional, Tuple, Union
import torch
import torch.nn as nn
from .norm import build_norm_layer
from .activation import build_activation_layer
class ConvModule(nn.Module):
"""A conv block that bundles conv/norm/activation layers.
This block simplifies the usage of conv... |
8b5ae750b63fc7b0e5d450acd907886bffe07d7b4163073ed078b357c891511c | Python | 8,693 | 255 | #!/usr/bin/env python3
import os
import unittest
import logging
from subprocess import CalledProcessError
import pkg_resources
from unittest.mock import patch
import pytest
import ciftify.config
logging.disable(logging.CRITICAL)
class SetUpMixin(object):
def setUp(self):
# Clear the shell environment, s... |
98f9382343e151d71daf0552f99174840308331a1dee4feada676a5671d7cf8e | Python | 8,701 | 230 | """
Find EEG files and select cases
===============================
This script scans through a dataset folder with EEGs/MEGs and collects meta information, such as the number of channels and the age of the subject.
The result is put in pandas DataFrame, which is stored as a file.
Some ... |
8739f0b6c0bb171b9bfbda54ff28d7da90a4905a832a85b34e4d6a11c73e9123 | Python | 8,708 | 207 | from __future__ import absolute_import
from __future__ import division
import numpy as np
import scipy.ndimage as scind
import unittest
import centriole.zernike as z
from centriole.cpmorphology import fill_labeled_holes, draw_line
from centriole._np_compat import np_product
class TestZernike(unittest.TestCase):
d... |
881e34b6e7b16d04b83b65b3801b5311862680ba404610bfc82322f0af88427f | Python | 8,711 | 251 | from typing import Optional
import torch
import torch.nn.functional as F
from GANDLF.utils import one_hot
from torch.nn import CrossEntropyLoss
def CEL(
prediction: torch.Tensor, target: torch.Tensor, params: dict = None
) -> torch.Tensor:
"""
Cross entropy loss with optional class weights.
Args:
... |
97cd72b919ef29d5236c4dfcbb0d3e1836ace08b0f8955e146984d094e059974 | Python | 8,722 | 226 | """
Example of an elaborate dialog showing a multiple views on the same data, with
3 cuts synchronized.
This example shows how to have multiple views on the same data, how to
embedded multiple scenes in a dialog, and the caveat in populating them
with data, as well as how to add some interaction logic on an
ImagePlane... |
461b9ba384585d2680f1d1e80b11980da82b6140d623d33958b884b992dc5686 | Python | 8,738 | 239 | """
Author: Ran Liu <rliu20@stanford.edu>
Implementation of phase-amplitude coupling estimation methods
"""
import numpy as np
import pathlib
from importlib.util import find_spec
from somata.basic_models import StateSpaceModel
from somata.exact_inference import inverse
from numpy import ndarray
from cmdstanpy import ... |
cc477c5ddf38fe538752795b4e1683dec0f3394653d1dc1dfe66deb71e64232b | Python | 8,744 | 224 | import os
import sys
from datetime import datetime
from pprint import pformat
import shutil
from imp import reload
# Add parent directory to path to allow imports.
top_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if not top_dir in sys.path: sys.path.insert(0, top_dir)
from cli.experime... |
56eb71cff020f3bd6302aa1222173937a1457f9ab8b93833827d64dea0a6851a | Python | 8,752 | 208 | import PyDSTool
import matplotlib.pyplot as plt
import pickle
import numpy as np
from matplotlib.ticker import FormatStrFormatter,ScalarFormatter
from scipy import stats
from matplotlib.lines import Line2D
import matplotlib as mpl
'''
This script runs the ode model, and plot the results along the average traces of the... |
71871d327e0dd004a1874f78d8ebf8468e4ec4789514c2a170d6898f3643b8be | Python | 8,758 | 240 | import os
import urllib.parse
import urllib.request
import logging
from functools import cached_property
import numpy
from cellprofiler_core.constants.image import MD_SIZE_S, MD_SIZE_C, MD_SIZE_Z, MD_SIZE_T, MD_SIZE_Y, MD_SIZE_X, \
MD_SIZE_KEYS, MD_SERIES_NAME
from cellprofiler_core.constants.modules.metadata imp... |
308ceb9fad558bb43cabb2bbc9a02adb2f5d712fdaa4c6bbd323b23f23568aa3 | Python | 8,765 | 243 | # -*- 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... |
bedbcc61a655b3b2107708ed9bf51279448263d1ea68dfb4df4ae4c642e31f29 | Python | 8,766 | 146 | import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import gridspec, lines
import matplotlib.transforms as transforms
import seaborn as sns
import statsmodels.api as sm
from statsmodels.formula.api import ols
import scipy.stats as stats
from scipy.stats import mannwhitneyu
... |
dda037bd23bab4b09424252801076e13059968c950897b3ef5c19c47c4dad8ed | Python | 8,768 | 282 | # -*- 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... |
501df5850c999749e310bb63c00a822e24a4dc7d4d726f2cbc4d19e1f518593d | Python | 8,773 | 247 | import torch
import torch.nn as nn
from torch import optim
from pytorch_lightning import seed_everything
import argparse
class MultiOutputRegression(torch.nn.Module):
def __init__(self,
n_src=6,
n_feat=21140,
ff_hid=64,
**kwargs
):... |
06e16c0d2c165dd11edf21a81175e64a2ff15a3541b59b71ef5de4db64196be9 | Python | 8,775 | 203 | import numpy as np
import pytest
from pysteps.postprocessing.probmatching import (
nonparam_match_empirical_cdf,
resample_distributions,
)
class TestResampleDistributions:
@pytest.fixture(autouse=True)
def setup(self):
# Set the seed for reproducibility
np.random.seed(42)
def te... |
c24ec18cd41384f542786118cd043739adb6d8380aafc625795746f5ddfd441d | Python | 8,784 | 265 | from copy import deepcopy
from enum import Enum
from os.path import join, dirname, basename, exists
from mrHARDI.compute.utils import validate_affine
import numpy as np
from traitlets import Dict, List, Bool, Integer, Float, Unicode
from traitlets.config.loader import ConfigError
from mrHARDI.base.application import ... |
a610cc27e04f487f27b1fa9c24b5277614046f4db551fd4289ca400790be82f6 | Python | 8,785 | 267 | from torch.optim import (
Optimizer,
SGD,
ASGD,
Rprop,
Adam,
AdamW,
# SparseAdam,
Adamax,
Adadelta,
Adagrad,
RMSprop,
RAdam,
NAdam,
)
def sgd(parameters) -> Optimizer:
"""
Creates a Stochastic Gradient Descent optimizer from the PyTorch `torch.optim` module ... |
95f2245c68580f32468d8d5aa0d1d5e64049ff41700b7dde7643b0591c46c9f3 | Python | 8,790 | 269 | from __future__ import division
import numpy as np
from scipy.stats import ttest_rel,ttest_1samp,ttest_ind,zscore
from matplotlib.pylab import *
from pickle import dump,load
from scikits import bootstrap
import seaborn as sns
from scipy.stats import *
from scipy.io import loadmat
import warnings
warnings.filterwarnings... |
b9fe452a398c00443d0bda3e9f59cd3200c6ef4532c7db575750cb2b730f3183 | Python | 8,791 | 219 | # --------------------------RuleShift Reward for Hole-2 Protocol Task File----------------------
# Subject were habituated to hole 2 and 4 previously now they need to learn new rule, i.e only one hole
# .... (either 2 or 4 depending on reward hole) gives reward, irrespective of illumination (hole_2 or hole_4)
# cue ... |
5300783ee4fc22e4cebacaed914f64e7c079b82832a0e6a26ef83a30214fca3f | Python | 8,792 | 249 | # -*- coding: utf-8 -*-
"""
pysteps.utils.cleansing
=======================
Data cleansing routines for pysteps.
.. autosummary::
:toctree: ../generated/
decluster
detect_outliers
"""
import warnings
import numpy as np
import scipy.spatial
def decluster(coord, input_array, scale, ... |
7ffd41fef091e4bd9e2358181b427cb2f718b9e1a26263e172757a6fafeb449a | Python | 8,801 | 219 | # --------------------------RuleShift Reward for Hole-4 Protocol Task File----------------------
# Subject were habituated to hole 2 and 4 previously now they need to learn new rule, i.e only one hole
# .... (either 2 or 4 depending on reward hole) gives reward, irrespective of illumination (hole_2 or hole_4)
# cue ... |
a41fda304cfba862b147ac05454fbafa6e8cde27835797d420488ea86d0ca83d | Python | 8,804 | 180 | from __future__ import print_function
import svgwrite
import os
import logging
import argparse
logger = logging.getLogger('root')
logger.propagate = False
boxWidth = 10
box_size = 15
v_spacing = 3
colors = {'G': '#F5F500', 'A': '#FF5454', 'T': '#00D118', 'C': '#26A8FF', 'N': '#B3B3B3', '-': '#FFFFFF'}
def parseSi... |
74b77b752365fc941e3636d5ee4fe4c50731bbd559c1311345aee537f6f197a7 | Python | 8,808 | 214 | import numpy as np
import torch
import torch.nn as nn
from . import GVP, GVPConvLayer, LayerNorm, tuple_index
from torch.distributions import Categorical
from torch_scatter import scatter_mean
class CPDModel(torch.nn.Module):
"""
GVP-GNN for structure-conditioned autoregressive
protein design as described... |
8765b8f155676467786fd787ea2b17dc1766d53a0f71751d9d3ab384a0cf8701 | Python | 8,812 | 256 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for charge.py"""
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
import logging
from rdkit import Chem
from molvs.standardize import Standardizer, standardize_smiles
from molvs.charge import Reionizer... |
a6f388e6868cf862c31764dd2bd17d8ff28ccafca9361d79e47badfc0bd9a618 | Python | 8,814 | 203 | import os, sys, pickle
from typing import Optional
from pathlib import Path
import SimpleITK as sitk
from GANDLF.utils import (
get_filename_extension_sanitized,
parseTrainingCSV,
populate_header_in_parameters,
get_dataframe,
get_correct_padding_size,
)
from GANDLF.config_manager import ConfigManag... |
ecfe010ac9302e80a1a271e2653990e24b17e0968280e9e12a338cdc3a2adbb6 | Python | 8,814 | 230 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# ==== Libraries ====
import os
# ==== Functions ====
def replace_allnew(astr, bstr, dict):
with open(astr, 'r') as afile:
with open(bstr, 'w') as bfile:
data = afile.read()
for key, value in dict.items():
data = data.re... |
ab5bad480db524593be1342c7e00b7923f5c2e4ebd95f15cccdc2ed88a9f1c95 | Python | 8,818 | 223 | import torch
import pytorch_lightning as pl
from torch.optim.lr_scheduler import ReduceLROnPlateau
def flatten_dict(d, parent_key="", sep="_"):
"""Flattens a dictionary into a single-level dictionary while preserving
parent keys. Taken from
`SO <https://stackoverflow.com/questions/6027558/flatten-nested-di... |
03523ff82311a4618f53342c310e76c1c1633446a26de3b36811d9fa17335f71 | Python | 8,823 | 233 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 5 15:58:38 2021
@author: filtsem
"""
from pathlib import Path
import numpy as np
from matplotlib import pyplot
import os
import mne
import pandas as pd
import pickle
import matplotlib
subjects_dir = '/Volumes/project/3027007.01/processed/'
fnam... |
20bd0427f6206b5062285d0f6015cdac857be1c19edc25f3d31f5f2a1571f956 | Python | 8,832 | 192 | import os
import numpy as np
import pandas as pd
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import matplotlib.colors
from scattermap import scattermap
import matplotlib.pyplot as plt
from matplotlib import lines
import seaborn as sns
import sszpalette
colorsmaps=sszp... |
a8ffd14c5c94dcf59269cd193133f18b773266a09fdf50aab157962c68f3495d | Python | 8,839 | 228 | """Build a visualization of the network diagram. The specific use case this was
designed for is post-compilation Loihi networks, to get a clearer vision of the network
layout after the passthrough remove function has run and DecodeNeurons are added in.
Ensembles - Octagons
- black: off-chip
- green: on-chip
Nodes - B... |
b4a9b11fde73ec36eb81c2f16dd79de5281ca3ba40993c45c097fcb38bba8373 | Python | 8,863 | 238 | """rules - code for parsing and applying rules from CPA
"""
from difflib import SequenceMatcher
from rapidfuzz import process
import re
import numpy
from cellprofiler_core.module import Module
from cellprofiler_core.setting import Binary
FUZZY_FLOAT = 0.7 # We may eventually want to parametrize this with a setting,... |
c093871397f1f3be1e7083ab8dfc7d457cc83798f684e37b31ab328d86316217 | Python | 8,865 | 229 | """Packet segmentation: split each transformable parent grain into martensite packets.
Two regimes, as in the original implementation:
* A grain that touches the RVE surface may have been split by periodicity into several disconnected
pieces. Each connected component becomes its own packet -- a k-means split across... |
fe9bbc903f558ec200a44c552b0e70bc169bc1464733349ca1336383cd2c4d2f | Python | 8,883 | 280 | import re
from collections import OrderedDict
import numpy as np
from itertools import cycle
# Light version of webcolors
# http://stackoverflow.com/a/4382138/1060738
# Kelly's 22 colors of maximum contrast
kelly_colors = OrderedDict()
kelly_colors_dic = dict(vivid_yellow=(255, 179, 0),
strong_purp... |
9f6b65b59e36ec6ef642445c3e72dc2be5444d277e8fe3f45d8287341550c34c | Python | 8,885 | 239 | import argparse
import os
import warnings
from pathlib import Path
import optuna
import pandas as pd
import pytorch_lightning as pl
import torch
import wandb
import yaml
from optuna.integration import PyTorchLightningPruningCallback
from pytorch_lightning.loggers import WandbLogger
from sklearn.model_selection import ... |
da5b9e7bf9da6d1ad01de385b5c14c0b352cf8e83c5291eb833549ffbae14b77 | Python | 8,892 | 251 | # -*- coding: utf-8 -*-
#
# MolVS documentation build configuration file, created by sphinx-quickstart on Thu Apr 24 14:35:38 2014.
# This file is execfile()d with the current directory set to its containing dir.
# Note that not all possible configuration values are present in this autogenerated file.
# All configurati... |
dcc8a89acb1f3b78eb367ad3cf5af7c03678b4abf96559b1f0a605cf861cf2ec | Python | 8,902 | 233 | """ Dataset Factory
Hacked together by / Copyright 2021, Ross Wightman
"""
import os
from typing import Optional
from torchvision.datasets import CIFAR100, CIFAR10, MNIST, KMNIST, FashionMNIST, ImageFolder
try:
from torchvision.datasets import Places365
has_places365 = True
except ImportError:
has_places3... |
9a15a343f66d9dadf80a8318ff3270a18112e4253300f73b41340b7f7268f950 | Python | 8,904 | 258 | from xml.etree import ElementTree as xml_parser
from ipython_genutils.text import wrap_paragraphs
from traitlets.config import (Configurable,
HasTraits,
Config,
PyFileConfigLoader,
ConfigFileNotFound... |
ec7a5c1518f8245d62a8a20b42aac514fe0fb6b7aa260e83cf678d8e47861145 | Python | 8,906 | 227 | import os
import pickle
from PIL import Image
import h5py
import json
from torchmeta.utils.data import Dataset, ClassDataset, CombinationMetaDataset
from torchvision.datasets.utils import download_file_from_google_drive
class MiniImagenet(CombinationMetaDataset):
"""
The Mini-Imagenet dataset, introduced in ... |
7ea07b690bd7a2c5a0339a4f2ef5f9e42373e7674864a99f7d7b204d8fd89150 | Python | 8,912 | 288 | '''
JHK
Python script for conducting binnning analysis
'''
from netCDF4 import Dataset
import numpy as np
import os, pathlib
#==========================================================
# Set main directory
#==========================================================
hdir = '/home/jhkim/model/deep_detection'
#=======... |
79f082eb6b9909c6e27c3258d1c7c8d722021abcd15b2aa4d62f6ea79cccbc66 | Python | 8,913 | 221 | import sys
import numpy as np
import torch
import torch.nn as nn
from numpy import prod
from torch.distributions.beta import Beta
sys.path.append("..")
import torch.nn.functional as F
import utils
spike_args = {}
spike_args['thresh'] = utils.args.thresh
spike_args['lens'] = utils.args.lens
spike_args[... |
57dcfd01dec457f9de84aeb3f70a6789cd530cc32fd0a3e69e6c3454f2071894 | Python | 8,914 | 298 | #!usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import argparse
import ast
from typing import Optional
from deprecated import deprecated
import click
from GANDLF import version
from GANDLF.cli import main_run, copyrightMessage
from GANDLF.entrypoints import append_copyright_to_help
from GANDLF.u... |
a9951292fcfda262ef6114178204c3a06c3d8b4214d62777f1ab570f9ea6df02 | Python | 8,922 | 254 | #!/usr/bin/env python3
import os
from datetime import datetime
import joblib
import pandas as pd
from julearn import run_cross_validation
from julearn.scoring import register_scorer
from scipy.stats import pearsonr, spearmanr
from sklearn.metrics import make_scorer
os.environ["OPENBLAS_NUM_THREADS"] = "1"
# -----... |
747f4b52d7e27c14057619aaa30327131938589241c0c963a44c14d25f675730 | Python | 8,924 | 251 | import argparse
import os
import warnings
from pathlib import Path
import pandas as pd
import pytorch_lightning as pl
import torch
import wandb
import yaml
from pytorch_lightning.callbacks import ModelCheckpoint
from pytorch_lightning.loggers import CSVLogger, WandbLogger
from sklearn.model_selection import Stratified... |
f3dc2029c140ed3111a6f7bdd1629014af4dfdfc2e954eb4a1f1c5559c443411 | Python | 8,938 | 233 | # -*- coding: utf-8 -*-
"""
Implementation of UNet
"""
from .modelBase import ModelBase
from GANDLF.models.seg_modules.DownsamplingModule import DownsamplingModule
from GANDLF.models.seg_modules.EncodingModule import EncodingModule
from GANDLF.models.seg_modules.DecodingModule import DecodingModule
from GANDLF.models.s... |
92c8b37792ad19e7a9ea93d292acf2ccd0cdb5fd876114fbe354e07719db3fcf | Python | 8,939 | 242 | """
Tests for bidsmri2nidm.py
Focuses on edge cases in how participants.tsv (and phenotype/*.tsv) column
headers are handled. These tests do not require network access and run
entirely from a synthetic BIDS directory built in a pytest tmp_path.
"""
from __future__ import annotations
import argparse
from io import St... |
4969f87fe2055ae260ee39bba63cc5000123f38ec13c499a2bc542bcd1a61ef4 | Python | 8,946 | 287 | import os
import os.path
import hashlib
import gzip
import errno
import tarfile
import zipfile
import tqdm
def gen_bar_updater():
pbar = tqdm(total=None)
def bar_update(count, block_size, total_size):
if pbar.total is None and total_size:
pbar.total = total_size
progress_bytes = ... |
0d4aca911dde008bf730522f630ea60e336ef869e5beeb9a5530660c3bed05ca | Python | 8,947 | 295 | from __future__ import annotations
import hashlib
import json
import math
from pathlib import Path
from typing import Any, cast
import numpy as np
import pytest
from hypothesis import given
from hypothesis import strategies as st
from datamonger._canonical import canonical_bytes, canonical_sha256
from datamonger._mo... |
2047ce241398537d6e502716f1f3bb7a285b006554f2e27e9a68618d68376ac2 | Python | 8,956 | 231 | """ DropBlock, DropPath
PyTorch implementations of DropBlock and DropPath (Stochastic Depth) regularization layers.
Papers:
DropBlock: A regularization method for convolutional networks (https://arxiv.org/abs/1810.12890)
Deep Networks with Stochastic Depth (https://arxiv.org/abs/1603.09382)
Code:
DropBlock impl ins... |
5bba853c42bcdea124c8c5602cd767b91209d6286a85228a13af19881d52b025 | Python | 8,960 | 254 | #!/usr/bin/env python3
import os
import unittest
import logging
import shutil
import random
import copy
import pytest
from unittest.mock import patch
import ciftify.utils as utils
logging.disable(logging.CRITICAL)
class TestGetSubj(unittest.TestCase):
path = '/some/path/somewhere'
@patch('os.path.exists')
... |
bdb8db10fbfdc733b9c9ffffb66fdec7650c6f20d215b2b846c31faedc305383 | Python | 8,960 | 178 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.parallel
import torch.optim
import torch.utils.data
from torch.utils.data.dataloader import DataLoader
import argparse
import os
import time
import math
import matplotlib
matplotlib.use('agg')
from util import (prepar... |
f3084242e001b337663646ee8bbf951bb7992a0746acc187815fb2ce17d98b80 | Python | 8,962 | 289 | # -*- 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... |
8ebf9542a2003c135dd0ab3c1968535e0d1b374e6ae293a42e265541f65db59d | Python | 8,964 | 245 | """RAG (Retrieval-Augmented Generation) for the AFIDs guided learning mode.
Knowledge chunks (landmark definitions, protocol passages, etc.) are stored in
PostgreSQL alongside their embeddings. At query time the most semantically
relevant chunks are retrieved and injected into the LLM context window,
replacing the lar... |
d2f8f7d3d3c6db7f0a0741d77cb0d5bc0a17e885f6edeafce0e4c81b8d5cec73 | Python | 8,964 | 251 | import torch
import torch.nn as nn
from sklearn.metrics import r2_score, accuracy_score, f1_score, roc_auc_score
class EngineSol:
def __init__(self, model, optimizer, device):
self.model = model
self.device = device
self.optimizer = optimizer
@staticmethod
def loss_fn(... |
e59780ab754d81afb6e21dc70381dcdbe369fc2a359bbda0b7bb069559eb62e4 | Python | 8,973 | 246 | import re
from collections import OrderedDict
from functools import partial
from typing import Any, List, Optional, Tuple
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as cp
from torch import Tensor
__all__ = [
"DenseNet",
"DenseNet121_Weights",
"DenseNet... |
2598754eae44080a2f99f3085e785c41bb7425b90315b1ff1ec28f59ffbdfa09 | Python | 8,975 | 243 | import os
import pkgutil
from copy import deepcopy
from typing import Optional
from torch import nn as nn
from timm.layers import Conv2dSame, BatchNormAct2d, Linear
__all__ = ['extract_layer', 'set_layer', 'adapt_model_from_string', 'adapt_model_from_file']
def extract_layer(model, layer):
"""Extract a layer f... |
764339f2ec44aecc3e7acdfce61d5c03bccc85da106193a844d11de5cbdedc81 | Python | 8,975 | 232 | # # coding=utf-8
# """Tests for cellprofiler.gui.html.manual"""
#
# import cellprofiler.gui.html.manual
# import cellprofiler_core.preferences
# import os
# import re
# import tempfile
# import traceback
# import unittest
#
#
# class TestManual(unittest.TestCase):
# def setUp(self):
# self.temp_dir = tempfi... |
3221a10a5be47e81ef5f23df726bdafbc15c25bf531316da1e3683e8d7089d40 | Python | 8,982 | 267 | """ Lion Optimizer
Paper: `Symbolic Discovery of Optimization Algorithms` - https://arxiv.org/abs/2302.06675
Original Impl: https://github.com/google/automl/tree/master/lion
References for added functionality:
Cautious Optimizers: https://arxiv.org/abs/2411.16085
Why Gradients Rapidly Increase Near the End of ... |
9345ad1924dae30276b2d371f885404fd5c0acf06ac77019b6cee09d4c1f2292 | Python | 8,983 | 237 | #!/usr/bin/env python3
"""
Produces a correlation map of the mean time series within the seed with
every voxel in the functional file.
Usage:
ciftify_seed_corr [options] <func> <seed>
Arguments:
<func> functional data (nifti or cifti)
<seed> seed mask (nifti, cifti or gifti)
Options:
... |
76ec61f6ba979dc45bedfe166a689dfe9d1467bef915196092c3eba4d9d1a458 | Python | 8,990 | 229 | import os
import sys
from ._text import Text
from .._validation_error import ValidationError
from ...preferences import ABSOLUTE_FOLDER_NAME
from ...preferences import DEFAULT_INPUT_FOLDER_NAME
from ...preferences import DEFAULT_INPUT_SUBFOLDER_NAME
from ...preferences import DEFAULT_OUTPUT_FOLDER_NAME
from ...prefere... |
b36aff07e855d1186d68c678647dbf1c718d5fcbe17a8b6358ad6e68b47d5af8 | Python | 8,990 | 239 | # -*- coding: utf-8 -*-
"""
Handling of no-data in Lucas-Kanade
===================================
Areas of missing data in radar images are typically caused by visibility limits
such as beam blockage and the radar coverage itself. These artifacts can mislead
the echo tracking algorithms. For instance, precipi... |
ac05e60b3db2678919a422cbd24da4bad31ea0211670787ba84d992b8b531679 | Python | 8,995 | 233 | import numpy as np
import torch
from hausdorff import hausdorff_distance
from sklearn.metrics import roc_curve, auc, roc_auc_score, r2_score
from torch import sigmoid
from torch.nn.functional import binary_cross_entropy
from torch.autograd import Function
from torch_geometric.data import Data
from .progress_bar import... |
83293dd5d1653ec5e4c50e5780fc0ac9673398a60f9baa93d7b5c9964ce84c2f | Python | 9,002 | 205 | # Neural Oblivious Decision Ensembles
# Author: Sergey Popov, Julian Qian
# https://github.com/Qwicen/node
# For license information, see https://github.com/Qwicen/node/blob/master/LICENSE.md
"""Dense ODST Block"""
from warnings import warn
import numpy as np
import torch
import torch.nn as nn
from .utils import Modu... |
18b86fbf8351cca2625f7dd424df1497c885efd32eda63d53f471f71caaaf53d | Python | 9,006 | 168 | #### Master Script 4e: Calculate metrics for test set performance ####
#
# Shubhayu Bhattacharyay
# University of Cambridge
# email address: sb2406@cam.ac.uk
#
### Contents:
# I. Initialisation
# II. Calculate testing set calibration and discrimination metrics based on provided bootstrapping resample row index
### I. ... |
c340a86a566d1965847ef17fe79d756cb0896301e0e3a09a280288c8eb25f637 | Python | 9,021 | 229 | import sys
import os
from parsers import actions
from parsers import formula_actions
from parsers import nist_ion_descriptions
from parsers import formula
electron = 0.00054858
#
# Based on: https://github.com/suzaku/plain_obj
#
def make_constructor(fields):
assignments = '\n'.join([f' self.{f} = {f}' for f ... |
afd73f70eb936ecc8ca5cfacb54a8759eefca1a1598294c47c50e2cb0dac59d7 | Python | 9,029 | 184 | #!/usr/bin/env python3
""" Class Weights
Count per-class labels over a dataset split and write the class stats (per-class positive counts and the
sample count) used by train.py `--class-stats`. From the stats train.py derives `--loss-pos-weight neg_pos`,
`--loss-class-weight inv_freq / effective_num` weights (bce, mul... |
759bee82e934260f449251adf1da7b85bf7145ee0dd1c78014c337492920a0e0 | Python | 9,033 | 244 | import json
import math
import os
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from utils import timer
from distance_calculation import get_mds
def get_dataset(datafile):
with open(datafile, "r") as json_file:
return np... |
1c5108798f618d759b1e639660af5c26d7d1d9d1e582b60423c5a2837bcb24e8 | Python | 9,034 | 230 | # -*- 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... |
2fd6246d10609b3cad8af1cea979ab55e65ba8b2e4e5c54f953e60c2dd721e4d | Python | 9,035 | 260 | import logging
import sys
from datetime import datetime
from enum import Enum
from typing import Dict, Optional, Sequence
from dateutil.parser import parse
from imctools.data.channel import Channel
from imctools.data.slide import Slide
if sys.version_info >= (3, 8):
from typing import TypedDict # pylint: disabl... |
8b8e002629c7180248b3c93837d42489fadd5813ee4c3290d5c667289ce05c88 | Python | 9,039 | 205 | import PyDSTool
import numpy as np
import pickle
import matplotlib.pyplot as plt
from matplotlib.ticker import FormatStrFormatter,ScalarFormatter
import matplotlib as mpl
from matplotlib.lines import Line2D
'''
This scrip regenates figure 7 of the paper. It shows the effect of the number of VDACs on ATP efflux
08.11.2... |
bf38cf2a69732059bb6ec37a0766f6a69c6503372b5670a5ec72a7166a7ebc99 | Python | 9,039 | 258 | """
SaveCroppedObjects
==================
**SaveCroppedObjects** exports each object as an individual image. There are two modes to this module
depending on whether the user wants to save cropped **Images** or **Masks**:
* In **Images** mode, the input image is cropped to the bounding box of each object. Pixels
co... |
8e05f4dc0166b7d044a23be2256c82cae4d510751de3b49b6ee0c133fb3c356d | Python | 9,048 | 310 | import os
from itertools import combinations
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from baycomp import two_on_single
from etspredict.prediction.scoring_utils import compare_propabilites
##########################################################... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.