sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
850ce1fdab564495dbb5117687283189417df96a37c698143cce0dadd55017a3 | Python | 264 | 10 | read('inTrees.phy')
stm = STMcmc(var.trees, sampleInterval=10, beta=2.0)
stm.run(500)
tp = TreePartitions("mcmc_trees_0.nex", skip=25)
t = tp.consensus(minimumProportion=0.5)
for n in t.iterInternalsNoRoot():
n.name = "%.0f" % (100. * n.br.support)
t.draw()
|
e996b14d7de70947ee87613b971675998c3048b501c242f9be82a436535b12bc | Python | 265 | 4 | # 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 sbi.inference.trainers.vfpe.fmpe import FMPE
from sbi.inference.trainers.vfpe.npse import NPSE
|
1c1d6a656b91ee20634096a236978d35b2fcfb5e36fb297a2edf63b59a133d10 | Python | 266 | 11 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 30 16:20:42 2021
@author: fhu14
Module for handling a posteriori dispersion correction of energy terms
outputted from DFTB
"""
from .lj_dispersion import LJ_Dispersion
from .util import torch_geom_mean, np_geom_mean
|
2be418a923e5e6765fa410f3b8076c05bf6a5b1607e107e6352b335cf6a8360e | Python | 266 | 7 | # setup.py
# Usage: ``python setup.py build_ext --inplace``
from distutils.core import setup, Extension
import numpy
setup(name='_tifffile',
ext_modules=[Extension('_tifffile', ['tifffile.c'],
include_dirs=[numpy.get_include()])])
|
ce6e61feb345741d09e465c07a81f482d579088b8594246016e229895c0da8dc | Python | 268 | 10 | cpr = McmcCheckPointReader()
cpr.writeProposalAcceptances()
cpr.writeSwapVectors()
#cpr.writeProposalProbs()
m = cpr.mm[0]
m.tunings.dump(advice=False)
cpr.compareSplits(2, 3)
print("\n\nComparing all splits from all pairs of checkPoints ...")
cpr.compareSplitsAll()
|
e1ada7cdf9829646bae1a17cabd83484ee05f4df8edc969b4ef32542b4259915 | Python | 270 | 10 | read('../noTRuberNoGapsNoAmbiguities.nex')
a = var.alignments[0]
d = Data()
print('Using all sites ...')
d.compoChiSquaredTest(verbose=1)
a.setNexusSets()
a.excludeCharSet('constant')
d = Data()
print('After constant sites removal ...')
d.compoChiSquaredTest(verbose=1)
|
53772c4d4ff91b178da81c5c094a8b6c7d0e6e75537e6c50f7f3d08ebc9afc9a | Python | 271 | 10 | __all__ = [
'__version__', 'cv', 'metrics', 'make_affinity', 'snf', 'get_n_clusters'
]
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
from . import (cv, metrics)
from .compute import (make_affinity, snf, get_n_clusters)
|
99f73db9bf68202582396b90082188308deb1797ae4fa90b2f178f93e4ff00f0 | Python | 271 | 8 | # Copyright (c) OpenMMLab. All rights reserved.
from .builder import build_match_cost
from .match_cost import BBoxL1Cost, ClassificationCost, FocalLossCost, IoUCost
__all__ = [
'build_match_cost', 'ClassificationCost', 'BBoxL1Cost', 'IoUCost',
'FocalLossCost'
]
|
16264d7d74cd8bb0ddbe38b1688d45e2aa0d2ff16f10413450177c1339b699a6 | Python | 272 | 13 | import sys
from pkg_resources import VersionConflict, require
from setuptools import setup
try:
require('setuptools>=49.2')
except VersionConflict:
print("Error: version of setuptools is too old (<49.2)!")
sys.exit(1)
if __name__ == '__main__':
setup()
|
480ca9c277a7aca48f77db3103b3fcd9dad7ff5e72dc0b46d69724d153ddb188 | Python | 272 | 10 | import torch
def accuracy(output, target, misc):
with torch.no_grad():
pred = torch.argmax(output, dim=1)
assert pred.shape[0] == len(target)
correct = 0
correct += torch.sum(pred == target).item()
return correct / target.numel()
|
69f7fab260d99963b4176b8775d3cead6eba912c4995450baec32c526f6887df | Python | 273 | 6 | from latentvelo.models.vae_model import VAE
from latentvelo.models.annot_vae_model import AnnotVAE
from latentvelo.models.atac_reg_model import ATACRegModel
from latentvelo.models.refine_model import RefineODE
from latentvelo.models.velocity_field import VelocityFieldReg
|
e5b3e7f4461f77e4cd1b9976b8645835e3ab59d9bcc730f2ac916b1decb14b51 | Python | 274 | 6 | from .common.ds_base import collate, get_dataset
from .common.ds_loader import get_loader
from .common.ds_transform import get_transform
from .common.ds_estimator import get_estimator
from .common.ds_formatter import get_formatter
from .common.ds_sampler import get_sampler
|
172ba691550e1c0b984d21815cfc489773ad8ef425efd9133e613e0eee2c9a4f | Python | 275 | 10 | """
Dummy conftest.py for eeg_ltt.
If you don't know what this is for, just leave it empty.
Read more about conftest.py under:
- https://docs.pytest.org/en/stable/fixture.html
- https://docs.pytest.org/en/stable/writing_plugins.html
"""
# import pytest
|
51c77ce6b5b6267e239e63360cdd9e9f0648e8aa59460baac32b52b20d6bdccd | Python | 275 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.utils import Registry, build_from_cfg
MATCH_COST = Registry('Match Cost')
def build_match_cost(cfg, default_args=None):
"""Builder of IoU calculator."""
return build_from_cfg(cfg, MATCH_COST, default_args)
|
6ad092c5897f3842d45b9bf955bdd82f57843012f4188d3d9cda351f044a8388 | Python | 277 | 8 | init_weights = None # Michele, 2021/10/04. Variable to store initial random weights used for all cv runs to avoid information leakege in the loop
tensorboard_port = 999
inner_cv_loop = 0
outer_test_loop = 0
dir_tgt = None
trial_number = None
val_group = None
test_group = None |
1b27dabef2035629c638686f657652df3e4ea0766be257ae63b6cdaedab01622 | Python | 279 | 11 | """Internal module with utility functions"""
import eagerpy as ep
def flatten(x: ep.Tensor, keep: int = 1) -> ep.Tensor:
return x.flatten(start=keep)
def atleast_kd(x: ep.Tensor, k: int) -> ep.Tensor:
shape = x.shape + (1,) * (k - x.ndim)
return x.reshape(shape)
|
607df8f1c9c63e06c669e984b6b0fdb01c3082d66a6de6bf1147a3faa12ed5c6 | Python | 279 | 13 | """
This module provides key classes for managing and processing oligonucleotide-related databases.
"""
from ._oligo_database import OligoDatabase
from ._reference_database import ReferenceDatabase
__all__ = [
"OligoDatabase",
"ReferenceDatabase",
]
classes = __all__
|
f1e13063641542c8ddfd51d33b062e2587bb7993f64fd8a7f956605a46e785be | Python | 279 | 5 | # import all functions and ABCs for convenience
from .classifier import classify, vote, Classifier, available_classifiers, register_classifier
# import all the classifiers for convenience
from .common import SVM, LDA, RandomForest, NaiveBayes, KNN, LogisticRegression, MLP
|
fe85fe06bd3408077772c81992edfaeac12620b5d1cbcb690b19413f3d866163 | Python | 280 | 8 | # Copyright (c) OpenMMLab. All rights reserved.
from .builder import (OPTIMIZER_BUILDERS, OPTIMIZERS,
build_optimizer_constructor, build_optimizers)
__all__ = [
'build_optimizers', 'build_optimizer_constructor', 'OPTIMIZERS',
'OPTIMIZER_BUILDERS'
]
|
fbb9fe3789e4296f0682e904deec7efb6e2e63b85f9c060434907d0d5e9b96a4 | Python | 283 | 7 | # 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 sbi.inference.abc.mcabc import MCABC
from sbi.inference.abc.smcabc import SMCABC
__all__ = ["MCABC", "SMCABC"]
|
9fb0eedeee6cf2ee5e27fbc0abf3459e4e387ef473e36a05d640b7adf694799e | Python | 284 | 8 | # Copyright (C) 2024-2025 ETH Zurich, Niels Maeder and other DASH contributors.
CLEANER_CONTENT = """
#! /bin/bash
python -c "from serenityff.charge.gnn.attention_extraction.extractor import Extractor;
Extractor._clean_up(num_files=${1}, batch_size=int(${2}), sdf_file='${3}')"
"""
|
a659a73374c09f7a4999db254a0769d91292c1178a2caaa7c594c7fb0749d7a1 | Python | 284 | 13 | from .algorithm import run
from .wrapper import (
FeatureSelectionGA,
MultiObjFeatureSelectionNSGA2
)
from .environment import (
USE_NOTEBOOK_ENVIRONMENT
)
from . import fitness
from . import pso
from . import io
from . import base
from .io import save, load
|
1f777066812825ee26e990728ff44297cdeae67f5f98aa2595fc3cf50ef9e3b7 | Python | 285 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .collect_env import collect_env
from .logger import get_root_logger
from .setup_env import setup_multi_processes
from .timer import StopWatch
__all__ = [
'get_root_logger', 'collect_env', 'StopWatch', 'setup_multi_processes'
]
|
e4153ec1ff2a44881f99dbbd3c6efa59e1781b76855fd00cf3cfb102801b1e10 | Python | 285 | 8 | from .causal_conv import * # NOQA
from .pqmf import * # NOQA
from .residual_block import * # NOQA
from .residual_stack import * # NOQA
from .sine import * # NOQA
from .tade_res_block import * # NOQA
from .upsample import * # NOQA
from .vector_quantize_codebook import * # NOQA
|
3f447d086142f93b5e030af2d62952d84f723c8859d70e8976a1bd6f24d0192f | Python | 288 | 9 | var.verboseRead = 0
read('d.nex')
d = Data()
d.compoChiSquaredTest(verbose=1, skipColumnZeros=1, useConstantSites=1, skipTaxNums=None, getRows=0)
read('opt.p4_tPickle')
t = var.trees[0]
t.data = d
t.compoTestUsingSimulations(nSims=100, doIndividualSequences=0, doChiSquare=0, verbose=1)
|
f42af941207d66ccda0507cfb677c5ad8d2bf8b8d3e747561cfbb1aad055279e | Python | 291 | 10 | import torch
from torch.nn import functional as F
def cross_entropy_loss(output, target, misc, weight=None):
if weight is None:
return F.cross_entropy(output, target)
else:
weight = torch.Tensor(weight)
return F.cross_entropy(output, target, weight=weight)
|
6270af55e2af0f6495eaddd4fa7f880f9eee39814fbb77a2d97b6b0eea85f5e2 | Python | 292 | 8 | import os
for root, dirs, files in os.walk("D:\Tuo\yolov5-cell\inference\output/"):
print(files) #当前路径下所有非目录子文件
for file in files:
with open ("D:\Tuo\yolov5-cell\inference\output/"+file,"r") as f:
lines=f.readlines()
print(len(lines)) |
0ef85e4db3ad4dcc84cb1da982c72d6bdc85846b0f5228571e050f715a04c1c8 | Python | 293 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.utils import Registry, build_from_cfg
IOU_CALCULATORS = Registry('IoU calculator')
def build_iou_calculator(cfg, default_args=None):
"""Builder of IoU calculator."""
return build_from_cfg(cfg, IOU_CALCULATORS, default_args)
|
34842d8c5b1cbec83a4eb1d430f3f2f2c34f59e2eb0f7466f7759e2610419f45 | Python | 295 | 10 | import tensorflow as tf
import sys
print(tf.__version__)
# The export path contains the name and the version of the model
tf.keras.backend.set_learning_phase(0) # Ignore dropout at inference
model = tf.keras.models.load_model(sys.argv[1])
export_folder = sys.argv[2]
model.save(export_folder) |
fde6117775a9f2c0f4bea45f61ed138106e5264509154ba069bc490fdad1740d | Python | 297 | 7 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
from pathlib import Path
default_dash_tree_path = Path(__file__).parent / "default_dash_tree"
additional_data_dir = Path(__file__).parent / "additional_data"
dash_props_tree_path = additional_data_dir / "dashProps"
|
00340d27705aeccecb59240c3466e593f7b2f1557544cd6216ce49b33c5c13fd | Python | 298 | 7 | # import for convenience. Individual dataset implementatios are kept separate as
# they may require several subroutines that otherwise clutter the namespace
from .dataset import Dataset
from .nst import NST
from .graz import GrazB
from .khushaba import Khushaba
from .nst_emg import NST_EMG
|
c07b98ba7a78e114f810632be8aea56ff478e5e8d89ef00f3365ac745e5e88d4 | Python | 298 | 14 | read('inTrees.phy')
inTrees = var.trees
var.trees = []
read('stMcmcCons.nex')
read('mrpMajRuleConsTree.nex')
read('mrpStrictConsTree.nex')
var.trees[1].name = 'mrpMajRule'
var.trees[2].name = 'mrpStrict'
tt = Trees(taxNames=var.trees[0].taxNames)
tt.inputTreesToSuperTreeDistances(inTrees)
|
f5ddc9f360a89f9f4890932a6f62d7c3a5daa4e3bb454e7579b4b1ef53965b2f | Python | 301 | 12 | # from .deconvolution import deconvolve
from .psf import PSF
import multipagetiff
from multipagetiff.io import *
from multipagetiff.plot import *
from multipagetiff.stack import Stack
from . import transformation
from . import skew_correction
from . import registration
from .deconvolution import *
|
14201195af18eddad168164ea10508c5a5808ccbcfec3b9dbd62aef7507c4160 | Python | 302 | 7 | import pandas as pd
import os
# This function is placed in a separate python file and does not require matplotlib in tuning (it was slowing down condor)
def LoadCleanedLabel(config):
return pd.read_csv(os.path.join(config.data_dir, config.AOI + '_STATS_cleaned' + str(config.prct2retain)+'.csv')) |
73b7f7e16715da3869613c9d4e2799e29a44e5f12afac864d338d00d984e395a | Python | 303 | 20 | read('dB.nex')
a = var.alignments[0]
read('mbout.con')
tMB = var.trees[0]
var.trees.pop()
read('paupBootTree.nex')
tPAUP = var.trees[1]
tMB.taxNames = a.taxNames
tPAUP.taxNames = a.taxNames
tMB.tvTopologyCompare(tPAUP)
read('combinedSupportsTree.nex')
tCombined = var.trees[2]
tCombined.tv()
|
56737564bbdacc30309aa1f50c3495ff8b3875a763ff29809791855ecf54e752 | Python | 304 | 10 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
files = snakemake.input['files']
dfs = [pd.read_csv(file, index_col='epoch') for file in files]
df = pd.concat(dfs, axis=1)
df.columns = [f.split('/')[-1].split('.')[0] for f in files]
df.plot()
plt.savefig(snakemake.output['loss']) |
39eb290445ac75f5f8a22018d3ec75caec25a64e5cd062a5ffbd4cf43bd4b1e1 | Python | 305 | 14 | #!/usr/bin/python
# -*- coding: UTF-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import division
from __future__ import nested_scopes
from __future__ import generators
from __future__ import unicode_literals
from __future__ import print_function
|
8c1ce735de463222f8973438cc6cba69af9bae811921d5eb7a548608cda76119 | Python | 305 | 10 | # -*- coding: utf-8 -*-
"""
Created on Thu Jun 10 14:26:30 2021
@author: fhu14
"""
from .all_consts import Model, RawData, RotData, Bcond, atom_nums, atom_masses,\
ANGSTROM2BOHR, H_entries, S_entries, atom_header_entries, valence_dict, gross_charge,\
dipole_line, cm5_charge, DEBYE2EA, DEBYE2AU
|
ecc8ff891393a18f6c0397e713d5e63dbf992fe1bfa54fb55117096d18c21ce8 | Python | 306 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .dist_utils import allreduce_grads, sync_random_seed
from .model_util_hooks import ModelSetEpochHook
from .regularizations import WeightNormClipHook
__all__ = [
'allreduce_grads', 'WeightNormClipHook', 'sync_random_seed',
'ModelSetEpochHook'
]
|
a4bb4f1df852972213ee68786412800e6a0f22865ff44039e8306100d0569cfa | Python | 307 | 5 | # 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 sbi.simulators.linear_gaussian import diagonal_linear_gaussian, linear_gaussian
from sbi.simulators.simutils import simulate_in_batches
|
a298052229aa098496e6b93204b54d70431949bdcaf46ba7ca01b8de9aac59d3 | Python | 309 | 13 | skip=200
tp = TreePartitions("mcmc_trees_0.nex", skip=skip)
tp.read("mcmc_trees_1.nex", skip=skip)
tp.dump()
t = tp.consensus()
# put support on node.name's, for the text drawing
for n in t.iterInternalsNoRoot():
n.name = "%.0f" % (100. * n.br.support)
t.draw()
# Save it
t.writeNexus(fName='cons.nex')
|
24a2bc8bbb96108a257dbc95df633b0dd4810479710204c9ef6c5f5386de83bc | Python | 310 | 10 | # Copyright Universitat Pompeu Fabra 2020-2023 https://www.compscience.org
# Distributed under the MIT License.
# (See accompanying file README.md file or copy at http://opensource.org/licenses/MIT)
__all_models__ = [
"graph-network",
"transformer",
"equivariant-transformer",
"tensornet",
]
|
1e131c59a7c0da1b50f797509e9132e2278109929df69e1776e181d27780facb | Python | 311 | 18 | # Calculate a likelihood.
read("d.nex")
d = Data()
read("t.nex")
t = var.trees[0]
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=0, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=1, val=0.2)
t.optLogLike()
t.writeNexus('optTree.nex')
t.model.dump()
|
e691b388b91220c975a9409bad22850f132bb21064dad86435a6f36523dd8779 | Python | 315 | 11 | import torch
class LogisticRegression(torch.nn.Module):
def __init__(self, input_dim, output_dim):
super(LogisticRegression, self).__init__()
self.linear = torch.nn.Linear(input_dim, output_dim)
def forward(self, x):
outputs = torch.sigmoid(self.linear(x))
return outputs
|
9d66dfc1ca3573bb8098be114126ede4b5c66835eae76082cd828f680cfe1dda | Python | 316 | 12 | import numpy as np
pulses = np.load(snakemake.input["files"], allow_pickle=True)
curves = []
for pulse in pulses:
diff1 = np.gradient(-pulse*100)
diff2 = np.gradient(diff1)
curve = diff2/(1 + diff1**2)**(3/2)
curves.append(curve)
np.save(snakemake.output['curvature'], np.stack(curves)) |
1062e711c5f5799f92b8270c52315a743c82184111000c3cfdf2f028002cb072 | Python | 317 | 12 | import numpy as np
import os
import sys
import pdb
core_output = np.load(sys.argv[-2])
labels = np.load(sys.argv[-1])
core_res = np.argmax(core_output, axis = 0)
nimg = core_res.shape[0]
labels = labels[:nimg]
ncorrect = np.where(core_res == labels)[0].shape[0]
print("nimg:%d acc:%f"%(nimg, ncorrect * 1.0 / nimg))
|
6bdbd11429fd682ac77403c4ac013b85d09134ddc2995dc0d49fc29bea5b13cd | Python | 318 | 17 | # -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 20:13:27 2021
@author: fhu14
"""
import numpy as np
ANGSTROM2BOHR = 1.889725989
def TriuToSymm(matrix):
for ind in range(matrix.shape[0]):
matrix[ind:, ind] = matrix[ind, ind:]
return matrix
def BMatArr(matrix):
return np.array(np.bmat(matrix)) |
7ea4f73684d9620aa336ffbb50fbe514e5720e3ce9c0378ae797bc851d316c4c | Python | 319 | 13 | from .tdctox import TDCTox
from .moleculenet import MoleculeNet
from .moleculenet_single import MoleculeNetSingle
from .tdctox_single import TDCToxSingle
from .moleculenet_props import MoleculeNetProps
__all__ = [
"TDCTox",
"MoleculeNet",
"MoleculeNetSingle",
"TDCToxSingle",
"MoleculeNetProps",
]
|
e0026888a2870560fbe5ec9d4a2217d5c7143cf6e5be48d908964ec039fee231 | Python | 322 | 8 | # Copyright (c) OpenMMLab. All rights reserved.
from .image import (imshow_bboxes, imshow_keypoints, imshow_keypoints_3d,
imshow_mesh_3d, imshow_multiview_keypoints_3d)
__all__ = [
'imshow_keypoints', 'imshow_keypoints_3d', 'imshow_bboxes',
'imshow_mesh_3d', 'imshow_multiview_keypoints_3d'
... |
b835eb6fb489db413f70def6af5c9c44dd981faa39bfea86de423b5721b3e059 | Python | 326 | 14 | read("d.nex")
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=0, val=0.0)
m = Mcmc(t, nChains=1, runNum=0, sampleInterval=100, checkPointInterval=None)
m.run(200... |
4dc6ea5564b648bb61a1dcbf4d144fd6b60d1d750d0105af3721142338cfd13d | Python | 327 | 11 | import glob
import subprocess
# Starts bash scripts for random-search-based hyperparameter optimization.
run_file_prefix = 'run_hparam_search'
rel_working_dir = 'profile/selbstaufsicht/scripts/'
for filename in glob.glob("%s*" % run_file_prefix):
command = "sbatch %s" % filename
subprocess.run(command, shell... |
784ba3b4ec1b825927717fabc5d6e23dc98ba9d0edf4d17bad910b5ab8821e43 | Python | 327 | 13 | # Get the test quantity, X^2, from the original data.
read("../../K_thermus/noTRuberNoGapsNoAmbiguities.nex")
d = Data()
ret = d.compoChiSquaredTest()
#print ret
originalStat = ret[0][0]
# Get the sim stats
n = Numbers('mcmc_sims_0', col=1, skip=500)
# Evaluate the tail area probability
n.tailAreaProbability(original... |
01a3d9d04edcdc247067925ce5c235c910ea8a6aeaf406aec5ae254eab697af7 | Python | 328 | 14 | read("../d.nex")
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=1, val=0.2)
m = Mcmc(t, nChains=4, runNum=0, sampleInterval=10, checkPointInterval=2000)
m.run(4... |
7fc340071e8be0a8550ff8d6521401a189205dc1576e0283bec808cdb22a02ce | Python | 328 | 11 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .cascade_rcnn import CascadeRCNN
@DETECTORS.register_module()
class SCNet(CascadeRCNN):
"""Implementation of `SCNet <https://arxiv.org/abs/2012.10150>`_"""
def __init__(self, **kwargs):
super(SCNet, self).__init__(**... |
cc222e86d515e13da811df18e9b546292c7eb06925e5827d949d0c8206f817e5 | Python | 328 | 9 | import requests
if __name__=="__main__":
source_url = 'https://cloud.tsinghua.edu.cn/d/e1ccfff39ad541908bae/files/?p=%2Fall_six_datasets.zip&dl=1'
headers = {'User-Agent': 'Mozilla/5.0'}
res = requests.get(source_url, headers=headers)
with open('dataset/datasets.zip', 'wb') as f:
f.write(res.c... |
09a0a11ab60c9cc48c3c3c278376f2df072772ddc012f61192af924182b5ba1d | Python | 332 | 6 | from .ds_base import ds_base, collate, register as regdataset
from .ds_loader import pre_loader_checkings, register as regloader
from .ds_transform import TBase, have, register as regtrans
from .ds_estimator import register as regestmat
from .ds_formatter import register as regformat
from .ds_sampler import register as... |
547934dfc4a5626ea9c3b38ad823c56d82a06231c5a6f935a09ac9a1bbcad9d5 | Python | 332 | 18 | import numpy as np
def gen_labels(in_annot,
out_annot):
peaks = np.load(in_annot).astype(int)
p1, p2 = peaks[:, 0], peaks[:, 1]
mask = (p1 > 0) & (p2 > 0)
annots = mask.astype(float)
np.save(out_annot, annots)
gen_labels(snakemake.input['annots'],
snakemake.output['annots'])... |
04a2ce5406337b40889ca2530b7dc7e94c033cdeb98ea79e30864a96755527b6 | Python | 333 | 16 | import sys
import os
# Disable
def blockPrint():
sys.stdout = open(os.devnull, 'w')
# Restore
def enablePrint():
sys.stdout = sys.__stdout__
class Printer():
"""Print things to stdout on one line dynamically"""
def __init__(self,data):
sys.stdout.write("\r\x1b[K"+data.__str__())
sys.s... |
ad1be6a9b6729425d787e5f1d5243690e28435fe14ce84b5eb9ab91dab7e8742 | Python | 333 | 9 | class GlobalFigureMixin:
"""If no `figure` was passed to an initializer, use the figure stored in configs
(set at the beginning of extraction)"""
def __init__(self, fig):
if fig is None:
import configs.config
self.fig = configs.config.Config.FIGURE
else:
s... |
f32fd40b5f5b4ae042e27f17db3c2cc67ca9905474423a9d204b4e036d032843 | Python | 333 | 15 | import tensorflow_federated as tff
def download_and_save_shakespeare():
tff.simulation.datasets.shakespeare.load_data(cache_dir='./')
"""
Or with Tensorflow dependencies, you can run this to process the data from Tensorflow locally:
```
python dataset.py
```
"""
if __name__ == "__main__":
download_and_save_... |
357619969e6e518154a4e2b9c745b5a8a9175468f499162d885c1f5c89f0273e | Python | 334 | 19 |
class MyOVBox(OVBox):
def __init__(self):
OVBox.__init__(self)
def initialize(self):
# nop
return
def process(self):
# print the string specified in the box configuration.
# 'Message' is the name of the config entry.
print(self.setting['Message'])
def uninitialize(self):
# nop
return
bo... |
94154d09837d0e649bf80af5bcb490fb8dddf476f671bc59a584f65d486be884 | Python | 334 | 11 | from typing import Union
import numpy as np
import pandas as pd
import sklearn.cluster
def calculate_local_centers(data: Union[np.ndarray, pd.DataFrame], no_of_centers: int) -> pd.DataFrame:
kmeans = sklearn.cluster.KMeans(no_of_centers)
kmeans.fit(data)
return pd.DataFrame(kmeans.cluster_centers_, colum... |
60432b775df74f04e6dbcaf55b99042420a17a946241457c6b72b179447a10db | Python | 335 | 16 | from abc import ABC, abstractmethod
import neo
class INeoConverter(ABC):
"""Interface for neo converters"""
@abstractmethod
def to_neo(self) -> neo.Block:
"""
Create a neo structure based on the given recording
:return: A neo block containing the data from the recording
... |
2e524c75c6dc21c8f78f83f207082dd8471ad3bf069e93946aa8cb1120470c38 | Python | 338 | 16 | from typing import NewType, NamedTuple, Union, Tuple, Optional, Dict, Any
class Bounds(NamedTuple):
lower: float
upper: float
BoundsInput = Union[Bounds, Tuple[float, float]]
L0 = NewType("L0", float)
L1 = NewType("L1", float)
L2 = NewType("L2", float)
Linf = NewType("Linf", float)
Preprocessing = Optiona... |
6bfee9f7dc72958ec42950a2413c498b09bd0239ca6c664d47d4fc75e5380eeb | Python | 339 | 12 | import torch
import models
import numpy as np
model = eval(f"models.{snakemake.wildcards['nn']}()")
model.load_state_dict(torch.load((snakemake.input['model'])))
arr = np.load(snakemake.input['pulse'], allow_pickle=True)
pulses = torch.from_numpy(arr)
res = model(pulses.float()).detach().numpy()
np.save(snakemake.ou... |
4a33d6b5876c891dc2e1c229cf2119312de1b0a21c9667de6cc02289b2601545 | Python | 340 | 14 | import numpy as np
import typing
_T = typing.TypeVar('_T')
def calc_2D_weights(x: _T, y: _T, center: typing.Tuple[float, float], range: _T) -> _T:
dist = np.sqrt((x - center[0]) ** 2 + (y - center[1]) ** 2)
in_range = dist < range
ret = x * 0
ret[in_range] = np.abs(1 - (dist[in_range] / range)**2) *... |
f1d794024764ed917ac01ad639217268576851c5b6961ce65e47271e728b1cfb | Python | 341 | 13 | from setuptools import find_packages, setup
setup(
name="ndeep",
version="1.0.0",
setup_requires=["pytest-runner"],
tests_require=["pytest"],
description="Research Library for the nDeep project",
author="Ngoc-Dung Nguyen",
author_email="nguyenn@moadata.ai.kr",
license="MIT",
package... |
c6b62fc566c3fbcd4b30652ffaa5c537049d33381bb02b205892706b91091cc3 | Python | 343 | 15 | from __future__ import annotations
import sys
def float_comp(f1: float, f2: float, epsilon=sys.float_info.epsilon) -> bool:
"""
Checks if two floats are equal enough
:param f1: Value 1
:param f2: Value 2
:param epsilon: Value used for check
:return: abs(f1-f2) <= epsilon
"""
return a... |
0753f451fe90ff719b937de81878b81112038939954aa431e831705b7b2ba050 | Python | 344 | 14 | import hashlib
import os
def sha256_hash(git_uri: str) -> str:
m = hashlib.sha256()
m.update(git_uri.encode())
return m.hexdigest()
def home_directory_path(folder: str, hash_digest: str) -> str:
# does this work on all operating systems?
home = os.path.expanduser("~")
return os.path.join(hom... |
40739cc0d538aae0f1fe9d5233c843500417e077598ee0754376e16b8adde220 | Python | 344 | 7 | import os
os.system('python check_train_hamilton.py --ckpt ../../ckpts/spring_chain/Euler \
--solver euler\
--dt 0.2')
os.system('python check_train_hamilton.py --ckpt ../../ckpts/spring_chain/Runge_Kutta4 \
--solver rk4\
... |
5d89c5a9547880fb1a255812c1e90fd158eb92e7c4eb3d95ecfecac8a1ccc660 | Python | 346 | 11 | var.verboseRead = 0
var.doCheckForBlankSequences = False
read('dA.nex')
read('dB.nex')
d = Data()
d.compoChiSquaredTest(verbose=1, skipColumnZeros=1, useConstantSites=1, skipTaxNums=[[2], []], getRows=1)
read('opt.p4_tPickle')
t = var.trees[0]
t.data = d
t.compoTestUsingSimulations(nSims=100, doIndividualSequences=1, ... |
82e87103bd3860d11d1f297b4e42b00dbdeacf70948924aefeae6cbceccdd537 | Python | 346 | 13 | # Copyright (c) OpenMMLab. All rights reserved.
from mmcv.runner import HOOKS, Hook
@HOOKS.register_module()
class ModelSetEpochHook(Hook):
"""The hook that tells model the current epoch in training."""
def __init__(self):
pass
def before_epoch(self, runner):
runner.model.module.set_trai... |
a725e0cab4aa6adbb678ba66027bc6ef8d437853323089b3b7f9bed52be381c3 | Python | 347 | 26 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 30 17:43:55 2021
@author: fhu14
"""
class tst_class:
def __init__(self):
self.vars = [1, 2, 3]
def get_vars(self):
return self.vars
b = tst_class()
x = b.get_vars()
print(x)
print(b.vars)
print(x is b.vars)
x[1] = 6
print(x)
print... |
24cf76ec3f8846ed64863c9f00ec6dd33ec3ffa00dad53d2c04d79f1fbd0a263 | Python | 349 | 11 | read("d.nex")
a = var.alignments[0]
dm = a.logDet(correction='L94', doPInvarOfConstants=True,
pInvar=None, pInvarOfConstants=None,
missingCharacterStrategy='fudge', minCompCount=1,
nonPositiveDetStrategy='invert')
dm.writeNexus("dm.nex")
t = dm.bionj()
#t.taxNames = a.taxNames
... |
98e697140e24a82e9c758d61e32cf05240a9df2c3949be3bd37e5fdb593a8ae7 | Python | 349 | 18 | read('../../noTRuberNoGapsNoAmbiguities.nex')
d = Data()
read('../../tt.nex')
for t in var.trees:
t.data = d
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=0, val=0.0)
t.optLogLike()
tt = Trees... |
c0fe3a8047fee52dcc96bdc2382a88dee994cc4a1a50eda72edcaaa5ffde269e | Python | 349 | 6 | # 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 sbi.samplers.score.correctors import Corrector, get_corrector
from sbi.samplers.score.diffuser import Diffuser
from sbi.samplers.score.predictors imp... |
0264aba2281204e5309d5ca1453acb38983dd73432bd46ed68351553ddbbf4d2 | Python | 351 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .mask_target import mask_target
from .structures import BaseInstanceMasks, BitmapMasks, PolygonMasks
from .utils import encode_mask_results, split_combined_polys
__all__ = [
'split_combined_polys', 'mask_target', 'BaseInstanceMasks', 'BitmapMasks',
'PolygonM... |
ba9f1d18ee1d8b57388bd8430d53219622dc4c0ec5bdc7e6a22fabc11f11a796 | Python | 352 | 14 | # Copyright (C) 2024-2025 ETH Zurich, Niels Maeder and other DASH contributors.
"""Utilitary functions for running the pytests."""
import json
import os
from pathlib import Path
def are_in_CI() -> bool:
return any((os.getenv("GITHUB_ACTIONS") == "true", os.getenv("GITLAB_CI")))
def read_json(file: Path):
r... |
c98c9e113f9974aaad61af4d1745eae5c6df3378e5fd38fc1c078ff181633db7 | Python | 352 | 16 |
# models.py
import datetime
from peewee import *
db = SqliteDatabase("/data/database.db", pragmas=[('journal_mode', 'wal')])
class ClassifyEntity(Model):
smiles = TextField(unique=True, index=True)
classification_json = TextField()
class Meta:
database = db
#Creating the Tables
db.create_tabl... |
d755f08673f2bcc7dbcf41392da2515e02ec8430ae6ebee25e418d93c0036178 | Python | 352 | 18 | var.verboseRead = 0
var.doCheckForDuplicateSequences=False
read('ds.nex')
if 0:
var.nexusSets.dump()
if 1:
a=var.alignments[0]
a.writePhylip(None)
c = a.subsetUsingCharSet('cs2', inverse=True)
c.writePhylip(None)
if 1:
b = var.alignments[1]
b.writePhylip(None)
c = b.subsetUsingCharSet... |
e8919e5378bbae6dc5c322229118e29d15ce2455b58455a5ecdc040ff1659127 | Python | 354 | 12 | import torch.nn as nn
class VFLClassifier(nn.Module):
def __init__(self, input_dim, output_dim, bias=True):
super(VFLClassifier, self).__init__()
self.classifier = nn.Sequential(
nn.Linear(in_features=input_dim, out_features=output_dim, bias=bias),
)
def forward(self, x):
... |
62d377797ad390e950112f9c715cf454eb18c088f9e6fadcf7049fe8a63cc0ea | Python | 355 | 28 | read('t.1111.nex')
read('t555.nex')
read('t43.nex')
read('t39.nex')
read('sets1.nex')
if 1:
t = var.trees[0]
t.setNexusSets()
t.btv()
t = var.trees[1]
t.btv()
# Out with the old nexusSets, in with the new.
var.nexusSets = None
read('sets2.nex')
t = var.trees[2]
t.setNexusSets()
t.tv()
t = var.t... |
8bcf841c876012265d18d3578ce1fb8e94ae73c9e665861a15504a3782d2dbca | Python | 355 | 12 | import numpy as np
import pandas as pd
import shelve
fishlabel = '210121_F05'
plane = '70um_bh'
output_path = '/network/lustre/iss01/wyart/analyses/mathilde.lapoix/MLR/Calcium_Imaging/' + fishlabel + '/' + plane
shelf_in = shelve.open(output_path + '/shelve_calciumAnalysis.out')
for key in shelf_in:
globals()[key... |
bceec45e6dbfd1ad595f6b4741c36496c0c0364d574d2783f4758e7d3057190e | Python | 355 | 14 | import logging
from sklearn.feature_extraction.text import TfidfVectorizer
class SKTokenizer():
def __init__(self):
self.tokenizer = TfidfVectorizer()
def fit(self, x):
logging.info('fitting Scikit-Learn Tokenizer')
self.tokenizer.fit(x)
def transform(self, x):
return sel... |
cd0d0c0fedaa5ce5b1f83087d5a8bd42e97e3a5d899fdd19473a5b2c3f9f5011 | Python | 355 | 12 | import numpy as np
class ReplaceTensor:
def __init__(self, image_label, mask_label):
self.image_label = image_label
self.mask_label = mask_label
def __call__(self, sample):
image, mask, misc = sample[self.image_label], sample[self.mask_label], sample['misc']
return {'image': ... |
ae24fbf97aa1f6e547e481bbdd022b95b35f60260e6c1f166dd72cb7bb9b8c06 | Python | 356 | 13 | import torch
import models
import numpy as np
model = eval(f"models.{snakemake.wildcards['nn']}()")
model.load_state_dict(torch.load((snakemake.input['model'])))
arr = np.load(snakemake.input['pulse'], allow_pickle=True)
pulses = torch.from_numpy(arr).float()
res = model(pulses.float())
res = res.detach().numpy()
np... |
f7c485c08b06a046ab43c79135b6078ed64613c9e17ba348b1c45f9892606430 | Python | 356 | 17 | # setup.py
from setuptools import setup
setup(
name='keras2c',
version='2.0',
packages=['keras2c'],
package_dir={'':'src'},
install_requires=[
# Add dependencies here
],
classifiers=[
'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)',
# add ... |
cd234c766af24499054baca6f3265d7e1a02aa6e0e20fc7e08ebbe9cc5d050b3 | Python | 358 | 14 | # Copyright (C) 2022-2025 ETH Zurich, Niels Maeder and other DASH contributors.
# from serenityff.charge.gnn import ChargeCorrectedNodeWiseAttentiveFP, NodeWiseAttentiveFP, Extractor, Trainer
# from . import _version
__version__ = "2.0.1"
# __all__ = [
# Trainer,
# Extractor,
# ChargeCorrectedNodeWiseAtten... |
771764c2d550c2101abefa21edc70e82fa0565fcbfa5dccd6d8e3768b2bab2a2 | Python | 361 | 9 | # Copyright (c) OpenMMLab. All rights reserved.
from .bottom_up_transform import * # noqa
from .gesture_transform import * # noqa
from .hand_transform import * # noqa
from .loading import * # noqa
from .mesh_transform import * # noqa
from .pose3d_transform import * # noqa
from .shared_transform import * # noqa
f... |
cb681902e5fe9a4072f2775ca22a83d48110aef2027e911f86c794a53367badd | Python | 361 | 17 | from pybrid.scripts import main
from pybrid.config import default_cfg as cfg
cfg.exp.log_dir = "results/local_hybrid"
cfg.exp.test_hybrid = True
cfg.exp.test_amort = True
cfg.data.train_size = 2000
cfg.data.test_size = 1000
cfg.infer.num_train_iters = 20
cfg.infer.num_test_iters = 100
cfg.infer.train_thresh = 0.001... |
64222ef63c5aa9304a3293b17530cb8d1f49c11cc82fe69dcad194410092dcbd | Python | 364 | 10 | # Copyright (c) OpenMMLab. All rights reserved.
from .detector_node import DetectorNode
from .hand_gesture_node import HandGestureRecognizerNode
from .pose_estimator_node import TopDownPoseEstimatorNode
from .pose_tracker_node import PoseTrackerNode
__all__ = [
'DetectorNode', 'TopDownPoseEstimatorNode', 'PoseTrac... |
8cbc0154abfe745179f34780df41654da4c10ea6fc800563476681ab4912da3c | Python | 364 | 14 | read('opt.p4_tPickle')
t = var.trees[0]
print('The rate matrix for the second partition is:')
print(t.model.parts[1].rMatrices[0].val)
print('The composition of the model in the last partition is:')
print(t.model.parts[2].comps[0].val)
print('The relative rate of the first partition is:')
print(t.model.parts[0].relR... |
6b3a30ee072196fa62f8334d3e1bfe8f7f307f9831d636f9a7399c2991931626 | Python | 365 | 17 | from pybrid.scripts import main
from pybrid.config import default_cfg as cfg
cfg.exp.log_dir = "results/local_predcoding"
cfg.exp.test_pc = True
cfg.model.train_amort = False
cfg.data.train_size = 2000
cfg.data.test_size = 1000
cfg.infer.num_train_iters = 20
cfg.infer.num_test_iters = 100
cfg.infer.train_thresh = 0... |
b59070562adffb5546e041e1e3f9fccb4a923c5b2ccd35a6ad296ff8a0838e2e | Python | 365 | 11 | # Copyright (c) OpenMMLab. All rights reserved.
from .builder import DATASETS
from .coco import CocoDataset
@DATASETS.register_module()
class DeepFashionDataset(CocoDataset):
CLASSES = ('top', 'skirt', 'leggings', 'dress', 'outer', 'pants', 'bag',
'neckwear', 'headwear', 'eyeglass', 'belt', 'footw... |
e9466f9a433e6a33b331020fde0769a699acf12a66504f82bac9b1fe245f0095 | Python | 365 | 13 | read('../../tt.nex')
t = var.trees[1] # Under this model, the attract tree is the ML tree
read('../../noTRuberNoGapsNoAmbiguities.nex')
t.data = Data()
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=1, val=0.5)
t.setPInvar(free=0, val=0.0)
t.optLogLike... |
bf1dba278ea9bb694a1bbd5743c85dfa09df9acef9deddc6e35bdd9466ef699b | Python | 367 | 10 | # Copyright (c) OpenMMLab. All rights reserved.
from .bigeye_effect_node import BigeyeEffectNode
from .notice_board_node import NoticeBoardNode
from .object_visualizer_node import ObjectVisualizerNode
from .sunglasses_effect_node import SunglassesEffectNode
__all__ = [
'ObjectVisualizerNode', 'NoticeBoardNode', 'S... |
34fba40882cb139f116d7cca3e63f41df87d3a7caf4cccda969823b0a26062c9 | Python | 368 | 15 | import runpy
from pathlib import Path
import pytest
from clipkit.version import __version__
@pytest.mark.integration
def test_repository_api_example_remains_runnable(capsys):
script_path = Path(__file__).parents[2] / "test-api.py"
runpy.run_path(str(script_path), run_name="clipkit_api_example")
assert... |
e919d712b2bcec5ac6504c04302522980232c5847ae6046655cee8b988dfeb4b | Python | 368 | 13 | # Copyright (c) OpenMMLab. All rights reserved.
import torch
from mmpose.models import builder
def test_v2v_net():
"""Test V2VNet."""
cfg = dict(type='V2VNet', input_channels=17, output_channels=15),
model = builder.build_backbone(*cfg)
input = torch.randn(2, 17, 32, 32, 32)
output = model(input)... |
475674ddf6248c3907ebebbda0a9e3264f9cd9fb32d9eb8ae8bc67fd1d357c70 | Python | 372 | 14 | #!/usr/bin/env python
import sys
from setuptools import setup
import versioneer
SETUP_REQUIRES = ['setuptools >= 30.3.0']
SETUP_REQUIRES += ['wheel'] if 'bdist_wheel' in sys.argv else []
if __name__ == "__main__":
setup(name='snfpy',
setup_requires=SETUP_REQUIRES,
version=versioneer.get_versi... |
7cacaeddd33674dc6a05d720548c562faca18c8a0441d03b1d1b0e6756fb2b72 | Python | 372 | 16 | 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')
#The file is then used to calculate the leaf stabilities
ls = LeafSupport('input.cherries.removed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.