sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
9bea0156ff54f1ab13c0fa7724ce64753ac82cfb0671a2fca69b9f2d2d8235fb | Python | 761 | 17 | with open(snakemake.input[0]) as fin, open(snakemake.output[0], "w") as fout:
current_qseqid = None
for line in fin:
qseqid, sseqid, _, qcovhsp, scovhsp, _ = line.split()
qcovhsp, scovhsp = float(qcovhsp), float(scovhsp)
qseqgen, sseqgen = qseqid.rsplit("_", 2)[0], sseqid.rsplit("_", 2)[... |
d42c69913e13d293ee2799f3d72a5e851f1c7d38c92f305a7eb4abf67b6bebcb | Python | 761 | 27 | 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'
from p4.supertreesupport import SuperTreeSupport
print("%20s %6s %6s %6s %6s %6s" % (' ', 'S', 'P', 'Q', 'R',... |
04055377e6a3b0f2b43a56e4fd35746faa2a93198114df70cb85ae942864eb96 | Python | 762 | 25 | import tensorflow_federated as tff
def download_and_save_stackoverflow():
tff.simulation.datasets.stackoverflow.load_data(cache_dir='./')
def download_and_save_word_counts():
tff.simulation.datasets.stackoverflow.load_word_counts(cache_dir='./')
def download_and_save_tag_counts():
tff.simulation.datas... |
52774d929921ceb9f3b1738fb198bf1dd864cfe76568201ae2a820db52718387 | Python | 762 | 17 | """CUDA-graph replay of repeated ``AIMNet2Calculator`` evaluations.
``CUDAGraphCache`` is created by ``AIMNet2Calculator(..., cuda_graph=True)`` (opt-in; disabled by default) and
handles the calls it supports with static-layout engines replayed as CUDA graphs:
* ``dense``: ``N <= nb_threshold`` (dense mode), shared m... |
62c8772072a5a972eac0482ba910d0d992e29e5b096f5630fd300e3672d03c49 | Python | 762 | 13 | allTaxNames = ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7', 't8', 't9', 't10', 't11', 't12', 't13', 't14', 't15', 't16', 't17', 't18', 't19', 't20', 't21', 't22', 't23', 't24', 't25', 't26', 't27', 't28', 't29', 't30', 't31', 't32', 't33', 't34', 't35', 't36', 't37', 't38', 't39', 't40', 't41', 't42', 't43', 't44']
... |
94d21664fcdf6fe2c0547802a9b771eee1bd6248ea161a262e20737f788999fe | Python | 762 | 28 | var.verboseRead = 0
var.warnReadNoFile = 0
read('data.nex')
d = Data()
d.compoSummary()
read('(A,B,C,D,E);')
t = var.trees[0]
t.data = d
c1 = t.newComp(free=1, spec='empirical')
c2 = t.newComp(free=1, spec='empirical')
# Put the c1 comp on all the nodes of the tree. Then put c2 on the
# root, over-riding c1 that is ... |
ad981550b557e7960d18353b62645d44150554bebff7878f1c3a36869646c161 | Python | 762 | 26 | import numpy as np
from .ABCEnvironment import ABCEnvironment
class OpenField(ABCEnvironment):
def __init__(self, low=(0, 0), high=(2.2, 2.2)):
"""
high,low define OpenField sampling range
"""
self.low, self.high = low, high
def sample_uniform(self, ns=1, seed=None):
... |
a0a75f6fa8cb84fa8f7fefe1135a38fce362b080da77b0d1ce67c35eae7a284f | Python | 767 | 17 | # Copyright (c) OpenMMLab. All rights reserved.
from .kpt_2d_sview_rgb_img_bottom_up_dataset import \
Kpt2dSviewRgbImgBottomUpDataset
from .kpt_2d_sview_rgb_img_top_down_dataset import \
Kpt2dSviewRgbImgTopDownDataset
from .kpt_2d_sview_rgb_vid_top_down_dataset import \
Kpt2dSviewRgbVidTopDownDataset
from .... |
340bc0b304266d93bfa8efa65a9ad911f3ee2a826d83079adbe5cc224a4f303d | Python | 768 | 16 | # Copyright (c) OpenMMLab. All rights reserved.
from .base_visualizer_node import BaseVisualizerNode
from .helper_nodes import MonitorNode, ObjectAssignerNode, RecorderNode
from .model_nodes import (DetectorNode, PoseTrackerNode,
TopDownPoseEstimatorNode)
from .node import Node
from .registry ... |
42bfbc34cd473995bf8a4be3f965756a34baf89afd45d67c5987ab53b9359e5b | Python | 768 | 35 | # Simulate data
if 0:
read("d.nex")
d = Data()
if 1:
nTax = 5
taxNames = list(string.ascii_uppercase[:nTax])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=200)
d = Data([a])
if 0:
read("t.nex")
t = var.trees[0]
#t.taxNames = taxNames
if 0:
read('(B:0.5, ((... |
ad9cf9f7add3e8d90ddd6f6ba43ce38f40894f8632c9b53d05e7818009552875 | Python | 770 | 34 | #!/usr/local/bin/python
import sys
import subprocess
import os
import numpy as np
if len(sys.argv) < 3:
print('usage:' + sys.argv[0] + ' <max> <out file> <in bam 1> <in bam 2> <..>')
exit(1)
max_c = int(sys.argv[1])
out_file = sys.argv[2]
o = open('.exclude.tmp','w')
for i in range(3,len(sys.argv)):
bam... |
f672903e76acbf14d7257dfa70e67e45f40b140158d8522ed9904bfc05583c56 | Python | 771 | 25 |
import matplotlib
matplotlib.use('agg')
import re
from pylab import *
data = {}
f = open('tmpdir/test.data', 'r')
for line in f:
t = line.split(' ');
t[2] = t[2].strip();
if (t[2] not in data):
data[t[2]] = [[], []]
data[t[2]][0] += [float(t[0])];
data[t[2]][1] += [float(t[1])];
fig = fi... |
a4dd582f105af96f0659d871312a539ee8362c0bd3ff7609bbb82b0b8114127f | Python | 772 | 27 | class MyMessage(object):
"""
message type definition
"""
# server to client
MSG_TYPE_S2C_INIT_CONFIG = 1
MSG_TYPE_S2C_SYNC_MODEL_TO_CLIENT = 2
MSG_TYPE_S2C_STOP = 3
# client to server
MSG_TYPE_C2S_SEND_MODEL_TO_SERVER = 4
MSG_TYPE_C2S_SEND_STATS_TO_SERVER = 5
MSG_TYPE_C2... |
68c02045f3565cefacb80cc45b6967ec7490687036ace0e96fb8149f48bfcf64 | Python | 774 | 24 | var.verboseRead = 0
var.warnReadNoFile = 0
taxNames = list(string.ascii_uppercase[:5])
a = func.newEmptyAlignment(dataType='dna', taxNames=taxNames, length=5000)
d = Data([a])
read('((A:0.3, B:0.3):0.1, C:0.4, (D:0.3, E:0.3):0.1);')
t = var.trees[0]
t.data = d
c1 = t.newComp(free=0, spec='specified', val=[0.4, 0.1, 0.... |
a9672853eec05ed6226e4769e30d9d5338950258fe76482a5aef227a0f31f67b | Python | 776 | 26 | # 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.diagnostics.kl import kl_divergence_mc
from sbi.diagnostics.lc2st import LC2ST, LC2ST_NF, LC2STScores, LC2STState
from sbi.diagnostics.misspecifi... |
e1dab279fbcb2fcd84ae9424e3797a020c821e55d71b427fbcc1b11efab4b739 | Python | 777 | 26 | import logging
from torch import nn
from fedml_api.standalone.fedavg.client import Client
class TA_Client(Client):
def __init__(self, local_training_data, local_test_data, local_sample_number, args, device, client_idx):
self.local_training_data = local_training_data
self.local_test_data = local_... |
1f30d3f2ccb6eb126a59fbd54607efae9de53b01b83d0140b338df9dc4e42131 | Python | 783 | 27 | import time
from functools import wraps
def timeit(func):
@wraps(func)
def timeit_wrapper(*args, **kwargs):
start_time = time.perf_counter()
result = func(*args, **kwargs)
end_time = time.perf_counter()
total_time = end_time - start_time
print(f'Function {func.__name__} ... |
505d99522e8cc5b12793b7e8ccbc6f6a17c1ba77d6bf4863a8b361b643693791 | Python | 784 | 24 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .single_stage import SingleStageDetector
@DETECTORS.register_module()
class RepPointsDetector(SingleStageDetector):
"""RepPoints: Point Set Representation for Object Detection.
This detector is the implementation of:
... |
cdb0ec76281dfd30650dd4b68fa2908a2e713b4caa94997f3406cffd26d73f37 | Python | 784 | 31 | 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='specified', val=[2., 3., 4., 5., 6., 7.])
t.setNGammaCat(nGammaCat=4)
t.newGdasrv(free=0, val=0.5)
t.setPInvar(free=0, val=0.0)
t.calcLogLike()
ps = PosteriorSamples(t, runNum=0,... |
0e28895d1245a75edeac8e45490a5a1fa62bc4ca3b8d705bafdd4a9ad9c8ab53 | Python | 785 | 19 | from torchvision import transforms
from base import BaseDataLoader
from dataset.mura_dataset import MuraDataset
class MuraDataLoader(BaseDataLoader):
def __init__(self, data_dir, batch_size, shuffle=True, validation_split=0.0, num_workers=1, training=True,
img_size=128):
trsfm = transfor... |
1df087324a15271a4cecb9584e6f9afc22d6ff2a528452bda4755a226886b08b | Python | 785 | 33 | import os
#euler
os.system('python train_poly_segments.py \
--train_dir ../../data/spring_chain/euler_trainset.npy\
--test_dir ../../data/spring_chain/validationset.npy\
--gpu_id 0\
--ckpt neurvec_spring_euler\
--epoch 500\
--model_name orgNN\
--lr 0.001\
--T_train 2\
--optim adam\
... |
13efa6f77d352211905da4ab3bad7c385d8cefe4fcb706961a8ab6a3a47fc0e0 | Python | 786 | 24 | # Copyright (c) OpenMMLab. All rights reserved.
import os.path as osp
from mmcv.utils import build_from_cfg
from mmdet.datasets.builder import PIPELINES
def test_default_format_bundle():
results = dict(
img_prefix=osp.join(osp.dirname(__file__), '../../data'),
img_info=dict(filename='color.jpg')... |
29622e1827f699be5ba468204428b1061ebc8fea554158bbb0bfd91dac04d3eb | Python | 789 | 26 | ls = LeafSupport('../input.nex')
# A clade can be specified using the taxon names in the following
# way. This will produce a list of stabilities using only the quartets
# or triplets that are defined by the taxa in the clade.
ls.defineClade(['Pholiderpeton', 'Proterogyrinus', 'Baphetes',
'Megalocephal... |
c14438e4210f155f9fbb00d7cd0855daf1cf52ac783ec878f3feb7f20220daa9 | Python | 795 | 29 | import tensorflow.keras.metrics
import tensorflow_probability as tfp
from tensorflow.keras import backend as K
__all__ = ['rmse', 'mpe', 'correlation', 'r_2','diff_std']
def rmse(y_true, y_pred):
return K.sqrt(tensorflow.keras.metrics.mse(y_true,y_pred))
def mpe(y_true, y_pred):
min_value: float = 0.1
... |
85104a248645253bc5e1852385a6e2ad7a05172b1e126b1f88d1e3bcfc2e31d8 | Python | 796 | 25 | import logging
from features_processing.bert_tokenizer import BERTTokenizer
from features_processing.sk_toknizer import SKTokenizer
from features_processing.torch_tokenizer import TorchTokenizer
def get_processor(args):
proc_type = args['type']
parmas = args['params']
logging.info("Pre-processing: {}".f... |
bd2caa6b2af664bc0dddec6ef0f2dac0ed411d3fb32303d664123c077d3004d5 | Python | 796 | 27 | import jax.numpy as jnp
k = 3
c_rj = jnp.array([
[11/6, -7/6, 1/3],
[1/3, 5/6, -1/6],
[-1/6, 5/6, 1/3],
[1/3, -7/6, 11/6],
])
d_r = jnp.array([3/10, 3/5, 1/10])
d_r_t = jnp.array([1/10, 3/5, 3/10])
roll_list = (2,1,0,-1,-2)
def get_... |
c6aaaaca2dc1dc0d05da27bb7bfe0c22a5defefe706a5e7b12926ed1278faeea | Python | 797 | 26 | """
subsample slices and shift the short axis and long axis slices
"""
import cv2
import numpy as np
import random
from scipy import ndimage
from scipy.ndimage.interpolation import shift
class ExpNormSdm:
"""
Normalized the signed distance map to [-1,1]
"""
def __call__(self, sample):
# image... |
9838e7824448d74e92246e89be42d8a20d455cf1bd8130c90487102139c231dd | Python | 798 | 16 | # Copyright (c) OpenMMLab. All rights reserved.
from mmdet import digit_version
def test_version_check():
assert digit_version('1.0.5') > digit_version('1.0.5rc0')
assert digit_version('1.0.5') > digit_version('1.0.4rc0')
assert digit_version('1.0.5') > digit_version('1.0rc0')
assert digit_version('1.... |
6bbbdcc75c86602d013af52c6b9a4d13f7a857dff10b19a7e3a390b500ffe0ae | Python | 799 | 34 | """
This test file contains tests related to plotting functions.
"""
import unittest
import powerlaw
from numpy.testing import assert_allclose
import numpy as np
class TestPlotPDF(unittest.TestCase):
def test_custom_bins(self):
import numpy as np
import powerlaw
import matplotlib.pyplot ... |
4388e87c46f5a4b32d10592e6518d9ce1e0a0ddcbb41a39ee0bdc1962cd522fe | Python | 803 | 29 | #!/usr/bin/env python3
# Example client program that walks through all available stimuli.
from flystim.stim_server import launch_stim_server
from flystim.screen import Screen
from time import sleep
def main():
manager = launch_stim_server(Screen(fullscreen=False, server_number=0, id=0, vsync=True))
stims ... |
76d6cf1f402ed14419cf9de97afaa449a44569c20e35d97e53266fe4013b1231 | Python | 803 | 27 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class MaskRCNN(TwoStageDetector):
"""Implementation of `Mask R-CNN <https://arxiv.org/abs/1703.06870>`_"""
def __init__(self,
backbone,
... |
d71ca23f60028fabc8dc24464fb7d35ab04ee30ffe1bc34d733245202b2051ca | Python | 803 | 16 | # Copyright (c) OpenMMLab. All rights reserved.
from .class_names import (cityscapes_classes, coco_classes, dataset_aliases,
get_classes, imagenet_det_classes,
imagenet_vid_classes, voc_classes)
from .eval_hooks import DistEvalHook, EvalHook
from .mean_ap import avera... |
d4b1da0b801f5bec7556e49808bd030843490cec7b38af80a93d486427c5c757 | Python | 804 | 28 | """Custom losses for PyTorch models."""
import torch
from typeguard import typechecked
# to ignore imports for sphix-autoapidoc
__all__ = ['kl_div_to_std_normal']
@typechecked
def kl_div_to_std_normal(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
"""Compute element-wise KL(q(z) || N(0, 1)) where q(z)... |
7c06f6d9b3635f73af760ff6522c2425ade0854caf45449337368865cbfa1c55 | Python | 805 | 32 | import os
import pandas as pd
import numpy as np
def main():
root = './results/exp_ids_'
subdirs = ('cnn','weibull','mlp')
fold = ('train','test','valid')
dataset = 'ADNI'
exp = list(range(5))
for f in fold:
for ex in exp:
mods = []
fi_list = []
... |
8c802fc1f6e5c9f31f3ff795830ce0e83aac1a2f17d440314ef0d19ac97ae307 | Python | 805 | 27 | # Copyright (c) OpenMMLab. All rights reserved.
import numpy as np
import torch
from mmdet.models.utils import interpolate_as
def test_interpolate_as():
source = torch.rand((1, 5, 4, 4))
target = torch.rand((1, 1, 16, 16))
# Test 4D source and target
result = interpolate_as(source, target)
asser... |
d37bbdc0ad982912566ba802e2b4c5a7fd9120760b63d620461fb09bf839ac62 | Python | 807 | 36 | from contextlib import contextmanager
import threading
import traceback
from mpi4py import MPI
@contextmanager
def raise_MPI_error():
import logging
logging.debug("Debugging, Enter the MPI catch error")
try:
yield
except Exception as e:
logging.info(e)
logging.info('traceback... |
4a7e809e9c9ac49094bfb8574cf445f6588e3a1ab323051048e9290e320a35d6 | Python | 808 | 27 |
import metric.surface_distance.metrics as metrics
# import torch
import numpy as np
def hd95_and_sd_3D(output, target, misc):
if "spacing_mm" in misc:
spacing_mm = misc['spacing_mm']
else:
spacing_mm = [1, 1, 1]
pred = np.argmax(output, axis=1)
pred_bool = (pred > 0)
target_bool =... |
893b863a2a777f0daf2bae20d28e423f09b2dcd3cf8c633e4e9b7f506c0f5df3 | Python | 808 | 30 | read("d.nex")
read('sets.nex')
a = var.alignments[0]
a.setCharPartition('p1')
d = Data()
t = func.randomTree(taxNames=d.taxNames)
t.data = d
pNum = 0
t.newComp(partNum=pNum, free=1, spec='empirical')
t.newRMatrix(partNum=pNum, free=0, spec='wag')
t.setNGammaCat(partNum=pNum, nGammaCat=4)
t.newGdasrv(partNum=pNum, free... |
8ac096bd204f49701570acd2d8bfb1587f90cd58ed3f29e54e3bb67663d8aaf5 | Python | 808 | 26 | from pathlib import Path
def is_binary(file_name):
try:
with open(file_name, 'tr') as check_file:
check_file.read()
return False
except Exception:
return True
input_path = Path(snakemake.input[0])
with open(snakemake.output[0], "w") as fout:
for genome_path in inp... |
59443e1457b1b325a9dd32ca9371a54369002decf4ba4a8bfc9fc89b131caf45 | Python | 809 | 27 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class FasterRCNN(TwoStageDetector):
"""Implementation of `Faster R-CNN <https://arxiv.org/abs/1506.01497>`_"""
def __init__(self,
backbone,
... |
1d0c7e994866dba8667895798e6b1335857f71693c67a1d8c2458cb458528539 | Python | 810 | 34 | # Calculate likelihood with more than one data partition.
read("d.nex")
a = var.alignments[0]
a.setCharPartition('p1')
d = Data()
#d.dump()
read("t.nex")
t = var.trees[0]
t.data = d
pNum = 0
t.newComp(partNum=pNum, free=0, spec='empirical')
t.newRMatrix(partNum=pNum, free=1, spec='ones')
t.setNGammaCat(partNum=pNum, ... |
32e608b11d180a97a302f1dba9986d2e1941aadf4d7fe841516abd7e4431b895 | Python | 810 | 27 | import random
class ExpRandomFlip:
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/and vertical... |
59a48a97d0fa667f3a83fbf880cebcbed593194405123c0eb2480f7ebb77da4e | Python | 810 | 20 | # Copyright (c) OpenMMLab. All rights reserved.
from .associative_embedding import AssociativeEmbedding
from .cid import CID
from .gesture_recognizer import GestureRecognizer
from .interhand_3d import Interhand3D
from .mesh import ParametricMesh
from .multi_task import MultiTask
from .multiview_pose import (DetectAndRe... |
a96dd7c4e473d0e0d4afc26170f42d547d994421dc2bf38648a863ecd68551d4 | Python | 811 | 27 | import random
class ExpRandomFlip:
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/and vertical... |
eb2a5297c3a43fbe3dfd419a8b5e77ef91acf9d9158f29cba3dafa7912209107 | Python | 811 | 34 | import pandas as pd
from collections import defaultdict
def get_path(file):
steps = file.split("_")
path = ' '.join((steps[-2], steps[-1]))
return path.split('.csv')[0]
def stats(df):
tot = len(df)
TP = sum(df['TP'])/tot
TN = sum(df['TN'])/tot
FP, FN = 1-TP, 1-TN
precision = TP + TN
... |
47b7973926330a3cd10ea389813a3f425947696a19a13d66296b1c5ef4eb38ca | Python | 812 | 37 | # Copyright (C) 2024-2025 ETH Zurich, Niels Maeder and other DASH contributors.
"""Test `serenityff.charge.utils.exceptions`."""
import pytest
from serenityff.charge.utils.exceptions import (
DataDownloadError,
DataExtractionError,
DataIncompleteError,
ExtractionError,
NotInitializedError,
)
@p... |
fba2a288914bb6fc779b0a51f91d5df895e4f26e02989fbb6a15cae0fbb3c6ec | Python | 812 | 30 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class MaskScoringRCNN(TwoStageDetector):
"""Mask Scoring RCNN.
https://arxiv.org/abs/1903.00241
"""
def __init__(self,
backbone,
... |
1f75c11c4d0835fc311709c41517396c36bc07043a78c4f542b3acd8a8f4b805 | Python | 813 | 28 | import os, sys
import pandas as pd
# 328943 db_sets.csv
root = os.path.dirname(os.getcwd())
chembl = pd.read_csv(root + "/data/chembl/prep_chembl_v31.csv",header=None)
print("writing chembl to db_sets.csv")
print(chembl.shape)
chembl.to_csv(root + "/data/db_sets.csv", index=None, header=None)
print("writing vanweste... |
43ae47c10bfd3f85c6e231bb4c8ec878ae7b89195f038bf526adff20884cc3d1 | Python | 815 | 30 | import glob
import torch
import numpy as np
from torch.utils.data import Dataset
import torch
# Ignore warnings
import warnings
warnings.filterwarnings("ignore")
class PulsesDataset(Dataset):
def __init__(self, pul, ann):
fp = glob.glob(f"{pul}/*")
fa = glob.glob(f"{ann}/*")
... |
378abdd6ae747c3d6478f6f188ff9e726dc9a10e68eaf1816b7a53d7bfb01537 | Python | 817 | 29 | # We need to have a tree with its data. The tree needs a model, and
# it needs to have model parameters optimized.
# Read in the tree and give it a name
read("myTree.nex")
t = var.trees[0]
# Read in the data and give it a name
read("myData.nex")
d = Data()
# Attach the data and a model to the tree.
t.data = d
t.new... |
de2987d845ecfcaa3c99fb546dac2e1cf9927bed0ef28f3e2d22bcf4c01c44d0 | Python | 818 | 15 | import seaborn as sb
import pandas as pd
PROBE_PRETTY = { 'butterfly-iq' : 'Butterfly iQ', 'clarius-l7hd' : 'Clarius L7HD', 'sonoque-l5c' : 'Sonoque L5C', 'sonivate' : 'Sonivate SonicEye', 'interson-spl01' : 'Interson SPL01' }
PROBE_ORDERED = [ 'Butterfly iQ', 'Clarius L7HD', 'Sonoque L5C', 'Sonivate SonicEye', 'Inter... |
1d22aff10e077e85a363b1b0c6fe96eedff55ac1e423fda7fd28152aadb554d6 | Python | 822 | 29 | from ..builder import DETECTORS
from .single_stage_instance_seg import SingleStageInstanceSegmentor
@DETECTORS.register_module()
class SOLO(SingleStageInstanceSegmentor):
"""`SOLO: Segmenting Objects by Locations
<https://arxiv.org/abs/1912.04488>`_
"""
def __init__(self,
backbone,
... |
94b94f204aece083ddcf0bdc738f84b58e936e3f33b0f593e130113a2c3a0628 | Python | 822 | 22 | import logging
import datetime
import os
import sys
def set_logging(filename):
# base_folder ='../logs'
# timeStamp = '_{0:%b}-{0:%d}_{0:%H}-{0:%M}'.format(datetime.datetime.now())
# filename, file_extension = os.path.splitext(filename)
# filename = os.path.join(base_folder,filename+ timeStamp+'.log')... |
02493469dbd312275c23d1bb89b8fe5ea279f6e5ed24d2c7cb8d1c94df81d0fd | Python | 823 | 29 | """Custom losses for PyTorch models."""
import numpy as np
import torch
from typeguard import typechecked
# to ignore imports for sphix-autoapidoc
__all__ = ['kl_div_to_std_normal']
@typechecked
def kl_div_to_std_normal(mu: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
"""Compute element-wise KL(q(z) || ... |
d6a8b11c6c82dcf42304a3e2be5d1c56636d6ec6273e8aaccd3381568b024344 | Python | 826 | 33 | import collections
def is_disjoint(l1, l2) -> bool:
"""Determines if two lists share any common elements
:param l1: List 1
:param l2: List 2
:return: A bool determining if lists overlap at all
"""
return len(set(l1).intersection(set(l2))) == 0
def intersection(lst1, lst2):
"""Returns a... |
6d6d710b1195e8542a3def061e8e0428b9323136ae5cea0fd541fd640baa0b96 | Python | 827 | 27 | from typing import Any, Optional
import eagerpy as ep
from ..types import BoundsInput, Preprocessing
from .base import ModelWithPreprocessing
class JAXModel(ModelWithPreprocessing):
def __init__(
self,
model: Any,
bounds: BoundsInput,
preprocessing: Preprocessing = None,
... |
4059325ca48dde5c742791ce1c357ac8657b51865f6c48633e97425c99cc27b8 | Python | 829 | 27 | import os
import shutil
from csutil import util
if __name__ == "__main__":
gap_num = [37, 40, 80, 51, 39, 89, 45, 52, 56]
root_dir = 'E:/Zhu/ETreg/newdata/HUA3/'
data_dir = root_dir + '/TOM/stack/result/'
resultdir = root_dir + '/TOM/stack/Finaltemp/'
util.mkdir(resultdir)
imgid = 0
img... |
38db2ab8971964d535bdee975d417850c7d19cd619af378aa4c822a1fb4ba47e | Python | 831 | 30 | import collections
def is_disjoint(l1,l2) -> bool:
""" Determines if two lists share any common elements
:param l1: List 1
:param l2: List 2
:return: A bool determining if lists overlap at all
"""
return len(set(l1).intersection(set(l2))) == 0
def intersection(lst1, lst2):
""" Returns al... |
4d7c4c48d34bb6f79bf4b57479ca07b86979feffcd2d3d2a9393e302cec97d83 | Python | 833 | 32 | from setuptools import setup, find_packages
setup(
name='flystim',
version='2.0.0',
description='Visual stimulus generator for fruit fly experiments.',
long_description='Multi-monitor perspective-corrected visual stimulus generator for fruit fly experiments.',
url='https://github.com/ClandininLab/f... |
e1f4b306088705c02e91e9755a0f6f5d5dc2009d96c46b597514d081bb2fd9a1 | Python | 836 | 18 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 16 13:33:59 2021
@author: fhu14
Package containing code used for visualizing saved models and losses
"""
from .loss_visualizer import visualize_loss_tracker
from .spline_plot import plot_all_splines
from .skf_plot import plot_skf_values
from .repulsive_plot import plot_r... |
f16c7b0a878c0f97c3c185c044e050cb19e637b5a28fafe911dd697c240c52de | Python | 840 | 29 | # Copyright (c) OpenMMLab. All rights reserved.
import pytest
import torch
from mmdet.models.plugins import DropBlock
def test_dropblock():
feat = torch.rand(1, 1, 11, 11)
drop_prob = 1.0
dropblock = DropBlock(drop_prob, block_size=11, warmup_iters=0)
out_feat = dropblock(feat)
assert (out_feat =... |
92492efff487eb356ae5c751e7eb5488e7be00537ce8eec6bfacd963cfc62966 | Python | 841 | 28 | import utils
import sqldbutils as dutils
import random
template_concept_ann_query = """
select cn_doc_id, start_offset, end_offset, string_orig from
physical_phenotype_annotations where inst_uri='{concept}'
"""
def random_extract_mentions(cui, db_conf, query_template, sample_size=200):
rows = []
dutils.quer... |
60403ec7b01c01ea994f57ea025eabe4ecedb1c0cd43f34d50c5b7b7048a1cb8 | Python | 844 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from .approx_max_iou_assigner import ApproxMaxIoUAssigner
from .assign_result import AssignResult
from .atss_assigner import ATSSAssigner
from .base_assigner import BaseAssigner
from .center_region_assigner import CenterRegionAssigner
from .grid_assigner import GridAssign... |
053872a7047baf4ab556f83deef27fb70e60aea1a3dc02c7518a1c317deeaf42 | Python | 845 | 21 | class Homochrome:
def __init__(self, img_single_ch=0, label_single_ch=0):
"""
Just select one channel for labels. For instance, from (X, Y, Z, 3) to (X, Y, Z).
"""
self.img_single_ch = img_single_ch
self.label_single_ch = label_single_ch
def __call__(self, sample):
... |
21e6ad63540b9c69b4fb71ae58a78326ce51725ca7f0bd6d84ebfdb53d336fb7 | Python | 855 | 30 | import os
import cv2
import numpy as np
def AvergeImg(imgdir):
imgnamelist = os.listdir(imgdir)
imgsum = 0
for i in range(len(imgnamelist)):
img_ori = cv2.imread(imgdir + imgnamelist[i])
if img_ori.ndim == 3:
img_ori = cv2.cvtColor(img_ori, cv2.COLOR_RGB2GRAY)
imgsum = ... |
923c36d1667612739d7a08b8d20581c777fb94451be2c4490c01174a6de3d116 | Python | 857 | 32 | class MyMessage(object):
"""
message type definition
"""
# server to client
MSG_TYPE_S2C_INIT_CONFIG = 1
MSG_TYPE_S2C_SYNC_MODEL_TO_CLIENT = 2
# client to server
MSG_TYPE_C2S_SEND_MODEL_TO_SERVER = 3
MSG_TYPE_C2S_SEND_STATS_TO_SERVER = 4
MSG_ARG_KEY_TYPE = "msg_type"
MS... |
0926e85d9cfe09f867f7e26522fa2f7fc72c3ed58b23b2a49e5a59e49582d645 | Python | 858 | 26 | import torch
import torch.nn as nn
class WeibullLoss(nn.Module):
def __init__(self):
super(WeibullLoss, self).__init__()
def __call__(self, pred: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
"""Defines Weibull loss function from XXX et al.
Args:
pred (torch.Tensor... |
b6fefd07a5998ce0febb6d52da837637ea6cc4de030fcc864dba6de0bfc6f5b4 | Python | 858 | 24 | # -*- coding: utf-8 -*-
"""
Created on Fri Jul 7 11:21:10 2023
@author: Daniel
"""
from phase_to_rate.neural_coding import load_spikes, load_spikes_DMK, load_spikes_DMK_plus_lec, rate_n_phase
import shelve
path_new = r'C:\Users\Daniel\repos\phase-to-rate\data\noise_lec_identical\grid-seed_trajectory_poisson-seeds_d... |
5d10a38ddda7899d4530820d126a07d09815da756b600a679a097d9187e0e11f | Python | 859 | 17 |
def generate_shap_values(repeat, model_name, setting, Wrapper):
print('Evaluation metric: {}'.format(setting['metric']))
for exp_idx in range(repeat):
cnn = Wrapper(fil_num = setting['fil_num'],
drop_rate = setting['drop_rate'],
batch_size ... |
9cb8c710ab8561906b4f409f6ce61bf86f7bd64183b852c82e2034e275ecaba5 | Python | 859 | 39 | import os
import os.path as osp
import numpy as np
import numpy.random as npr
import torch
import cv2
import scipy.ndimage
from PIL import Image
import copy
import gc
import itertools
def singleton(class_):
instances = {}
def getinstance(*args, **kwargs):
if class_ not in instances:
instanc... |
cfc27e2f2743df94df842600909d72d5338972c40da40eca6ac4706f6cf78475 | Python | 859 | 34 |
import tables
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description="Writes names of samples "
"contained in HDF5 file to stdout")
parser.add_argument("h5file", help="HDF5 file containing /samples table")
... |
0b01bf076a02514212702c8fe0847ab93af6504db14fbd1588f46a06ddf6fe1a | Python | 864 | 32 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 26 14:50:02 2021
@author: Anandita
"""
'''This file contains radius and volume functions.'''
import numpy as np
from scipy.special import gamma
def volume_n_sphere(r,d):
'''Function returns volume of a d dimensional sphere with radius r'''
V=((np.... |
0e7b10ad62704e5746c1dce16dd481b9b6f91caa53edb9ddc9c32e22f24dd7e5 | Python | 866 | 36 | import os
import torch
class Exp_Basic(object):
def __init__(self, args):
self.args = args
self.device = self._acquire_device()
self.model = self._build_model().to(self.device)
def _build_model(self):
raise NotImplementedError
return None
def _acquire_device(self)... |
3d8204dc076da254e6d296f4c0a0ebcc47d69cbb093142980372ae15f853467d | Python | 870 | 40 | """LayerNorm for specific dimensions.
Adapted from ESPnet Transformer LayerNorm.
"""
import torch
class LayerNorm(torch.nn.LayerNorm):
"""Layer normalization module.
Args:
nout (int): Output dim size.
dim (int): Dimension to be normalized.
"""
def __init__(self, nout, dim=-1):
... |
407b700a381b6d49d8aa8942835966e79ac3722491fe0d2c3b301b7d947f5f4f | Python | 871 | 37 | import pandas as pd
import moses
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--input', default='sample.txt',
help='path to token file')
parser.add_argument('--valid',
help='path to validation file')
parser.add_argument('--output', ... |
14d8b027a421dd369a341b0ae00ca719550f69306e982de48b02c5eaddfb7f19 | Python | 872 | 40 | '''
Author: ----
Date: 2022-06-15 16:27:54
LastEditors: ----
LastEditTime: 2022-06-15 16:38:09
'''
import torch
import torchvision.transforms as transforms
import os
from tqdm import tqdm
transform = transforms.Compose(
[
transforms.ToPILImage(),
transforms.Resize(size=[48, 48]),
transforms... |
386c3141ed0e659996b280b12c4df7e6bcb923df32a795910307046b1e03cd8a | Python | 872 | 42 |
# make scripts more portable (no need to use numpy or scipy)
from studentC import student_table
def mean(x):
return sum(x)/len(x)
def var(x):
m1 = mean(x)
m2 = mean([y*y for y in x])
return m2 - m1*m1
def unbiased_var(x):
m = len(x)
return m/(m-1)*var(x)
def covar(x1, x2):
m1 = mean(x1... |
ee083936f66f8fdaa2b42a26b2d568fd1e732f5c1ebd3251a1a3408b2595dd55 | Python | 872 | 24 | # -*- coding: utf-8 -*-
"""
Created on Tue Jun 8 15:14:56 2021
@author: fhu14
"""
from .batch_test import run_batch_tests
from .data_invariants_test import run_invariant_tests
from .dftbplus_test import run_dftbplus_tests
from .dispersion_test import run_dispersion_tests
from .gamma_construction_test import run_gamm... |
f090b789d9c80a477c0baf748b0d181dd135263143c8129a8d7841e8c09536f8 | Python | 872 | 27 | # 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/>
import warnings as _warnings
from sbi.inference.trainers.nle.mnle import MNLE # noqa: F401
from sbi.inference.trainers.nle.nle_a import NLE_A # noqa: F... |
594f863c1ac522671510d25db94c8518d3e9a8644b31fd3412cc75c8dc32a99f | Python | 874 | 23 | import shutil
import os
file_List = ["train", "val"]
for file in file_List:
if os.path.exists('../VOC/images/%s' % file):
shutil.rmtree('../VOC/images/%s' % file)
os.makedirs('../VOC/images/%s' % file)
if os.path.exists('../VOC/labels/%s' % file):
shutil.rmtree('../VOC/labels/%s' %... |
a445ed00a141e89fca734fad511dafbeb10743c9df29f018c5c416b441a9a7c6 | Python | 875 | 41 | import numpy as np
def RSE(pred, true):
return np.sqrt(np.sum((true - pred) ** 2)) / np.sqrt(np.sum((true - true.mean()) ** 2))
def CORR(pred, true):
u = ((true - true.mean(0)) * (pred - pred.mean(0))).sum(0)
d = np.sqrt(((true - true.mean(0)) ** 2).sum(0) * ((pred - pred.mean(0)) ** 2).sum(0))
retu... |
a397262dbc6d4e96bee162451b980f42afa78178e92305b12302be686cc8bdc9 | Python | 876 | 38 | """Temporal Gaussian Mixture model implemented in PyTorch."""
import numpy as np
from sklearn.metrics import accuracy_score
import torch
from torch import nn
from daart.models.base import BaseModel
# to ignore imports for sphix-autoapidoc
__all__ = []
class TGM(BaseModel):
def __init__(self, hparams):
... |
bc5e4653e657782fd6d9883042ba4f7761566715b721d9ce0d98d003a5a50778 | Python | 876 | 17 | # Copyright (c) OpenMMLab. All rights reserved.
from .classfication_loss import BCELoss
from .heatmap_loss import AdaptiveWingLoss, FocalHeatmapLoss
from .mesh_loss import GANLoss, MeshLoss
from .mse_loss import JointsMSELoss, JointsOHKMMSELoss
from .multi_loss_factory import AELoss, HeatmapLoss, MultiLossFactory
from ... |
7020e93e702fc9f8bcec2fa95e9c9aa4aeab7dd66fd45dcc1529e91167533402 | Python | 877 | 24 | # 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.potentials.likelihood_based_potential import (
likelihood_estimator_based_potential,
mixed_likelihood_estimator_based_potential... |
e960c5d51ea93924af79dd1ee8402c038ab67ab6eec5d527f5bf6e21dc1698b2 | Python | 878 | 27 | from setuptools import setup
from setuptools import find_packages
with open("README.md", encoding='utf-8') as fh:
long_description = fh.read()
setup(
name='pystoi',
version='0.4.1',
description='Computes Short Term Objective Intelligibility measure',
author='Manuel Pariente',
author_email='par... |
6d9a0e68b6c76eea5704108099096cc12af47b5839f995b47a50348c6d3fe8e6 | Python | 883 | 22 | import os
import torch
from selbstaufsicht import datasets
from selbstaufsicht.models.self_supervised.msa.utils import get_downstream_transforms
from matplotlib import pyplot as plt
root = os.environ['DATA_PATH']
downstream_transform = get_downstream_transforms(subsample_depth=50, threshold=10., device='cpu')
ds = da... |
5c102f214a357765b664081c25c350d5c6ba54fd89087b227ab2f464ac150c71 | Python | 884 | 26 | import numpy as np
from numpy.testing import assert_allclose
from pystoi.stoi import N_FRAME
from pystoi.utils import _overlap_and_add
def test_OLA_vectorisation():
"""test the vectorised overlap_and_add comparing to the old one"""
def old_overlap_and_app(x_frames, hop):
num_frames, framelen = x_fra... |
63bb953fae11e4487f8a6b4ad5bb33978db81e31579f7c1889de39e8cc13a0fb | Python | 884 | 32 | # Copyright (c) OpenMMLab. All rights reserved.
from ..builder import DETECTORS
from .two_stage import TwoStageDetector
@DETECTORS.register_module()
class PointRend(TwoStageDetector):
"""PointRend: Image Segmentation as Rendering
This detector is the implementation of
`PointRend <https://arxiv.org/abs/19... |
8a5101b7db4996296886a1ee880bd750b54050cc883906710616f3cd6ca48651 | Python | 884 | 33 | # This script shows how to load an AceFF checkpoint
# and use it for force and energy predictions for a single molecule or a batch
import torch
# The AceFF models are available from HuggingFace under apache2.0 license
from huggingface_hub import hf_hub_download
model_file_path = hf_hub_download(
repo_id="Aceller... |
f04a67c1e05a5bab1b26a45cf8cef7eacc69e53dfe6a3a9680c25fe2a49f218c | Python | 890 | 26 | from model.builders.builders import build_full_network
import os
filename = os.path.basename(__file__)
from copy import copy, deepcopy
vocab_size = 20000
data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0}}
training_splits = [0,1,4,6,7,9... |
bc184759cfcf4e7829505dadceb915df86342a228343309c54314aaa2bc7d1a9 | Python | 892 | 26 | # from model.builders.builders import build_full_network
import os
filename = os.path.basename(__file__)
from copy import copy, deepcopy
vocab_size = 20000
data_base ={'id':'response','type': 'updated_label' , 'params': {'outcome': 'response', 'text': 'NARR+IMPRESS', 'training_split':0}}
training_splits = [0,1,4,6,7... |
3b5045b728606392d021f02e0636671c75170efa3dc96ca9695ab54dd8c9ecef | Python | 894 | 30 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 24 15:14:27 2020
@author: bariskuru
"""
import numpy as np
def ct_a_bin(arr, bin_start_end):
bin_start = bin_start_end[0]
bin_end = bin_start_end[1]
counts = np.empty((arr.shape[0], arr.shape[1]))
for index, value in np.ndenumerate... |
7aaebc1c15e98b6a42eb9a9a15317a8370b58a2696b98ed8fa531ffc89a1a7d6 | Python | 897 | 29 | import torch
import PIL.Image
import numpy as np
from utils.util import convert_to_uint8
class ToImage:
def __init__(self, training=True):
"""
Convert numpy array to PIL Image, and convert back.
"""
self.training = training
def __call__(self, sample):
image, mask, mis... |
51c1ee96a0cec8d3145cf604a0da2ea018366450fca298b28d9c1892533b65a2 | Python | 899 | 43 | var.warnReadNoFile = 0
var.verboseRead = 0
read('d.nex')
d = Data()
read('((A:0.4, B:0.4), C:0.4, D:0.4);')
t = var.trees[0]
t.data = d
print('==== Homogeneous model =========================')
t.newComp(free=1, spec='empirical')
t.newRMatrix(free=1, spec='ones')
t.setNGammaCat(nGammaCat=1)
t.setPInvar(free=0, val=0.... |
cd3e137f83cfacd27286a8ecd496b91448ded12235e4b3619cf744c228980951 | Python | 899 | 19 | # Copyright (c) OpenMMLab. All rights reserved.
from .backbones import * # noqa: F401,F403
from .builder import (BACKBONES, DETECTORS, HEADS, LOSSES, NECKS,
ROI_EXTRACTORS, SHARED_HEADS, build_backbone,
build_detector, build_head, build_loss, build_neck,
... |
e51431627e6d816a02bae0649c96aaa4c2e68218b6022fbddb893ae2eb18031e | Python | 902 | 27 | # from model.builders.builders import build_full_network
import os
filename = os.path.basename(__file__)
from copy import copy, deepcopy
vocab_size = 20000
data_base ={'id':'progression','type': 'updated_label' , 'params': {'outcome': 'progression', 'text': 'NARR+IMPRESS', 'training_split':0}}
training_splits = [0,1... |
3efa6bd5314d63c0a273fc24aaf7e99ffbadb4579ba460ae41125a652ffa7db7 | Python | 904 | 37 | import joblib
import seaborn as sns
import argparse
import matplotlib.pyplot as plt
parser = argparse.ArgumentParser()
parser.add_argument("--study_loc", type=str)
args = parser.parse_args()
data = joblib.load(args.study_loc)
outloc = args.study_loc.replace(".pkl", ".png")
df = data.trials_dataframe()
df.dropna(inpl... |
7af09dcaf2df086762f84be20e6267c0815c1cb5eb2488ca1c1fc2ee3735271d | Python | 905 | 30 | from pathlib import Path
import subprocess
import sys
import PySimpleGUI as sg
def statistics_menu():
"""Show the statistics launcher and open the selected analysis tool."""
sg.theme("DarkTeal2")
layout = [
[sg.T("")],
[sg.Text("Choose a statistical analysis tool.")],
[sg.T("")],
... |
12538e4bbc1300d36c7da1f622412d8204ae95e2210eafac08b845151b54f5ed | Python | 908 | 29 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
from .version import __version__, short_version
def digit_version(version_str):
digit_version = []
for x in version_str.split('.'):
if x.isdigit():
digit_version.append(int(x))
elif x.find('rc') != -1:
patch_v... |
f8251dd9e42ffb8520d9aacf9be3b4f693dcc1bbfc8579a7d4981318672a57df | Python | 908 | 29 | # Copyright (c) OpenMMLab. All rights reserved.
import mmcv
from .version import __version__, short_version
def digit_version(version_str):
digit_version = []
for x in version_str.split('.'):
if x.isdigit():
digit_version.append(int(x))
elif x.find('rc') != -1:
patch_v... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.