sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
c48fb829e4a9061a85ae52a29e90b34759dce085ee97eb1b677187a40ebf08d3 | Python | 1,846 | 49 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 28 15:52:34 2021
@author: Jia-lan Chen
modified by Yaolong Zhang for a better efficiency
"""
import torch
import ase.io.vasp
from ase import Atoms, units
import getneigh as getneigh
from ase.calculators.fireann import FIREANN
from ase.io import extxyz
from ase.io.traje... |
77e9511f2590452b8d8dfc2b1ed4e61a7b4f2924352b437ed4b2c15f524b4de6 | Python | 1,847 | 59 | import os
from dotenv import load_dotenv
from omop_learn.backends.bigquery import BigQueryBackend
from omop_learn.data.cohort import Cohort
from omop_learn.data.feature import Feature
from omop_learn.utils.config import Config
from omop_learn.omop import OMOPDataset
load_dotenv("bigquery.env")
config = Config({
... |
4e5ec04d8db25283a0db88f6e5da278b1c8611cb8aa23f43b5a2a338a1513662 | Python | 1,848 | 37 | import argparse
from pathlib import Path
from src import datasets, readout, train, util
def main(args):
readout_model = readout.Readout(args.n_pca, util.get_dataset_number_of_neurons(args.dataset))
train_dataset = datasets.PCDataset(args.root, args.model, args.dataset, "train", args.ntau, args.nlat, args.nsp... |
8cfc8fd68aaf17bb1b66477982eaf22f7450960d246545581e6af0ddd8083ca4 | Python | 1,848 | 59 | """Regression tests for train-mode out retention."""
from __future__ import annotations
import pytest
import torch
import torchlens as tl
from torchlens.options import CaptureOptions
from .conftest import TwoLayerMlp
def _assert_backward_populates_grad(model: torch.nn.Module, loss: torch.Tensor) -> None:
"""A... |
caa0a58ea4daf10acb1c1a8940cd35722c18836ca5def6823af528135051fd3f | Python | 1,848 | 47 | from typing import Optional, Union
import numpy as np
from anndata import AnnData
from numpy.random.mtrand import RandomState
from scipy.sparse import issparse
import scanpy
def run_diffmap(adata: AnnData, n_comps: int = 15, copy: bool = False):
"""\
Diffusion Maps [Coifman05]_ [Haghverdi15]_ [Wolf18]_.
D... |
4bd5793bb0f1da1d3c32074c00e254ae5b26467a58eeaacdf4eb6dd11087d78a | Python | 1,849 | 57 |
import unittest
import os
from bleualign.align import Aligner
import io
class TestS2tAndT2s(unittest.TestCase):
def setUp(self):
pass
def test_1989googlefr(self):
current_path = os.path.dirname(os.path.abspath(__file__))
eval1989de = os.path.join(current_path, '..', 'eval', 'eval1989.de')
eval1989fr = os.pa... |
ec4de2c72efe2e2246b3b3bcdf6a03f5c743f45492ebc3642b32e8902f9facdf | Python | 1,849 | 48 | import re
import pytest
import torch
from flash_attn.models.vit import vit_base_patch16_224 as flash_vit_base_patch16_224
from timm.models.vision_transformer import vit_base_patch16_224
@pytest.mark.parametrize("fused_mlp", [False, True])
# @pytest.mark.parametrize('fused_mlp', [False])
@pytest.mark.parametrize("opt... |
d3571c6ba990b22d9452ff09d0778e06445a091ef92873dc9543dc04c26af27f | Python | 1,850 | 68 | # ruff: noqa: F401
from _plotly_utils.importers import relative_import
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ._kaleido import (
to_image,
write_image,
write_images,
full_figure_for_development,
)
from . import json
from ._json import to_json, from_json... |
6981aa7f86e2592590af105fc9db2c252d1e7047365ab0b38724e03f9e8f2cdb | Python | 1,851 | 49 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
8ee6e96fcc28aa75835425277014263f5b19f0341524670dae7c0afd5fb84445 | Python | 1,852 | 64 | """
This script places .abfinfo files next to .abf files in the data folder.
Abfinfo dumps don't contain the filename so GUIDs are used to match them up.
"""
import glob
import os
import sys
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/")
PATH_SRC = o... |
80ba9300ebfbfe93e6b3189cb7ece19f89b0bd1648cb68794599687bc74081b8 | Python | 1,853 | 59 | """
active_channels.py
Modules to filter for active channels.
"""
###################################################################################################
###################################################################################################
def filter_activechannels(spiketimes, timeinterva... |
cab8ea6e41796276fac47b948bb29b1bae1f3f982b46d49ddf37d13c30cdedd3 | Python | 1,853 | 54 | import torch
def create_dataset(dataset, lookback):
batch = len(dataset) - lookback
X=torch.zeros((batch,lookback,dataset.shape[1]-1))
y=torch.zeros((batch,lookback,1))
for i in range(len(dataset)-lookback):
feature = dataset[i:i+lookback,:-1]
target = ... |
4488d2ed2754d5eb6fc3855d825d3b2e7cb5e49b78223ea59a17eecded9176f3 | Python | 1,854 | 74 | #!/usr/bin/env python
__author__ = "Bjoern Gruening"
__version__ = "0.1"
__date__ = "2012"
__license__ = "GLP3+"
import argparse
import ftplib
import os
import shutil
import subprocess
import tempfile
from multiprocessing import Pool
def main(output, processors=4):
output_handle = open(output, "w+")
td = t... |
449cd2d5685b9c9fa0bfbeab3d4f7d8c961f7c7f5980b721d4582bc516b216a7 | Python | 1,854 | 73 | import os
import re
from pathlib import Path
import setuptools
META_PATH = Path('caper', '__init__.py')
HERE = os.path.abspath(os.path.dirname(__file__))
def read(*parts):
"""
Build an absolute path from *parts* and and return the contents of the
resulting file. Assume UTF-8 encoding.
"""
with ... |
60e29a663b50c254169fda0cf09fdfb05e306c6e7d17d88434e85cea20cebbfb | Python | 1,854 | 57 | import random
import cv2
import os
import shutil
import numpy as np
os.chdir('..\\DATA_extend')
original_dir = os.getcwd()
folder = next(os.walk('.'))[1]
for f in folder:
os.chdir(original_dir + '\\' + f)
folders = []
filenames = []
# get all directories within patient folder
dirs = [x[0] for... |
7b805146817c208c454fef4a0129b1c4bc6b6109a7ac5e42473b2143d557d013 | Python | 1,854 | 54 | import os
import torch
from tlib import ttorch
# ------------------------------------------------------------------------------------------------------------
# Please check the following configurations:
# working_dir:
# Logging files, model checkpoints and figures will be saved here and will be loaded from here.
#... |
50b895918c6b1f81147e32abe7f75af9b9ded2197be0d79d075d2c6d11b2df7c | Python | 1,855 | 48 | from __future__ import annotations
from enum import Enum, auto
from pytest_celery import CeleryTestWorker
from celery.canvas import Signature
from celery.result import AsyncResult
from t.smoke.tasks import (self_termination_delay_timeout, self_termination_exhaust_memory, self_termination_sigkill,
... |
57f00477e0fbefdc45890eb810de2cfdb37d2ff924f438ad81828f57cccd943c | Python | 1,855 | 56 | # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
__version__ = "8.4.196"
import importlib
import os
import sys
from typing import TYPE_CHECKING
# Set ENV variables (place before imports)
if not os.environ.get("OMP_NUM_THREADS"):
os.environ["OMP_NUM_THREADS"] = "1" # default for reduced CPU ut... |
8470290fa72952ccd03c84741e41d9bee18a34a148779cbfde743990bed5d38b | Python | 1,855 | 47 | import unittest
from carbontracker import exceptions
class TestExceptions(unittest.TestCase):
def test_no_components_available_error(self):
with self.assertRaises(exceptions.NoComponentsAvailableError):
raise exceptions.NoComponentsAvailableError
def test_unit_error(self):
with sel... |
105af005ab43edfd80b00065e8968b00ded81afdeceeb4a5e8e63fa70692630f | Python | 1,856 | 50 | #FROM VQVAE
import functools
import random
import torch.nn as nn
class NLayerDiscriminator(nn.Module):
"""Defines a PatchGAN discriminator"""
def __init__(self, input_nc, n_class, ndf=64, n_layers=3, norm_layer=nn.InstanceNorm2d):
"""Construct a PatchGAN discriminator
Parameters:
... |
5283689afeb08897e0c0038093a52dcc546951e7f52bbe70580b01935276d874 | Python | 1,856 | 63 | import pandas as pd
import numpy as np
import argparse
from tqdm import tqdm
import torch
from torchmetrics import MeanSquaredError, R2Score, SpearmanCorrCoef, PearsonCorrCoef
from thermompnn_benchmarking import get_metrics
def get_metrics_cpu():
return {
"r2": R2Score(),
"mse": MeanSquaredError(... |
8d58e65e6aefd33295e05ec5f1d9c9acc2906e0d4827780e7bac343f72afd899 | Python | 1,856 | 55 | from types import SimpleNamespace
from unittest import mock
from uuid import UUID
from carbonserver.api.infra.repositories.repository_organizations import (
SqlAlchemyRepository,
)
from carbonserver.api.schemas import OrganizationWithRole
ORG_ID_1 = UUID("f52fe339-164d-4c2b-a8c0-f562dfce066d")
ORG_ID_2 = UUID("e5... |
f28d2ec00cf55a281c304111f211c0524de1379cc6af7d54a86df874907b1857 | Python | 1,856 | 56 | import logging
from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version("pyrosm")
except PackageNotFoundError: # running from a source tree without an install
__version__ = "unknown"
# pyrosm reports progress through the "pyrosm" logger; the application decides what is shown.
l... |
0874f842ef7ca745b804ec16dbef5b7e1c6faad14542647bddd239304289ef04 | Python | 1,857 | 65 | """Rerun a generation-style trace with a post-hoc intervention.
What this demonstrates
----------------------
Capture a tiny recurrent loop that emits several steps, then attach a
post-hoc intervention and rerun the model. Real language-model generation uses
the same intervention idea, but this example avoids external... |
733a5ba72874154cc923d672be51e50908f47a08725c206da2d2d60ae5f444eb | Python | 1,857 | 48 | """
Script to compute latency and fps of a model
"""
import os
import argparse
import time
import torch
from gluoncv.torch.model_zoo import get_model
from gluoncv.torch.engine.config import get_cfg_defaults
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Compute FLOPs of a model.')
p... |
d24ca06d2b0d031983c70b8748e2d551ccbca0859bf6b562cf292a9656c31cf0 | Python | 1,857 | 61 | import os
import tqdm.auto as tqdm
from modular_splicing.example_figure.find_example_exon import find_both_exons
from modular_splicing.example_figure.renderer import main_example_figure
from modular_splicing.example_figure.replicates import attach_alternate
def produce_images(species, lssi, *, fms, ams, range_multi... |
f10db735fbd79037179e0b05a2b8f8461c1145f135fd79b90feb5c963b12c233 | Python | 1,857 | 70 | """
Tests to make sure preprocess functions works
"""
import eugene as eu
import pytest
from pathlib import Path
from eugene.dataload import SeqData
HERE = Path(__file__).parent
@pytest.fixture
def sdata():
sdata = eu.datasets.random1000()
return sdata
def test_sanitize_seqs_sdata(sdata):
sdata_copy =... |
0cc05650a8213cc2d8efea30b7e3e7bc5a3a3151d4ba02b7661acdcce712c04c | Python | 1,858 | 61 | import sys
from robustness import datasets
from robustness.attacker import AttackerModel
from robustness.model_utils import make_and_restore_model
from model_analysis_folders.all_model_info import IMAGENET_PATH
def build_net(ds_kwargs={}, return_metamer_layers=False):
# We need to build the dataset so that the num... |
784f007bf6d8295a59ff87c2d02c389083a1412db480b1f3870e043fcedfdfc6 | Python | 1,858 | 68 | """
see if a simpler stimulus class can be designed
"""
import os
import sys
PATH_HERE = os.path.abspath(os.path.dirname(__file__))
PATH_DATA = os.path.abspath(PATH_HERE+"../../../data/abfs/")
PATH_SRC = os.path.abspath(PATH_HERE+"../../../src/")
sys.path.insert(0, PATH_SRC)
import pyabf
import glob
import numpy as np... |
92991475a520b1722261fb6dffc98462aa3610f98b5ca304823be92592c7976e | Python | 1,859 | 66 | import torch
from torch import Tensor
from torch.nn import Module, PairwiseDistance, functional
class KoLeoLoss(Module):
"""KoLeo loss based on [0].
KoLeo loss is a regularizer that encourages a uniform span of the features in a
batch by penalizing the distance between the features and their nearest
... |
ee7c30afac8cadf3bb6cd01324dd0e0bdd0bbe9f6c326d9c8e653e7709710b00 | Python | 1,860 | 59 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: sphinx
# format_version: '1.1'
# jupytext_version: 1.10.2
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
"""
.. _exa-utsstat:
UTS-statistics (``UTSStat``)
==... |
86c56e071cd036ea4d7168b0426b2c9e08a1ab8f098651b51b70cb6bbd40d534 | Python | 1,861 | 73 | from mongoengine import connect
from config import Config
from .annotations import *
from .categories import *
from .datasets import *
from .lisence import *
from .exports import *
from .images import *
from .events import *
from .users import *
from .tasks import *
import json
def connect_mongo(name, host=None):
... |
05f11a7bde2e595ba9edcea70f5debe8c8e8d8f894d2a09ccb63fc338bb2e2b8 | Python | 1,862 | 45 | from torchvision.models import resnet50
from torchcam.methods import GradCAM
import torch
from torchvision.io.image import read_image
from torchvision.transforms.functional import normalize, resize, to_pil_image
import numpy as np
from PIL import Image
def overlay_mask(img: Image.Image, mask: Image.Image):
if not... |
298e50de63d43ff19386cf3d2a09f43064a9b77cf98959a139daa62fe5b463e1 | Python | 1,862 | 46 | """Prepare Cityscapes dataset"""
import os
import shutil
import argparse
import zipfile
from gluoncv.utils import download, makedirs
from mxnet.gluon.utils import check_sha1
_TARGET_DIR = os.path.expanduser('~/.mxnet/datasets/citys')
def parse_args():
parser = argparse.ArgumentParser(
description='Initial... |
8dbba2021efca3d6068e4d46a7679f3a750e00853816f45d1790cdfddcc104a9 | Python | 1,862 | 55 | from setuptools import setup, find_packages
with open("README.md", "r", encoding="utf-8") as readme_file:
readme = readme_file.read()
requirements = [
"black<=21.12b0",
"datasets>=1.7.0",
"flake8",
"isort==5.8.0",
"pytest",
"pyyaml>=5",
"streamlit==0.82",
"jinja2",
"plotly",
... |
c137b4cca19c53d61830a5aa6c8685bee567aaf1a1e78686497f781e6bb00e53 | Python | 1,862 | 65 | import torch.nn as nn
from modular_splicing.utils.construct import construct
from .activations import activation_types
class ResidualUnit(nn.Module):
"""
Residual unit proposed in "Identity mappings in Deep Residual Networks"
by He et al.
Shapes: (N, C, L) -> (N, C, L)
True width is 2 * w - 1, ... |
6c5b06c8952a764cca043c426214439ed5a3a0bdf3feccf0b9750338248852e8 | Python | 1,863 | 47 | import open3d as o3d
import numpy as np
from copy import deepcopy
from math import sin, cos
from helpers.configurations import DEPTH_SCALING, OR_4D_DATA_ROOT_PATH
def vec_ang(v1, v2):
""" Returns the angle in radians between vectors 'v1' and 'v2' """
cosang = np.dot(v1, v2)
sinang = np.linalg.norm(np.c... |
4d774c445c224fcb0e765ebe4be7e5419e518ebc758704f316aaa247ff0f1d34 | Python | 1,864 | 65 | #!/usr/bin/env python3
# coding: utf-8
"""
@author: Simon Delarue <sdelarue@enst.fr>
"""
from typing import Union
import numpy as np
from scipy import sparse
from sknetwork.utils import get_degrees
class UniformNeighborSampler:
"""Neighbor node sampler.
Uniformly sample nodes over neighborhood.
Parame... |
5bfdd9df90ca64aa91f041ab0a4baf069d6f6ed83203eb4fe3244bc843e04f95 | Python | 1,864 | 54 | from collections.abc import Callable
from dataclasses import dataclass
import numpy as np
import torch
from torch import nn
from neurogym.wrappers.components.modules.base import LayerProbeBase
@dataclass
class LSTMLayerProbe(LayerProbeBase):
layer: nn.LSTM
@staticmethod
def layer_types() -> set[type[nn... |
9829f02daa6767478d9261199d43346ada4fd2d5647afa0bff59e8b84db55df0 | Python | 1,864 | 54 | import warnings
from .base import Renderer
from ..exporter import Exporter
class VincentRenderer(Renderer):
def open_figure(self, fig, props):
self.chart = None
self.figwidth = int(props["figwidth"] * props["dpi"])
self.figheight = int(props["figheight"] * props["dpi"])
def draw_line(... |
ae669c0616b0aafee19adcaddc2230d2979ce2d2a9bd918e1536bffdd2e9c3ab | Python | 1,864 | 50 | from __future__ import annotations
import copy
import logging
from bream4.device_interfaces.devices.base_device import BaseDeviceInterface
from bream4.toolkit.procedure_components.voltage_operations import maintain_relative_unblock_voltage
DEFAULTS = {
"voltage_min": -500,
"voltage_max": -150,
"unblock_v... |
bb130dd26b63d8b05b03f30bec61878401d9f44572470b32ba5d8ece7fac3ab2 | Python | 1,864 | 47 | import json
from pathlib import Path
from helpers.scene_graph_vis_helpers import visualize_scene_graph
from tqdm import tqdm
def main():
visualize_closeto = False
USE_IMAGES = True
print(f'Visualize CloseTo {visualize_closeto}')
split_name = 'val'
scene_graphs_path = Path(f'scan_relations_training... |
1171efcd14b40d77bf6a2c07c8ff79b0bc5a609e1775698f5f1e39ef91745525 | Python | 1,865 | 65 | """
File: force_normaliser.py
Created: 2021/03/02
Last Changed: 2021/09/23
Author: M.Vochteloo
Copyright (C) 2020 University Medical Center Groningen.
A copy of the BSD 3-Clause "New" or "Revised" License can be found in the
LICENSE file in the root directory of this source tree.
"""
# Standard im... |
60103ae772f86647b27b4d5e78ab0f6abe395b0fe4b48b4f6fb890338a5da1c1 | Python | 1,865 | 59 | import argparse
import pandas as pd
import numpy as np
import os, sys, shutil, importlib, glob
from tqdm.notebook import tqdm
import celloracle as co
from celloracle import motif_analysis as ma
from genomepy import Genome
import scanpy as sc
import pyprojroot
packdir = f"{pyprojroot.here()}/package/python"
sys.path.ins... |
57c933f2e3cbb84f2009d2eb57d59d314ad315baad21965cde208afbf3f990e6 | Python | 1,866 | 66 | from typing import Dict, List, Tuple, Union
from PIL.Image import Image
from torch import Tensor
from lightly.transforms.torchvision_v2_compatibility import torchvision_transforms as T
from lightly.transforms.utils import IMAGENET_NORMALIZE
class MAETransform:
"""Implements the view augmentation for MAE [0].
... |
62947c15b41d2561942723f5dffab359e69bc805db867cfbf330751734d56481 | Python | 1,866 | 49 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
814cb6f75abd8b0422051759fa5428ed6e6759f4c42068e1268ece743b9477f8 | Python | 1,867 | 50 | """Tests for spiketools.plts.trials"""
import numpy as np
from spiketools.tests.tutils import plot_test
from spiketools.tests.tsettings import TEST_PLOTS_PATH
from spiketools.plts.trials import *
###################################################################################################
####################... |
29d4c28584184b5ade0054b2bf03129fb07a3a11aa47cc070586192bf083e9a8 | Python | 1,868 | 68 | #######################################################################################################
##################### Preprocessing for multi-task models #############################################
#######################################################################################################
impo... |
c8f49d26b11bb687fb63bf4c6a66808192f70d4c07d9ac0bd14714935bcc0637 | Python | 1,868 | 67 | """Smoke tests for fastlog dry-run live visualization helpers."""
from __future__ import annotations
import torch
from torch import nn
import torchlens as tl
from torchlens.fastlog.types import RecordContext
def _mlp() -> nn.Module:
"""Return a small two-layer MLP."""
return nn.Sequential(nn.Linear(4, 5),... |
f637136b6590e77d935c1e5cb9ea55be0ec26d0a0fd1c9fd6bfbff97c5119adc | Python | 1,868 | 61 | # -*- coding: utf-8 -*-
# @Author : Yue Liu
# @Email : yueliu19990731@163.com
# @Time : 2022/9/21 0:56
import numpy as np
from munkres import Munkres
from sklearn.metrics import accuracy_score, f1_score
from sklearn.metrics import adjusted_rand_score as ari_score
from sklearn.metrics.cluster import normalized_mut... |
50b15dd4d13ec26addc4b01aa03cf7177e706e3332a671f1d0a80b27a467972f | Python | 1,870 | 70 | import inspect
from ..geometry._check import ( # noqa: F401
check_function,
check_init,
check_like,
check_matrix_pair,
check_weights,
)
def check_metric(metric, expected_keys=["mean", "distance"]):
"""Check metric argument.
Parameters
----------
metric : string | dict
M... |
d6a9fef3cff1c9b438cb18e25bc14cc0c3c194dc00ee6b6edb2cc57f88055523 | Python | 1,870 | 75 | import unittest
from modular_splicing.data_pipeline.chunk_iteration_order import (
dataset_indices_generator,
)
class TestChunkIterationOrder(unittest.TestCase):
def test_even_chunks(self):
self.assertEqual(
list(dataset_indices_generator(9, 3)),
[
(0, [0, 1, 2... |
fa10d831087fd031f93b7774aa2686b4a97778774b230fede538769a1cdb28b7 | Python | 1,870 | 46 | import sqlite3
from .db import DB
class CaseDetailsTable(DB):
def __init__(self):
self.table_name = 'PB_cases'
self.table_desc = 'Punjab samples, cases, and vaccination information. Table page 1'
self.cols = self.getcolumns()
def getcolumns(self):
cols = {
'date':... |
7ea360d99aa114f6e4254d0a1689b42075194e4bb239bae75e69dcc7fdc78c5c | Python | 1,871 | 51 | from __future__ import division
import unittest
import numpy as np
from wyrm.types import Data
from wyrm.processing import calculate_classwise_average
class TestCalculateClasswiseAverage(unittest.TestCase):
def setUp(self):
ones = np.ones((10, 2))
twoes = ones * 2
# 7 epochs
da... |
025085a4eeb472074a5859a232969d7760e714a217e621c5d3327ba0f8011aa0 | Python | 1,872 | 42 | import json
def projection_from_json(fn):
with open(fn, "r") as fid:
cfg = json.load(fid)
assert "class" in cfg, "Must specify Cache class!"
assert "args" in cfg, "Must parameterize Cache class!"
cache_cls = cfg["class"]
cache_args = cfg["args"]
if cache_cls == "CachedProjections"... |
7582491a9ba78a2af4186d78ff5ca0ade0e114791897759fd7ee3f85cf9ed563 | Python | 1,872 | 58 |
import numpy as np
## some multiclass methods that I never got to get working
def obj_multiclass(x0, X, y, alpha, n_class):
n_samples, n_features = X.shape
W = x0.reshape((n_features + 1, n_class-1))
Wk = - W.sum(1)[:, None]
W = np.concatenate((W, Wk), axis=1)
X = np.concatenate((X, np.ones((n_s... |
71635255b486382422b0a308246bc39da55bdb2d6784478598fe73ed53b99f7f | Python | 1,873 | 44 | import requests
import os
import zipfile
from tqdm import tqdm
def download_and_install(url):
# borrowed from https://stackoverflow.com/questions/16694907/download-large-file-in-python-with-requests
local_filename = os.path.join(os.environ['OV_DATA_BASE'], 'temp.zip')
# NOTE the stream=True parameter below... |
79713fc76a450969998dcc19d9179e2f3012963ca41dc0916aaf2bf584f9c43a | Python | 1,873 | 45 | def break_loop(swc_matrix):
"""
removes any loops in the SWC tree
"""
updated_swc_matrix = swc_matrix
tree_traversed = []
for row_index, row_data in swc_matrix.iterrows():
p_id = row_data.ParentIndex
if p_id == -1:
tree_traversed.append(row_index)
continue... |
07307796e6d0ca500dca9f78ce07b8a0e0bb28d41a1dc879dcde0065fdecd596 | Python | 1,874 | 47 | #!/usr/bin/env python3
'''
This script will generate the new types file with the lines from generate_counterexample_typeslines.py
Assumptions
i) The data structure is <ROOT>/<POCKET>/<FILES>
ii) The name of the file containing the types lines to add is <NAME> for each pocket in the types file.
iii) the input types ... |
9b2571823ff8eee58cbfa4cf3dc0f0ccd7ff70eeaa9bf8c38c1ba91fb87d481a | Python | 1,874 | 54 | import numpy as np
import torch
from sklearn.metrics.pairwise import cosine_similarity
def construct_gene_graph(gex_features, corr_method='cosine', corr_threshold=0.9):
"""Generate nodes, edges and edge weights for dataset.
Parameters
----------
gex_features: anndata.AnnData
Gene data, contai... |
7a4fb09e52f2f4ee6e7d0b7bb86bfe08467b756e9b81304bef988483d242ff05 | Python | 1,875 | 69 | """IO functions for MERFISH technology.
"""
import numpy as np
import pandas as pd
from anndata import AnnData
from scipy.sparse import csr_matrix
from ..configuration import SKM
from ..logging import logger_manager as lm
def read_merfish_as_anndata(path: str) -> AnnData:
"""Read MERFISH matrix as AnnData.
... |
89195699091bcc616549a8c0cad595e9c80382845aa48c4b3e153ee046958085 | Python | 1,875 | 59 | #!/usr/bin/env python3
"""
This script can be symlinked to samtools, bcftools, bgzip, or tabix.
When invoked under one of those names, it will emulate that tool's
behaviour by using pysam's facilities.
"""
import argparse
import gzip
import os
import sys
import tempfile
import pysam
command = os.path.basename(sys.ar... |
5afef6e355df9dbc22a1a31b21cccb3180563bdcdf61ab98ff946f442a68ef42 | Python | 1,876 | 54 | # Copyright 2019 Novartis Institutes for BioMedical Research Inc. Licensed
# under the Apache License, Version 2.0 (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless
# required by applicable law... |
7b34c747d6710cef42291f2e17abcd83bd45c1c3ae858c8c18c128dbe1b9d793 | Python | 1,876 | 52 | from __future__ import absolute_import, print_function
# checks
try:
import tensorflow
del tensorflow
except ModuleNotFoundError as e:
from six import raise_from
raise_from(RuntimeError('Please install TensorFlow: https://www.tensorflow.org/install/'), e)
import tensorflow, sys
from ..utils.tf import... |
ab2708e11dafb2767aadbc0e21e6b7ef94bcfcce7c18b90d9d5cc09885f9f8cf | Python | 1,876 | 55 | """
Script to preprocess MOT17 data into our format for easier evaluation.
Please first download MOT17 data from official website
https://motchallenge.net/data/MOT17/
"""
import os
import argparse
import json
import numpy as np
parser = argparse.ArgumentParser()
parser.add_argument('--mot-folder', type=str, required=... |
41da4a5a82d504d683327bec97f599af17c7ff4c40149419b34f714f666877ef | Python | 1,878 | 72 | from collections import OrderedDict
import numpy as np
def to_map(*args):
"""Produces ordered dict from given inputs."""
var_list = args[0] if isinstance(args[0], list) else args
od = OrderedDict()
for i, v in enumerate(var_list):
od[v] = i
return od
def get_idx(t, start_end):
"""A... |
908aac184f50bceba68512fc80c0d9f3f42f7d2f6327f2c6fc821ac97e202861 | Python | 1,878 | 54 | from ourmodel.loss import adv_loss, CORAL, kl_js, mmd, mutual_info, cosine, pairwise_dist
class TransferLoss(object):
def __init__(self, loss_type='cosine', input_dim=512):
"""
Supported loss_type: mmd(mmd_lin), mmd_rbf, coral, cosine, kl, js, mine, adv
"""
self.loss_type = loss_ty... |
d401240ee2a437ae0bd2613965222448af974d8a24e7731ffc68b5596cc87a8e | Python | 1,878 | 59 | import pandas as pd
import pymc as pm
import arviz as az
import matplotlib.pyplot as plt
def main():
data = pd.read_csv("data/veteran.csv")
X = data[['age', 'celltype', 'trt']]
X['celltype_1'] = data['celltype'] == 1
X['celltype_2'] = data['celltype'] == 2
X['celltype_3'] = data['celltype'] == 3
... |
c66e1f419619d4b9e1a1f27a37b816378dbb1adc26ffb3db27705f4270a1b9c0 | Python | 1,879 | 61 | import argparse
import pickle
import os
import glob
import subprocess
import numpy as np
from deep_audio_features.bin import basic_test as btest
from deep_audio_utils import get_wav_duration
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument(
'-i', '--input_wav', required=True,... |
4ee87a74f04e8d6636a0f33ba0786b5db77d8f21abdcc870bab6cd13547aec54 | Python | 1,880 | 74 | """Grep audit for deferred intervention features."""
from __future__ import annotations
import subprocess
from pathlib import Path
def _repo_root() -> Path:
"""Return the repository root.
Returns
-------
Path
Absolute repository root path.
"""
return Path(__file__).resolve().parent... |
7cdc450ab659de585a6fa49a66f57389b68713a1d90626387068ce852c906dc9 | Python | 1,880 | 59 | from Configurations import config as cfg
from nn_model.fcsnet import tf_model_fcsnet
from tensorflow.keras.callbacks import Callback
import os
# for saving only the one/last best model.
class modeltracker():
def __init__(self, fntemplate, onlylast=False):
self.epoch = 0
self.loss = float("inf")
... |
16eb3615351868ba16d7af98fabeb90abaaa0d8671affa24b7e77a1941398415 | Python | 1,881 | 49 | """
Repeated measures ANOVA
=======================
Based on [1]_.
"""
# Author: Christian Brodbeck <christianbrodbeck@nyu.edu>
from eelbrain import *
y = Var([7, 3, 6, 6, 5, 8, 6, 7,
7, 11, 9, 11, 10, 10, 11, 11,
8, 14, 10, 11, 12, 10, 11, 12],
name='y')
a = Factor('abc', repeat=8,... |
36770423cc092dce39df689d018b3b627714b4cfee9dffa43af93cc66dc11f26 | Python | 1,881 | 65 | import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from pymatgen.core.structure import Molecule
import pandas as pd
from instance_mongodb import instance_mongodb_sei
if __name__ == "__main__":
"""Make a potential energy surface plot for the difficult transition state."""
db = insta... |
686be54f9b3df0c1d93b4d5e635b68f6b3da26890d0741f212ca47560a761c61 | Python | 1,881 | 58 | """
Video Helper Utilities
This module provides utility functions for video file management specific to
the node package backup operations. These utilities were extracted from the
device package to maintain package independence.
Note: This is a local copy to avoid cross-package dependencies. Originally from
ethoscope... |
c3f1c670329431906cca8c859f4e401eb7453cdec6b51c193cd9368ee953229c | Python | 1,881 | 50 | import flywheel
import datetime
import csv
from pathlib import Path
now = datetime.datetime.now().strftime("%Y-%m-%d_%H:%M")
fw = flywheel.Client() #make sure your CLI and flywheel-sdk are the most recent version
qsiprep = fw.lookup('gears/qsiprep-fw-hpc/0.3.16_0.8.0RC3') #this was the chosen version of QSIPrep
proj =... |
e2ab59f8b57cd56753e75941b360045e0d2ec2eeb9b9a10a1b00f758d6537aa6 | Python | 1,881 | 50 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This script:
Uses cosine similarity instead of face recognition's default metric.
Compares test images against trained features.
Evaluates precision and recall.
"""
import pickle
import pandas as pd
import glob
import face_recognition
from sklearn.metrics.pairwise im... |
71ebd40fe3754e76263f33cda9c646f2e4abbdacf89934c971071f670d91cdca | Python | 1,882 | 54 | import torch
import torch.nn as nn
from modular_splicing.models.motif_models.types import motif_model_types
from modular_splicing.utils.construct import construct
class ParallelMotifModels(nn.Module):
"""
Run several motif models in parallel, and concatenate the results.
Arguments
---------
spec... |
742afacdf1a19ca0c236d76c3c67c5141087416085da20f965b491299bd9950c | Python | 1,882 | 54 | import logging
from itertools import count, cycle
from subprocess import CalledProcessError, run
from textwrap import dedent
from typing import Generator, Tuple
import numpy as np
import polars as pl
import zarr
from more_itertools import mark_ends, repeat_each
from numcodecs import VLenArray, VLenBytes, VLenUTF8
fro... |
a4b4bf0ed993b5fdbd2073b5ceaea70eec5654e856de4386a344fe0e33c2c0c6 | Python | 1,882 | 47 | """ An implementation of Adaptive Gradient Clipping
@article{brock2021high,
author={Andrew Brock and Soham De and Samuel L. Smith and Karen Simonyan},
title={High-Performance Large-Scale Image Recognition Without Normalization},
journal={arXiv preprint arXiv:},
year={2021}
}
Code references:
* Official JAX im... |
bd4b0282369837eefba05d43b2823d110af0c1c349b93219399df8c79a343da7 | Python | 1,882 | 62 | """
Environment classes for the agent-based-modeling simulations,
including the arena and any objects and impassable obstacles located within it,
as well as any existing sensory landscapes.
"""
from __future__ import annotations
from typing import Any
__displayname__ = "Environment"
__all__: list[str] = ["Arena"]
... |
3352fed92ebee729e8300a404248d317a3d46ab435781773d519c1addaccb9b0 | Python | 1,883 | 60 | from __future__ import annotations
import pytest
from pybind11_tests import ConstructorStats, UserType
from pybind11_tests import opaque_types as m
def test_string_list():
lst = m.StringList()
lst.push_back("Element 1")
lst.push_back("Element 2")
assert m.print_opaque_list(lst) == "Opaque list: [Ele... |
949747a85938e64d5818f15ccee4c0e95c90a96be78f679e426240196149d63d | Python | 1,884 | 49 | import numpy as np
from pyrates import CircuitTemplate
from pycobi import ODESystem
# PyRates initiation
qif = CircuitTemplate.from_yaml(
"model_definitions/qif_sfa"
)
# set model parameters
qif.update_var(node_vars={'p/qif_sfa_op/Delta': 2.0, 'p/qif_sfa_op/alpha': 1.0, 'p/qif_sfa_op/eta': 3.0},
... |
0ebb58c07496458cbe26349a6ef161b21e07ab8446ccf8696945b70f7ba388f2 | Python | 1,885 | 56 | from eelbrain import *
# uncomment the following line to embed plots as PNG instead of the default SVG
# configure(format='png')
# create the initial report
report = Report("Test Report", "Test Author")
# add a new section to the report and add some text
s1 = report.add_section("The Big Analysis")
s1.append("This i... |
0e82d4c0cf07aa6da622f4eb58a59e83325a9a6423544e862c1dce73969a9428 | Python | 1,887 | 50 | """
Implementation of "Convolutional Sequence to Sequence Learning"
"""
import torch.nn as nn
from bioseq2seq.encoders.encoder import EncoderBase
from bioseq2seq.utils.cnn_factory import shape_transform, StackedCNN
SCALE_WEIGHT = 0.5 ** 0.5
class CNNEncoder(EncoderBase):
"""Encoder based on "Convolutional Sequen... |
0f61c4b847f32575095fd0be77c8f69cf4229f2c0d2e8f3ede8e2405957ce259 | Python | 1,887 | 59 | from Configurations import config as cfg
from nn_model.imfcsnet import tf_model_imfcsnet
from tensorflow.keras.callbacks import Callback
import os
# for saving only the one/last best model.
class modeltracker():
def __init__(self, fntemplate, onlylast=False):
self.epoch = 0
self.loss = float("inf"... |
5ce6856ac715769a00d87a059d9e42c40a501fcb1c907aef56c2ef22bf899021 | Python | 1,887 | 61 | import torch
import torch.nn as nn
from modular_splicing.utils.construct import construct
from modular_splicing.models.motif_models.types import motif_model_types
class UseInputsIn(nn.Module):
"""
Use the given channels as inputs in the given underlying motif model.
This is useful when we want to conca... |
a838713287bcbb4b5bbae5f724cc7a3a77dc9bb868a8c272bb76f2894eeb988f | Python | 1,887 | 68 | # -*- coding: utf-8 -*-
"""**Lightly Magic:** Train and embed in one command.
This module contains the entrypoint for the **lightly-magic**
command-line interface.
"""
# Copyright (c) 2020. Lightly AG and its affiliates.
# All Rights Reserved
import hydra
from omegaconf import DictConfig
from lightly.cli._helpers i... |
fdc3d506dc9daf8d0a5aa2dff7e899b4f74f48455af7f361fe79a9bea50094e1 | Python | 1,887 | 64 | import codecs
import unicodedata
class STMSegment(object):
r"""
Representation of an individual segment in an STM file.
"""
def __init__(self, stm_line):
tokens = stm_line.split()
self._filename = tokens[0]
self._channel = tokens[1]
self._speaker_id = tokens[2]
... |
55db6c40e677eeb2db331791bd90474db698764af3954281589d462225d733b0 | Python | 1,888 | 51 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
This script:
Loads face encodings from test images.
Compares them against the trained model using face recognition.
Evaluates precision and recall for face recognition performance.
"""
import pickle
import pandas as pd
import glob
import face_recognition
from PIL imp... |
9456e0325d70bd547bf6eae62edbdea9c5ea74e65e6f3cb015253a59502b4553 | Python | 1,888 | 61 | from types import SimpleNamespace
import tqdm.auto as tqdm
import numpy as np
import torch
from shelved.donorlike_motifs.utils import load_sparsest
from modular_splicing.dataset import basic_dataset
from modular_splicing.utils.run_batched import run_batched
from modular_splicing.models.modules.lssi_in_model import ... |
c42413e060362090929dae2f84f48b39e2c10963ec11746971ad5bb6e2201545 | Python | 1,889 | 41 | from pyrosm.data_manager import get_osm_data
from pyrosm.frames import prepare_geodataframe
from pyrosm.utils import validate_custom_filter
import warnings
def get_building_data(node_coordinates, way_records, relations,
tags_as_columns, custom_filter, bounding_box):
# If custom_filter has no... |
ec78119168ac4b3a16806bec3446a36ef7d4488c7bcb5536a1bb5456743da3a0 | Python | 1,889 | 60 | _author__ = 'quentin'
from ethoscope.hardware.interfaces.lynx_motion import SimpleLynxMotionInterface
from ethoscope.hardware.interfaces.sleep_depriver_interface import SleepDepriverInterface
import time
class OdourDelivererInterface(SimpleLynxMotionInterface):
_positions_to_angles = {1: -25,
... |
32541ee6de6bf0c22e556b3c96a79db483c83f87646fcbeab2eca0d4ab0f7142 | Python | 1,890 | 41 | from pyrosm.data_manager import get_osm_data
from pyrosm.frames import prepare_geodataframe
from pyrosm.utils import validate_custom_filter
import warnings
def get_landuse_data(nodes, node_coordinates, way_records, relations,
tags_as_columns, custom_filter, bounding_box):
# If custom_filter h... |
372b0bf11d5d781179fd04691e24faaa9946732f0dcd16ba6716f60f8d645bf6 | Python | 1,890 | 88 | '''Loading EPIs module.
This file is a part of BdPy.
'''
import itertools as itr
import os
import re
import string
import nipy
import numpy as np
import scipy.io as sio
def load_epi(datafiles):
'''Load EPI files.
The returned data and xyz are flattened by C-like order.
Parameters
----------
... |
7f57dab30213e59687e47b0b55efd98e016671918ad8f4804f5a8a96d371f468 | Python | 1,890 | 57 | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
bb86925d8d07d44aa1ff1557f0f3afa212b29271750cf0c88f0065f6ad25bf2c | Python | 1,890 | 51 | import torch
from torch import nn
from torch.utils.data import Dataset
class StructureDataset(Dataset):
"""
Stores example feature data and the associated labels for training a neural network
"""
def __init__(self, features):
self.labels = features['residue_labels'].long()
s... |
ecad7ae50a30bea51d3f300b42c1bd7edb2520966e8adf32b031eff66adaf802 | Python | 1,890 | 41 | from pyrosm.data_manager import get_osm_data
from pyrosm.frames import prepare_geodataframe
from pyrosm.utils import validate_custom_filter
import warnings
def get_natural_data(nodes, node_coordinates, way_records, relations,
tags_as_columns, custom_filter, bounding_box):
# If custom_filter h... |
0d50a0ee29782d784f21f729600da762e0014d9e598d50b931acda421d657a04 | Python | 1,891 | 48 | """Prepare Multi-Human Parsing V1 dataset
=========================================
`Multi-Human Parsing V1 (MHP-v1) <https://github.com/ZhaoJ9014/Multi-Human-Parsing/>`_ is
a human-centric dataset for multi-human parsing task. It contains
five thousands images annotated with 18 categories.
This tutorial helps you to ... |
73260a54dbd8f84cc564ae259d95407c99fdb9d57b4be13369f558438e6a54d2 | Python | 1,891 | 59 | import os
from dotenv import load_dotenv
from omop_learn.backends.postgres import PostgresBackend
from omop_learn.data.cohort import Cohort
from omop_learn.data.feature import Feature
from omop_learn.utils.config import Config
from omop_learn.omop import OMOPDataset
load_dotenv("postgres.env")
config = Config({
... |
7618f12d8160f4c546b0e5118c80f8b21387d18e2d4d72ecd63382525fd5e43d | Python | 1,891 | 50 | # LICENSE
#
# _This file is Copyright 2018 by the Image Processing and Analysis Group (BioImage Suite Team). Dept. of Radiology & Biomedical Imaging, Yale School of Medicine._
#
# BioImage Suite Web is licensed under the Apache License, Version 2.0 (the "License");
#
# - you may not use this software except in compl... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.