sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
c582d5ef8f593666e643f42fb5f1cb3812e853fc424de59a214927fe42311378 | Python | 2,435 | 108 | from torch import nn
from genie.model.modules.pair_transition import PairTransition
from genie.model.modules.triangular_attention import (
TriangleAttentionStartingNode,
TriangleAttentionEndingNode,
)
from genie.model.modules.triangular_multiplicative_update import (
TriangleMultiplicationOutgoing,
TriangleMultipl... |
506d2f77f322a90333c758035c87ddaf2fedf1d6ede6ddc0ef4be8df5fe7552b | Python | 2,437 | 79 |
"""
In this file the testing for the GCAPs for 34 bus network is performed
GCAPS results can be reproduced here.
"""
import numpy as np
import gym
from stable_baselines3 import PPO
import torch
from stable_baselines3 import A2C, PPO
from stable_baselines3.common.callbacks import CheckpointCallback, BaseCal... |
3e988aa33d78fe5fc0084da2765793aff37b8b9a9f90eb7deffe8d5cfdfc3e86 | Python | 2,438 | 68 | """Property tests for pydeepmapper.transform. Stdlib + pytest + hypothesis only (no numpy/torch)."""
from __future__ import annotations
import os
import sys
from hypothesis import given, settings
from hypothesis import strategies as st
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
... |
d61218e31264761245ef979af3277517661e02c77d816341fe1ba2737051882a | Python | 2,438 | 78 | """
In this file the testing for the MLP is performed for 34 bus network
"""
import numpy as np
import gym
from stable_baselines3 import PPO
import torch
from stable_baselines3 import A2C, PPO
from stable_baselines3.common.callbacks import CheckpointCallback, BaseCallback
from stable_baselines3.common.torch_... |
60c8ee3e7f0dfcc38396570fb1aa61c2293ef116f28f078001bd031dfd2a0de9 | Python | 2,440 | 98 | #!/usr/bin/env python3
"""
Calculate the local intensity gradient using a 3D Sobel filter
Usage
----
sobel.py -i <input image> -o <output image>
sobel.py -h
Example
----
>>> sobel.py -i T1.nii.gz -o T1_sobel.nii.gz
Authors
----
Mike Tyszka, Caltech Brain Imaging Center
Dates
----
2016-01-06 JMT From scratch
Licen... |
d5dd5c57851572f51b12c5385dbcc3d2ea7559c8c871f49b51a45db40e11a90c | Python | 2,440 | 93 | #!/usr/bin/env python3
"""
Flip 3D (xyz) or 4D (xyzt) data volume in x, WITHOUT ALTERING THE HEADER
The usual caveats apply. ONLY RUN THIS ON ABSTRACTED DATA (eg atlases)
Usage
----
mirror.py <3D or 4D image>
mirror.py -h
Example
----
>>> mirror.py atlas_labels.py
Authors
----
Mike Tyszka, Caltech Brain Imaging Cent... |
2384f8424fad2a3566180ceb7014831a28bf083de69157628f0d1506a128c257 | Python | 2,441 | 64 | """
Wrapper for RandomSurvivalForest to work with the experiments script.
Authors: George H. Chen, Lexie Li, Ren Zuo
"""
import numpy as np
import pandas as pd
import sys
from baselines.nonparametric_survival_models import RandomSurvivalForest
sys.path.append('../')
from utils import compute_median_survival_times
... |
4bf8c5c994cafab6db6bd6ae7017321fbe10cc4efdb53dd8cf20b5339c4ac284 | Python | 2,441 | 86 | #!/usr/bin/env python3
"""
Output summary statistics for each label in an integer-valued atlas
- volume in voxels and microliters
- center of mass
Author
----
Mike Tyszka, Caltech Brain Imaging Center
License
----
This file is part of atlaskit.
atlaskit is free software: you can redistribute it and/or modify
... |
16141292dc79a1a5dc4e583692165173916e71593ad25a048a66af2a23217dcd | Python | 2,442 | 45 | from pycromanager.acquisition.java_backend_acquisitions import JavaBackendAcquisition
from pycromanager.acquisition.python_backend_acquisitions import PythonBackendAcquisition
from pycromanager.acquisition.acquisition_superclass import Acquisition as PycromanagerAcquisitionBase
from inspect import signature
from mmpyco... |
84b8af13d6f653e9d589c7f9873cc7be3464118398d2e8fb2e315e1e9c4fe215 | Python | 2,443 | 72 |
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('seaborn-white')
plt.rcParams.update({'font.size':15})
plt.rc('xtick', labelsize=36)
plt.rc('ytick', labelsize=36)
T2_Results = pd.read_csv("../../logs/1D_final_case_study_Three_P2_y/prediction_per_actual.csv")
R_Results = pd.read_... |
22e913b568256fe701b751a698824a26bb4a97359f64349f1e98eea043fcba71 | Python | 2,445 | 62 | """Servers from two MCP protocol eras, in one agent.
MCP changed how a client and server agree on what each supports: the 2025-11-25
era negotiates with an `initialize` handshake, the 2026-07-28 era with
`server/discover` instead. FastMCP negotiates per connection, so tools from both
can end up in the same agent and n... |
58e9d006046055cfc94652e63298d869c4cd28e18d1fda2e6aacb9e19af12375 | Python | 2,445 | 71 | import json
import re
from re import Pattern
from langchain_core.agents import AgentAction, AgentFinish
from langchain_core.exceptions import OutputParserException
from langchain_classic.agents.agent import AgentOutputParser
from langchain_classic.agents.chat.prompt import FORMAT_INSTRUCTIONS
FINAL_ANSWER_ACTION = "... |
40744b31c96f5c11fb8c28bf2e9fd416671aa45d16f7feb3890704f23ef35b95 | Python | 2,446 | 69 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 10 18:20:23 2024
@author: Shencong Ni
"""
'''
Combine the SUA data from each network realization obtained by 'extractDataforRRRforEachNet.py'
The Combined data will be used in reduced rank regression (RRR) analysis
Run 'onoff_detection.py' and 'extractDataforRRRforEachNe... |
df51340085ba1be02f66ec170e957625348b6d9c19f8146b4e6b1a81844be72d | Python | 2,446 | 86 | from scipy import stats
import matplotlib.pyplot as plt
import numpy as np
import torch
from scipy.io import loadmat
from sklearn.model_selection import StratifiedKFold
from sklearn.model_selection import KFold
def train_val_test_split(n_sub, kfold, fold):
id = list(range(n_sub))
import random
random.se... |
4977e407aab3b1bc6453106f7a3030e6d6530ac7462c0df496f7dc3c189d9829 | Python | 2,449 | 69 | import time
from logging import getLogger
from pathlib import Path
import hydra
import matplotlib.pyplot as plt
import numpy as np
from omegaconf import DictConfig
from libs.common.connenction import Connection
from libs.function.function import Tanh
from libs.function.utils import aline_unspatial
from libs.utils.loa... |
c109eab4d9b3e0cb90298ebedb3959b14d74f545bb38cedb0d11a536fa5fadd9 | Python | 2,449 | 64 | #!/usr/bin/env python3
from dataclasses import dataclass
@dataclass
class Sequence:
name: str
seq: str
class SequenceIO:
# Stolen from https://github.com/lh3/readfq/blob/master/readfq.py
def each(self, fp): # this is a generator function
last = None # this is a buffer keeping the last unproce... |
cabfe06896427f7b2b955a85bec7acb977e30d6da9b2b556e8dca3d0df603781 | Python | 2,449 | 88 | from __future__ import annotations
import logging
import random
import subprocess
from pathlib import Path
from typing import Any, Dict
import mlflow
import numpy as np
import yaml
from omegaconf import DictConfig, ListConfig
log = logging.getLogger(__name__)
def connect_server(uri: str, exp_name: str) -> tuple[st... |
6b1e5ffe1f0ae5b96736be0a3da6f9c61aa38d70df7c54197dce083118244757 | Python | 2,451 | 77 | ####################################################################################
#
# 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... |
848e7a4a67f734806a2c7c10bfb06a874004c88521185b9381b96853406f5200 | Python | 2,451 | 75 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 8 23:16:55 2023
@author: weihan
"""
import pandas as pd
from torch.utils.data.dataset import Dataset
from sklearn import preprocessing
class PygLinkPrediction(Dataset):
"""
The PygLinkPrediction object can convert graph for pyg using.
... |
8811d99b495f48783642a3cdd038af819dd849303f1df125c3dccec87665a660 | Python | 2,451 | 65 | """ Import a General data.
Import data from any source, even transcriptomics/ metabolomics/etc.
To construct its own data, user should prepare an Excel file with 3 sheets.
1. The 1st sheet must be the assay data, in which the first row is the
sample name and furthers are the expression levels of each
protein/metabo... |
a0a01fe9ddf6f1ff45f4edf47381b069a57ca85e92430b7947a504bdde745ef0 | Python | 2,451 | 31 | NEWS_DOCS = """API documentation:
Endpoint: https://newsapi.org
Top headlines /v2/top-headlines
This endpoint provides live top and breaking headlines for a country, specific category in a country, single source, or multiple sources. You can also search with keywords. Articles are sorted by the earliest date published... |
bacaf9faaa915ecadae87b36c767b3f3ac242613ed5d1a3f96717e1648fa562a | Python | 2,451 | 80 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 14 14:21:23 2022
@author: pierre
"""
import numpy as np
def Bridson_sampling(width=1.0, height=1.0, radius=0.025, k=30):
# References: Fast Poisson Disk Sampling in Arbitrary Dimensions
# Robert Bridson, SIGGRAPH, 2007
def... |
87b879bdc09e0c13b57d912788ba0d189bffbe9b8674c0ba29583eedf1910aad | Python | 2,452 | 66 | import numpy as np
import torch
import time
seed = 268945
torch.autograd.set_detect_anomaly(True)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
import argparse
def parse_args():
# input arguments
p... |
f8dade396442e412a94d4a1a2533085aa73cb95df8f5bf05c8725775d9b341c8 | Python | 2,452 | 68 | import argparse
from dival import DataPairs
from dliplib.reconstructors import (tvadam_reconstructor,
fbp_reconstructor,
diptv_reconstructor,
learnedgd_reconstructor,
learnedp... |
8539856017f8e8ee505cb9341422311b2491c997a4503eeede452adcb6f679a9 | Python | 2,453 | 80 | ########################################################################
# Stochastic degradation-diffusion process.
# AIMS: to verify if zero order reactions are inserted correctly to the SSA
# after bugfix https://github.com/CNS-OIST/HBP_STEPS/pull/146
# Note:
# 1. This is not validated against analytical result, ... |
8a0fe210e35c6f2de418b34da3413ff2de3353e867be680c7e43b27e5c288b7b | Python | 2,453 | 54 | # -*- coding: utf-8 -*-
import torch.nn as nn
class ModuleUnit(nn.Module):
def __init__(self, input_size, output_size, bias=True, hidden_size=None, hidden_layers=None, activation=None, dropout=None):
super(ModuleUnit, self).__init__()
fc_ac = {"relu": "nn.ReLU",
"leaky_relu": "nn.... |
b2e3c42b5fc9174450280c791cff7b1eb46acb4ccb8f2858412557c7617c543c | Python | 2,453 | 81 | # # -*- coding: utf-8 -*-
# """
# Created on Thu Apr 23 11:36:41 2020
# @author: gritti
# """
import sys, time, tqdm, copy, os
sys.path.append(os.path.join('..'))
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import warnings
warnings.filterwarnings("ignore")
from ma... |
0fe4472b3cf3c99f0a6875d6a1f6d50de70846b441c6c752d220799c19b2b17e | Python | 2,455 | 82 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
7be637e0c93ce17d35c15c35baf8debb96aece053446ff37b9423dade48872de | Python | 2,458 | 77 | import torch
import torch.nn as nn
import torch.nn.functional as F
from utils.tensor_operator import to_device, tensor2array, force_fp32
from . import atom_loss_register
from ..utils import symmetric_loss_wrapper
@atom_loss_register
@symmetric_loss_wrapper
@force_fp32()
def cdist_loss(X, Y, margin):
dist = torch... |
962459acd14aac70b7c9251e016752e9b8a3838dc09f2eebcc5fa135c00da1e6 | Python | 2,459 | 100 | import torch
from tqdm import tqdm
from torch.optim import Adam
from abc import ABC, abstractmethod
from pytorch_lightning.core import LightningModule
from genie.model.model import Denoiser
class Diffusion(LightningModule, ABC):
def __init__(self, config):
super(Diffusion, self).__init__()
self.config = confi... |
7f73de17b9c6ddb53c00cba3dbd9278e262c301521f0123a3b7e1f3df182375a | Python | 2,460 | 69 | import matplotlib.pyplot as plt
import numpy as np
#%%
batchSize = [0,32,128,512]
gpuTime = np.array([443.9, 12.6, 3.4, 1.1])
cpuTime = np.array([163.6, 9.1, 6.2, 5.1])
gpuAcc = [0.79, 0.47, 0.56, 0.52] #cpu vs gpu acc should be comparable for a given batchSize since both versions saw the same number of samples... |
4b208dd5b7dec823ac874228eb1f01ed2313745a2e2b8b97de7e5b0b1fd6eb4a | Python | 2,461 | 59 | import os
import numpy as np
import pandas as pd
def get_max_acc_experiment(experiment):
mx_idx = 0
max_accs = 0
for n, exp in enumerate(experiment['experiments']):
exp_hist = pd.read_csv(os.path.join(exp, 'history.csv'))
mx = max(exp_hist.val_accuracy)
if max_accs < mx:
... |
c24bf0deb731dba1d00aab3d174e754c4860798da11ce5f034c2104cd788fc54 | Python | 2,462 | 67 | #!/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
import torch
from embanded.embanded_torch import EMBanded
# Load data from the 'example03.mat' file
data = scipy.io.loadmat('example03.mat')
device = torch... |
800d7a185f71f6447ab2e96a297d302ffeff824f63f862f92b6f5446a7101bf4 | Python | 2,463 | 85 | # This provides functions that create shapes for generating synthetic 3D
# shapes.
#
# Author: vivekv2@gmail.com
from typing import Tuple
import numpy as np
def get_centered_zyx_meshgrid(shape: np.ndarray) -> Tuple[np.ndarray, ...]:
"""Return a tuple (Z,Y,X) of coordinates for a 3D array generated via
np.mes... |
cbfaa275f5b2fd2d1050ff217b16727eef30c10514cd9c2581b852147c551566 | Python | 2,463 | 84 | from collections import OrderedDict
import torch
from torch import nn
class Flatten(nn.Module):
"""
Helper module for flattening input tensor to 1-D for the use in Linear modules
"""
def forward(self, x: torch.Tensor) -> torch.Tensor:
return x.view(x.size(0), -1)
class Identity(nn.Module)... |
ec666902236d4b873ddb5c4cb724ab182e14650c5ce2ee849ac148c82fb932a3 | Python | 2,465 | 66 | # kinetic monte carlo simulation
import random
import numpy as np
class KMC():
def __init__(self, attempt_frequency, boltzmann_constant, temperature, vacancy_id, time_scale):
self.attempt_frequency = attempt_frequency
self.boltzmann_constant = boltzmann_constant
self.temperature = ... |
04bb4f97a0faacfb7b2ce4fa39219daf93c75c3e66256560eb7d4d1423a435a1 | Python | 2,467 | 86 | import os
import cv2
import numpy as np
import torch
from torch.utils.data import Dataset
# Additional Scripts
from config import cfg
class DentalDataset(Dataset):
output_size = cfg.transunet.img_dim
def __init__(self, path, transform):
super().__init__()
self.transform = transform
... |
f93c67de970f4c9e1a96a7d2bed1df89c521faf6ca94e36455267605b1ad585f | Python | 2,468 | 63 | import torch
import torch.nn as nn
from torch.nn.utils import weight_norm
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous()
class TemporalBlock(n... |
cd718be532a4eb1be24f212d831d7f0e8ab835b50ced4b9e53ddd29da7e65c23 | Python | 2,469 | 86 | """Utilities for environment variables."""
from __future__ import annotations
import os
from typing import Any
def env_var_is_set(env_var: str) -> bool:
"""Check if an environment variable is set.
Args:
env_var: The name of the environment variable.
Returns:
`True` if the environment v... |
6a2ba5380446eb282772e597a75aacb99ece2f418fe00ac4bf6eed6ee708a465 | Python | 2,470 | 80 | """
In this file the testing for the MLP is performed for 13 bus network
MLP results are not reproducible as it computes a new decision each time.
"""
import numpy as np
import gym
from stable_baselines3 import PPO
import torch
from stable_baselines3 import A2C, PPO
from stable_baselines3.common.callbacks ... |
c5f264421f92890fe38b40bcaec673addac5d7e32f2b38cb754f2dd5ceef46fb | Python | 2,470 | 69 | # /// script
# requires-python = ">=3.12"
# dependencies = ["requests"]
# ///
"""Download the QPI-from-defocus sample dataset for the tutorial.
Fetches ``recOrder_session.zip`` from zenodo and prints the path to the
brightfield defocus stack. It is already an **OME-Zarr**, so it plugs straight
into ``wo view`` / ``wo ... |
fb1443a0421750748271d65cde39e8b082af68cecf5290a96197bc7242557ea9 | Python | 2,470 | 80 | ########################################################################
# Stochastic degradation-diffusion process.
# AIMS: to verify if zero order reactions are inserted correctly to the SSA
# after bugfix https://github.com/CNS-OIST/HBP_STEPS/pull/146
# Note:
# 1. This is not validated against analytical result, ... |
8b284526426ac84cf21d95bb17a45ee37bd064d71fd41b17feb855dc68efe8fc | Python | 2,472 | 67 | """Mask-based skull stripping utility.
This script multiplies an input anatomical or diffusion-derived volume by a
binary brain mask to remove non-brain voxels. The behaviour matches the
original DDSurfer helper while providing a clearer interface and logging.
"""
from __future__ import annotations
import argparse
i... |
b4d242658a963b4cfce9860bb2e7398a92058250a401c233a78ef8fad4924f93 | Python | 2,472 | 54 | # Sconda conda activate abc; cd /mnt/BioAdHoc/Groups/RaoLab/Edahi/Projects/09.TimeCourse5hmC/ForFerhatGit/FCDNN/results/genes_coef_var_sq; python
# python expression_threshold_per_celltype.py
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
# Function to TPM norma... |
1d5d6d225cf4e399a159aadaa1e79609c419ed2a69f571cf5a266b81a2fa5644 | Python | 2,477 | 60 | import argparse
import gzip
import pickle
import re
import io
import tarfile
from tqdm import tqdm
PATTERN_COMP = re.compile(r"(data_[^\n]*\n)", re.MULTILINE)
PATTERN_COMP_SG = re.compile(r"(data_[^\n]*\n)loop_[\s\S]*?(_symmetry_space_group_name_H-M[^\n]*\n)", re.MULTILINE)
def extract_prompt(cif_str, pattern):
... |
a4bafe819aa9303e757a49623ee3a974635fcaaaf1d1f639be3ee05f641e4188 | Python | 2,477 | 69 | import argparse
import os
import matplotlib.pyplot as plt
import pandas as pd
from experiments import ROOT_DIR
benchmark_path = os.path.join(ROOT_DIR, "benchmark")
figure_path = os.path.join(ROOT_DIR, "figures")
if not os.path.isdir(benchmark_path):
os.makedirs(benchmark_path)
def main(start=100, stop=1000, st... |
259e0e34ce8ff1644d035b70e109c9639d15b08f78de90276a468fc1c515ddba | Python | 2,481 | 65 | from ..utils.utils import *
def save_movie(
container,
results,):
"""Visualize results in an annotated movie.
Visualize results as coloured annotations in a movie. Frames are generated
using the same data loading parameters used for tracking.
:param container: variable container, needs to co... |
9cf0436f52e95e8ab0b8cd769b482b69992db4f7634cbb1c9dcf23dc6755cbf7 | Python | 2,481 | 82 | #!/usr/bin/env python3
import argparse
import pathlib
from typing import Optional
import pandas as pd
import yaml
import tqdm
import shutil
def parse_arguments(
key: Optional[str] = None, stage: Optional[str] = None, method: Optional[str] = None
):
"""
Parses command line arguments
"""
parser = a... |
9fa6d13666b1f7e681bd96fbcae8f39fe83da2daf46f65c3a1f8c6cd7f9d6ab7 | Python | 2,481 | 71 | #!/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
import torch
from embanded.embanded_torch import EMBanded
# Load data from the 'example06.mat' file
data = scipy.io.loadmat('exampl... |
864c943d09177c0cbef955778d3186fc36be9499991cac583a503e287442b326 | Python | 2,482 | 71 | import os
import sys
from distutils.command.sdist import sdist
from setuptools import setup, find_packages
PACKAGE_NAME = "ants_tbss"
BUILD_REQUIRES = ["numpy", "nibabel", "argparse", "matplotlib", "scipy", "scikit-image"]
CLASSIFIERS = ["Development Status :: 3 - Alpha",
"Environment :: Console",
"Intended Audi... |
8688131f3e2754465739831391e94bb039fe59b27883f72d6c9dcc7a79282fb5 | Python | 2,483 | 74 | ########################################################################
# Stochastic degradation-diffusion process.
# AIMS: to verify if zero order reactions are inserted correctly to the SSA
# after bugfix https://github.com/CNS-OIST/HBP_STEPS/pull/146
# Note:
# 1. This is not validated against analytical result, ... |
5a15a64bf199a0d9aa75389c727548f9e33889eeb4fc7806083136b68395477d | Python | 2,485 | 78 | #!/usr/bin/env python3
import argparse
import collections.abc
import os
import re
import shutil
import yaml
def update_dict_recursively(d, u):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = update_dict_recursively(d.get(k, {}), v)
else:
d[k] = v
... |
3cdeef3434790c7bd189aedc9b4683683b4702e483bc76d768d08d8fb7aed209 | Python | 2,486 | 81 | import os
import glob
import torch
import numpy as np
def load_coord(filepath):
return np.loadtxt(filepath, delimiter=',')
def load_classes(filepath):
classes = {}
with open(filepath) as file:
for line in file:
elts = line.strip().split(',')
classes[elts[0]] = elts[1].split('.')[0]
return classes
def lo... |
9e3021c1d934c9776c03da2df664a3beee5ff1083d8747a078a47d3daf07c063 | Python | 2,487 | 77 | import asyncio
import os
import time
from collections import defaultdict, OrderedDict
from core.runner import runner_register, PretrainRunner
from utils.my_containers import AverageMeter, deep_dict_get
from utils.tensor_operator import to_device, tensor2array
from torch.cuda.amp import autocast, GradScaler
from utils... |
9aefaed1b7da9a5840adc0b91916eb37c6cffcb0776fce6a6836c23d5e0c7011 | Python | 2,488 | 72 | from KineticAssembly_AD import ReactionNetwork
from KineticAssembly_AD.reaction_network import gtostr
import numpy as np
from typing import Tuple, Union
import matplotlib
from matplotlib import pyplot as plt
from torch import DoubleTensor as Tensor
import sympy as sympy
def find_eq_eqns(rn):
# ensure same elem... |
37ef26978464748a2d8e551a2a5f3e5d9791cd59ddaa1c25339c48f71d60159e | Python | 2,489 | 61 | import torch
from torch.utils.data import DataLoader
import numpy as np
import argparse
import sys
sys.path.append("..")
from src.utils import set_random_seed
from src.data.featurizer import Vocab, N_ATOM_TYPES, N_BOND_TYPES
from src.data.finetune_dataset import MoleculeDataset
from src.data.collator import Collator_... |
a7e8536002a055911d076017861f14d28d7da537c52d18af413a13433cc4887e | Python | 2,489 | 66 | import json
import logging
import os
import socket
import sys
import pandas as pd
from configs.configs import get_config_dict
if __name__ == "__main__":
hostname = socket.gethostname()
print('\nHostname:', hostname)
data_set_name = sys.argv[1] # 'd2', 'd3d', 'd3s'
data_split = sys.argv[2] ... |
6879726b1d98649c63ee268d95b7d1e46b5f4905e97db10a43659a20e9f4ba73 | Python | 2,490 | 80 | """Test the scoring chains."""
import re
import pytest
from langchain_classic.evaluation.scoring.eval_chain import (
LabeledScoreStringEvalChain,
ScoreStringEvalChain,
ScoreStringResultOutputParser,
)
from tests.unit_tests.llms.fake_llm import FakeLLM
def test_pairwise_string_result_output_parser_parse... |
6d04261b0462ba9c6af89eb039cccae80461f282b3a0eebf39e71906082fe3ad | Python | 2,490 | 84 | """Recreate the 'memory capacity' experiement from Collins..Sussillo2016 w/ alternative network architectures"""
import sys
import joblib
import matplotlib.pyplot as plt
import torch.nn.functional as F
import torch
from dt_utils import Timer
from hebbian import HebbRecall
from plastic_gated import GSP1Recall
... |
88cdc9eb6b106c379a8e2cc6d0d51c9f1f04ce2bc132e575c6c44f40ee13aef7 | Python | 2,492 | 80 | """
In this file the testing for the GCAPs for 13 bus network is performed
GCAPS results can be reproduced here.
"""
import numpy as np
import gym
from stable_baselines3 import PPO
import torch
from stable_baselines3 import A2C, PPO
from stable_baselines3.common.callbacks import CheckpointCallback, BaseCallb... |
d015e56215ffb58400ac1d0c74d6121fa38f315729085a687c35fed849febc39 | Python | 2,494 | 74 | # Random Forest modelling of mental flexibility based on Yeo Network data
# load the data - network data and behavioural data
import pandas as pd
network_data = pd.read_csv(r'D:\Neuro\Random_Forest_Marco\Scripting\network_data_yeo17_167pat.csv')
behav_data = pd.read_csv(r'D:\Neuro\Random_Forest_Marco\Scripting... |
d6d239960045cc20dac39d11ca1a0758018ccdd279dfc6b334ee62cf7d0d2be8 | Python | 2,494 | 87 | """Test HyDE."""
from typing import Any
import numpy as np
from langchain_core.callbacks.manager import (
AsyncCallbackManagerForLLMRun,
CallbackManagerForLLMRun,
)
from langchain_core.embeddings import Embeddings
from langchain_core.language_models.llms import BaseLLM
from langchain_core.outputs import Gener... |
ba181875705de646edd184ade833ae04646b014426631438895f9cfd3e1af364 | Python | 2,495 | 33 | import argparse
def create_parser_main_DMS():
parser = argparse.ArgumentParser(description='Compute the accuracy of the network')
parser.add_argument('--save_dir', type=str, help='save_dir', default='../Simu')
parser.add_argument('--name', type=str, help='name', default='local/test')
parser.add_argumen... |
db430d0febd4b3ab330e230b0dbc5588abeff9531710252859dc102555bb0077 | Python | 2,495 | 75 | # Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... |
de36303c9872b3aee817f5c03b58759d12002d000b119e3a747a44f706556648 | Python | 2,495 | 82 | # Load in model weights and evaluate its goodness (ECE, MCE, error) also saves logits.
import os
os.environ['KERAS_BACKEND'] = 'tensorflow'
import numpy as np
import collections
import pickle
from sklearn.model_selection import train_test_split
from keras.optimizers import SGD
from keras.preprocessing.image import Im... |
eb394b19acd5c28d13d52047145ebe9aa53f814e2f6acf8b3954c9b61e9ed70e | Python | 2,495 | 62 | # -*- coding: utf-8 -*-
# @title Software configuration file
# @file SwConfigFile.py
# @author Romain Beaubois
# @date 01 May 2023
# @copyright
# SPDX-FileCopyrightText: © 2023 Romain Beaubois <refbeaubois@yahoo.com>
# SPDX-License-Identifier: GPL-3.0-or-later
#
# @brief Script to generate... |
1886c02bb7c29b6bfa49a3dbc99e611d64ca4fdee8d7c31355ad3112a5898263 | Python | 2,496 | 68 | """A per-user MCP fleet behind a `langgraph dev` graph factory."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any, cast
import httpx2
from _servers import token_for
from fastmcp.client import Client
from fastmcp.client.auth import BearerAuth
from fastmcp.client.group import ClientGroup
from... |
9edb76f96f7e533e0435c3ddbace597865a19f2d239ef5846e853d56ec4c01db | Python | 2,496 | 81 | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
347ddc9db3e73dc1a6d5ceafcea19de5b0d008f2101c9881aa6a5556979dc4e9 | Python | 2,497 | 85 | #!/usr/bin/env python3
"""
Combine several labels in a 4D prob atlas by simple addition (probabilistic OR)
Usage
----
prob_or.py -i <4D prob atlas> -o <3D prob atlas> <space separated label list>
prob_or.py -h
Example
----
>>> prob_or.py -i prob_atlas.nii.gz -o merged_labels.nii.gz 1 2 5 10
Authors
----
Mike Tyszka,... |
a78b639deb02188875359988830edb63e8ca3bf1d7c948b2a050f8e1929a8caf | Python | 2,499 | 45 | #TO BE UPDATED
import numpy as np
from NeuronModel import rate, fitzugh_nagumo
from NetworkModel import networkClass
from WeightModel import weightClass, rateBased, gapJuctions
from InitFunctions import gaussian_EI
from Input import inputClass
import pickle
class hermann(networkClass) :
parameters = {'neuron' : '... |
92082d0657d5a46fc1f930c3cda774d04dd38a63af0d914c453abe1339317118 | Python | 2,500 | 74 | ########################################################################
# Stochastic degradation-diffusion process.
# AIMS: to verify if zero order reactions are inserted correctly to the SSA
# after bugfix https://github.com/CNS-OIST/HBP_STEPS/pull/146
# Note:
# 1. This is not validated against analytical result, ... |
3474a9842a58b0557518a623f61d8e164628f88cf8f57c4e2deb50d21f501894 | Python | 2,502 | 66 |
import typer
from AnnoSpat import classify_IMCcells
import os
from pathlib import Path
app = typer.Typer()
@app.command('generateLabels')
def anno(
data_path: str = typer.Option(..., "--inputfile",'-i', help=""),
signature_path: str = typer.Option(..., "--markerfile","-m", help=""),
op_dir: str = typer.... |
608b7ad85f29bb22d02fbb7bc01d0f288421b61ae7ff88aad81659d58c8aa528 | Python | 2,502 | 73 | # Copyright 2024 Eelke Spaak, Donders Institute.
# See https://github.com/Spaak/rift-phase-and-visibility for readme/license.
# Belongs with:
# Spaak, E., Bouwkamp, F. G., & de Lange, F. P. (2024). Perceptual foundation and extension
# to phase tagging for rapid invisible frequency tagging (RIFT). Imaging Neuroscience,... |
e062f397f65548d2ab29d1a93db994e022f9c91656154a2c26c43a9856c040f3 | Python | 2,502 | 74 | # Load in pre-trained model weights and evaluate its goodness (ECE, MCE, error) also saves logits.
import numpy as np
from keras.optimizers import SGD
from densenet161 import DenseNet
from load_data_imagenet import load_data_imagenet_split
from resnet152 import resnet152_model
import keras
# Imports to get "uti... |
0393cedd49369875eb314c98ea7654dd4857db4735ba10a76d10611682068421 | Python | 2,503 | 81 | import io
import os
from contextlib import contextmanager
from importlib.resources import Package
from importlib.resources import path
from pathlib import Path
from typing import Any
from typing import BinaryIO
from typing import Dict
from typing import Iterator
from typing import List
from typing import Optional
from ... |
58d31380e196fe09fe7d52408f6e180a2792099e9777605272efed761839463b | Python | 2,503 | 77 | # Copyright 2021 AlQuraishi Laboratory
#
# 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 i... |
ff24b2aa8f932a944944ea7040f7c1ffe9c03bdbdd6668e8eb9ecb9631d91e7f | Python | 2,503 | 90 | """Simple Convolution and fully connected blocks example."""
from vulcanai import datasets
from vulcanai.models import ConvNet, DenseNet
import torchvision.transforms as transforms
from torch.utils.data import DataLoader
normalize = transforms.Normalize(mean=[x/255.0 for x in [125.3, 123.0, 113.9]],
... |
141549a6bd83c566c4743c718efdcf466971f9b2287935b107aeff06f55bc4b7 | Python | 2,504 | 88 | # Copyright 2021 AlQuraishi Laboratory
#
# 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 i... |
b9b07d81cac827eac18344899eebf25413fc421f4241069123c0886322e2a880 | Python | 2,505 | 83 | import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import conv1x1x1, Bottleneck, ResNet
from functools import partialmethod
def partialclass(cls, *args, **kwargs):
class PartialClass(cls):
__init__ = partialmethod(cls.__init__, *ar... |
674ef873cc09222903efd90583fa2c09c989487038c561789b1ef3882c27d4b4 | Python | 2,507 | 84 | import pytest
import torch
from ptrnets.utils.modules import unnormalize
def test_unnormalize_with_default_args():
# Create input tensor
tensor = torch.tensor([[[[0.0, 0.5], [1.0, 1.5]]]])
# Perform unnormalization with default arguments
unnormalized_tensor = unnormalize(tensor)
print(unnormali... |
72b287d46155649c288b188011eac1f16c91a9c380faa14c0df952ac74aae4ca | Python | 2,507 | 51 | """Null model for the 'top-40 discriminating lncRNAs are antisense' statement (round-3 Reviewer E #2).
Question: is the antisense (-AS) fraction among the top state-discriminating lncRNAs ENRICHED relative to
the antisense fraction of the DETECTED lncRNA background, or does it merely reflect that detected lncRNAs
are ... |
d45092e20552339ef32048ded793f0cc75dc960296404a7d62effd0f4925f526 | Python | 2,507 | 62 | # Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... |
48e4e8f0735da08b8f17685f6cfa1c06cf13aa9ab6c69adb816549fbc6ad57ae | Python | 2,508 | 105 | """qkill.py - kill jobs in the queue
==================================
Purpose
-------
This script kills jobs in the job queue according to certain criteria.
It is complementary to the ``qdel`` command, but provides more
flexible pattern matching.
This script requires the ``qstat`` and ``qdel`` commands to be in t... |
ad8acfed4b313d457871079ca84ad77d560a7cc5f8379b74a9ef8bb3354e403a | Python | 2,510 | 71 | """
Test storage layer.
TODO:
* Write tests
"""
__author__ = 'John D. Chodera'
################################################################################
# IMPORTS
################################################################################
import os
import os.path
import tempfile
from perses.analysis.an... |
d1bd72c189435f6935072871e69db5872570674dd36db2aa223174321d235955 | Python | 2,510 | 95 | """Tools are classes that an Agent uses to interact with the world.
Each tool has a description. Agent uses the description to choose the right tool for the
job.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from langchain_core._import_utils import import_attr
if TYPE_CHECKING:
from l... |
d3cffc49dede640d77626f73fa96cfc023448774320c3b2a179a59aeed88167d | Python | 2,510 | 59 | import torch.nn as nn
import torch
import torch.nn.functional as F
from models.pointnet2_utils import PointNetSetAbstraction,PointNetFeaturePropagation
class get_model(nn.Module):
def __init__(self, num_classes, normal_channel=False):
super(get_model, self).__init__()
if normal_channel:
... |
ce54368048287ee606e162bc745cc4f053eb588c64b88735011fc350a41e8685 | Python | 2,512 | 59 | import torch.nn as nn
import torch
import torch.nn.functional as F
from models.pointnet2_utils import PointNetSetAbstractionMsg,PointNetSetAbstraction,PointNetFeaturePropagation
class get_model(nn.Module):
def __init__(self, num_classes, normal_channel=False):
super(get_model, self).__init__()
if ... |
138db2a42cd740e8c0491faa5dd6d8565fa636202db07a50d36f07971bb3a71d | Python | 2,513 | 64 | import numpy as np
small = 1e-10
def max_PSP_exp(tau_m, tau_syn, C_m=1., E_l=0.):
"""
Calculates the maximum psp amplitude for exponential synapses and unit J.
Parameters:
tau_m (float): Membrane time constant [ms]
tau_syn (float): Synapse time constant [ms]
C_m (float): ... |
c3737bd1ea96dc257eac397c2f1d1517e4f4fabd10c81d39eb93235556e7f6c5 | Python | 2,513 | 52 | # For each CG site this script picks the Infinium 2 probe with the most species covered and outputs how many
# species that probe covers. The output from this can be used to sort by number of species covered and look at the
# coverage of each species.
#
# This script assumes that each CG site has 4 probes in the input ... |
53ae61ee114de6ac84e08f0ec9ae7987c65772c197a2d4bd66cdb08b63b6ed0a | Python | 2,515 | 62 | from langchain_core.messages import HumanMessageChunk
from langchain_core.outputs import ChatGenerationChunk, GenerationChunk
def test_generation_chunk() -> None:
assert GenerationChunk(text="Hello, ") + GenerationChunk(
text="world!"
) == GenerationChunk(text="Hello, world!"), (
"GenerationCh... |
1cedbfe6a5feb665cc004627b5cc24911a60e448e5d97c1500f69e1a3e56206c | Python | 2,516 | 84 | #!/usr/bin/env python3
import argparse
import pathlib
import subprocess
from typing import Optional
import pandas as pd
import yaml
def parse_arguments(
key: Optional[str] = None, stage: Optional[str] = None, method: Optional[str] = None
):
"""
Parses command line arguments
"""
parser = argparse.... |
36cde993a7f6191bf23feb0f37820d8cb7e248853465c38cb3569f651a1443b6 | Python | 2,516 | 67 | # main file for CNN classifier
# Updated: 12/25/2021
# Status: OK
# CUBLAS_WORKSPACE_CONFIG=:4096:8 python cnn_pre.py
import sys
import torch
import numpy as np
from networks import CNN_Wrapper
from utils import read_json
from tabulate import tabulate
def CNN(model_name, config, Wrapper, num_exps):
print('Eval... |
63c9f4f1b448524ccd94c4ef7db5d6335170ce8217784e69485dacccfc505dd2 | Python | 2,516 | 68 | import shutil
from batchgenerators.utilities.file_and_folder_operations import *
import SimpleITK as sitk
from nnsegnext.paths import nnSegnext_raw_data
if __name__ == '__main__':
#data is available at http://medicalsegmentation.com/covid19/
download_dir = '/home/fabian/Downloads'
task_id = 69
task_n... |
db44b3bdeb1498be8e186400ae422778bd52df4a4379d3cd2a7030336e4f699b | Python | 2,516 | 67 | import pandas as pd
import matplotlib.pyplot as plt
import json
from skimage import draw
import numpy as np
from scipy.stats import norm
import cv2
def get_img_coord(tissue_dir, metafile, barcode_tag = '_1', hires=1):
tissue_pos_file = tissue_dir+ 'spatial/tissue_positions_list.csv'
imcoord = pd.read_csv( tis... |
eb6d4e52938cc8ff918f4e3a3b64c2b76d0d0b9e7939fec8fb74b4ad2f3eba3f | Python | 2,518 | 61 | """Tests for device propagation through .to() across the Environment -> Effector -> {Muscle, Skeleton} tree.
Environment, Effector, Muscle, and Skeleton each override .to() to track their own `self._device`
bookkeeping attribute (used elsewhere as `device=self.device` when constructing new tensors).
Calling .to(device... |
0f58f60fac2a4d4cbe88597034936d7a7c02ab26ea2275d87e988c029fe863f5 | Python | 2,521 | 74 | """
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
import torch.nn as nn
# Different encodings for the atom distance embeddings
class GaussianSmearing(torch.nn.Module):
def ... |
9e81a52ad7c13ce92f5be15ec22eaa76da58f38250d8486316fc41dfe024b783 | Python | 2,521 | 76 | """
Unit and regression test for the openforcefields package.
"""
import glob
import os
import pytest
from openforcefields import get_forcefield_dirs_paths
try:
import openff.toolkit # noqa
has_off_toolkit = True
except ModuleNotFoundError:
has_off_toolkit = False
def find_all_offxml_files():
""... |
d386e75bf8f7943133eb3727751b658b80012e18154bdb73b5acf0024cefdcca | Python | 2,522 | 71 | import os
import gc
import numpy as np
import matplotlib.pyplot as plt
from scipy.io import loadmat, savemat
import scipy.signal as signal
import pandas as pd
from utils.read_mda import readmda
F_SAMPLE = 30e3
WINDOW_LEN_IN_SEC = 30e-3
SMOOTHING_SIZE = 11
session_folder = "/media/luanlab/Data_Processing/Jim-Zhang/... |
360cd8c48ccd21f75474a3cc52337f4296566ae535b485b72a6e5414f48bc677 | Python | 2,523 | 68 | #!/usr/bin/env python3
from anna16 import Preprocessing, get_model # , predict_from_fasta
import pandas as pd
import numpy as np
import warnings
warnings.filterwarnings("ignore")
import argparse
import os
# from multiprocessing import Pool
parser = argparse.ArgumentParser()
parser.add_argument('-r', '--region', type=... |
eced81fbe500b7793758ab168f094fd4d95bd863962ba5d99213b04103a42799 | Python | 2,525 | 45 | from perses.analysis.visualization import Visualization
from pkg_resources import resource_filename
import os
from unittest import skipIf
running_on_github_actions = os.environ.get('GITHUB_ACTIONS', None) == 'true'
@skipIf(running_on_github_actions, "Skip helper function on GH Actions")
def test_protein_mutation():
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.