sha256
stringlengths
64
64
language
stringclasses
27 values
size
int32
1
491k
lines
int32
1
21.8k
content
stringlengths
1
200k
5e3e0687f24140be241fe9fa9794a13f36a5af3aef73eae4133493752f1ca7ba
Python
553
20
from tractseg.experiments.base import Config as BaseConfig class Config(BaseConfig): EXPERIMENT_TYPE = "peak_regression" CLASSES = "20" BATCH_SIZE = 44 LOSS_WEIGHT = 10 LOSS_WEIGHT_LEN = 400 # nr of epochs LABELS_TYPE = "float" TRAINING_SLICE_DIRECTION = "y" GET_PROBS = True INF...
6660a893388b5c397ca9b1663085030eb912fa7361331a70440b1e14cfa0da67
Python
556
18
# encoding: utf-8 """ @author: Jiayang Chen @contact: yjcmydkzgj@gmail.com """ from .baseline import Baseline def build_model(cfg): model = Baseline( backbone_name=cfg.MODEL.BACKBONE_NAME, seqwise_predictor_name=cfg.MODEL.SEQWISE_PREDICTOR_NAME, elewise_predictor_name=cfg.MODEL.ELEWISE_PR...
a810c8d04599d53631a7dc9fe7f129d48793638c413f0eadcf875abccee5f6b6
Python
557
18
import haiku as hk import jax import jax.numpy as jnp from ..types import MolecularConfiguration class HydrogenicDensityModel(hk.Module): def __call__( self, r: jax.Array, mol_conf: MolecularConfiguration, only_network_output: bool = False ) -> jax.Array: assert mol_conf.nuclei.n_active == 1 ...
cc1921f434af15b3b799839dceaa3a46d357a6b29a657e1365835eef2f63a6ef
Python
557
23
from __future__ import annotations import sys from pathlib import Path def main() -> int: path = Path(sys.argv[0]) if sys.argv[1] == "absolute": if not path.is_absolute(): raise RuntimeError(f"sys.argv[0] is not an absolute path: {path}") if not path.exists(): raise R...
56184609fc5abd957f644d128c05f663e5a46ab8ff9b6fe17d62a0e927f5a5c6
Python
558
18
"""Guards on the ad-hoc scripts that write the packaged data files.""" from importlib import resources import pytest from brenda_references import brenda_references as package from scripts import generate_dataset def test_generate_dataset_writes_where_the_package_reads() -> None: assert generate_dataset.DATA_D...
ce4161f7a20081eb4035b690a9bbcca5eb97fe3741196370e0836119b4a85e89
Python
558
19
"""Evaluation metrics for classification.""" from sklearn.metrics import accuracy_score, precision_recall_fscore_support, roc_auc_score def compute_metrics(y_true, y_pred, y_prob): acc = accuracy_score(y_true, y_pred) precision, recall, f1, _ = precision_recall_fscore_support( y_true, y_pred, average...
718930a68a988468c6b519f1fbdb2822cfa2feb261926056ab00105d563a188a
Python
561
21
import os import re import pandas as pd def extract_mouse_name(file_path: str) -> str | None: """Extract the mouse name (letters followed by numbers) from a file path, or None if not found.""" base_name = os.path.splitext(os.path.basename(file_path))[0] pattern = r"[A-Za-z]+\d+" matches = re.findall(...
bf6d9262259222d77f5a2588dc4d0755b3c3ec6db0e954d08df053e80b41f350
Python
561
23
from __future__ import annotations from typing import TYPE_CHECKING import pytest from poetry.core.exceptions import PoetryCoreError from poetry.toml import TOMLFile if TYPE_CHECKING: from pathlib import Path def test_pyproject_toml_file_invalid(pyproject_toml: Path) -> None: with pyproject_toml.open(mo...
0c0a643b2e7c0133032f94264d7361911dd6272ba791ff6b28927f308981ddd9
Python
562
17
import gl gl.resetdefaults() gl.azimuthelevation(70, 15) gl.meshload('BrainMesh_ICBM152.rh.mz3') gl.overlayload('motor_4t95vol.nii.gz') gl.overlayminmax(1,2,12) gl.overlayload('motor_4t95vol.nii.gz') gl.overlayminmax(2,-1,-2) gl.colorbarvisible(1) gl.overlaytransparencyonbackground(25) gl.meshcurv() gl.shade...
193b3a9cb2d47ffe5ac747aff318e17d380d8a3a87f702fea90d5f84eaa3a6be
Python
562
18
# Authors: Christian O'Reilly <christian.oreilly@sc.edu> # Scott Huberty <seh33@uw.edu> # License: MIT """Configure the dash tests with the chrom webdrive for CI.""" from selenium.webdriver.chrome.options import Options # As per https://community.plotly.com/t/dash-integration-testing- # with-selenium-and-...
a7d7388e75eee3b27db1b8917eccf353857f90f2dfcfd941475803115e6ec34e
Python
563
15
import glob from ecephys_spike_sorting.common.visualization import plotContinuousFile mouse = '72112' #, '425589', '432104', '425597'] #,'434845','434494','434843'] probes = ['probeA','probeB','probeC','probeD','probeE','probeF'] for probe in probes: output_path = r'/mnt/nvme0/continuous_file_qc/' + mouse + '...
54316b455fa74ec2650a3f733a6f5b87dfd1472a050efbc4ed7aa11ccf898441
Python
565
16
from __future__ import annotations from poetry.core.packages.package import Package from poetry.utils.env.mock_env import MockEnv from poetry.utils.log_utils import format_build_wheel_log def test_format_build_wheel_log() -> None: env = MockEnv(version_info=(3, 13, 1), platform="win32", platform_machine="AMD64"...
dbc387a585972890e34f7637a7cf972e38a1e6b1d6f77aede0ae79265bb7fc43
Python
565
23
#!/usr/bin/env python # -*- coding: utf-8 -*- import os from tractseg.experiments.base_legacy.tract_seg_legacy import Config as TractSegConfig class Config(TractSegConfig): EXP_NAME = os.path.basename(__file__).split(".")[0] NUM_EPOCHS = 250 DATA_AUGMENTATION = True MODEL = "UNet_Pytorch_DeepSup" ...
a2fd53641a48e20d6c55d6ef293a35a440c141b53b85c91ac9071dab443039a7
Python
566
18
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from torch import nn from fairseq.models import FairseqEncoder class CTCDecoder(FairseqEncoder): def __init__(self, dictionary, in_dim)...
f4c0a312de25e872e62d965586fcac41884c9fc523ffd11b73ab7b16ef60ae49
Python
566
15
"""DFer/PFer raw photometry analysis. This package ports the Argotech/Tussock Innovation DFer_v1.4 + PFer_2.4 analysis workflow (OCT-2024). That workflow is based on analysis methods from GuPPy: Sherathiya, V. N., Schaid, M. D., Seiler, J. L., Lopez, G. C., & Lerner, T. N. GuPPy, a Python toolbox for the analysis of ...
af091440a48f7f4ce82429b5d5cf601b124b2603287a3633bf1a323d9c3e3c2f
Python
567
24
from .BIF import BIFReader, BIFWriter from .NET import NETReader, NETWriter from .PomdpX import PomdpXReader, PomdpXWriter from .UAI import UAIReader, UAIWriter from .XDSL import XDSLReader, XDSLWriter from .XMLBeliefNetwork import XBNReader, XBNWriter from .XMLBIF import XMLBIFReader, XMLBIFWriter __all__ = [ "XM...
4cf7adad6f7610d697941e70376acf99f58b1e18ae29f180ea41c3f0f4206760
Python
568
19
from paper2.bands_paper2 import assign_band2 def test_lipid_band_still_assigned(): assert "C=O" in assign_band2(1743)["assignment"] def test_water_band_assigned_for_juice(): a = assign_band2(3300) # broad O-H stretch (water / sugars) assert a["assignment"] != "Unassigned" def test_sugar_co_ba...
2de9d7a6027f2aaf0a386af3769efc65ec400a135a32764b17adfdd5949d8023
Python
570
24
import unittest from pyecharts.charts import Bar, Line from pyecharts.charts.mixins import CompositeMixin class CustomCompositeChart(CompositeMixin): def __init__(self): self._charts: list = [] def add(self, chart, tab_name): chart.tab_name = tab_name self._charts.append(chart) ...
e40febc8aa990a8fe6d2b627d66b7572dbf5c6275e9ba7425d8a751a48b081a5
Python
570
21
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from functools import lru_cache from . import BaseWrapperDataset class LRUCacheDataset(BaseWrapperDataset): def __init__(self, dataset,...
23533502721032f511f053b09961511de08d50eda8ba7be3824b3dc49ffa4174
Python
572
16
"""Manual-loop training infrastructure: checkpoints, TensorBoard, epoch aggregation (not Lightning).""" from .checkpoint_io import load_checkpoint, resolve_checkpoint_path, save_checkpoint from .epoch_aggregates import EpochBatchAggregator, StatHistory from .experiment_paths import tensorboard_log_dir from .tenso...
0fb2e48eedc5f31320c6b0f37351686180a956ee97edce8f1141fc8c34e7f341
Python
574
20
import os import unittest from pyecharts.globals import RenderSepType class TestGlobals(unittest.TestCase): def test_render_sep_type(self): # normal test render_sep_type = RenderSepType.SepType self.assertEqual(os.linesep, render_sep_type) # test modification before_modif...
d0b39bcf6c884ee01d539c72c91b19786eff5f792c439504119d18842fbbb342
Python
574
26
from __future__ import annotations from distutils.core import setup packages = ["project_with_extras"] package_data = {"": ["*"]} extras_require = {"extras_a": ["pendulum>=1.4.4"], "extras_b": ["cachy>=0.2.0"]} setup_kwargs = { "name": "project-with-extras", "version": "1.2.3", "description": "This is...
71a43b6e2057b55f682e47203ab5f03ff02073491b875a009cf42ecabe1f73d9
Python
575
15
""" Baseline transformer models package for GI classification experiments. """ from .deit_base import DeiTBaseClassifier from .vit_b16 import ViTB16Classifier from .vit_l32 import ViTL32Classifier from .transunet import TransUNetClassifier from .transfuse import TransFuseClassifier from .medvit import MedViTClassifier...
4a997f5ebb5bf17357b338cdfc1c557d5f37797b0f9fd05f51a08635adf25d87
Python
577
23
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import abc from typing import Generic, TypeVar import torch from mattergen.diffusion.data.batched_data import BatchedData Diffusable = TypeVar("Diffusable", bound=BatchedData) class ScoreModel(torch.nn.Module, Generic[Diffusable], abc.ABC): ...
90e8f863fbb6ffcf857a9fa48ebfb98b69b20231d82563a13d8fec042d168e64
Python
577
17
from ._minification import get_minified_adata_scrna, get_minified_mudata __all__ = ["get_minified_adata_scrna", "get_minified_mudata"] def __getattr__(name: str): """Lazily provide private utilities.""" if name in { "_de_core_for_annbatch", "_peakvi_differential_accessibility_result", ...
bb7a29881600fda7bf8896c808eeeb52093da02955d040232a6e5547b1ab7050
Python
577
21
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .huffman_coder import HuffmanCodeBuilder, HuffmanCoder from .huffman_mmap_indexed_dataset import ( HuffmanMMapIndex, HuffmanMMapI...
58f7171699304cef9f891652aa7d01220e315add4c54fe28524a7afe8b0b54f5
Python
578
18
import torch.nn as nn class SELayer(nn.Module): def __init__(self, channel, reduction=16): super(SELayer, self).__init__() self.avgpool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel//reduction,bias=False), nn.ReLU(inplace=True), ...
d3a5178bcffaf2dea41fb79734c18e0ef40700fd10daf7365cb596c08ea33d02
Python
578
8
# flake8: noqa # There's no way to ignore "F401 '...' imported but unused" warnings in this # module, but to preserve other warnings. So, don't check this module at all. from .glue import glue_convert_examples_to_features, glue_output_modes, glue_processors, glue_tasks_num_labels from .squad import SquadExample, Squad...
6da1c8a0094171f12fa0638cdac1fea102ca568e55d0ce59ab339b8239b6238d
Python
580
23
""" Wrapper functions for pytorch. """ import torch def torch_device(index=-1): if torch.cuda.is_available(): if index >= 0: return torch.device(f"cuda:{index}") return torch.device("cuda") elif torch.backends.mps.is_available() and torch.backends.mps.is_built(): return to...
f355d80f19740eb14171c6822dcbfd36371b4b8b2118b7fa7bc5e80c15eb7ac7
Python
580
22
import qrcode # Code for input email_address = input("Enter email address: ") subject = input("Enter subject: ") content = input("Enter content: ") # Command email_url = f"mailto:{email_address}?subject={subject}&body={content}" # QR code generation qr = qrcode.QRCode(version=1, error_correction=qrcode.constants.ER...
059383738677503843de20f42871c7ad6b1fbae098da082abebdcc4681914885
Python
581
17
"""Dynamic segmentation visualize payload + panel rendering.""" from tasks.dynamic_segmentation.visualize.metrics_payload import SegEvalPayload, load_payload, save_payload from tasks.dynamic_segmentation.visualize.panel_plot import ( render_panels_from_payload, render_panels_from_saved_payload, ) from t...
a530a7283cbae15b8b53a7a6f211fda337eb35f7ebba799126ef7650dabe9b78
Python
581
23
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name="lig...
0815e91a5f7b8357872d31f16f8732c7361ef4a054f3b3f0829fa7ce4da03b0e
Python
582
24
from scvi.utils import error_on_missing_dependencies from ._beta_binomial import BetaBinomial from ._gamma import ZeroInflatedGamma from ._lognormal import Log1pNormal, ZeroInflatedLogNormal from ._negative_binomial import ( NegativeBinomial, NegativeBinomialMixture, Poisson, ZeroInflatedNegativeBinomi...
d79426c74dd91d075a3e2c85c6f65dde122637dbc09e250a192141d0107a8e2f
Python
582
21
import torch from scvi.distributions._constraints import open_interval def test_open_interval(): lower_bound = 0 upper_bound = 1.0 constraint = open_interval(lower_bound=lower_bound, upper_bound=upper_bound) # Within the interval is ok assert constraint.check(torch.tensor(0.5)) # Values ou...
f47d50430c12ec3bb11bdb146b4905e8c336384c6ed0e819198d47c6cfcda27d
Python
582
19
import polars as pl from src.utils import read_gtf signalp5 = pl.read_csv("export/orfanage_peptide_summary.signalp5", separator = "\t", comment_prefix="#", new_columns=["ID","Prediction","SP(Sec/SPI)","OTHER","CS Position"]) pbids = read_gtf("nextflow_results/V47/orfanage/orfanage.gtf")\ .filter( pl.col("...
6306b38724154b4791e74145a667fdf8ba0bea2278a8080596d0685ac37d177a
Python
583
25
import sys root_dir = __file__.rsplit("/", 2)[0] if root_dir not in sys.path: sys.path.append(root_dir) import gradio as gr from modules.search import build_search_module from modules.compute_score import build_score_computation # from modules.tmalign import build_TMalign # from modules.cli import build_cli from ...
6388e1504e3a475ae03d4007b2d867620ec1503008f863c9f0365ac5c45590bc
Python
584
12
Res = [[] for i in range(32)] for i in ['Test_dataset_R1_1234.txt','Test_dataset_R2_1234.txt','Test_dataset_R3_1324.txt','Test_dataset_R4_1324.txt','Test_dataset_R5_2134.txt','Test_dataset_R6_2134.txt','Test_dataset_R7_2314.txt','Test_dataset_R8_2314.txt','Test_dataset_R9_3124.txt','Test_dataset_R10_3124.txt','Test_dat...
fd58c739a50bef6dc5c23c5df83e34605f0d0811a924f0ffcb69dfe79b8116ad
Python
585
20
import generate_counting_table as ct input_path = "Data/TREC/Relevance_Matrix/trec_simplified_relevance_matrix.tsv" # Comment out this step if table exists with cosine similarities data = ct.load_relevance_matrix(input_path) data = ct.random_cosine_similarities(data) counting_table = ct.create_counting_table(data) ...
837b0d910bfc541feb0774c464a066cfa3cbc06ded0fe5d68b542c31261c1b76
Python
587
20
from .base import Inference # isort: skip # noqa: E402 from .CausalInference import CausalInference from .ExactInference import BeliefPropagation, BeliefPropagationWithMessagePassing, VariableElimination from .ApproxInference import ApproxInference from .dbn_inference import DBNInference from .mplp import Mplp __all...
a31da901ba16fd2fbb77b46936d2ac1aee9c301ef9437a3fc999cacf96d48117
Python
588
32
import pandas as pd import stackprinter from .brenda_references import ( add_abstracts, expand_doc, main, noise_documents, psycholinguistics_data, sync_doc_db, test_data, training_data, validation_data, ) from .sampling import relation_records pd.options.mode.copy_on_write = True ...
51bccbe2838f03a4433b4949fbc06a1ead33c66b2fbd018e054a566f1b10c943
Python
590
21
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import re from fairseq.data.encoders import register_tokenizer from fairseq.dataclass import FairseqDataclass @register_tokenizer("space", ...
901bd9f32356ad98a500ef2be0184db31f6b3b3dc2edf9ec73dd129d7c98a8f4
Python
591
19
import os import sys from nicheformer.data.constants import DefaultPaths from nicheformer.data.download import download_zip if len(sys.argv)==1: out_path = DefaultPaths.SPATIAL else: out_path = sys.argv[1] if not os.path.exists(f"{out_path}/raw"): os.mkdir(f"{out_path}/raw") download_zip( url="http...
09ee3e2d95dae691162417b79b7e32d53b1ea992a89f3cb82b1c1c31aac683c2
Python
595
16
import time from datetime import datetime import vak.common.constants import vak.common.timenow def test_timenow(): before_timestamp = time.mktime(datetime.now().timetuple()) timenow_str = vak.common.timenow.get_timenow_as_str() assert len(timenow_str) == len(vak.common.constants.STRFTIME_TIMESTAMP) ...
69b06a86aa8f3f5d232baa4d084b795435597d82b4bb47d0ba04e9d800b42b89
Python
596
13
# Copyright 2015 Google Inc. All Rights Reserved. # # 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 or a...
df26b8863d815f7eb7a7a30594e595600281d9a76a8d8e1b6b5ec9b627203fb7
Python
596
18
from __future__ import annotations from html.parser import HTMLParser class HTMLPageParser(HTMLParser): def __init__(self) -> None: super().__init__() self.base_url: str | None = None self.anchors: list[dict[str, str | None]] = [] def handle_starttag(self, tag: str, attrs: list[tuple...
f077458aa63e1e7229f770ac3808df105a0ae5befe594c612841cadf39d3de54
Python
596
25
#!/usr/bin/env python # -*- coding: utf-8 -*- """Stores types""" from typing import Literal, Tuple, TypeAlias, TypedDict from nd2.structures import Color _axes_interp: TypeAlias = Literal["distance"] class MetaLike_ND2(TypedDict): name: str color: Color index: int emission_lambda: float excita...
62c3dbc633f6eb91fb868d81852382a2ebf7ba823d647f5418a6404f14f753ed
Python
597
25
from __future__ import annotations import os from pathlib import Path from platformdirs import user_cache_path from platformdirs import user_config_path from platformdirs import user_data_path _APP_NAME = "pypoetry" DEFAULT_CACHE_DIR = user_cache_path(_APP_NAME, appauthor=False) CONFIG_DIR = Path( os.getenv("...
6eb29dc87bdcbb2728dba261f46873bc70c96283971ec8afa27b9a614adfc83e
Python
598
20
import os import random class Tempname: """ A context manager that generates a temporary pathname, which is renamed to its permanent name upon leaving the context. The renaming is guaranteed to be atomic at least on POSIX systems. """ def __init__(self, path: str) -> None: self.path = path self.temp_path = ...
9a2801489cad7f915a5c5f0c707c487f2c233ab07bfec19a0ef707617bcd75a8
Python
598
20
import torch.nn as nn """ https://zhuanlan.zhihu.com/p/76378871 arxiv: 1804.03821 ExFuse """ class SematicEmbbedBlock(nn.Module): def __init__(self, high_in_plane, low_in_plane, out_plane): super(SematicEmbbedBlock, self).__init__() self.conv3x3 = nn.Conv2d(high_in_plane, out_plane, 3, 1, 1) ...
c036b3f4a8a39f7ea4eb32f1bea4cf39cce443763899333204bb3161c91b30de
Python
598
24
"""Mapping from libvips band formats to numpy dtypes. Shared by the morphology and visualization helpers that wrap pyvips ``Image`` outputs into numpy arrays. Kept here so the lookup table has a single source of truth. """ from __future__ import annotations import numpy as np FORMAT_TO_DTYPE: dict[str, type] = { ...
c6d2d61a6575cf6826acc4a20eb2f05ccf149cab37bc6f2aeb4b4aa6701b0fe8
Python
598
15
import os from pathlib import Path # List of PDB files to rename cur_dir = Path('/cta/users/guludogan/ProteinWorkshop/proteinworkshop/data/GeneOntology/pdb') # Loop through each file and rename it for file in cur_dir.iterdir(): # Split the filename to extract the new name format new_name = "_".join(file.name.s...
260c455f898cf1eedc3aa378bc845087b0f595f7e66508d8a132f7b8f2a0208a
Python
599
23
""" Inference Pipelines for NeuroVFM High-level APIs for loading models and running inference on medical imaging studies. """ from .encoder import EncoderPipeline, load_encoder from .diagnostic import DiagnosticHead, load_diagnostic_head from .preprocessor import StudyPreprocessor from .generator import FindingsGener...
7382fda0e0584e7277401f6852498cc88f5f624b72b3255b57082cb5f153c0a9
Python
599
18
from collections.abc import Callable from functools import wraps from scvi.data._constants import ADATA_MINIFY_TYPE def unsupported_if_adata_minified(fn: Callable) -> Callable: """Decorator to raise an error if the model's `adata` is minified.""" @wraps(fn) def wrapper(self, *args, **kwargs): if...
f20720ea79811bb8b751bb94d91634c89811f65cf9b6d7bcb6a3f97dea40e589
Python
599
20
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import importlib import os from .ema import EMA def build_ema(model, cfg, device): return EMA(model, cfg, device) # automatically imp...
0bc8d5cc3c63904526232c5e27e58c1b0a04afea25805d3ec919faa483ddd45b
Python
602
23
import neuroglancer.read_precomputed_annotations reader = neuroglancer.read_precomputed_annotations.AnnotationReader( "gs://h01-release/data/20210601/c2/synapses/precomputed/" ) print( list( reader.get_within_spatial_bounds( limit=1000, lower_bound=[70258.0, 115184.0, 1892.0], ...
dbfaf3362d2e3268ce6969ff79235a6da50227c1dcf77d9029a829a7ba525f39
Python
602
23
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from setuptools import setup from torch.utils.cpp_extension import BuildExtension, CUDAExtension setup( name="dyn...
e6cf9da8b0843edfe0519caef83a5b51fce91cfcd89c919b537c7d58bb8044c8
Python
602
23
from mdt import CompositeModelTemplate __author__ = 'Robbert Harms' __date__ = "2015-06-22" __maintainer__ = "Robbert Harms" __email__ = "robbert@xkls.nl" class Tensor(CompositeModelTemplate): model_expression = ''' S0 * Tensor ''' inits = {'Tensor.d': 1.7e-9, 'Tensor.dperp0': 1.7e-1...
853cdd5c98d67b17f471cc350ed35876f3be39605315fef80d9bdde252493dc7
Python
604
25
from scvi.utils import error_on_missing_dependencies from ._base_module import ( BaseMinifiedModeModuleClass, BaseModuleClass, LossOutput, PyroBaseModuleClass, SupervisedModuleClass, ) from ._decorators import auto_move_data from ._embedding_mixin import EmbeddingModuleMixin from ._priors import Ga...
11a3d99074082b384132d524240f88b9eaa0dc17082591d16b69373137e9e329
Python
605
26
import numpy as np def sparseness( W: np.ndarray, dim: int = 0, ) -> np.ndarray: """ Vector sparseness along specified dimension. Parameters ---------- W : np.ndarray Input array. dim : int, optional Dimension along which to compute sparseness, by default 0. Retur...
6a9e7cc227d8a3ae6c8d40a4d99416c6f350c755def046e4ca7615c6e9000753
Python
606
16
import os import pandas as pd import random data_root = "/nfs/turbo/umms-tocho-snr/exp/akhilk/torchmr/raw_data/mri/processed/" num_studies = len([f for f in os.listdir(data_root) if os.path.isdir(os.path.join(data_root, f))]) print(f"Number of studies: {num_studies}") df_list = [] for study in os.listdir(data_root):...
75d4ea5125a168763ae4d1a441d11c7909484c154d78761e1afd248cf80d8a12
Python
606
18
# The script is modified from scGPT (https://github.com/bowang-lab/scGPT), copyright (c) 2022 suber __version__ = "1.0" import logging import sys logger = logging.getLogger("stFormer") # check if logger has been initialized if not logger.hasHandlers() or len(logger.handlers) == 0: logger.propagate = False log...
0de279a0651eeb63f114bc838e2c8fa7f6ef7f3f5d7da0f4cd52b6bec782b876
Python
607
27
from pgmpy.datasets._base import BaseCovarianceDataset class Cities(BaseCovarianceDataset): """ References ---------- - :footcite:t:`spirtes_glymour_scheines_2001` """ _tags = { "name": "cities", "n_variables": 7, "n_samples": 164, "has_expert_knowledge": True,...
5088f17d07c9a86a63f1a3f7f2898c6882a69e01ae28772847286781821b39f4
Python
607
21
import qrcode # Email details email_address = "gutsie@kuleuven.be" subject = "Info Clinical Trial" content = "Please, could you send me more information about your study?" # Format the email URL email_url = f"mailto:{email_address}?subject={subject}&body={content}" # Generate the QR code qr = qrcode.QRCode(version=1...
7b4e24a45ecfd4e32685107c20b0a5030931a307732a9bf6b4ea1225a1b254b0
Python
608
20
import torch import torch.nn as nn import torch.nn.functional as F class SEBlock(nn.Module): def __init__(self, channel, reduction=2): super(SEBlock, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential( nn.Linear(channel, channel // reduction), ...
e7165189ee15e3d5b4bd160727ab0f5684033d12b1e6351fcda5fe20b08fb623
Python
609
23
import pandas as pd import numpy as np pd.set_option("display.max_columns", None) pd.set_option("display.width", 1000) df = pd.read_csv("results/aggregated_features_folded_with_demographics.csv") df = df[[col for col in df.columns if ('Oddball' in col or 'Resting' in col or col == "Group") ]] for name, g in...
35adbb1ea6f2d8b8ab9e389b9ce91aad74d2326580e6e9fa8b397b623268b267
Python
610
21
from ._base import BaseSupervisedMetric, BaseUnsupervisedMetric, get_metrics from .adjacency_cm import AdjacencyConfusionMatrix from .correlation_score import CorrelationScore from .fisher_c import FisherC from .implied_cis import ImpliedCIs from .orientation_cm import OrientationConfusionMatrix from .shd import SHD fr...
6b5c58d825963738c90dda7db5ece45e75d5563ddaf213463d591d22585c9a3a
Python
611
24
import jax from flax.struct import PyTreeNode from folx import forward_laplacian from ...physics import LaplacianOperator from ...types import RandomKey class ForwardLaplacianOperator(LaplacianOperator, PyTreeNode): """Thin wrapper around folx.forward_laplacian.""" sparsity_threshold: float = 0.6 def _...
f3a058dd8a1c2e060d96af86371afa174909b15b7e7ee055f7b5f48f85d7a8f3
Python
611
19
# scBank is the single cell data bank toolbox for building up large-scale single # cell dataset to allow flexible cell data access and manipulation across studies, # and to support large-scale computing. import logging import sys logger = logging.getLogger("scBank") logger.setLevel(logging.INFO) handler = logging.Stre...
4cd830b93db8e62f8c4dc9d7d7ccb419156ecf075bceed850b0af6ee863194be
Python
612
26
from ._utils import ( fill_invalid_indices, get_reference, iter_slides, lower_var_names, parse_device_args, pretty_model_repr, pretty_num_parameters, tqdm, unique_leaves_indices, unique_obs, valid_indices, store_inference_mode, sample_latent, ) from ._train import con...
421f5ee0d5465799de08725a80779a4805414232b72afb41d0f65e8af4142552
Python
613
22
#!/usr/bin/env -S uv run # /// script # requires-python = ">=3.11" # /// import os import zipfile SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) def create_zip(directory_path: str, zip_path: str): with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_STORED) as zipf: for root, dirs, files in os.walk(...
141182514b86d830571c543e16834c78a63bd7855c1f4c73344f852976beb50b
Python
614
14
import tensorflow as tf def iou_tf(y_true, y_pred, threshold=0.5): y_pred = tf.cast(y_pred > threshold, tf.float32) intersection = tf.reduce_sum(tf.cast(y_true * y_pred, tf.float32)) union = tf.reduce_sum(tf.cast(y_true + y_pred, tf.float32)) - intersection iou = (intersection + 1e-7) / (union + 1e-7) ...
94e9dc7ca92495347f0c306b9f74d1e82e5c9b4f7f782d1499678d664b4d16b1
Python
614
24
import torch import torch.nn as nn class sSE(nn.Module): def __init__(self, in_channels): super().__init__() self.Conv1x1 = nn.Conv2d(in_channels, 1, kernel_size=1, bias=False) self.norm = nn.Sigmoid() def forward(self, U): q = self.Conv1x1(U) # U:[bs,c,h,w] to q:[bs,1,h,w] ...
0ec5f972e6d87ba39090766b51f188a93f216a8c3d4178cd2662d9c4c4356dc6
Python
615
22
from __future__ import annotations from typing import TYPE_CHECKING from cleo.exceptions import CleoLogicError from cleo.loaders.factory_command_loader import FactoryCommandLoader if TYPE_CHECKING: from collections.abc import Callable from cleo.commands.command import Command class CommandLoader(FactoryC...
9e3f7813394098432a6da17e143c05702c6d7134b74b08b26e66dbe214aa6bd9
Python
615
19
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import torch.nn.functional as F def unfold1d(x, kernel_size: int, padding_l: int, pad_value: float = 0): """unfold T x B x C to T x B x ...
a237ba59c7c0a012e927739e8b3e984b283f696af466dddab2d920c3aac087be
Python
617
14
# Copyright 2021 DeepMind Technologies Limited # # 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 or agr...
0b52f881c1ab7a485ad2fc581d2c42c486c54f6b5ec00a46b7f3ceed0e786e3b
Python
618
14
# Copyright 2021 DeepMind Technologies Limited # # 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 or agr...
f4b5b310d396790597c7f297d3247b75c42bb23f5541925c0124ab74ad0d2b5e
Python
619
16
import pytest from src.string_ops.string_utils import normalize_deduplicate_and_order_strings @pytest.mark.parametrize("input_behaviours, expected_output", [ (["walking", "RUNNING", "EaTing"], ["Eating", "Running", "Walking"]), ([], []), (["cat", "Cat", "bat"], ["Bat", "Cat"]), ([" walking ", "runnin...
17c89a18e0091bcc4d31e0a8b3a2efc541bc04ff2738d5354f0f8ada75022fd7
Python
620
21
import numpy as np from pytorch_grad_cam.base_cam import BaseCAM class RandomCAM(BaseCAM): def __init__(self, model, target_layers, reshape_transform=None): super( RandomCAM, self).__init__( model, target_layers, reshape_transfo...
948f2dfb7a0e0aa71c6c810d54bc83a4c1bdbaa5ad8d4246d38dacf22559f7b1
Python
620
33
import pandas as pd import stackprinter from .brenda_references import ( add_abstracts, expand_doc, main, noise_documents, psycholinguistics_data, sync_doc_db, test_data, training_data, validation_data, ) from .data_paths import corpus_files, documents_path pd.options.mode.copy_on_...
8cae32f2183bd149201a7cfc390a044c97e0d4e773142e57f3f61053a5c575bc
Python
621
21
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import numpy as np from . import BaseWrapperDataset class SortDataset(BaseWrapperDataset): def __init__(self, dataset, sort_order): ...
0583e99fe90c091b5df9321eff5d49719f1ba36f1ed7c5f39e8ddcabceb8cf7a
Python
622
31
from .ANM import ANM from .ChowLiu import ChowLiu from .ExpertInLoop import ExpertInLoop from .ExpertKnowledge import ExpertKnowledge from .GES import GES from .HillClimbSearch import HillClimbSearch from .IGCI import IGCI from .LLMPairwise import LLMPairwise from .PC import PC from .R2Sort import R2Sort from .SP impor...
718f020a868f977719bdca507f288d6f6cf8cba0143ecb826e30eeb0bc440975
Python
622
23
import os import sys from nicheformer.data.download import download_tar from nicheformer.data.constants import GeneExpressionOmnibus, DefaultPaths if len(sys.argv)==1: out_path = DefaultPaths.DISSOCIATED else: out_path = sys.argv[1] geo_id = 'GSE172127' if not os.path.exists(f"{path}/raw"): os.mkdir(f"{...
f6ba9faa42e5ecf1c86e06ee5769915fbf6efe200444efa991e5874f4f958299
Python
622
17
import numpy as np import pytest from scvi.data import synthetic_iid @pytest.mark.parametrize("sparse_format", ["csr_matrix", "csc_matrix", None]) def test_synthetic_iid_sparse_format(sparse_format: str | None): _ = synthetic_iid(sparse_format=sparse_format) @pytest.mark.parametrize("return_mudata", [False, Tr...
0b2dcb1bbe53697a73a340cf319d59cda4116c93f5ecc088ce60bb0fb471f5e9
Python
623
23
import os import os.path as op from glob import glob base_dir = '/media/lukas/goliath/MVCA/ID1000/raw' subs = sorted(glob(op.join(base_dir, 'ID????'))) for sub in subs: t1s = sorted(glob(op.join(sub, '*T13D*', '*T13D.nii.gz'))) dtis = sorted(glob(op.join(sub, '*DTI32*', '*DWI.nii.gz'))) for i, t1 in enu...
f37c5adcddcf2810c0140ba7184187d0cdaa7fa69245322ac48e4707e8adf86b
Python
623
21
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """ transpose last 2 dimensions of the input """ import torch.nn as nn class TransposeLast(nn.Module): def __init__(self, deconstruct_id...
a794aa0a9dda827a1306567166da372b2466ef8f7ff395e7ada01e4e89d93099
Python
624
21
from typing import NamedTuple class _REGISTRY_KEYS_NT(NamedTuple): X_KEY: str = "X" ATAC_X_KEY: str = "atac" BATCH_KEY: str = "batch" SAMPLE_KEY: str = "sample" LABELS_KEY: str = "labels" PROTEIN_EXP_KEY: str = "proteins" CAT_COVS_KEY: str = "extra_categorical_covs" CONT_COVS_KEY: str ...
3a0f9738a3587ec7d758ec64eb227dc913d26341f381e805b409ef9043443a9d
Python
626
14
# Copyright 2021 DeepMind Technologies Limited # # 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 or agr...
b4b807fd9c6e758632f6c1ba29f33d6ad888e6c08f25714ab8ac01e94715da4b
Python
626
18
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from .image_pretraining import ImagePretrainingTask, ImagePretrainingConfig from .image_classification import ImageClassificationTask, ImageCl...
ea5e21d57a801bff2354714f5cd31505141c1dfcec560360f4b4430c93f0d88c
Python
626
22
from types import SimpleNamespace import torch from gpn.embeddings import OneHotAuxEmbedding def test_one_hot_embedding_accepts_continuous_auxiliary_features() -> None: config = SimpleNamespace( vocab_size=6, n_aux_features=2, hidden_size=8, aux_features_vocab_size=None, ) ...
4a2a230abd95b9784125ba353c9c8ff03b91a89953adcc08339f6ba47cc92d6d
Python
628
27
import logging from pathlib import Path from ...monitor.log import wandb_log_dir log = logging.getLogger(__name__) def _load_wandb_artifact(name: str) -> Path: import wandb api = wandb.Api() if not name.startswith("novae/"): name = f"novae/novae/{name}" artifact = api.artifact(name) ...
bf175cd15816afad56a134859cd7205f804441435ac2de2bbffd92875781641d
Python
629
16
"""task × dataset compatibility for ``unet`` (see README §3.2).""" from __future__ import annotations from omegaconf import DictConfig def assert_compatible(cfg: DictConfig) -> None: task = str(cfg.task.name) ds = str(cfg.dataset.name) if task not in ("dynamic_segmentation", "dynamic_segmentat...
70a3f7ecec6db4a8cedaa3b835d1309bbc4ab36a90186c6f26a293291c08b5ab
Python
630
27
from typing import NamedTuple class _MODULE_KEYS(NamedTuple): X_KEY: str = "x" # inference Z_KEY: str = "z" QZ_KEY: str = "qz" QZM_KEY: str = "qzm" QZV_KEY: str = "qzv" LIBRARY_KEY: str = "library" QL_KEY: str = "ql" BATCH_INDEX_KEY: str = "batch_index" Y_KEY: str = "y" CON...
f2640f9d8cc4d33f03031d581fc3396a4fa1caeb3ff50fe5c41a01c8b8a5624e
Python
630
19
import torch from neurovfm.pipelines import load_encoder, load_diagnostic_head # 1. Load encoder + preprocessor from your HF repo encoder, preproc = load_encoder( "mlinslab/neurovfm-encoder", # your repo ID device="cuda" if torch.cuda.is_available() else "cpu", ) dx_head = load_diagnostic_head( "mlinslab...
41edd7562bc59c4ce7b0a017d4db77c8648e818f16918d71610e0170bb336981
Python
631
24
import pandas as pd import resource def calculate_mean_std(csv_path, col_name): # Load the CSV file data = pd.read_csv(csv_path) # Extract the column with predicted probabilities predictions = data[col_name] # Calculate mean and standard deviation mean = predictions.mean() std_dev...
b7aadf429d218fbfc38037ad0ea2c240e25f3db11d12b5424d5cb0d0b0617a98
Python
631
23
import pytest def pytest_addoption(parser: pytest.Parser) -> None: parser.addoption( "--run-published-models", action="store_true", default=False, help="run opt-in tests that download published Hugging Face checkpoints", ) def pytest_collection_modifyitems( config: pytest...
3e80fa01a4d182567670e2d0b19fdf3af19540a50b72228eed24d9e5976f3bec
Python
632
21
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="PCIst", version="0.1.15", author="Renzo Comolatti", author_email="renzo.com@gmail.com", description="Short library to calculate PCIst.", long_description=long_description, long_des...
7e3b71e230c160268f92c14416fcc3dfa205c13de9250be392d63b1d156fa4fa
Python
632
28
#!/usr/bin/env python # -*- coding: utf-8 -*- """Saves processed images""" import json from pathlib import Path import numpy as np import matplotlib.pyplot as plt from utils.types import MetaLike_ND2 def save_image_nd2_meta( out_dir: Path, name: str, img: np.ndarray, meta: MetaLike_ND2 ) -> None: """Saves...
c4587572afbb6d9f8c0326ed26aba738c5768b0cd65bbbd6404002fdfb797211
Python
632
19
import torch from neurovfm.pipelines import load_encoder, load_diagnostic_head # 1. Load encoder + preprocessor from your HF repo encoder, preproc = load_encoder( "mlinslab/neurovfm-encoder", # your repo ID device="cuda" if torch.cuda.is_available() else "cpu", ) dx_head = load_diagnostic_head( "mlinslab...
7ee47be79cc30b61cf7111de0d29f6fa5e15737c741145502e998ff7b657ba05
Python
633
14
# Copyright 2021 DeepMind Technologies Limited # # 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 or agr...
9fbad6d49a22e5687eba7f57058bbbbe75f6248997ca51f83cceb6071db65b1d
Python
634
14
# Copyright 2021 DeepMind Technologies Limited # # 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 or agr...