sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
2de420f03182155ca2f7431996eebdb40b48e44f301d733cad5a8fc68eae6ba9 | Python | 2,138 | 36 | """Deterministic linear backbone for DeepMapper, penalised logistic regression on the FULL feature set,
with no imagification and no multi-pass accumulation.
Why this exists (the methodological point): for a linear classifier the iterate-N-accumulate machinery is
redundant. (i) A flatten+linear model is permutation-eq... |
5e6df271bfd51e68fd4d234f8e5172221e97fe25a019216130e14ee95a2cb005 | Python | 2,139 | 69 | import pandas as pd
from .power_divergence import PowerDivergence
class GSq(PowerDivergence):
"""
G-squared test for conditional independence on discrete data.
This class is a thin specialization of :class:`PowerDivergence` with
``lambda_="log-likelihood"``. For the contingency-table construction, c... |
3b73fd2a8b5f308a561449accc627396e9231903c13e6ff748aa31e71afbb129 | Python | 2,141 | 55 | import torch.nn as nn
import torch.nn.functional as F
from models.pointnet2_utils import PointNetSetAbstraction,PointNetFeaturePropagation
class get_model(nn.Module):
def __init__(self, num_classes):
super(get_model, self).__init__()
self.sa1 = PointNetSetAbstraction(1024, 0.1, 32, 9 + 3, [32, 32,... |
cb986a969a35bcac3d367a1f53568844bc9673ca65334c6350c403367efd5aac | Python | 2,141 | 79 | import numpy as np
from voxcell import VoxelData
import sys
import flatmap_util as fmutil
norm_eps = 1e-12
flatmap_nrrd = sys.argv[1]
orient_x_nrrd = sys.argv[2]
orient_y_nrrd = sys.argv[3]
orient_z_nrrd = sys.argv[4]
mask_nrrd = sys.argv[5]
output_nrrd = sys.argv[6]
# load flat map
fmap_vd, fmsk = fmutil.load_fla... |
26792f5fc8a2b2f44648054f29b977039749955b12a544f520668e2c129486a3 | Python | 2,144 | 40 | import argparse
import numpy as np
def extract_peak_lengths(bed_file, type_, bl_file):
starts = np.loadtxt(bed_file, delimiter="\t", dtype=int, skiprows=1, usecols=1)
ends = np.loadtxt(bed_file, delimiter="\t", dtype=int, skiprows=1, usecols=2)
if bl_file is not None:
# blacklist reading specific ... |
8c310db29cc53c575f0991da418af973e116506b2a7ccdb59c125d5610151ee3 | Python | 2,144 | 61 | from pathlib import Path
from MRdataset.dicom import DicomDataset
base_dir = Path('/media/sinhah/extremessd/ABCD/active_series/non-recommended/vertical_subset/dicom')
ds_name = 'vertical_subset_ABCD' # 'ABCD' # 'wpc7888' # 'test_data'
dcm_root = base_dir / ds_name
# dcm_root = Path('/Users/Reddy/Downloads/dicom/... |
9d6ca6b902697acbcef9bd14c37e86881b70ba197d08f3ba38bf04d6db420df2 | Python | 2,144 | 53 | from __future__ import print_function, division
import os
import torch
import numpy as np
import pandas as pd
import scipy.io as io
import torch
#import torchvision
#from torchvision import transforms
#from PIL import Image
from torch.utils.data import Dataset
from torch.utils.data import DataLoader
import nibabel as n... |
9e39763683cf3b572a506bd3bbe918e2112725bf61670b57c4021efec678b339 | Python | 2,147 | 72 | import time
import torch
def evaluate(model, loader, loss_fn, ema, device):
if ema is not None:
with ema.average_parameters():
eval_metrics = run_eval(
model=model,
loss_fn=loss_fn,
loader=loader,
device=device,
)
... |
7e8e2ae6d9133a04e60007818ed36ed1e23c7fe47bd3cd5ff0b40756786bb11f | Python | 2,148 | 45 | """Where do the memory-defining ribosomal genes fall in HVG selection? Computes each gene's
highly-variable-gene rank (normalised dispersion) on the sorted CD4 data and records where the
ribosomal-protein genes land relative to the top-2000 cutoff. Feeds Fig2 (the honest mechanism:
HVG discards the genes that carry mem... |
c74f6bef1fa0bbe6d8d6da33063615be5cdd164f89bcb41128bbb1d39d9366a8 | Python | 2,149 | 70 | from tqdm import tqdm
import torch
from torchvision import transforms
from torch.utils.data import DataLoader
# Additional Scripts
from utils import transforms as T
from utils.dataset import DentalDataset
from utils.utils import EpochCallback
from config import cfg
from train_transunet import TransUNetSeg
class Tr... |
db4b6afc41d736721615d07e95c91e29f7145bb4b8ee2d28ff381900a1f218cd | Python | 2,149 | 71 | import argparse
from dival import TaskTable, DataPairs
from dival.measure import SSIM, PSNR
from dliplib.reconstructors import get_reconstructor
from dliplib.utils.helper import load_standard_dataset
from dliplib.utils.reports import save_results_table
def get_parser():
"""Adds arguments to the command"""
p... |
6c5a5bd263269cf6efbab9792a2888f20206508447181d59c5114a1a96270d62 | Python | 2,150 | 61 | """A server behind a static bearer token.
The simple end of MCP auth: the server never issues credentials, it only
verifies the token arriving in `Authorization: Bearer <token>`. No discovery,
no browser, no refresh — you provisioned the token out of band and the client
presents it.
uv run examples/mcp/auth_beare... |
e6bc03f20934aaf44224b514d3d4fa2bf447572d69346bcc46625829d6048051 | Python | 2,150 | 58 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders.parsers.audio import OpenAIWhisperParser
from langchain_community.document_loaders.parsers.docai import DocAIParser
from langchain_community.document_loaders... |
40488884a35ca8233de98c3525727005f0e8675408eefef4e90eeec4fc257a89 | Python | 2,151 | 69 | #! /usr/local/bin/python
#'#################################################################################
#'#################################################################################
#' Transfer learning using features from TCGA model
#'#######################################################################... |
bcf8b9b1d56b23a56c495130b619302ab370d8405d750cd1d92bd0de0d2e3a5f | Python | 2,151 | 55 | """Prompts for scoring the outputs of a models for a given question.
This prompt is used to score the responses and evaluate how it follows the instructions
and answers the question. The prompt is based on the paper from
Zheng, et. al. https://arxiv.org/abs/2306.05685
"""
from langchain_core.prompts.chat import ChatP... |
b168013096c73b8a8801d8bb3a0d1cd660927573518a29dfe0861de3466a715c | Python | 2,153 | 45 | #!/usr/bin/env python
import os
import tempfile
from ..constants.constants import HUMAN_SOMATIC_CHROMOSOMES, BASELINE_FREQUENCIES_URL
from ..utilities.utilities import untar
class Frequencies:
SUFFIX = ".frq"
@staticmethod
def validateDirectory(directory, chromosomes = HUMAN_SOMATIC_CHROMOSOMES, prefix... |
e3b14867981f7e33734511eea745d62d1817239debad70599546912ad63a4621 | Python | 2,154 | 64 | from collections.abc import Hashable
from pgmpy.structure_score.log_likelihood_gauss import LogLikelihoodGauss
class AICGauss(LogLikelihoodGauss):
r"""
AIC structure score for Gaussian Bayesian networks.
This score penalizes the Gaussian log-likelihood using a sample-size independent complexity term. Th... |
f9c5b76cfdd4e19ddc7ab207c85705b7b864558cba768b2bc05f7466d00737d6 | Python | 2,154 | 62 | from __future__ import division
import pickle
from io import StringIO
import numpy as np
import pandas as pd
from pymatgen.core.structure import Structure, Lattice
from pymatgen.io.lammps.data import LammpsBox
def dump_to_pmg_structure(dump_file, species_dict,
sort_index=True):
"""
P... |
2aa1c0704799020083f43601bde895016c571218c819d6c036c348ef531684a6 | Python | 2,155 | 55 | import torch.nn as nn
import torch.nn.functional as F
from models.pointnet2_utils import PointNetSetAbstraction,PointNetFeaturePropagation
class get_model(nn.Module):
def __init__(self, num_classes):
super(get_model, self).__init__()
self.sa1 = PointNetSetAbstraction(1024, 0.1, 32, 9 + 3, [32, 32,... |
1992f9384958c451d0f97883a2a5fd06e596f4f3c1e250b7ad92b87554411136 | Python | 2,156 | 73 | import matplotlib.pyplot as plt
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.reconstructors.dip import DeepImagePriorReconstructor
from dliplib.utils.helper import load_standard_dataset, set_use_latex
set_use_latex()
# load data
dataset = load_standard_dataset('ellipses')
test... |
d176bd791c57b3a8861b74d21b1b5cb68498853463a6d87834336dbf7fb7403e | Python | 2,157 | 69 | import pytest
import torch
from chroma.models.graph_design import GraphDesign, ProteinTraversalSpatial
@pytest.fixture
def model():
model = GraphDesign(predict_S_marginals=True, predict_S_potts=True)
model.eval()
return model
def test_sequential_decoding(model, XCS):
"""Test that the sequential and... |
668cacb8da0d5f3849d0e1e724e9ec50434cc2d02b169210ae10d1266470c5aa | Python | 2,159 | 53 | """
qupkake
Predict micro-pKa of organic molecules
"""
import sys
import versioneer
from setuptools import find_packages, setup
short_description = __doc__.split("\n")
# from https://github.com/pytest-dev/pytest-runner#conditional-requirement
needs_pytest = {"pytest", "test", "ptr"}.intersection(sys.argv)
pytest_run... |
c992ff09e97e8bbd7b7b77eccc9c9df2e0b9f4c18eb97cebc29ef557e5fe8886 | Python | 2,159 | 52 | import mxnet as mx
from nowcasting.config import cfg
from nowcasting.ops import reset_regs
from nowcasting.operators.common import grid_generator
class PredictionBaseFactory(object):
def __init__(self, batch_size, in_seq_len, out_seq_len, height, width, name="forecaster"):
self._out_typ = cfg.MODEL.OUT_TY... |
e677459914525a5b7bc491dc322ebcf43e91d65affa06ab2d713089dd1a21801 | Python | 2,159 | 55 | import unittest
from synister.gp import SynapseSourceMongo
from synister.synister_db import SynisterDb
from gunpowder import *
import os
class SynapseSourceMongoTestCase(unittest.TestCase):
def setUp(self):
self.db_credentials = os.path.join(os.path.abspath(os.path.dirname(__file__)) + "/../../db_credentia... |
c9a5b8141c2a0b486809a113744d358c0ac71a7bc51d5b07773a189181b8766c | Python | 2,162 | 71 | """Regression tests for chain-group tracing finalization on BaseException.
`trace_as_chain_group` / `atrace_as_chain_group` used to catch only `Exception`,
so a `BaseException` such as `asyncio.CancelledError` skipped both `on_chain_error`
and `on_chain_end`, leaving the group's run pending.
See https://github.com/la... |
f13b30fd58365d3cc5bdde03387497ecb6b68e617f7c16875e08494fea0ac323 | Python | 2,162 | 63 | from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
import torch.nn as nn
import torch.nn.functional as F
import torchvision.models as models
from torch.autograd import Function
from models.net_utils import Identity
class MLP(nn.Module):
def __init__(self, d, hidden_d, nr_classes):
super(MLP,... |
c68c3b51dfd9398ec1a8787f707003a601c569287d7951a0ca00db16f795c88d | Python | 2,163 | 72 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.cache import (
AstraDBCache,
AstraDBSemanticCache,
AzureCosmosDBSemanticCache,
CassandraCache,
CassandraSemanticCache,
FullLLMCache,
... |
5c2abfb7b9b2deab88dd0390e5c423f4ebf45be007db950286faad983ee7cee6 | Python | 2,164 | 70 | """Human message."""
from typing import Any, Literal, cast, overload
from langchain_core.messages import content as types
from langchain_core.messages.base import BaseMessage, BaseMessageChunk
class HumanMessage(BaseMessage):
"""Message from the user.
A `HumanMessage` is a message that is passed in from a ... |
b6e86b6e5e63a782c73e336f66b5e21f4147c7d8db262f85f0f4028e2d1e1f27 | Python | 2,165 | 73 | import matplotlib.pyplot as plt
from dival.measure import PSNR, SSIM
from dliplib.utils import Params
from dliplib.reconstructors.dip import DeepImagePriorReconstructor
from dliplib.utils.helper import load_standard_dataset, set_use_latex
set_use_latex()
# load data
dataset = load_standard_dataset('ellipses')
test... |
1f7f64a24d4e7198f03812564691faa7557365b610482c7df0c2006b15a0e7ef | Python | 2,166 | 85 | """Example02."""
# pylint: skip-file
import time
import numpy as np
import compare_models
import pandas as pd
keys = ['EMB1', 'EMB2', 'EMB3', 'EMB4', 'RidgeCV1',
'RidgeCV2', 'RidgeCV3', 'ARD', 'BRR', 'OLS', 'LassoCV',
'GroupRidgeCV1', 'GroupRidgeCV2']
sweep = [128, 1024, 16384, 65536]
# We are not i... |
5c8fae683e6e9bd23b0969a77333713c5cb387ad78ef1d50018c78dbdc4716a9 | Python | 2,166 | 68 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
ca6da7536b11fec08a2394033c3eac3d70c10e537569b82c2b8a4c03e256687a | Python | 2,166 | 75 | #!/usr/bin/env python3
import re
import subprocess as sp
import shlex
import sys
import time
import logging
logger = logging.getLogger("__name__")
logger.setLevel(40)
STATUS_ATTEMPTS = 20
jobid = int(sys.argv[1])
job_status = "running"
# WARNING this currently has no support for task array jobs
for i in range(STAT... |
3bc1ccb0e97ddb3318478ae765208b81efea77173c594807cf72ea127a777e9a | Python | 2,167 | 71 | #! /usr/local/bin/python
#'#################################################################################
#'#################################################################################
#' Train a neural network defined in Keras
#'################################################################################... |
2b724710191b2498c8f44a630158f5ca7e3970f4477d72214f91fc4b02205934 | Python | 2,168 | 62 | """
Source: https://github.com/zongyi-li/fourier_neural_operator
"""
import torch
import math
from timeit import default_timer
class GaussianRF(object):
def __init__(self, dim, size, domain_size, alpha=2, tau=3, sigma=None, boundary="periodic", device=None):
self.dim = dim
self.device = device... |
fbf5867e28bedcf1ddb8e23ae72c90b7f878623ac7d4e20932990f703f6ea7b9 | Python | 2,168 | 78 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import nibabel as nib
import numpy as np
import os
import sys
DESCRIPTION = 'Calculation of the Jacobi Determinant from a given warp field. Cornelius Eichner 2018'
# Hard-coded max jacobian determinant for siemens, taken from grad unwarp file of Human... |
0492037e4060b40b3bce5799253bbb5f2c6bd0bafc1dd07840380da891d4c9b0 | Python | 2,169 | 59 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
from pytorch_lightning.cli import LightningCLI
from pdearena import utils
from pdearena.data.cond_datamodule import CondPDEDataModule
from pdearena.lr_scheduler import LinearWarmupCosineAnnealingLR # noqa: F401
from pdearena.models.co... |
90f12ec267e51eabdb242afd0a86106b336a0bf0af2c65c7b5926c5ee0653be6 | Python | 2,169 | 73 | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 24 12:26:12 2020
@author: gritti
"""
import tqdm
import os
import glob
import shutil
###############################################################################
parent_folder = os.path.join('test_data','2020-09-22_conditions')
start = 0
dN = 5
combine_subfolders =... |
e71fc19debc3d7d0293520063d8bdcfecae89fb6555aef1dd830bf92f8032fee | Python | 2,171 | 65 | from collections.abc import Hashable
from pgmpy.structure_score.log_likelihood_cond_gauss import LogLikelihoodCondGauss
class AICCondGauss(LogLikelihoodCondGauss):
r"""
AIC structure score for Bayesian networks with mixed discrete and continuous variables.
This score penalizes the conditional-Gaussian l... |
15436940de3412eb0232e88a7aef84564bee123729fbfd2728195f5c89195a0b | Python | 2,172 | 69 | import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import numpy.ma
from ChipseqReport import *
class ReproducibilityBetweenSamples(DefaultTracker):
def __call__(self, track, slice=None):
set1 = track + "R1"
set2 = track + "R2"
stat... |
4b4bb474698f84e1cbf8ef9d8cd440fd062e7d745a86023467746526821f12cb | Python | 2,172 | 62 | import os
import gc
import warnings
from copy import deepcopy
from time import time
import numpy as np
from .openEphys import Binary
from .utils.mdaio import DiskWriteMda
N_CH = 32
# def walk_dict(dict_node, depth=0):
# for k in dict_node.keys():
# print(" "*depth + k)
# if isinstance(dict_no... |
784ef71b231c7a8aed773220502519cde8bf7c53e19dd6a214e675804c9c45e2 | Python | 2,174 | 66 | import logging
from zipfile import ZipFile
from ...exceptions import DoesNotExistException
from ...transforms import StaticTransform
from ...utils import convert_static_h5_dataset_to_folder, zip_dir
from ..base import FileTreeDatasetBase
logger = logging.getLogger(__name__)
class FileTreeDataset(FileTreeDatasetBase... |
bc744e0c6503c11aa20737787faee14e740d143756f6c4879defd83da108d8c5 | Python | 2,174 | 70 | """System message."""
from typing import Any, Literal, cast, overload
from langchain_core.messages import content as types
from langchain_core.messages.base import BaseMessage, BaseMessageChunk
class SystemMessage(BaseMessage):
"""Message for priming AI behavior.
The system message is usually passed in as ... |
cd1402d23526e60c9fbd5da639ca9597c2ba896b5ba3e14b289b90f6a6737e0c | Python | 2,179 | 47 | """Pack surface overlays for one FreeSurfer mapping and preserve its scalar outputs."""
from pathlib import Path
import shutil
import nibabel as nib
import numpy as np
FIELDS = ('thickness', 'curv', 'sulc', 'area.pial')
def write_stack(surf, hemi, destination, vertex_count, fields=None):
values = []
for fie... |
829b7b96e69dfce1afc64b0701227c03561ffa25f9cdac3a787538d67f5ab771 | Python | 2,181 | 74 | import os
import warnings
import pandas as pd
import pytest
from qupkake.mol_dataset import MolDataset, MolPairDataset
@pytest.fixture
def test_data_folder(tmpdir_factory):
# Create a temporary directory for test data
tmpdir = tmpdir_factory.mktemp("test_data")
return tmpdir
@pytest.fixture
def mol_da... |
b77898347a3666b61c0d2299359da2dcc18daed6cc9ad8354919ecf531a09087 | Python | 2,183 | 60 | import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
import matplotlib.image as mpimg
import os
import re
import random
import glob
def close_event():
plt.close() #timer calls this function after 3 seconds and closes the window
ica_dir='/project/4180000.19/multiRat/export/aromas_qa/'
ica_files ... |
d1abd2081295c73347dddf8e3cae5a9e779de88a1f9f4ebd4506ee985c9d7982 | Python | 2,183 | 67 | from torch.nn import ReLU, ELU, Identity, Tanh, Dropout, PReLU, GELU
try:
from torch.nn import SiLU
except ImportError:
pass
from torch.nn import Sequential as Seq, Linear as Lin, BatchNorm1d as BN
def MLP(channels, batch_norm=True, act='relu', bn_kwargs={}, dropout=0.0, dropout_position="right", batchnorm_pos... |
48f5e28aad43912eb47dcd1f75b4ba8035ef6bfa526bd403d98a56ff8ce84099 | Python | 2,184 | 61 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: skip-file
import sklearn.linear_model
import scipy.io
import matplotlib.pyplot as plt
import numpy as np
from embanded.embanded_numpy import EMBanded
# Load data from the 'example01.mat' file
data = scipy.io.loadmat('example01.mat')
# Split the data into predi... |
6eccc5fb3b5950fd81ce191dc3b3614b6d496d4bfa87230af707d8258d4c1c8c | Python | 2,187 | 84 | import logging
import os
import hydra
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from omegaconf import DictConfig, OmegaConf
from src import PROJECT_DIR
log = logging.getLogger(__name__)
@hydra.main(
config_path=os.path.join(PROJECT_DIR, 'configs'),
config_name='draw_loss_plo... |
c8f9c2066cc3cd1c99aa006df36962dc46902a5d12296872524b793769690075 | Python | 2,188 | 71 | #!/usr/bin/env python
'''
Script to interact with the existing conda installation.
It assumes that a conda environment is active, and will
run conda commands to:
* Get the install folder for conda
* Get a list of the existing environment
* Pin all packages in all conda environments
Refer... |
3e81ef5ef65a694eccee4416d34b378c8b70ad131d2c65e9d713144db8379b59 | Python | 2,189 | 65 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.document_loaders import (
AmazonTextractPDFLoader,
MathpixPDFLoader,
OnlinePDFLoader,
PagedPDFSplitter,
PDFMinerLoader,
PDFMinerPDFasH... |
99f3eb941a90cee552bcfa61bb3d4fcd0503874af44cdf9b7d199fc2cb9f5aac | Python | 2,189 | 77 | """
Utils specific to biological / nanopore data.
"""
def valid_cpg_mc_kmer(kmer):
"""
Determine if a k-mer is either unmethylated, or is methylated at a CpG site.
kmer : str
string k-mer (assume alphabet = 'ACGTM')
return : bool
whether kmer is valid or not
"""
if 'M' not in km... |
df1eb04c3dbbebdc15b958441dff74565d3dd23377deb32a99be50ae402c49e4 | Python | 2,190 | 69 | import pytest
import yaml
def pytest_addoption(parser):
parser.addoption(
"--runslow", action="store_true", default=False, help="run slow tests"
)
def pytest_configure(config):
config.addinivalue_line("markers", "slow: mark test as slow to run")
config.addinivalue_line("markers", "gpu_ci: ma... |
cad8fc228b800a3d89c14cfce7e04f10779646a16621797f281432d879b5804a | Python | 2,192 | 81 | import os
import pytest
from pycromanager import Acquisition, Core, multi_d_acquisition_events
import napari
# Skip tests in this module if it is running in GitHub Actions, which does not support NDViewer
# https://docs.pytest.org/en/7.1.x/how-to/skipping.html
# https://docs.github.com/ko/actions/learn-github-actions/... |
80bf70bb48014b5ab6103e24c43755f035157e50c5ec28b3390dfce3c95e5eab | Python | 2,193 | 90 | '''cgat_cwd2list.py - list directory contents
========================================
Purpose
-------
create a flat file that lists the current contents of the current
directory and its subfolders. Useful for when data is deleted due to
space contraints. If files need to be recreated then the difference
between th... |
01e08c412851994886598bf41880a464a6079e1102c90c8c4e674e5b12fab9cb | Python | 2,194 | 73 | import json
import logging
from collections.abc import Sequence
from typing import Any
from langchain_core.agents import AgentAction
from langchain_core.messages import (
AIMessage,
BaseMessage,
ToolMessage,
)
from langchain_classic.agents.output_parsers.tools import ToolAgentAction
_logger = logging.get... |
7b1fda519de73b412d3ebedd6fb023a5d8cfcc7dc1220a3cafde275a64ef666e | Python | 2,195 | 59 | # third party modules
import numpy as np
# pnabind modules
from .get_class_segmentations import getClassSegmentations
from .laplacian_smoothing import laplacianSmoothing
def smoothMeshLabels(edges, labels, num_classes,
threshold=16.0,
faces=None,
area_faces=None,
ignor... |
c84bf8a1adb2e0f77670c5b98e8e23fb4fad8d1338d699b3e31b9b2cc253ae4b | Python | 2,195 | 70 | from pytorch_lightning import Trainer
from pytorch_lightning.callbacks.base import Callback
import copy
from mlflow.tracking.client import MlflowClient
from optuna import Study
import optuna
import settings
def getXrefByDatabase(line, database):
fields = line.split('|')
for field in fields:
parts = fi... |
f5dd58849ccad83516892acfd3993b4f6bbdd7a18f21764ee9239cea9721e0c4 | Python | 2,196 | 62 | from typing import Any
from langchain_core._api import deprecated
from langchain_core.messages import BaseMessage, get_buffer_string
from typing_extensions import override
from langchain_classic.memory.chat_memory import BaseChatMemory
@deprecated(
since="0.3.1",
removal="2.0.0",
alternative="langchain.... |
f7575fe185aab8ed1f5226abced7593db9346a31a9b1617dd7f32d5752634f38 | Python | 2,196 | 51 | import os, math
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch.utils.data import TensorDataset
import plotting
from data import generate_recog_data, generate_recog_data_batch, GenRecogClassifyData
from net_utils import load_from_file
#%%
folder = '/Users/danil/My/School/Co... |
d7aa54e4c67616d2170eed87cd24defed22268ee3e38917a1ffa4825e7ced3ab | Python | 2,197 | 66 | import glob
import numpy as np
from scipy.stats import iqr
import matplotlib.pyplot as plt
from paths import TEST_DATA_PATH
test_data_path = TEST_DATA_PATH + "/baseline/"
ground_truth = np.squeeze(np.load(test_data_path + "baseline.npz")["oxygenations"])
wls = []
results = []
est_oxy = []
for filename in glob.glob(... |
f16b2452bf6450940c2dd48ee20991df2c4f0203ac828ce53d5528dee6d77894 | Python | 2,198 | 78 | # Copyright (c) DP Technology.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function
import yaml
import os
from addict import Dict
class YamlHandler:
"""handle yaml file
"""
... |
604f8fb3cb5647e2df944aef4a6af92d8e644e8c26768fe429ae277d79e6f5aa | Python | 2,200 | 82 | '''simple image data augmentation for training.
'''
import tensorflow as tf
IMG_KEY = 'image'
TARGET_KEY = 'targets'
def vertical_flip():
'''flip up down with p=0.5
'''
return _cond_op(tf.image.flip_up_down, 0.5)
def horizontal_flip():
'''flip left right with p=0.5
'''
return _cond_op(tf.... |
21bd70637b32a199908a192197bcc1f737a25478500d52803b96169aa2112d5b | Python | 2,201 | 61 | #%%
import os,csv,re
import pandas as pd
import numpy as np
import scanpy as sc
import math
import SpaGCN as spg
import stlearn as st
import argparse
dataset_dir = "spatial_prompt/"
dt_dir = "benchmark/"
from scipy.sparse import issparse
import random, torch
import warnings
warnings.filterwarnings("ignore")
import matp... |
5e0fc6fc49dc7a2f8c9e2a985bfdea27a6a5b12d37ae8a222dbabeefb05f32f6 | Python | 2,202 | 69 | import pandas as pd
from .power_divergence import PowerDivergence
class LogLikelihood(PowerDivergence):
"""
Log-likelihood ratio test for conditional independence on discrete data.
This class is a thin specialization of :class:`PowerDivergence` with
``lambda_="log-likelihood"``. In this implementati... |
b7d6b3f91d437b61dd884861a46c881689c2a98d3750092a31dbedb71d75ae13 | Python | 2,204 | 64 | """Chat Message."""
from typing import Any, Literal
from typing_extensions import override
from langchain_core.messages.base import (
BaseMessage,
BaseMessageChunk,
merge_content,
)
from langchain_core.utils._merge import merge_dicts
class ChatMessage(BaseMessage):
"""Message that can be assigned a... |
06cb4820908f03e2e6e1e548858671a4d23c8bb15528457da398cf8f332af314 | Python | 2,205 | 54 | # Copyright (c) MONAI Consortium
# 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 agreed to in writing, so... |
64074901de3731c7ffd7b6e952a562d818e98af00bdf5f08aa99e0865ae1c00d | Python | 2,207 | 44 | import mne
from config_FaceName import Results_data_path,Ids,MEG_data_path,group_name,MRI_data_path,stats_conds_list,stats_comparisions
from custom_functions import do_cluster_permutation_1samp_test
from functools import partial
import os.path as op
resample_rate=200
Ids.remove(18)
evks_all = {condtion: [] for condti... |
5711f752a8b992bf009970256b688078369e1966ca8ae19e8a8fff748454a458 | Python | 2,209 | 71 | import traceback
import os
from inspect import signature
import pickle
import datetime
def pickle_function_call_wrapper(func, output_dir='pickled_inputs'):
i = 0
os.makedirs(output_dir)
# pickle.dump({'args': args, 'kwargs': kwargs}, fh)
def wrapper(*args, **kwargs):
"""
Wrap th... |
9e2067b4ea9e21f602dc0ca0012e73d08c66c2f797b610cc304e83d04a1061d0 | Python | 2,209 | 80 | import os
import sys
import re
import types
import itertools
import matplotlib.pyplot as plt
import numpy
import numpy.ma
import Stats
import Histogram
from cgatReport.Tracker import *
from cpgReport import *
from cgatReport.odict import OrderedDict as odict
###########################################################... |
c82c002ea07948113c9811d9efad81bab501a17fb731221201ac5426499981ad | Python | 2,209 | 57 | #
import os
import torch
import numpy as np
import scanpy as sc
def adata_preprocess(adata_vis, min_cells=50, min_counts=10, pca_n_comps=200):
adata_vis.layers['count'] = adata_vis.X.toarray()
sc.pp.filter_genes(adata_vis, min_cells=min_cells)
sc.pp.filter_genes(adata_vis, min_counts=min_counts)
# ada... |
72e8f086644aeac8c59304539126dceb3e0e1e7df9d966eab4b6e8b6935e6b9b | Python | 2,210 | 63 | """
This script prepares the eQTL results (tensorQTL) for mash modeling.
"""
import argparse
import pandas as pd
from pyhere import here
def load_eqtl(filename):
df = pd.read_csv(filename, sep='\t', nrows=100,
usecols=["phenotype_id","variant_id","b_gi","b_gi_se"])
return pd.read_csv(filen... |
b8aaa9e6d22884a382d5409c0dfd7baf4969aeb7e1cbf045b78dfd637b821e41 | Python | 2,210 | 79 | #!/usr/bin/env python3
import pathlib
import pandas as pd
import tqdm
import argparse
from typing import Optional
import numpy as np
import yaml
def parse_arguments(
key: Optional[str] = None, stage: Optional[str] = None, method: Optional[str] = None
):
"""
Parses command line arguments
"""
pars... |
3d7960df2b63b8a494157c665210545586569ba70b317e59fdbfedde81e18b2d | Python | 2,212 | 71 | from langchain_core.utils.function_calling import convert_to_openai_function
from pydantic import BaseModel, Field
def test_convert_pydantic_to_openai_function() -> None:
class Data(BaseModel):
"""The data to return."""
key: str = Field(..., description="API key")
days: int = Field(defaul... |
dabaf609790832a8ee7b8a093d7d42765cc3c4aaaa2ab855e94a44c90a90346c | Python | 2,213 | 74 | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.nn.functional as F
from ....models.pytorch.ekan.src.efficient_kan.kan import KANLinear
class Stochastic(nn.Module):
"""
Base stochastic layer that uses the
reparametrization trick [Kingma 2013]
to draw a sample from a ... |
7564383ecc83c51bfdfc07e004cff6a3735d2706f731025d6ac149efdd67b0bb | Python | 2,214 | 85 | #!/usr/bin/env
"""
# Author: Kai Cao
# Modified from SCALEX
"""
import numpy as np
import torch
def onehot(y, n):
"""
Make the input tensor one hot tensors
Parameters
----------
y
input tensors
n
number of classes
Return
------
Tensor
"""
if ... |
b3148df27f9474e470fa94866942a5fbb570c8430283980f2020e2ee3bdc6cdd | Python | 2,214 | 40 | from datetime import datetime
from model import *
from data import *
data_directories = ["../DATA/b_cells_filtered_gene_bc_matrices/filtered_matrices_mex/hg19/",
"../DATA/cd4_t_helper_filtered_gene_bc_matrices/filtered_matrices_mex/hg19/",
"../DATA/cd14_monocytes_filtered_gene_... |
b0a3c3fdec61bf580cc1286a30d400a5d619b7443a8990afef6aef8ada92e162 | Python | 2,217 | 56 | import torch
import torch.nn as nn
from models import SpatialDescriptor, StructuralDescriptor, MeshConvolution
class MeshNet(nn.Module):
def __init__(self, cfg, require_fea=False):
super(MeshNet, self).__init__()
self.require_fea = require_fea
self.spatial_descriptor = SpatialDescriptor(... |
3b71fe8313063cb13a9d56b7bddea6eeb1157725417253645e23abceb7b6cf51 | Python | 2,218 | 57 | import pandas as pd
import cv2
import numpy as np
import os
from skimage.measure import label
from skimage.io import imread, imsave
"""
Résultats de quantification noyaux morts vivants et marqués KI-67/EDU.
"""
def generate_results_table(masks1, masks2, noyaux_positifs):
masks1_path = sorted([os.path.join(masks... |
6f2516693ec2990bd2993825e57f6d80e87e7c38c3057937cce6a68c05131e02 | Python | 2,218 | 66 | import numpy as np
import copy
from InitFunctions import gaussian
import matplotlib.pyplot as plt
hsv = plt.get_cmap('hsv')
def colors(n):
return hsv(np.linspace(0., 1.0, len(n)+1))
class weightClass:
parameters = {'save': False}
def __init__(self, neuronInstance1, neuronInstance2, synapticInstance, init... |
847b73c91b81556786f410fa66c778d0cd8890f30bab2828f6929f0e73d34a3e | Python | 2,218 | 59 | from copy import deepcopy
from itertools import chain
from unicore.optim.fp16_optimizer import pad_numel
import torch
class ExponentialMovingAverageModel:
def __init__(self, model, decay, init_param=None):
self.model_ema = deepcopy(model).float()
self.decay = decay
self.param = self.flatte... |
c208caca3f31bba11fc8ffead521ff09aa1e3c316a4ba73bc465a2a5ad61b228 | Python | 2,219 | 68 | #!/usr/bin/env python3
"""
Some code in this script was generated in part with ChatGPT, OpenAI's large-scale
language-generation model. Upon generating draft code, the author reviewed, edited,
and revised the code to their own liking and takes ultimate responsibility for the
content of this script.
"""
import sys
imp... |
a14b5069845aae1ee5c9e858cee047475db2f15bb0438bdac9c61dbc1e1c679a | Python | 2,220 | 56 | #!/bin/env python
"""
Illustrate how to combine a SMIRNOFF parameterized small molecule with an AMBER parameterized protein using ParmEd.
"""
#
# Load and parameterize the small molecule
#
# Load the small molecule
from openff.toolkit.utils import get_data_file_path
ligand_filename = get_data_file_path('molecules/t... |
26d0c2bfa3d28ec7540c2de3b57c960ea63c82c13f7f46443cc9fd259b52d021 | Python | 2,223 | 59 | """
from PhiSNet SE(3)-equivariant prediction of molecular wavefunctions and electronic densities
<https://arxiv.org/abs/2106.02347>
"""
import math
import torch
import torch.nn.functional as F
"""
IMPORTANT NOTE: The cutoff and the switch function are numerically a bit tricky:
Right at the "seems" of these function... |
b86f14fb66500fe0c2f148d8524715ff12efabd5c7b4a827496b85001e6c3397 | Python | 2,223 | 65 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: sorenaf
"""
# pylint: skip-file
import sklearn.linear_model
import scipy.io
import matplotlib.pyplot as plt
import numpy as np
from embanded.embanded_numpy import EMBanded
# Load data from the 'example06.mat' file
data = scipy.io.loadmat('example06.mat')
# ... |
b697fe75905b059169569106705c77d0db561427ec9f541b0e9babbcfb10dfd7 | Python | 2,226 | 56 | #!/usr/bin/env python
import asyncio as _asyncio
import json as _json
import os
import traceback as _tb
from datetime import datetime as _dt
import websockets as _websockets
def _run(local, remote):
async def _func(websocket, path):
msg = await websocket.recv()
try:
msg = _json.loads(... |
a43693706edbd9c211b2b774b13d2e8dceae6d839c88c75319dc63b8df5866ca | Python | 2,228 | 53 | """
adopted from: https://github.com/Bjarten/early-stopping-pytorch/blob/master/pytorchtools.py
"""
import numpy as np
import torch
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience=7, verbose=False, delta=0, path='checkp... |
a014b84acb21476563d9f9982832b3b4ff0a9a14b6c11586dfea9d0279881d46 | Python | 2,230 | 65 | """
PLIER uses singular vectors as a starting point for its optimization. This script uses
incremental PCA to calculate PCs to use as a starting point without running out of memory
"""
import argparse
import os
import numpy as np
import pandas as pd
from sklearn.decomposition import IncrementalPCA
from tqdm import tq... |
e3085bdf8c555736578cec18a5d37ed69d08ebc78d7b5784319571c819bf6511 | Python | 2,230 | 60 | import pandas as pd
import numpy as np
import argparse
def get_data(path,reference_path,label_path,save_path):
feature_data=pd.read_csv(reference_path+'/gene_all.txt',header=None)
feature_data=list(feature_data[0])
label=pd.read_csv(label_path,sep='\t')
sample=list(label['sample_id'])
feature_type=... |
8ce074906fa90063da635af42bbdd9d32402899fc1ce191a34f26189cd1c81cd | Python | 2,231 | 48 | import numpy as np
def signedVolume(a, b, c, d):
"""Computes the signed volume of a series of tetrahedrons defined by the vertices in
a, b c and d. The ouput is an SxT array which gives the signed volume of the tetrahedron defined
by the line segment 's' and two vertices of the triangle 't'."""
r... |
f5117780d0d3b51c7bdce91013271c28776c127163611c9fb369f57bf88f4cc6 | Python | 2,232 | 72 | """
This script summarized DE results using mash model.
"""
import session_info
import pandas as pd
from pyhere import here
from functools import lru_cache
@lru_cache()
def get_mash_eqtl(tissue, fdr):
# lfsr < 0.05 for significant eQTL by features
df = pd.read_csv("../../_m/lfsr.sex_interaction.txt.gz", sep='\... |
9dcf414f67dc63b6142b891816605854be7a31bd5ccc0ac61ffc8aab612f4c3f | Python | 2,233 | 65 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# pylint: skip-file
import sklearn.linear_model
import scipy.io
import matplotlib.pyplot as plt
import numpy as np
from embanded.embanded_numpy import EMBanded
# Load data from the 'example03.mat' file
data = scipy.io.loadmat('example03.mat')
# Split the data into pred... |
851b145292ecaedc2392ce4f89d0dae6f4438d98a0d3b73e3df4413b880336de | Python | 2,234 | 70 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 30 11:54:53 2021
@author: shni2598
"""
import firing_rate_analysis as fra
import numpy as np
#sfrom sklearn.linear_model import LinearRegression
from scipy.stats import sem
#import matplotlib.pyplot as plt
#%%
class fano_no_mean_match:
... |
f1bc69f57342691aa571c32c250bfd3f3ee8277fba3881e226d0d45ee539d46c | Python | 2,234 | 63 | """Library for parsing different data structures."""
from Bio.PDB.Chain import Chain
import numpy as np
from data import residue_constants
from data import protein
Protein = protein.Protein
def process_chain(chain: Chain, chain_id: str) -> Protein:
"""Convert a PDB chain object into a AlphaFold Protein instance... |
4be89c02aa3d9279b477af3e55ff67711d523fb0ff59cb52ab3b7976c6c10864 | Python | 2,235 | 64 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2023 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for d... |
4277891a758c30c4cc59ad41e271fc2461c3d370b918f58049a0eed45fba6f0d | Python | 2,236 | 64 | ####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See the file AUTHORS for detai... |
6dd89bc56a54f8a8cdb726ded5875157a49c4091fa5cb0ad2d4f66d62f4fb6b6 | Python | 2,237 | 79 | import torch.nn as nn
from e3nn.o3 import FullyConnectedTensorProduct, Irreps, Linear
from e3nn.util.jit import compile_mode
import hienet._keys as KEY
from hienet._const import AtomGraphDataType
@compile_mode('script')
class SelfConnectionIntro(nn.Module):
"""
do TensorProduct of x and some data(here attrib... |
335679ec2721c7038040eff40a2de712e316b59c52338596105083c3c4214577 | Python | 2,240 | 63 | # -*- coding: utf-8 -*-
####################################################################################
#
# STEPS - STochastic Engine for Pathway Simulation
# Copyright (C) 2007-2026 Okinawa Institute of Science and Technology, Japan.
# Copyright (C) 2003-2006 University of Antwerp, Belgium.
#
# See t... |
e0ce5319a68ca9cde7e87bd5d24a9b257e69eebf541a89140e6175ab1765b91a | Python | 2,241 | 75 | #! /usr/GenNet/env_GenNet/bin/python
#'#################################################################################
#'#################################################################################
#' Extract features from bio DNN network
#'######################################################################... |
eff86e46544becac93d90ea1e22dc22f529cf080c40927082f8cede0ce96f202 | Python | 2,243 | 66 | from typing import TYPE_CHECKING, Any
from langchain_classic._api import create_importer
if TYPE_CHECKING:
from langchain_community.retrievers import AmazonKendraRetriever
from langchain_community.retrievers.kendra import (
AdditionalResultAttribute,
AdditionalResultAttributeValue,
Doc... |
e2dd834f1a1f5fd060c67c31552d5c446ef931c6509dfd441a145d292661f148 | Python | 2,244 | 51 | import os.path as op
import numpy as np
import mne
from mne.coreg import Coregistration
from mne.io import read_info
from config_FaceName import MEG_data_path,MRI_data_path,group_name,Ids,bids_root
from mne_bids import BIDSPath
for subject_id in Ids:
subject = group_name+"%02d" % subject_id
print("processin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.