sha256 stringlengths 64 64 | language stringclasses 27
values | size int32 1 491k | lines int32 1 21.8k | content stringlengths 1 200k |
|---|---|---|---|---|
5c9abbe06c5d6746844072eb47f218d4bca0165db466f285ab1fe48899fa23bd | Python | 3,185 | 104 | import numpy as np
import torch
import torch.nn as nn
# mask feature function
def drop_feature(x, drop_prob):
drop_mask = (
torch.empty((x.size(1),), dtype=torch.float32, device=x.device).uniform_(0, 1)
< drop_prob
)
x = x.clone()
x[:, drop_mask] = 0
return x
# Domain-specific B... |
2eb57bc281413eae5c52a780109cdd5cbcf31f77afb75ec15de04ae4a321c974 | Python | 3,186 | 112 | from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
import tomlkit
from poetry.core.packages.dependency import Dependency
from poetry.core.packages.package import Package
from poetry.core.packages.project_package import ProjectPackage
from poetry.__version__ import __version__
from poe... |
0bde37dd170b314ba693f95478db30da124088cc92f15b260618baa784ec770d | Python | 3,187 | 79 | from model.builders.prostate_models import build_pnet2
task = 'classification_binary'
selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'params': {
'data_type': ['mut_important_plus_hotspots', 'cnv_del', 'cnv_amp'],
... |
65dd87c06b7682a76b10ef3ad63fd986b6f3dcea365f6f3303b0d5f4a87dd7b5 | Python | 3,187 | 99 | #!/usr/bin/env python3 -u
# 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 argparse
import os
import os.path as osp
import math
import numpy as np
import tqdm
import torch
import torch... |
dd37bee91dc6e7cb9e3275dc29e96d58eb32de8bb7c37ce71c120d16958ce675 | Python | 3,187 | 80 | import matplotlib.pyplot as plt
import pandas as pd
# Right now the plotting functions can only plot up to 4 tasks
# may need to adjust it... Need to figure out how to set optimal figsize
def plot_trainingcurves(tasks, results, figname=""):
all_losses = results['train_loss']
all_val_losses = results['val_loss... |
837e4123fc3c94cde28d1622a45410bb73da36605b9b03ef77def0de838769f0 | Python | 3,188 | 74 | import pydoc
import warnings
from typing import Union
from nnunetv2.utilities.find_class_by_name import recursive_find_python_class
from batchgenerators.utilities.file_and_folder_operations import join
def get_network_from_plans(arch_class_name, arch_kwargs, arch_kwargs_req_import, input_channels, output_channels,
... |
b8549254049a84bf6d3cdeb83e2e6c4fe09ae0489f2448a75fcaebea35f0ef5b | Python | 3,189 | 106 | import json
import pandas as pd
from src.data.behaviour_settings_io import (
load_behaviour_static_inputs,
save_behaviour_static_inputs,
)
def test_save_behaviour_static_inputs_valid(tmp_path):
# Define a valid DataFrame
test_df = pd.DataFrame({
'Behaviour Name': ['Walking', 'Running', 'Eati... |
68ec7e1d4eacb1c746a8ebf48b03d594727e7b4875709a79e23606e049e3ab12 | Python | 3,191 | 109 | import os
from pathlib import Path
from types import SimpleNamespace
from typing import Optional, Union
import yaml
from ..utils import available_cpu_count
from .punchcards import PunchcardSubset, PunchcardView
def merge_namespaces(a: SimpleNamespace, b: SimpleNamespace) -> None:
for k, v in vars(b).items():
if... |
c3bf77981567ca012af0ac7e62390b20f5a982c9dfcb59b01f758131d62886a7 | Python | 3,192 | 91 | # -*- coding: utf-8 -*-
import os
import gc
import argparse
import json
import logging
import random
import math
import random
from functools import reduce
import numpy as np
import pandas as pd
from scipy import sparse
import scipy.io as sio
from sklearn.metrics import accuracy_score, f1_score, confusion_matrix, preci... |
d151c5d5c9d0ecf41d1138ec7b4ca3e0bf43625614e1a3380fab4be677df55d5 | Python | 3,193 | 94 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import os
import numpy as np
import torch
import CBIG_pMFM_basic_functions as fc
import warnings
def CBIG_mfm_validation_desikan_main(gpu_index=0):
'''
This function is... |
6e57e98b846f116185076fef5c2a40df196f00ffa0343ee6697827de3c0215cf | Python | 3,194 | 87 | import os
import shutil
from pathlib import Path
from nnunetv2.dataset_conversion.generate_dataset_json import generate_dataset_json
from nnunetv2.paths import nnUNet_raw
def make_out_dirs(dataset_id: int, task_name="ACDC"):
dataset_name = f"Dataset{dataset_id:03d}_{task_name}"
out_dir = Path(nnUNet_raw.rep... |
255a189cc0273b1fb164da723d756187d2fbab6569609047af8f36fe5d50846e | Python | 3,196 | 79 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.use("TkAgg")
import pandas as pd
from cal_KL_div import calculate_kl_divergence
def compute_cdf(data):
unique_values, counts = np.unique(data, return_counts=True)
cdf = np.cumsum(counts) / len(data)
return unique_va... |
212b4ceac6feb10f235171dd12a5ac510c0eb7daed87768af2e1bdb27ab9a34c | Python | 3,197 | 100 | def binary_search(
adata, n_clust_target,
method="louvain",
resolution_boundaries=None,
resolution_init=1,
resolution_update=2,
num_rs=1e2,
tolerance = 1e-3,
seed = 2023,
**kwargs,
):
"""
Uses binary search to find the resolution parameter that results in the target number of... |
8c36e327affc8c35022acfd851a092796fb70d70d038fd6a0b40c8350ca00d5c | Python | 3,197 | 104 | from __future__ import annotations
import re
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.core.packages.dependency import Dependency
from poetry.repositories.exceptions import PackageNotFoundError
from poetry.repositories.link_sources.html import HTMLPage
from poetry.reposito... |
d896787a8eb6898a4f8d59738662e4aef1ae2f1d033a2135cca08965a4ee3816 | Python | 3,198 | 85 | import torch
import numpy as np
import unittest
from fairseq.modules.rotary_positional_embedding import apply_rotary_pos_emb
from fairseq.modules import RotaryPositionalEmbedding
class TestRotaryPositionalEmbedding(unittest.TestCase):
def setUp(self) -> None:
self.T = 3
self.B = 1
self.C =... |
11dd3f78a7ba2c40c7d127c1cd786877e9565316dbea53628afb8d8926e57161 | Python | 3,200 | 71 | """
============================================================================
fig03or_perfusion_channel_split_merge__dmso_control_77764998.py — Fig 3r perfusion
============================================================================
What this script does: Jython for ImageJ: 3-channel deinterleave/merge. One ca... |
1ba279d7713d2d72ffa94dd4c4be793d0f565d513ab0dc5e6ae8192cfc72ef9a | Python | 3,200 | 101 | from gutils import *
import glob
import pandas as pd
import os
import itertools
def Link_Graph(outputdir):
path0 = os.path.join(os.getcwd(), outputdir)
#' import processed data
files1 = glob.glob(path0 + "/ST_count/*.csv")
files1.sort()
count_list = []
for df in files1:
print(df)
... |
9d556a58e39ef6d1f60b0b6bdc90649488fc15618958688ad5489f66daf2a3d8 | Python | 3,200 | 71 | """
============================================================================
fig03or_perfusion_channel_split_merge__imagej_macro_77764998.py — Fig 3r perfusion
============================================================================
What this script does: Jython for ImageJ: 3-channel deinterleave/merge. One ca... |
f85c47edd05af0f8420a6dd01901050664d499a3a71127c15f8e252e8f1509f1 | Python | 3,200 | 96 | import glob
import os
from mdt.lib.nifti import nifti_filepath_resolution
from mdt.utils import split_image_path
def get_shortest_unique_names(paths):
"""Get the shortest unique map name between two or more nifti file paths.
This function is useful when loading multiple maps like for example ``./foo.nii`` a... |
91b14178f4abf41557a1183ce92e76f380624e7031c4811199043c1438a6be14 | Python | 3,201 | 78 | import torch
from torch import nn
from ..downstream_module import DownStreamModule
class LDotProduct(DownStreamModule):
"""
contact predictor with attention
"""
def __init__(self, backbone_args, backbone_alphabet, num_classes=1, class_embed_dim_out=512, symmetric=False, depth_reduction="mean"):
... |
e9687329c96c3a9517243a9be77a3218312abf9845cfdfb59317bd669be443de | Python | 3,202 | 102 | import argparse
from pathlib import Path
import yaml
from BLPlot.PlotAUPRC import PlotAUPRC
from BLPlot.PlotAUROC import PlotAUROC
from BLPlot.PlotSummaryHeatmap import PlotSummaryHeatmap
from BLPlot.PlotEPRHeatmap import PlotEPRHeatmap
from BLPlot.PlotEPR import PlotEPR
def parse_args():
'''
:return: an ar... |
7a2a929e2943d6b89997825671803dfaf677f0e29ba82e87c30e434a9770066a | Python | 3,203 | 104 | from typing import Sequence
import numpy as np
import torch
from scgpt.data_sampler import SubsetSequentialSampler, SubsetsBatchSampler
from scgpt.utils import set_seed
set_seed(1)
def _check_reorder(a: Sequence[int], b: Sequence[int]) -> bool:
"""Check if a is a shuffled version of b."""
if len(a) != len(... |
d572f8313e182735131b177f181f56d042ba16719ab6fe0289bab36d7a3a17eb | Python | 3,206 | 81 | # Copyright (C) 2025 ETH Zurich, Moritz Thürlemann, and other AMP contributors
import json
import os
import numpy as np
import yaml
from pathlib import Path
def write_qm_mm_json(path:str):
parameters = {}
parameters["qm_zone_resnames"] = ["UNL"]
parameters["mm_zone_resnames"] = ["HOH"]
with open(pa... |
cf30967dd7f998f0b7ae4e08ff012a64a64dd4d2d0aad9a26fd3761f0d9a5f01 | Python | 3,207 | 52 | import numpy as np
from kanfood.split import stratified_group_kfold
from kanfood.preprocess import Preprocessor
from kanfood.features import PLSFeatures
from kanfood.models import build_model, front_end_components
from kanfood.metrics import regression_metrics
# Documented hyperparameter grids, selected by 3-fold inne... |
6cd55dc7540f7eebc2605bbc9473a5750a4fd1b4bed76d0f3dde90e4999f74af | Python | 3,208 | 118 | import os
import logging
class Logger:
"""
Attributes
----------
exp_name : str
Name of the experiment.
log_dir : str
Directory where the log file is stored.
format_str : str
Format string for the logger.
level : int
Level of the logger.
Methods
---... |
37cf78e3962ab40fa1bf8fffeafb5aa8e1ccdc50a1b292cd5b4daeed4a6b43b1 | Python | 3,209 | 87 | import argparse
import os
import re
from copy import deepcopy
from args import _add_only_observable_args, add_transferable_args
from evaluate_observable import main as evaluate
from transferable import main as finetune
from oneqmc.entrypoint import load_training_config
def main(args_finetune):
args_eval = deep... |
5625a9f5bb63fe34e3708be2c0977396967e62a9952f72675ed2e76b7ea3859a | Python | 3,209 | 85 | import pytest
from torch.nn import Linear
from scvi.data import synthetic_iid
from scvi.external import POISSONVI
def test_poissonvi():
adata = synthetic_iid(batch_size=100)
POISSONVI.setup_anndata(adata, batch_key="batch")
model = POISSONVI(adata)
model.train(max_epochs=1)
model.get_latent_repre... |
9f025ebc0ce8ae46ea8b9bb4f8f32c1bd1146cb911f554bf9422386b743a8d2d | Python | 3,210 | 81 | import numpy as np
from sklearn.decomposition import KernelPCA
def get_2d_projection(activation_batch):
# TBD: use pytorch batch svd implementation
activation_batch = activation_batch.copy()
activation_batch[np.isnan(activation_batch)] = 0
projections = []
for activations in activation_batch:
... |
c4af118c7cbe25a5cb729d6675a81d6630ff47d9210da5b5302b1e293cc424af | Python | 3,211 | 76 | # 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 fairseq.models import register_model, register_model_architecture
from fairseq.models.multilingual_transformer import MultilingualTransfo... |
c91fc7f211e616b297280e42e2c344b6a6978ee2e6a759c3b9a6860134493240 | Python | 3,212 | 89 | import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import AMap
from pyecharts.globals import ChartType
FAKE_API_KEY = "fake_application_key"
AMAP_API_PREFIX = "https://webapi.amap.com/maps?v=2.0"
TEST_LOCATION = ["London"]
TEST_VALUE = [1]
class TestAMapChar... |
d4e66952b38440736f839621cf13165d3af71c805878f2fe15e98d601f789cca | Python | 3,212 | 90 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 22 10:31:52 2024
@author: vbp
Figure S2B: anticipatory (CS-, CS+) and consummatory lick rate, per animal.
Data can be downloaded here: https://doi.org/10.17605/OSF.IO/DV724
"""
import numpy as np
import pandas as pd
import seaborn as sns
import m... |
92472fbe2ec4ccd39146583fe3a1d126833636d75e26794e06c42069682d8c18 | Python | 3,214 | 72 | __author__ = 'heroico'
import os
import logging
import gzip
import ZScoreCalculation
import GWASUtilities
import Normalization
import Exceptions
def chooseZscoreSchemeFromFiles(folder, beta_contents, covariance_entries, weight_db_logic):
if len(beta_contents) == 0:
raise Exceptions.ReportableException("N... |
f991ab12cbc8b6133772d08580bb021e2f083cd7581f20ce8eadc696c2b9d931 | Python | 3,214 | 69 | import numpy as np
from numpy import matlib
def Div_KL(P,Q):
"""
dist = KLDiv(P,Q) Kullback-Leibler divergence of two discrete probability
distributions
P and Q are automatically normalised to have the sum of one on rows
have the length of one at each
P = n x nbins
Q = 1 x nbins or n... |
04f4fc955d5bb871ca8ea201f1749d10ec78e135962ccb1cfc03073d56aa27db | Python | 3,215 | 100 | from typing import Any, Dict
import omegaconf
import torch
from torch.nn import functional as F
from .encoders import DimeNetppEncoder
class CrystGNN_Supervise(torch.nn.Module):
"""
GNN model for fitting the supervised objectives for crystals.
"""
def __init__(self, cfg) -> None:
super().__i... |
0f67cf617c6563eb5b26b949f3f142cec28e901fbdb91f3187f4a887d699f274 | Python | 3,215 | 62 | """CPU: python .../run_trainref3d_smoke.py
GPU: python .../run_trainref3d_smoke.py --gpu [--dataset authorized_dataset.zip]
Synthetic smoke data checks mechanics, never performance/generalizability.
"""
import argparse
import json
from pathlib import Path
import sys
import tempfile
import zipfile
sys.path.insert(0, st... |
cd9cf720c47b5141177bfd57769989103281b88ba2290698090095e84d4bdbc6 | Python | 3,217 | 86 | import torch
import torch.nn as nn
from pathlib import Path
import sys
from utils import DistanceFunction
class FieldComputation:
'''
This class constructs the displacement and phase fields from the NN outputs by baking in the
Dirichlet boundary conditions (BCs) and other constraints.
net: neural net... |
115997720311013738ebc8885a9bf791a5b50f20af7bec5826f11e28e8fcd8b1 | Python | 3,218 | 96 | # 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... |
a990a11f07d7a6e4c95ae0f5185cffaaae71ec71304a3733ec4fc1e5bb82c59b | Python | 3,218 | 68 | from DataLoader import load_sparse_indices, load_data
from Train import train_omics_net
from Eval import eval_omics_net
import torch
import numpy as np
from argparse import ArgumentParser
parser = ArgumentParser(description="Train omics data")
parser.add_argument("REP_ID", type=int, default=1)
parser.add_ar... |
d94b947518e4e3c2c71234374e6203cc2ff333565feaa9e44c7030a676fd2936 | Python | 3,218 | 85 | import matplotlib.pyplot as plt
import numpy as np
from matplotlib.collections import LineCollection
from scipy import sparse
import loompy
def radius_characteristics(ds: loompy.LoomConnection, out_file: str = None) -> None:
radius = 0.4
if "radius" in ds.attrs:
radius = ds.attrs.radius
knn = ds.col_graphs.KNN
... |
e840448a330d5d694192445ad7853b504f69e7218416d7a33e3b6661d0c5073a | Python | 3,219 | 117 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Visually compares automated vs. manual cell counts"""
import os
from typing import Optional
import numpy as np
import matplotlib
matplotlib.use("Qt5Agg")
import matplotlib.pyplot as plt # noqa E402
from matplotlib.axes import Axes # noqa E402
from utils import Ima... |
0cf93c687aeb27ad3cb26f0811229c2ca71726848f9a32b6d9e8ac842c4c0b75 | Python | 3,220 | 83 | import random
import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import Bar3D
from pyecharts.faker import Faker
class TestBar3DChart(unittest.TestCase):
@patch("pyecharts.render.engine.write_utf8_html_file")
def test_bar3d_base(self, fake_writer):
... |
b2ba18faeb8fcd3899f33b16b87535cd8aededbb22190e707fe5e5aa5e27e610 | Python | 3,224 | 54 | from typing import Union, List, Tuple
from torch import nn
from nnunetv2.experiment_planning.experiment_planners.default_experiment_planner import ExperimentPlanner
from dynamic_network_architectures.architectures.unet import ResidualEncoderUNet
class ResEncUNetPlanner(ExperimentPlanner):
def __init__(self, dat... |
3fca9fe20bc7a676247a0ac6686dc1c23514601ce758b9fb85a2bd43c4631305 | Python | 3,225 | 91 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import numpy as np
import torch
import os
import scipy.io as sio
import CBIG_pMFM_basic_functions as fc
def CBIG_mfm_validation_desikan_main(gpu_index=0, weight=0.5):
'''
... |
9e4ab5c01d5e0e965675a50aba3174996fcea16137b595ede5c2051027b99274 | Python | 3,225 | 94 | import cv2
import numpy as np
def find_min_avg_gray_region(image, region_size=32):
# Ensure the image is in grayscale
if len(image.shape) == 3:
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray_image = image
# Get the dimensions of the image
height, w... |
3aae1ff9b64392e0d5c50611c78426cc5b6f8b933b7281226f8f8a91be80cfb7 | Python | 3,227 | 130 | """FISSA functions to handle image and roi objects and return the right format.
If a custom version of this file is used (which can be defined at the
declaration of the core FISSA Experiment class), it should have the same
functions as here, with the same inputs and outputs.
Authors:
- Sander W Keemink <swkeemink... |
8fc6141eb63e6a6e031a7ff67ce93634c5b6b3c1d65c623c798aa249cf34fa1a | Python | 3,227 | 83 | from argparse import ArgumentParser
from pathlib import Path
import re
import nibabel as nib
import numpy as np
import pandas as pd
from scipy.stats import spearmanr
def parse_args(default_threshold):
parser = ArgumentParser()
parser.add_argument("fc_dir", type=Path)
parser.add_argument("atrophy_dir", ty... |
db017d53ea136c605a7b4888921934c9e1a970b587f820b9784f0d37ef008421 | Python | 3,227 | 99 | from typing import Dict, Tuple, List, Any
import torch
import torch.nn as nn
import math
def fetch_pkm_value_parameters(
module: nn.Module,
) -> Tuple[List[nn.Parameter], List[nn.Parameter]]:
params: List[nn.Parameter] = []
for m in module.modules():
if isinstance(m, PKM):
params.appen... |
d70c9fe08aa6702fb3ec6c2bb18ed6019e57fe13881eb6bf544956638d85a0d5 | Python | 3,228 | 80 | from model.builders.prostate_models import build_pnet2_account_for
task = 'classification_binary'
selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'params': {
'data_type': ['mut_important', 'cnv_del', 'cnv_amp'],
... |
ff994ad92a1221a6c8182e20fdbf40f6e0e46bc151e493cd293bb866ee738bcb | Python | 3,228 | 85 | # 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 collections.abc import Collection
from dataclasses import dataclass, field
from typing import List
from omegaconf import II
from fairse... |
9348903d55c51da41af67865f92a6ec3f374050e1cd5f208f155c217e05143f6 | Python | 3,229 | 40 | import pandas as pd
from apiadapters.ncbi.parser import is_scanned
from brenda_references.brenda_references import preprocess_labels
def test_is_scanned():
xml = """<jats:body xmlns:jats=\"https://jats.nlm.nih.gov/ns/archiving/1.3/\">\n <jats:supplementary-material content-type=\"scanned-pages\" position=\"flo... |
9d72807ac86e857599f1e9fa3202ce2065c08e1138e85fa8105edd99426cbcf5 | Python | 3,230 | 79 | from model.builders.prostate_models import build_pnet2
task = 'classification_binary'
selected_genes = 'cancer_genes.txt'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'params': {
'data_type': ['mut_important', 'cnv_del', 'cnv_amp'],
'drop_AR': False,
... |
2776342445f69dee8107d682ef0450d5ae3c81ec1473e6b03369cca35e0c3f03 | Python | 3,231 | 90 | import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
class TestPieChart(unittest.TestCase):
@patch("pyecharts.render.engine.write_utf8_html_file")
def test_pie_base(self, fake_writer):
c = (
... |
31f92182900725c0bede5fe2643410603df4c386e97b6f7ef2cea4906c62c10c | Python | 3,231 | 73 | import numpy as np
import pandas as pd
import scipy.sparse as sp
import torch
from sklearn.neighbors import NearestNeighbors
def cal_spatial_net(adata, n_neighbors=5, verbose=True):
"""Construct the spatial neighbor network."""
if verbose:
print("------Calculating spatial graph...")
coor = pd.Data... |
5201c46484213818b7b32729abf9547866274997d206be1f98459082010715b1 | Python | 3,233 | 112 | from __future__ import annotations
import pytest
from poetry.core.constraints.version import Version
from poetry.factory import Factory
from poetry.repositories import Repository
from tests.helpers import get_package
@pytest.fixture(scope="module")
def repository() -> Repository:
repo = Repository("repo")
... |
fc5fd3655067b16fb0d4bfc2d9b8c6cf71b6409ae037c1290e58449434115ca2 | Python | 3,233 | 91 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import numpy as np
import torch
import os
import scipy.io as sio
import CBIG_pMFM_basic_functions as fc
def CBIG_mfm_validation_desikan_main(gpu_index=0, weight=0.5):
'''
... |
ae7c4196bbee65d624d40fc95e557e462c86650ea758387e8094551ec448eadb | Python | 3,234 | 91 | """Run SIESTA SZP single-points on the 93-perovskite validation subset.
Parallelism: 6 jobs × 2 OMP threads each (= 12 cores total). Each SIESTA
run produces (E_eV, scf_converged, wall_time_s, kmesh). We persist
incrementally so a partial run can be inspected and resumed.
Usage:
python data/perovskites/run_siesta... |
d8feab420847c7bd77a1f8822f831f7ee868df8ed92ea795c07e165dd8671732 | Python | 3,234 | 117 | """Hack to add per-session state to Streamlit.
Usage
-----
>>> import SessionState
>>>
>>> session_state = SessionState.get(user_name='', favorite_color='black')
>>> session_state.user_name
''
>>> session_state.user_name = 'Mary'
>>> session_state.favorite_color
'black'
Since you set user_name above, next time your ... |
acd98e08290f079da52b8e4c08c0a3e957d0361bdfd564b788a2c804c7cd90e5 | Python | 3,235 | 70 | import scanpy as sc
import sys
import os
import sys
import pandas as pd
import scanpy as sc
from scipy.sparse import csr_matrix
from nicheformer.data.constants import DefaultPaths, ObsConstants, UnsConstants, VarConstants, AssayOntologyTermId, SexOntologyTermId, OrganismOntologyTermId, TissueOntologyTermId, Suspensi... |
63cdb5780f55d036f2b1e36cfd5cb5ebaa5eec8159ba4d4eb3f4838436b200d6 | Python | 3,236 | 73 | """Thin wrapper for the internal libjaccard C library."""
import bpreveal.internal.libjaccard as lj
from bpreveal.internal import constants
def slidingJaccard(importanceScores: constants.IMPORTANCE_AR_T,
cwm: constants.MOTIF_FLOAT_AR_T) -> \
tuple[constants.MOTIF_FLOAT_AR_T, constants.MOTIF... |
3ea707dae178624b27120f444d3e03f313029c3c01c28de4ddf8bdcef1c9add9 | Python | 3,237 | 105 | """
Learnable RAG-GNN model with end-to-end training in PyTorch.
Implements the trainable RAG-GNN framework with:
- Learnable GCN encoder with gradient-optimized weight matrices
- Learnable retrieval projection (two-layer MLP)
- Gated fusion mechanism
- Three-phase curriculum training
"""
import numpy as np
import to... |
fa99837324515ba827d667a4cb2d4b35d718545145a4f8b3c430dbc48dfc1a10 | Python | 3,238 | 83 | """Modules that perform neural network convolutions."""
import torch
from torch.nn import functional as F
# NOTE: added 2023-03-04
# in this class, we detect when one extra pixel should be added on the bottom or right
# and specifically pad those, see line 75, ``if rows_odd or cols_odd:``.
class Conv2dTF(torch.nn.Co... |
f5e8e7b1199522618d31c25b04278be5e67729833c6c53d31c0df6ae6d11642e | Python | 3,239 | 109 | # Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
import sys
import os
sys.path.insert(0, os.path.abspath('../..'))
# -- Project information -------------------------... |
475b4d7f60faf97a138ebdab798bc9c2e49a7720f837b2c30002cea38bede072 | Python | 3,241 | 86 | import os
import tempfile
import unittest
from pathlib import Path
from GMXMMPBSA.utils import remove
class CleanupTest(unittest.TestCase):
def test_clean_removes_default_csv_outputs_with_summary_outputs(self):
with tempfile.TemporaryDirectory() as tmpdir:
root = Path(tmpdir)
for ... |
fd3fc7bc2fa5ee69a726732cd5fb86f513d3009eb0eefae345ef905951b78665 | Python | 3,241 | 86 | import loompy
import numpy as np
import logging
from cytograph.preprocessing import Normalizer
class BinaryDifferentialExpression:
def __init__(self, sig_thresh: float = 0.001, fnnz: np.ndarray = None, mu: np.ndarray = None) -> None:
self.sig_thresh = sig_thresh
self.fnnz = fnnz
self.mu = ... |
8f322d2cdcc1c5a6634783ed324e01e0b6fe41419214282f438074124d39e4a3 | Python | 3,242 | 100 | #
# Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with
# Sandia Corporation, the U.S. Government retains certain rights in this software.
#
# See LICENSE for full license details
#
import os
import numpy as np
import cv2
from imagenet_path import imagenet_val_path
#... |
98efc9e9e4ce49a7c09833d1befec4d422852183b67b1419c34c9bba478a79ed | Python | 3,242 | 90 | import gzip
import logging
import re
import io
import numpy
import pandas
from .. import Exceptions
def gwas_data_source(path, snps=None, snp_column_name=None, skip_until_header=None, separator=None, handle_empty_columns=False):
s = {}
def _ogz(p):
return io.TextIOWrapper(gzip.open(p, "r"), newline=""... |
13d005f994fd43893d60519d2003191842ab9233169008b82958388aee7d8345 | Python | 3,243 | 105 | """A deposit recorded only in `designations` must still reach the bridge.
`surface_forms.strain_forms` indexes `cultures` and `designations` alike, so
a strain record naming its deposit only in `designations` — with a *different*
strain record naming the same deposit through `cultures` — must produce a row
for each: t... |
58e2fab6c13efe2d06c81a963a55b071b9d66942d178215014dfe8712f6bbd6a | Python | 3,243 | 102 | # @license
# Copyright 2016 Google 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 or agreed to in... |
4ff5202012fe46055b2be9d0907e1ea9ad2aa485784cc7d38455599312b6963c | Python | 3,245 | 99 | import pandas as pd
INPUT_PATH = "__MS_GEO_ROOT__/Filtered_Naive_Methylation_MS_Datasets_with_Tissues.xlsx"
OUTPUT_PATH = "__MS_GEO_ROOT__/Methylation_Target_Datasets.csv"
ADDITIONAL_PATH = "__MS_GEO_ROOT__/Additional_Methylation_Candidates.csv"
def contains_any(text: str, terms: list[str]) -> bool:
return any(... |
01f8d4a9cf5dd23a7d65d3e9c06f83861731354f673f4257051bee70f7730b8a | Python | 3,247 | 99 | import numpy
import logging
from numpy import dot as _d
from .. import MatrixManager
from .. import MatrixManager2
from .. import Utilities
from ..misc import Math
class GenotypeAnalysisContext(object):
def __init__(self, metadata, dosage, model_manager, standardize=False):
self.metadata = metadata
... |
0d97b479891b203b50a0809a99fb19afbe16eda5308336bcad342fdc9f36766f | Python | 3,248 | 103 | import torch.nn.functional as F
import torch.nn as nn
import torch
class Flatten(nn.Module):
# Use after nn.AdaptiveAvgPool2d(1) to remove last 2 dimensions
def forward(self, x):
return x.view(x.size(0), -1)
class Concat(nn.Module):
# Concatenate a list of tensors along dimension
def __init_... |
54ec056a233d11772c075870cb12a98361063c2ff5a9a707b971b73b38ca1f84 | Python | 3,248 | 87 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join
import random
import os
import numpy as np
import nibabel as nib
from batchgenerators.transforms.abstract_transforms import Compose
from batchgenerators.dataloading.multi_threaded_au... |
bbd4605b24d97ba49afeac37647178330bbed52450bcc502fa269326b8c9e7ea | Python | 3,250 | 75 | import SimpleITK as sitk
import shutil
import numpy as np
from batchgenerators.utilities.file_and_folder_operations import isdir, join, load_json, save_json, nifti_files
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
from nnunetv2.paths import nnUNet_raw
from nnunetv2.utilitie... |
82551918aca83d25719a0de432415d995d4751f6a37bf2b96b22d2b59ab4d901 | Python | 3,251 | 91 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import numpy as np
import torch
import os
import scipy.io as sio
import CBIG_pMFM_basic_functions as fc
def CBIG_mfm_validation_desikan_main(gpu_index=0):
'''
This func... |
a190a41afc1e2617f2c7a3c8d345aaf60a8b1dc55e984fdcabef1655f34ff53e | Python | 3,251 | 81 | from model.builders.prostate_models import build_pnet2
task = 'classification_binary'
selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'params': {
'data_type': ['mut_important', 'cnv_del', 'cnv_amp'],
... |
3951b02876769156bfe401f002c3bf401a5816dba4491996d5040bbd1ba015f7 | Python | 3,255 | 84 | """Ablation: does dropping 3-figures recover 4/4 isomer ranking on the
expanded training set? The C3H6O group (propanal vs propylene-oxide,
ΔE = 93 meV) is the failure mode of the full model."""
from __future__ import annotations
from collections import defaultdict
from pathlib import Path
import numpy as np
from sc... |
26c7041be541fb774e221d6cac3cdf435a557681b4b9b6b7caa86cba2241bbc7 | Python | 3,257 | 118 | from celltype_ibl.utils.c4_data_utils import get_c4_labeled_dataset
import celltype_ibl.models.mlp_classifier as mlp_probe
import celltype_ibl.models.linear_classifier as linear_probe
import numpy as np
VAE_DIRECTORY = "/mnt/sdceph/users/hyu10/c4_results_new/VAE_checkpoints"
OUT_DIR = "/mnt/home/hyu10/ceph/c4_results_... |
1daa828cea1951aa6683d77828a0a898e65b00e05e64b5f2bb7154a3f2d340ed | Python | 3,258 | 94 | import unittest
from unittest.mock import patch
from pyecharts import options as opts
from pyecharts.charts import Boxplot
class TestBoxplotChart(unittest.TestCase):
@patch("pyecharts.render.engine.write_utf8_html_file")
def test_boxplot_base(self, fake_writer):
v1 = [
[850, 740, 900, 10... |
bb5606a3a5b078f42e689156381c87d8ce5f0a24a18f827338ee807ee30b8f9a | Python | 3,259 | 66 | import torch
from nnunetv2.training.lr_scheduler.polylr import PolyLRScheduler
from nnunetv2.training.nnUNetTrainer.nnUNetTrainer import nnUNetTrainer
from torch.optim.lr_scheduler import CosineAnnealingLR
try:
from adan_pytorch import Adan
except ImportError:
Adan = None
class nnUNetTrainerAdan(nnUNetTraine... |
6be10837a915a8ce28362af68d01a25994856ca8b6b2e5d1f24923b0771a38b3 | Python | 3,260 | 72 | #!/usr/bin/env python3
"""A utility to convert interpretation hdf5 files to a format that modiscolite can use."""
import argparse
import numpy as np
import h5py
from bpreveal import logUtils
from bpreveal.internal.constants import IMPORTANCE_T, ONEHOT_T, IMPORTANCE_AR_T, ONEHOT_AR_T
def flipAndSave(inpAr: IMPORTANCE... |
40e3365075f334ffad92da97636f20ac85f48ab916327a5c4d31a257dc1d4a8e | Python | 3,262 | 93 | import torch
import torch.nn as nn
import torch.nn.functional as F
class ibl_representation_MLP_classifier(nn.Module):
def __init__(
self,
encode_model: nn.Module,
embedding_model: str = "contrastive",
n_classes: int = 10,
freeze_encoder_weights: bool = True,
use_fi... |
eed6e7aa3e14a8a565daef65db1d5d0b7fb1f3b5cff2225ebca91dfb07bce029 | Python | 3,264 | 65 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'UI/PrefsWindow.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow: QtWidgets.... |
09f9a3f2ba31559049b2362f382178653f11d60c87a6c7c55326b979465d3fed | Python | 3,265 | 93 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import os
import numpy as np
import torch
import CBIG_pMFM_basic_functions as fc
import warnings
def CBIG_mfm_validation_desikan_fccost(gpu_index=0):
'''
This function ... |
9da280c8521f64f7c21ce0295b18a248b91e997adecb903eb3f46a56948e2cb4 | Python | 3,265 | 80 | from model.builders.prostate_models import build_pnet2
task = 'classification_binary'
selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'params': {
'data_type': ['mut_important', 'cnv_del', 'cnv_amp'],
... |
a64b815a7e40c2279db0e3452cf3f65fe215724455d0fc1889554ae68a041111 | Python | 3,265 | 94 | # code from https://github.com/ts-kim/RevIN, with minor modifications
import torch
import torch.nn as nn
class RevIN(nn.Module):
def __init__(self, num_features: int, eps=1e-5, affine=True, subtract_last=False):
"""
:param num_features: the number of features or channels
:param eps: a val... |
518eab9398eb30d59047560adaaf6d86882bf112a305321208d6f731040db092 | Python | 3,266 | 96 | #!/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.
import argparse
import re
import sys
class OOVIndexError(IndexError):
def __init__(self, pos, source_seq, target_... |
fc9ab831b76279ef745ec5e82a9521b802df5d8245a94b3c2710bd6e3f16fc70 | Python | 3,266 | 87 | """Read a GO Annotation File (GAF) and store the data in a Python object.
Annotations available from the Gene Ontology Consortium:
http://current.geneontology.org/annotations/
"""
import sys
from .annoreader_base import AnnoReaderBase
from .init.reader_gaf import GafData, InitAssc
__copyright__ = "Copyr... |
089e71abb19b81644ebba33166e0694ef9b89fb814f99c653435bf36ba6d9d62 | Python | 3,267 | 80 | from model.builders.prostate_models import build_pnet2
task = 'classification_binary'
# selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes.csv'
selected_genes = 'tcga_prostate_expressed_genes_and_cancer_genes_and_memebr_of_reactome.csv'
data_base = {'id': 'ALL', 'type': 'prostate_paper',
'pa... |
0d45ad3be85ec51cb19d99924aeb0a7dc54121a817ad15eaeb8b2cc770e398aa | Python | 3,268 | 107 | #!/usr/bin/env python3
"""Exercise cleanup levels in a persistent external validation directory."""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
try:
from .common import DEFAULT_RESULTS_ROOT, timestamped_results_root
except ImportError:
from common import ... |
2c35457a14a6e70c3e468b3a3df69debb927ba13fb36d4d70b40b978aa0a93d4 | Python | 3,268 | 91 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import numpy as np
import torch
import os
import scipy.io as sio
import CBIG_pMFM_basic_functions as fc
def CBIG_mfm_validation_desikan_main(gpu_index=0):
'''
This func... |
b45a7d57280e8a6bd35fbc552bf44b1e1360eb511a7f574c7c26c68cd5dcdfb6 | Python | 3,268 | 91 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import numpy as np
import torch
import os
import scipy.io as sio
import CBIG_pMFM_basic_functions as fc
def CBIG_mfm_validation_desikan_main(gpu_index=0):
'''
This func... |
652b6ad13a442e71e451fa638c57a3b9becc6817217e69a8c1d0202636915a72 | Python | 3,269 | 86 | from collections.abc import Hashable
from math import lgamma
import numpy as np
from scipy.special import gammaln
from pgmpy.structure_score._base import BaseStructureScore
from pgmpy.utils import encode_columns, get_state_counts_array
class K2(BaseStructureScore):
r"""
K2 structure score for discrete Bayes... |
ec91289bac91f145011bf3af5004ec3cbe905472e2da1627b34279b748a318c6 | Python | 3,270 | 120 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import random
from typing import Dict, List
import numpy
import pytest
import torch
from mattergen.diffusion.corruption.corruption import Corruption
from mattergen.diffusion.corruption.d3pm_corruption import D3PMCorruption
from mattergen.diffus... |
f8c212729cb03de1cdf30859e5a29473464eb060e662a37351f007756bac0e0c | Python | 3,271 | 99 | #
# Copyright 2017-2023 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with
# Sandia Corporation, the U.S. Government retains certain rights in this software.
#
# See LICENSE for full license details
#
import os
import numpy as np
import cv2
from imagenet_path import imagenet_val_path
#... |
241809f5cc0ef6d16c3c6cc16ce2b69a51c969551cb4b8a89d5b4445589ebb05 | Python | 3,272 | 70 | from batchgenerators.utilities.file_and_folder_operations import join, load_json, isfile
from nnunetv2.utilities.dataset_name_id_conversion import maybe_convert_to_dataset_name
from nnunetv2.paths import nnUNet_results
from nnunetv2.utilities.file_path_utilities import get_output_folder
if __name__ == '__main__':
... |
71c7365da0386cf66e77e6544b7ae3a518900d1b994c1d2d4480cf5b45f9080e | Python | 3,273 | 96 | # /usr/bin/env python
'''
Written by Kong Xiaolu and CBIG under MIT license:
https://github.com/ThomasYeoLab/CBIG/blob/master/LICENSE.md
'''
import os
import numpy as np
import torch
import CBIG_pMFM_basic_functions_main as fc
import warnings
def CBIG_mfm_validation_desikan_main(gpu_index=0):
'''
This functi... |
73f76243af81dcbb5007fd96c35a194441e8698a905a509d2a13826aa86dfc0f | Python | 3,273 | 98 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 3 17:44:51 2019
@author: admin
"""
#print(__doc__)
import os
import numpy as np
import matplotlib
matplotlib.use("Agg") # matplotlib运行出现的Invalid DISPLAY variable, 切换后端
import matplotlib.pyplot as plt
# self-made for input of numpy
def plot_confusion_matrix(confus... |
672c2ee6492aa3c5de6b537248042a5f690b55fcd3f7b608be65b3c02a2f868e | Python | 3,277 | 83 | import numpy as np
import theano.tensor as T
from theano import config
import sys
sys.path.append('../funcs/')
import layers as ll
import lasagne.nonlinearities as lnl
import lasagne
def binary_crossentropy(output, target):
"""Clipped binary crossentropy"""
target = np.clip(target,0,1)
output = np.clip(o... |
e55b02fa54bedd79cc8b5d59dd0f25dfff1172cd656fce1155bc3edf42fc3ff9 | Python | 3,278 | 92 | #!/usr/bin/env python3 -u
# 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 argparse
import glob
import numpy as np
DIM = 1024
def compute_dist(source_embs, target_embs, k=5, return... |
8c23d6cb88bbcf7dbed099bfbeebdd1c71da5822df89d0d7c7789f0eeb166cef | Python | 3,280 | 91 | from typing import List
import matplotlib.pyplot as plt
import numpy as np
import loompy
from sklearn.neighbors import NearestNeighbors
from .colors import colorize, colors75
from scipy.stats import mode
def punchcard_selection(ds: loompy.LoomConnection, out_file: str = None, tag1: List[str] = None, tag2: List[str] =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.