sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
f8529ac321492d55c50f9cf79fa9f667fd87bb9b1abffbae21190e9744a70a93 | Python | 1,349 | 31 | import copy
import torch
from fedml_api.standalone.fedavg.client import Client
class Client(Client):
def train(self, global_round_idx, group_round_idx, w):
self.model.load_state_dict(w)
self.model.to(self.device)
if self.args.client_optimizer == "sgd":
optimizer = torch.optim... |
392021a12235dc6568861e037e5bcdb318ed72d55779925ed7e5d5f343696a27 | Python | 1,350 | 56 | #!/usr/bin/env python
import sys
import gzip
by_chrom = {}
libs, libChroms = {}, {}
for libl in open(sys.argv[2]):
lib=libl.rstrip()
sys.stderr.write("checking %s... "%lib)
libs[lib] = 0
libChroms[lib] = []
counted = {}
for ln in open(lib):
lnsplit=ln.split()
if len(lnsplit)<6... |
6850ed376f8a14d6ff18620ef7e4fed06da0f294b8d7dff213025e3912080c0a | Python | 1,355 | 57 | # import cPickle
import _pickle as cPickle
import logging
import time
from keras.models import Sequential
def save_model(model, filename):
print ('saving model in', filename)
f = file(filename + '.pkl', 'wb')
import sys
sys.setrecursionlimit(100000)
cPickle.dump(model, f, protocol=cPickle.HIGHES... |
fbdaabe38e9be1096454e18ebce34869a1897bfb46cda1c43d65de0edc94fbdc | Python | 1,357 | 41 | import numpy as np
from tensorflow.keras import Input
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.models import load_model, Model
from attention import Attention
def run_test(data_x, data_y, time_steps, input_dim, score):
# Define/compile the model.
model_input = Input(shape=(time_s... |
a47389323856423966ad354d11cdae11419b0d27fd1dc2e57b77b7f0a3c8ff16 | Python | 1,358 | 40 | # Copyright (c) OpenMMLab. All rights reserved.
import math
import torch
from torch.utils.data import DistributedSampler as _DistributedSampler
class DistributedSampler(_DistributedSampler):
def __init__(self,
dataset,
num_replicas=None,
rank=None,
... |
1749b9c57b01cedb1bae9982300e8a42886f746e690cced63bba354a1c369c03 | Python | 1,361 | 31 | """
This script measures the capacity to reconstruct full inputs, and plots the reconstructions.
"""
from scripts.load_data import load_data
from matplotlib import pyplot as plt
from scripts.network import Network
import numpy as np
# Set up network
img_width = 34
size_list = [img_width ** 2, 2000, 500, 30]
i_rates ... |
cea18c037d55f891573bd505d315d58612a297fecadc610b2ba24b932ef50d6a | Python | 1,363 | 50 | import torch
from torch.autograd import grad
from tqdm import tqdm
import torch.nn as nn
l0 = 10 #spring at rest
g = 9.81 #gravity
m = 1 #mass of particle
k = 40 #spring constant
def F(u):
size = u.size(1)//4
th, r, Vth, Vr = u[:, :size], u[:, size:s... |
9861303cd68135130c4e261f9bd99a14348d7438eb39820a9090eea8b9e27c44 | Python | 1,364 | 52 | import requests
import sys
import argparse
import json
import os
import os.path
import re
ap = argparse.ArgumentParser()
ap.add_argument('-i','--input', help = 'Input file')
ap.add_argument('-o','--out', help = 'Output file')
args = vars(ap.parse_args())
input = ""
out = ""
idhash = {}
cfile = "zhang-2014-rnaseq-nb... |
2678ede8feca68f1c106e2227f6d040997b3fdc24f53c8dae9891ebc38b9564c | Python | 1,365 | 27 | # Copyright (c) OpenMMLab. All rights reserved.
from .ae_higher_resolution_head import AEHigherResolutionHead
from .ae_multi_stage_head import AEMultiStageHead
from .ae_simple_head import AESimpleHead
from .cid_head import CIDHead
from .deconv_head import DeconvHead
from .deeppose_regression_head import DeepposeRegress... |
09c02a9d7688a9816f3b12520b72dbad2a1476af623e545ba61088519ebd34cd | Python | 1,368 | 40 | import torch
from torch.autograd import Function
from torch.nn.functional import softmax
from itertools import repeat
import numpy as np
def dice_lossv2(input, target):
"""
input is a torch variable of size BatchxnclassesxHxW representing log probabilities for each class
target is a 1-hot representation o... |
abb3ff3e8b876f61611aca9403068a67a007f35ed17eaded1bd46ff38c74fa28 | Python | 1,369 | 19 | # *************************************************************************
# * Copyright 2010 - 2016 Paulo Herrera *
# * *
# * This file is part of EVTK. *
# * ... |
560129fb158af8cb5fa87bf002f4084acb715b6ef256f6190c783ebdeb185c5d | Python | 1,370 | 31 | from pytorch_lightning.callbacks import Callback
import torchvision
import torch
class CleftImageLogger(Callback):
def __init__(self, num_images=12, log_steps=10):
self.log_steps = log_steps
self.num_images = num_images
def on_train_batch_end(self, trainer, pl_module, outputs, batch, batch_idx... |
0e9581f0d3d80b5ce7bebf55ee5d75538f0fe021d8dad1b4222c8352f95ac104 | Python | 1,372 | 39 | import os
import h5py
import numpy as np
from PIL import Image
from torch.utils.data import Dataset
class MuraDataset(Dataset):
MURA_FILE = "mura.hdf5"
CANDIDATE_TYPE = ["ALL", "ELBOW", "FINGER", "FOREARM", "HAND", "HUMERUS", "SHOULDER", "WRIST"]
def __init__(self, data_root, data_type="WRIST", train=Tr... |
594f2b890717895033923f1d2197364bea075d342680b6308e6b980838cfff92 | Python | 1,373 | 51 | from data_provider.data_loader import Dataset_ETT_hour, Dataset_ETT_minute, Dataset_Custom, Dataset_Pred
from torch.utils.data import DataLoader
data_dict = {
'ETTh1': Dataset_ETT_hour,
'ETTh2': Dataset_ETT_hour,
'ETTm1': Dataset_ETT_minute,
'ETTm2': Dataset_ETT_minute,
'custom': Dataset_Custom,
}
... |
59a18b44194fcce4995987ff31a53d6e35d9eddda0951b81b2e4645113f46c98 | Python | 1,375 | 34 | import numpy as np
class Padding:
def __init__(self, load_size, training=True):
"""
Padding the image: C x H x W, if H or W less than load_size, and will keep the overflow side.
"""
# TODO: Not just support static filling of the padding, but also mirror, etc...
if isinstan... |
7ee1bbe898a1145739caacc9ded9e9039727e1341aaf5ffe3cbf6558c6a38f0b | Python | 1,375 | 28 | from F_post_processsing import F100_analyze_hindcast_output
from A_config import a10_config
import manager_0_user_params as upar
import os
import json
import pandas as pd
if __name__ == '__main__':
# USER PARAMS
metric = upar.metric #metric for best model selection, while rRSD_sor_mil_20250428MSE_p only this ... |
60770995b709f187488d49dd6c723ffcfec7c819d3e4c7cb7be9616801851f3b | Python | 1,377 | 46 | import numpy as np
from mmdet.core.evaluation.recall import eval_recalls
det_bboxes = np.array([
[0, 0, 10, 10],
[10, 10, 20, 20],
[32, 32, 38, 42],
])
gt_bboxes = np.array([[0, 0, 10, 20], [0, 10, 10, 19], [10, 10, 20, 20]])
gt_ignore = np.array([[5, 5, 10, 20], [6, 10, 10, 19]])
def test_eval_recalls(... |
dc84437a54d1e71b69cf7f7758da2842594ad23d045d546310a2dbe0608323ef | Python | 1,379 | 44 | from typing import Annotated, Literal
from pydantic import Field
from oligo_designer_toolsuite.config._general_models import BlastnHitParameters, BlastnSearchParameters
from oligo_designer_toolsuite.config._specificity_filters import (
SpecificityBlastnFilterDisabled,
SpecificityBlastnFilterEnabled,
Varia... |
b358ab023f48522a9c2739627763ba6f21e0ebd9f00e2dbf28d4a2456aeb343a | Python | 1,380 | 37 | from .utils import transform_tensor_to_list
class FedOptTrainer(object):
def __init__(self, client_index, train_data_local_dict, train_data_local_num_dict, train_data_num, device,
args, model_trainer):
self.trainer = model_trainer
self.client_index = client_index
self.tr... |
1038aebe86643dbfc84c4440c5ee4f78d9a5967ba8f70c08e53997671785120c | Python | 1,382 | 38 | """
This module serves as an initializer for the package, aggregating various submodules related to genomic data processing and oligo sequence management.
Submodules:
- config: Provides pydantic models to check the configuration files for pipelines.
- database: Contains utilities for handling and processing oligo and ... |
716acb609dd5c0a14333d2376d3a63eeffdd55141c5f8393ffb12d3ca4b1425f | Python | 1,382 | 42 | # Copyright (c) OpenMMLab. All rights reserved.
# Copyright (c) 2019 Western Digital Corporation or its affiliates.
import torch
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class YOLOV3(SingleStageDetector):
def __init__(self,
backb... |
ae456a9a8da39dcc8ca379fe485e80c692dbe1a362d3a696c79cdedf7ab879fa | Python | 1,382 | 31 | from base import BaseDataLoader
from dataset.acdc_dataset import ACDC_dataset
from dataset.acdc_test_dataset import AcdcTestDataset
class AcdcDataLoader(BaseDataLoader):
def __init__(self, data_root, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True,
transforms=None):
... |
ae5fe132627e3e70a82a3e933e5eabd873632c018441d1584a09155f38856100 | Python | 1,387 | 36 | import multipagetiff as mtif
import argparse
import logging
import os
from . import utils
from ..skew_correction import skew_correct_matlab_one
def main(*args, **kwargs):
parser = argparse.ArgumentParser(description="Run skew-correction.")
parser.add_argument("input_path", help="The path of the stack to sk... |
14ffa0d58a9fe9e322b05076143b8fa6f52f3098e3e720284f746074832baf9d | Python | 1,390 | 33 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import Binarizer
from tpot.export_utils import set_param_recursive
from metstab_shap.config import utils_section, csv_section
from metstab_shap.config import p... |
f0ff233b2b5db17351a5b27c8e9862199f6cae0339691d7b0a2f28e1dc96d6fd | Python | 1,391 | 36 | import pandas as pd
import numpy as np
from statistics.survival_plot_xz import load_metadata_mlp_pivot_raw, load_metadata_mlp_pivot
import unittest
def _simplify_dataframe(*args):
output_dfs = []
for df in args:
df = df.copy()
df['Cluster Idx'] = df['Cluster Idx'].astype(int)
df = df.g... |
8a01531d04cb4260b22651bf0cdd37bd546826a89700dbb789fbdd3c31341ed6 | Python | 1,394 | 40 | import torch.nn as nn
import torch.nn.functional as F
import numpy as np
def conv_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
#nn.init.xavier_uniform(m.weight, gain=np.sqrt(2))
nn.init.normal_(m.weight, mean=0, std=1)
nn.init.constant(m.bias, 0)
class Ale... |
70158346a171f9edd439c8d5f84b2eb335ff1c2da3dde79696b55fd0722399b4 | Python | 1,395 | 42 | import numpy as np
import random
class RandomFlip:
def __init__(self, horizontal=True, vertical=True, training=True):
self.horizontal = horizontal
self.vertical = vertical
self.training = training
def __call__(self, sample):
"""
Randomly flip the numpy image horizontal... |
01253d98cfa6c061d22750ad5b920c80ad53e8d1d8c7c1f2da55e2cfbfca5ece | Python | 1,396 | 48 | from random import choice
import pysam
import os
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('input_bam', help="input BAM or SAM file (must be sorted!)")
parser.add_argument("output_bam", help="output BAM or SAM file")
options = parser.parse_args()
if options.input_bam.endswith(... |
da5c72a9b2cd601710d56cf37b4a8f390935d13023058d1888566eac98433bce | Python | 1,396 | 42 | dataset_info = dict(
dataset_name='nvgesture',
paper_info=dict(
author='Pavlo Molchanov and Xiaodong Yang and Shalini Gupta '
'and Kihwan Kim and Stephen Tyree and Jan Kautz',
title='Online Detection and Classification of Dynamic Hand Gestures '
'with Recurrent 3D Convolutional N... |
45b09f9edd01dbf727570fb274be6cc417f04605e813ac784649360b4180acad | Python | 1,404 | 42 | import torch.optim as optim
class SplitNN_client():
def __init__(self, args):
self.comm = args["comm"]
self.model = args["model"]
self.trainloader = args["trainloader"]
self.testloader = args["testloader"]
self.rank = args["rank"]
self.MAX_RANK = args["max_rank"]
... |
2fed7ef6b055a83caa6abf15448eaf07bb277dc54c24564ab54e7aae730bae4d | Python | 1,407 | 44 | from suite2p.extraction import dcnv
import numpy as np
import sys
import os
import logging
# extract from command line
output_path = sys.argv[1]
dff_name = sys.argv[2]
fishlabel = str(sys.argv[3])
trial = str(sys.argv[4])
# initialise
script = os.path.basename(__file__)
handlers = [logging.FileHandler(output_path... |
1fda59f5837dca223493c2375fa0d5d1fa0ca8e824dba7ea39400080bc2e0dd9 | Python | 1,410 | 24 | from distutils.core import setup
from distutils.extension import Extension
setup(name="fastSpa",
ext_modules=[
Extension("fastspa", ['fastSpa.cpp'],
# Adjust the following to be able to find boost-python and, boost-numpy.
# On my mac, using Homebrew, I did not need inclu... |
2399b1438defed36da44e224f833b53f52c041b8ba1d4353adc1f3b0a7c9952f | Python | 1,416 | 47 | import torch.nn as nn
class _MLP(nn.Module):
def __init__(self, in_size, drop_rate, fil_num):
super(_MLP, self).__init__()
self.bn1 = nn.BatchNorm1d(in_size)
self.bn2 = nn.BatchNorm1d(fil_num)
self.fc1 = nn.Linear(in_size, fil_num)
self.fc2 = nn.Linear(fil_num, 1)
s... |
cceacd2f42f92c67ecd56a21cdf5ba9b504deee5ee1ff8265f0bd028f03c4913 | Python | 1,419 | 42 | from p4.leafsupport import CherryRemover
#These three lines removes the cherries and saves the resulting trees in a file.
rc = CherryRemover('../input.nex')
rc.removeCherries()
rc.saveTrees('input.cherries.removed.nex')
ls = LeafSupport('input.cherries.removed.nex')
ls.defineClade(['Pholiderpeton','Proterogyrinus',... |
6a1d9af13e3f3aeb96e903bddbe45dc1280242e8e44be756ee779b652f678288 | Python | 1,420 | 36 | import multipagetiff as mtif
import argparse
import logging
import os
from glob import glob
from . import utils
from ..skew_correction import skew_correct_matlab
def main(*args, **kwargs):
parser = argparse.ArgumentParser(description="Run skew-correction.")
parser.add_argument("input_folder", help="The folde... |
6c22f9eb48f8e2291232dfa30c13d40f3d34e6d2368a34c2c24fac7c3bd7134e | Python | 1,420 | 43 | import numpy as np
import random
class Flip:
def __init__(self, horizontal=True, vertical=True, training=True):
self.horizontal = horizontal
self.vertical = vertical
self.training = training
def __call__(self, sample):
"""
Randomly flip the numpy image horizontal or/an... |
55c0fc72653c85fcc7e95262fc60ed721f4ae4042b6d48bc0a57f64a4338d6c8 | Python | 1,422 | 62 | from abc import ABC, abstractmethod
import os
class _ForceFieldBase(ABC):
def __init__(self):
pass
@abstractmethod
def get_atom_types(self):
pass
@abstractmethod
def get_charge(self, at):
pass
@abstractmethod
def get_mass(self, at):
pass
@abstractmet... |
0ea4f08cbc8b6dbe70fbff3440d72608d5ac6ca81e260836a519756d8f2ae879 | Python | 1,423 | 35 | import numpy as np
from trefide.pmd import batch_decompose
from trefide.decimation import decimated_decompose, decimated_batch_decompose, downsample_video, downsample_image, downsample_signal
def downsample_movie(fov_height, fov_width, d_sub, num_frames, t_sub, mov):
Y_ds = np.asarray([downsample_image(fov_heigh... |
24a482c6c5f4691bb3bea20e07970514c2d7464983a2183b6a49d98905595be3 | Python | 1,423 | 57 | from typing import Union, Any
import eagerpy as ep
from ..devutils import flatten
from ..devutils import atleast_kd
from ..criteria import Criterion
from ..distances import l2
from ..models import Model
from .base import FixedEpsilonAttack
from .base import T
from .base import raise_if_kwargs
from .base import ver... |
f3efe69cabe4ac00a997b2dad85d6cfa5f987f6aa242670a702e08fd090a7fef | Python | 1,423 | 45 | #----------------------------------------
# Compute all molecular layer thicknesses
# 1 February 2023
#----------------------------------------
import json
import numpy as np
import pandas as pd
import thickness as th
from convert_polygons_to_shapely_multipolygons import convert_polygons_to_shapely_multipolygons
data... |
60e2eca90dab72089c1dff18f44f155f5ea4ca6156d6b380a4ef52e11a76dfca | Python | 1,428 | 46 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
from __future__ import annotations
from typing import Any, Optional
from torch.utils.tensorboard.writer import SummaryWriter
from sbi.sbi_types import ... |
f2874dabb63e3d52c46ad7623f4f7e5f3aa3412ef6451251a51176ac331bb38d | Python | 1,430 | 31 | # We construct a box instance that inherits from the basic OVBox class
class MyOVBox(OVBox):
# the constructor creates the box and initializes object variables
def __init__(self):
OVBox.__init__(self)
self.stimLabel = None
self.stimCode = None
# the initialize method reads settings and outputs the first ... |
a0dbbd74440109eec6d0a0a32601c06338078659802e89ee3c7b5e0089e1e8bd | Python | 1,432 | 19 | from .chem import BOND_TYPES, BOND_NAMES, set_conformer_positions, draw_mol_image, update_data_rdmol_positions, \
update_data_pos_from_rdmol, set_rdmol_positions, set_rdmol_positions_, get_atom_symbol, mol_to_smiles, \
remove_duplicate_mols, get_atoms_in_ring, get_2D_mol, draw_mol_svg, GetBestRMSD
from ... |
01b2b30bbd394a651e9a37df5d6505d136622086edcc3183a0ddd09bab16342c | Python | 1,434 | 54 | # Do an MCMC with the NDCH2 model
# Here I assume only one data partition, part 0
# The defaults for these values are much smaller. These suggested
# changes may not be needed all the time, but seems to help for
# difficult data.
var.PIVEC_MIN = 1.e-6
var.RATE_MIN = 1.e-6
var.BRLEN_MIN = 1.e-5
var.GAMMA_SHAPE_MIN = 0... |
254c89b51498cc611bf6d5a1d456e1a9cdf49032887c27e7b852165709c8016b | Python | 1,434 | 41 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 22:55:09 2022
@author: fhu14
__init__.py file for the PostProcessing package which will be used to process analysis_dir
structures to generate tables, graphs, and figures.
An analysis_dir directory has the following structures:
analysis_dir
-> analysis_files (di... |
1f7efff45647fbc0c86f23b3cc2a3599930fa5f172334dddb3b8071f56ceaf42 | Python | 1,436 | 39 | # Copyright (c) OpenMMLab. All rights reserved.
from .alexnet import AlexNet
from .cpm import CPM
from .hourglass import HourglassNet
from .hourglass_ae import HourglassAENet
from .hrformer import HRFormer
from .hrnet import HRNet
from .i3d import I3D
from .litehrnet import LiteHRNet
from .mobilenet_v2 import MobileNet... |
2e6ce19c0551155290ebf742b7767f58ac473d378c6813989d15a73959a9ef68 | Python | 1,437 | 39 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmdet.models.utils import (LearnedPositionalEncoding,
SinePositionalEncoding)
def test_sine_positional_encoding(num_feats=16, batch_size=2):
# test invalid type of scale
with pytest.raises(Assertio... |
e2d5b9024182069b7f6e51568fe0227b580780022633ed7b1b910daa414e850d | Python | 1,439 | 40 | import torch
from numpy.core.umath_tests import inner1d
from skimage import morphology
import numpy as np
def hausdorff95(output, target, label_idx):
with torch.no_grad():
# pred = torch.sigmoid(output) > 0.5
# pred = output > 0.5
pred = torch.argmax(output, 1)
pred = (pred == 1)
... |
f5beebf0779ee7f7f48258922e23c0bc73a0a5913bf23896831376f6071955f6 | Python | 1,439 | 33 | import numpy as np
import pandas as pd
from metstab_shap.grid import SVC_rbf
from metstab_shap.config import utils_section, csv_section
from metstab_shap.config import parse_data_config, parse_representation_config, parse_task_config
from metstab_shap.data import load_data
# load data (and change to classification if... |
6805f6c90bdd220490a15fe757d67bee22f183a3ae98c9ddcf8235a5cf20f9dd | Python | 1,442 | 38 | import logging
class Client:
def __init__(self, client_idx, local_training_data, local_test_data, local_sample_number, args, device, model_trainer):
self.client_idx = client_idx
self.local_training_data = local_training_data
self.local_test_data = local_test_data
self.local_sample... |
c9b98e2f573d6f8c7876c86e7c00887b87fe65f0446377725bf885aec6999610 | Python | 1,442 | 43 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 22 13:20:35 2021
@author: fhu14
"""
"""
Script for debugging inconsistencies in the charge sign.
First thing's first, going to see if the predictions from DFTB+ agree with
the saved spline models. Going to use saved_model_driver_2.py as the
method for passing in the sa... |
1cd5b5504b9282afbae97f608355c496d4298861810c9b115818f3a158653b7f | Python | 1,444 | 46 | import numpy as np
import torch.nn.functional as F
from torch import nn
import torch
class ELBO(nn.Module):
def __init__(self, train_size):
super(ELBO, self).__init__()
self.train_size = train_size
def forward(self, input, target, kl, beta):
assert not target.requires_grad
ret... |
c53d94ab3f0c95672ae1fcc946badc24ab5acc1393e05418a791c4882e7b649d | Python | 1,444 | 37 | """Code for loading models from checkpoints saved in GoogleDrive
Model names are mapped to googleids in model_names_to_google_ids."""
import os
import pathlib
import torch
from exsclaim.utilities import download
# stores the google drive file IDs of default neural network checkpoints
# replace these if you wish to ... |
f727d49471f9997e168ffa0fffd1934668cd8e6515e1d9d62699626ee26e8708 | Python | 1,448 | 59 | import re
from copy import copy
import numpy as np
import logging
from sklearn.base import BaseEstimator
def preprocess_text(sen, lower=True, remove_tag=True, remove_special_chars=True, remove_numbers=False, remove_single_chars=True, remove_multiple_sapces=True):
sentence =copy(sen)
sentence=sentence.lower(... |
2622d4a35173cfc6356be9fcbeeb5f7749616252853eb5b001463852c8fa56ad | Python | 1,449 | 59 | # Copyright (c) OpenMMLab. All rights reserved.
import warnings
from mmcv.cnn import MODELS as MMCV_MODELS
from mmcv.utils import Registry
MODELS = Registry('models', parent=MMCV_MODELS)
BACKBONES = MODELS
NECKS = MODELS
ROI_EXTRACTORS = MODELS
SHARED_HEADS = MODELS
HEADS = MODELS
LOSSES = MODELS
DETECTORS = MODELS
... |
49a04fc527e4726f9b0b1ec54ed3209cc0434706b7d69d3a788b9cfbbcb13497 | Python | 1,449 | 37 | # Copyright (c) 2020-present Joindbre.com
# Authors: Patricia Maraver.
#
# This program is free software: you can redistribute it and/or modify
# it under the GNU Affero General Public License version 3
# as published by the Free Software Foundation.
# You should have received a copy of the Server Side Public Lic... |
65395538a462aea889e8f42a3aeff5b6f5500c2af2573381fae4814acb6fb35d | Python | 1,453 | 35 | import pandas as pd
pd.set_option('display.width', 5000)
pd.set_option('display.max_columns', None)
# fill new 2026 data of ObsAsForecast and SfAsForecast with previous year to allow OPE
fn_in = r'V:\foodsec\Projects\SNYF\SIDvs\ZA\summer2025data\SF2\Tuning_data\Maize_(corn)_WC-South_Africa-ASAP_SfAsForecast.csv'
fn_... |
e095e7eec8384d88f327f9d6de73e0ebb152134dd14f7437d4b1f10a9394f763 | Python | 1,453 | 52 | import numpy as np
import pandas as pd
import os
data_dir="D:/YS/M_D/Updata_2/evaluation/train_data_20220824/step_2/"
Negtivate_files=os.listdir(data_dir+"Negtivate/")
Negtivate=[]
for n in Negtivate_files:
Negtivate.append(list(pd.read_csv(data_dir+"Negtivate/"+n+"/"+n+"_cell.csv")["pred"]))
Positivate... |
419cb23e6b27f5bc8cd977eabd662a21b5555d6352a05dbfa5189a66ffe59ed2 | Python | 1,454 | 47 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 17 20:32:36 2021
@author: fhu14
"""
#%% Imports, definitions
from typing import List, Dict
import numpy as np
from MasterConstants import ANGSTROM2BOHR, Model
from Spline import get_dftb_vals
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
... |
909c10378d96fa06b089d03a524d0da3d7f9af922dcf011358ee4c3fc3c6485f | Python | 1,456 | 38 | import numpy as np
import random
from scipy import ndimage, misc
class RandomRotate:
def __init__(self, tilt=0, training=True):
self.training = training
self.tilt = tilt
def __call__(self, sample):
"""
Randomly flip the numpy image horizontal or/and vertical
Args:
... |
170d1ffb04fa388a3c5e045a2c1aee8e683d40ec58a77dd49dfac2bff8314bee | Python | 1,457 | 66 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 12:04:25 2021
@author: baris
"""
from grid_model import grid_simulate
import dentate_simulate
import neural_coding
import numpy as np
# shuffle = True
shuffle = False
#Seeds
grid_seeds = 520
# poiss_seeds = np.arange(360,365,1)
# poiss_se... |
b0ca2c6c63c867592a1b9d9feac2eccab527eb361171946f011b628ded4fd987 | Python | 1,458 | 47 | import pytest
from pathlib import Path
from clipkit.clipkit import execute
from clipkit.files import FileFormat
from clipkit.modes import TrimmingMode
from clipkit.settings import DEFAULT_AA_GAP_CHARS, DEFAULT_NT_GAP_CHARS
here = Path(__file__)
@pytest.mark.integration
class TestEndsOnly(object):
def test_ends_... |
3ad1efa1edf6cc59c075d242cd5e55acf580c68d1233f7ba59d5418c6de14bbe | Python | 1,459 | 39 | import logging
class Client:
def __init__(self, client_idx, local_training_data, local_test_data, local_sample_number, args, device,
model_trainer):
self.client_idx = client_idx
self.local_training_data = local_training_data
self.local_test_data = local_test_data
... |
889e00ed0e61dca9d85c752c70f80c68a4aa93bc3a796885a48049ef61d638ec | Python | 1,461 | 49 | read('../A_NavidiAlignFromYang/navidiSSRNA.nex')
read('t.nex')
d=Data()
d.calcUnconstrainedLogLikelihood1()
u = d.unconstrainedLogLikelihood
#fResults = open('results', 'w')
fResults = sys.stdout
fResults.write('\nTable 2\n=======\n\nHKY, no rates\n\n')
fResults.write(' tree diff kapp... |
fd89351f8b6cce7f1aee11e4db4904df53513322cef9a4fe539dd1bb0f6d508a | Python | 1,461 | 55 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from collections import defaultdict
from sklearn import metrics
def get_nn(file):
steps = file.split("_")
path = ''.join(steps[-1])
return path.split('.npy')[0]
def roc(preds, annots, graph, matrix_out):
#Metrics
... |
4946c909b70bfc92dcde4dbe0d2437e45553aea2c5f2137eb4b92862e2ab06e2 | Python | 1,463 | 42 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from ..builder import BBOX_SAMPLERS
from .base_sampler import BaseSampler
from .sampling_result import SamplingResult
@BBOX_SAMPLERS.register_module()
class PseudoSampler(BaseSampler):
"""A pseudo sampler that does not do sampling actually."""
def... |
6affd6358925c0ad749c844f5c6b528dd03c544e79c8028c7a7267f85fc8d5f8 | Python | 1,464 | 54 | from pathlib import Path
from invoke import task
basepath = "/Users/janbolts/qode/sbi-for-connectomics"
overleaf = "/Users/janbolts/qode/connectomics-inference-manuscript"
open_cmd = "open"
fig_names = {
"1": "paper/fig1",
"2": "paper/fig2",
"3": "paper/fig3",
}
@task
def convertpngpdf(c, fig):
_c... |
7c28dc8396a3eda86f50bed99032b38a4c90db57f2afb54685e7a62fddb51c9a | Python | 1,466 | 48 | import numpy as np
from scipy.signal import argrelmax
import inspect as isp
def min_len(func):
def wrapper(*args):
pred = func(*args)
if len(pred) <= 1:
return np.array([0, 0])
return pred
return wrapper
class Combination:
@min_len
def pdfFirst(self, pdf, curve... |
6ed3e327f70fd63c3eb2437f53146f9155b266b720bdd94acb1c0f826e75767c | Python | 1,468 | 29 | # Copyright (c) OpenMMLab. All rights reserved.
from .brick_wrappers import AdaptiveAvgPool2d, adaptive_avg_pool2d
from .builder import build_linear_layer, build_transformer
from .ckpt_convert import pvt_convert
from .conv_upsample import ConvUpsample
from .csp_layer import CSPLayer
from .gaussian_target import gaussia... |
79bf8bab62ff94cf974a2d09a72c0e7391739d14c284069e9c23689bf4652a3f | Python | 1,468 | 45 | import torch
import torch.nn as nn
import torch.nn.parallel
import numpy as np
from torch.nn.parameter import Parameter
class rational(nn.Module):
def __init__(self):
super(rational, self).__init__()
print('rational!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
self.a0 = Parameter(torch.FloatTens... |
7ea92a82ad024e207a26c6784de5c192435bdc639d1628ee280f10f8daf2a011 | Python | 1,468 | 45 | import torch
import torch.nn as nn
from sep.training.losses import CompositeLoss, SISDRLoss
class BaseNetwork(nn.Module):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.device=torch.device('cpu')
def set_loss(self, loss: str):
# Choose loss
... |
65fa9a3638dc6a75bd7392a8c1a27b250e42bf9ea1df9e3afbe0ceae5ca0180b | Python | 1,469 | 50 | import cv2
import numpy as np
class TileUtils:
@staticmethod
def add_border(a, thickness=0.05, color=(0, 0, 0)):
'''
:param a: the matrix image
:param thickness: border thickness
:return:
'''
h, w, c = a.shape
# some coordinates may be part of croppe... |
be9f35140c788023e7711d711007b47804820198f624e59e5abd6b4d365c1e05 | Python | 1,469 | 47 | from torch.utils import data
import os
import numpy as np
import time
import glob
class Dataset_training(data.Dataset):
'Characterizes a dataset for PyTorch'
def __init__(self, data_dir, train_T, seg_num=100):
self.data = np.load(data_dir) # T*bs*dim
idx = np.arange(self.data.shape[... |
8a979fd7156ef9af49db40e0f152ba63b94495b78e6afd95c447164eeb92fa5b | Python | 1,470 | 57 | import os.path
import random
import sys
import cv2
import h5py
import numpy as np
import scipy.ndimage as ndimage
from PIL import Image
from data.base_dataset import BaseDataset, get_params, get_transform
from data.brats1db_dataset import Brats1dbDataset
from data.brats_dataset import BratsDataset
from data.fsl1db_da... |
0fddf4efbf965caf9e7d20142a9c6b2074a3547edcbb839ba3ad58f4d7088d5e | Python | 1,471 | 52 | #!/usr/bin/env python3
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the ho... |
1dba61cab47a009e206b93a99e56fcb8d6bab27a9d0a7d3fa54e276143913fd7 | Python | 1,471 | 49 | from typing import Any, cast, Optional
from types import ModuleType
import sys
import importlib
import abc
from abc import abstractmethod
from ..models import Model
class ModelLoader(abc.ABC):
@abstractmethod
def load(
self, path: str, module_name: str = "foolbox_model", **kwargs: Any
) -> Model:... |
39642d4c5b3a6ae6cb49d5a9101076b67b3c55208acb882e7aa8d673134bd0b7 | Python | 1,471 | 48 |
from scipy import interpolate
import numpy as np
import pandas as pd
def inter(preds_raw, time):
bins = [0, 24, 48, 108]
interp = interpolate.PchipInterpolator(bins, preds_raw, axis=1)
return interp(time)
def pred_reversions(ds):
df = load_preds_and_reverters(ds)
df = df.dropna()
input_mat = ... |
677f963a25f1ce90cdea6ff9bbf942f2acef5f2a51522b4e962228dfd4bf88e5 | Python | 1,471 | 40 | from pycroscopy3D.registration import load_with_ants
import multipagetiff as mtif
import logging
import argparse
import os
from . import utils
def main(*args, **kwargs):
parser = argparse.ArgumentParser(description="Convert image from nii.gz to tif.\
Load an image with ANTS and save it as tiff.\
\
... |
bcce208adddf99ec3c64ee824bab5757b3a6fa094bf702329cf4ea8fa6dcf8db | Python | 1,475 | 53 | #!usr/bin/env python
#coding:utf-8
"""
@author: Haidong Zhang
@contact: haidong_zhang14@yahoo.com
@time: 2020/12/10 16:04
@project: MalariaDetection
@description:
"""
import glob
import os
import numpy as np
from PIL import Image
class Dataset(object):
def __init__(self, path, dataset='dataset1')... |
2f30bdc3b76c06e299ff3ab5ccd098bfca8773277a39c816aecc0a91b5d2d7fd | Python | 1,477 | 38 | import os
import h5py
import imageio
import numpngw
import numpy as np
def save_pairs_segmentation(data_path, save_root):
ct_stroke_data = h5py.File(data_path, "r")
test_data = ct_stroke_data["test"]
train_data = ct_stroke_data["train"]
_save_pairs(test_data, os.path.join(save_root, "test"))
_sav... |
1aed77339bf53d7b48cb7402098074e8f32957ff15f7e95807cc88014e3a8873 | Python | 1,478 | 42 | import numpy as np
import torch
import torch.nn as nn
class ResidualConvUnit(nn.Module):
def __init__(self, features):
super().__init__()
self.conv1 = nn.Conv2d(
features, features, kernel_size=3, stride=1, padding=1, bias=True)
self.conv2 = nn.Conv2d(
features, fea... |
5e51bb2558d47af7034bd8d0ab1f4f240345f0a13d1bb2fd532eef9bb3a97d3e | Python | 1,478 | 43 | # Copyright (c) OpenMMLab. All rights reserved.
import logging
from abc import ABCMeta, abstractmethod
import torch.nn as nn
from .utils import load_checkpoint
class BaseBackbone(nn.Module, metaclass=ABCMeta):
"""Base backbone.
This class defines the basic functions of a backbone. Any backbone that
inh... |
756abd3bd926f0ee013c7ae45f74cc51bb995c4410fa5a7cad9b40dd255e76f5 | Python | 1,480 | 46 | import numpy as np
import matplotlib.pyplot as plt
from random import sample
def compute_distance_to_midline(p1, p2, p3):
"""
Returns distance of point p3 to a line defined by points p1 and p2
:param p1: tuple of floats
:param p2: tuple of floats
:param p3: tuple of floats
:return: float
"... |
73fc9384c99191ce6d6409d20769dbce39bb8b229d51ddba3459d5c0fa231187 | Python | 1,481 | 31 | import glob
import os
import pandas as pd
import numpy as np
#Change this according to your structure of CryoEM_Final_Dataset directoryor
#comment this line if project dir has not changed
project_dir = '/bml/CryoEM/CryoEM_Final_Dataset/'
empiar_ids = ['10737', '10387', '10532', '10240', '10005', '10017', '10075', '... |
f3adfd02874abceed474a6fd03c7ea984860463ff96885fd784a4465dcb4d272 | Python | 1,483 | 57 | import os
from pickle import load
from warnings import simplefilter
simplefilter('ignore', UserWarning)
simplefilter('ignore', FutureWarning)
import numpy as np
from supervised.automl import AutoML
class Regressor:
def __init__(
self,
model_path: str,
):
# Check the existence of the ... |
94309b0b7dce7ebb04fb2e62676243f9ffec2d5dff8a9ca16c8a1767793cdab2 | Python | 1,484 | 42 | from scipy import interpolate
from sksurv.metrics import concordance_index_censored, brier_score, integrated_brier_score, cumulative_dynamic_auc
import numpy as np
def retrieve_brier_scores(bins, preds_raw, train_struc, test_struc):
"""
retrieve_brier_scores
Gets IBS
Parameters
----------
bi... |
edb882622b7fb0403b10be507bedb16623d35e1b6901eee3569ebf8fa7c99b0d | Python | 1,484 | 53 | dataset_info = dict(
dataset_name='coco',
paper_info=dict(
author='Lin, Tsung-Yi and Maire, Michael and '
'Belongie, Serge and Hays, James and '
'Perona, Pietro and Ramanan, Deva and '
r'Doll{\'a}r, Piotr and Zitnick, C Lawrence',
title='Microsoft coco: Common objects in ... |
97c4b65fafc5d6c9ecd575e27455417be537ca9bd2a3f35b57060f766c8c6383 | Python | 1,485 | 50 | import os
import shutil
from git import Repo
import logging
from .common import sha256_hash, home_directory_path
FOLDER = ".foolbox_zoo"
class GitCloneError(RuntimeError):
pass
def clone(git_uri: str, overwrite: bool = False) -> str:
"""Clones a remote git repository to a local path.
Args:
git... |
b1f63f860e9017ffb79d09f779932ea58cc9eeb0ef5320279e37ed2f521f219f | Python | 1,486 | 45 | """Create final RDM figure after runnning train.py.
Example:
$ python post_run_analysis/plot_rdm.py --simulation_id <simulation_id> (optional: --mode <mode>)
"""
import argparse
import numpy as np
import os
import matplotlib.pyplot as plt
# Get plotting style and simulation name
parser = argparse.ArgumentParser(... |
def3f032c4566e615823aeb5926454495bca593f9a6060450bba9c491deb1987 | Python | 1,486 | 47 | import os
import numpy as np
import rasterio
# full path to ENVI image (the .img file)
fns = [r"V:\asap\asap_analysis\2026 Pheno4Droughts\CF_FPR_LTA_ENVIs1.img", r"V:\asap\asap_analysis\2026 Pheno4Droughts\CF_FPR_LTA_ENVIs2.img", r"V:\asap\asap_analysis\2026 Pheno4Droughts\CF_FPR_LTA_ENVIe1.img", r"V:\asap\asap_analys... |
09098af1146b0bd6f9868af573bf48af4fbad491ab100eb385cd6b09c6415651 | Python | 1,487 | 40 | import numpy as np
import torch
import torch.nn.functional as F
def one_cls_dice(output, target, label_idx):
"""
Calculate Dice metrics for one channel
:param output:Output dimension: Batch x X x Y (x Z) float
:param target:Target dimension: Batch x X x Y (x Z) int:[0, Channel]
:param label_idx:
... |
b54bb647ce1d9df0ce87692c9295d174dd15702ec46ec1ca9bac3312f1ceca28 | Python | 1,487 | 39 | import numpy as np
from moleculekit.periodictable import periodictable_by_number
class npzMolecule:
def __init__(self, file: str):
"""Class to load npz files in torchmd, essentially a wrapper around the npz file. Necessary information is extracted from the npz file
and stored in the class, such as... |
8fd0aeaab27ab06b08e12ecd917f553740c37a36a380a45fbf8361514a4e7afc | Python | 1,489 | 41 | import setuptools
with open('README.rst') as file:
long_description = file.read()
### Crap to be able to create a binary installer for Windows
import codecs
try:
codecs.lookup('mbcs')
except LookupError:
ascii = codecs.lookup('ascii')
func = lambda name, enc=ascii: {True: enc}.get(name=='mbcs')
... |
7e1d07639a28a3cad06ab501f4da5b97d4973d25f37cca2d0fcb447ba4138e42 | Python | 1,495 | 44 |
import h5py
import numpy as np
train_all = "../../../../datasets/fedgan_syn/heart_h5_all/heart_resnet_9blocks_epoch110_experiment_0.h5"
train_h5 = "../../../../datasets/fedgan_seg_data_heart/heart_resnet_9blocks_epoch110_experiment_0_trainset.h5"
val_h5 = "../../../../datasets/fedgan_seg_data_heart/heart_resnet_9bloc... |
2afee95cad0883fa6ace3b6eb0ebfe468a8a746424b996aebc2890769adc86a2 | Python | 1,496 | 34 | import glob
import shutil
import os
import pandas as pd
import logging
df = pd.read_excel('only_1000_images.xlsx', skiprows = 1)
empiar_ids = df['EMPIAR_ID']
micrographs_extensions = df['Image Ext']
SOURCE_ADDRESS = '/gpfs/alpine/bif135/scratch/ashwind/CryoEM/data_downloads_dump_has_more_than1000/444_micrographs_data/... |
2f88853a7e8d6015c0b823d93724b04840d3b26b3c12490c812d5377a2d98bd2 | Python | 1,498 | 69 | import requests
import sys
import argparse
import json
import os
import os.path
import re
ap = argparse.ArgumentParser()
ap.add_argument('-i','--input', help = 'Input file')
ap.add_argument('-n','--num', help = 'num')
ap.add_argument('-c','--cls', help = 'cluster file')
ap.add_argument('-o','--out', help = 'Output fi... |
0234bc98ec63915475ca8c13689b41e36467207d5a1d3c015842c997d2f18e63 | Python | 1,500 | 35 | import numpy as np
class Padding3d:
def __init__(self, load_size, training=True):
"""
Padding the image: C x H x W x D, if H, W, D less than load_size, and will keep the overflow side as it is.
"""
# TODO: Not just support static filling of the padding, but also mirror, etc...
... |
731ad0bad59e73b0b53696e152cae636c03e1008829f80867e47a1e13fb9063a | Python | 1,500 | 52 | from model.builders.builders import build_simple
import os
filename = os.path.basename(__file__)
data ={'type': 'manual_label' , 'params': {'outcome': 'response'}}
pre = {'type' : None}
vocab_size = 20000
report_max_length = 500 # number of words per report
embedding_dims = 150
filters = 250
kernel_size = 3
hidden_dim... |
9f63196c720af4d549c7bd19349978aaf60f232631d8677cc03937dfca1bb258 | Python | 1,500 | 51 | rNum = 0
read('d.nex')
#read('simTree.nex')
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
var.strictRunNumberChecking = False
pNum = 0
# comp for each node
for n in t.iterNodes():
c = t.newComp(partNum=pNum, free=1, spec='empirical', symbol="-")
t.setModelComponentOnNode(c, node=n, clade=Fals... |
4386cd43cf7efed738c791a4f6f6aa33b120c60b2bec08266324bbc0bbc4e4bb | Python | 1,502 | 56 | # This file is part of sbi, a toolkit for simulation-based inference. sbi is licensed
# under the Apache License Version 2.0, see <https://www.apache.org/licenses/>
# NOTE: This is inspired by the sbibm-package <https://github.com/sbi-benchmark/sbibm>
from typing import Callable
import torch
from torch.distributions ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.