sha256 stringlengths 64 64 | language stringclasses 28
values | size int32 1 491k | lines int32 1 23.2k | content stringlengths 1 200k |
|---|---|---|---|---|
0920518561067d4251bdb6b27b7c5943cc92f9aa101a1bc2603af96c5bcc72fb | Python | 3,906 | 105 | import argparse
import logging
import re
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as grid_spec
from scipy.io import loadmat
from typing import Optional
from pathlib import Path
logger = logging.getLogger("gen_contamination_report.py")
def main(agg_dir: Path, analysis_dir: Path, ... |
b760c3e2160b1f1ab4f8436dec1f4783e885e5d02ed1010abf6e5f2fed369eac | Python | 3,907 | 81 | from spycon_inference import SpikeConnectivityInference
import elephant
import neo
import quantities
import numpy
from scipy.stats import poisson
class MyConnectivityMethod(SpikeConnectivityInference):
def __init__(self, params: dict = {}):
"""
Implements my connectivity inference method.
... |
ca2d14daaa82bd9e15941af12c01b5c66344bb6763ac05c5ad9fbb833e4627a4 | Python | 3,907 | 105 | # Copyright 2025 Xanadu Quantum Technologies 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 agre... |
968959623ecc93d76b97dcc7a98234bb4173113550ed91f7376b2dff3f0d3cef | Python | 3,908 | 128 | import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
from sequence_models.losses import VAELoss, SequenceCrossEntropyLoss
from sequence_models.vae import FCDecoder, FCEncoder, VAE, Conductor
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.devic... |
d979392bca8fc57c99b9b9109953a9615e5d9af25d7c481eca7aade066bc2f2d | Python | 3,908 | 96 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride, dropRate=0.0):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
se... |
4d07452e81e458bbcbe021cea3d76d6cfb45429f18bd365a050256fba9bd688b | Python | 3,909 | 138 | #%%
from src import simulation
from src.prep import bin_data
from src.transform import DiMap, SelectCols, OneHotPD, NormEITV, get_column_transformer
import pandas as pd
import numpy as np
import pytest
from sklearn.compose import ColumnTransformer
# %% generate dataset with two columns and two categories
def _generat... |
ee184b1ee41e92d7ee72cd3e2d6cf25263aa9244e66b3ae7dc991fb062777d5e | Python | 3,911 | 106 | # Copyright 2018-2023 Xanadu Quantum Technologies 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... |
0bba420d53faded656803b3b7a9982c11375e511f98fe776c9bd9ebbef2391c1 | Python | 3,916 | 127 | import base64
import hashlib
import json
import os
import pickle
import dill
import shutil
from typing import Union, List, Callable
import lz4
import lzma
import numpy as np
import pandas as pd
from .log import auto_log
from .configs import DATA_DIR, MODEL_DIR
DATASET_DIR = DATA_DIR / 'dataset'
def tag_to_str(tag... |
3700a0e6e3b6e65e54285eafe98e350db7053face15decc0630152662cae3486 | Python | 3,921 | 108 | from datetime import (
UTC,
datetime,
)
import numpy as np
import pytest
from pandas._libs.tslibs.dtypes import NpyDatetimeUnit
from pandas._libs.tslibs.strptime import array_strptime
import pandas as pd
import pandas._testing as tm
creso_infer = NpyDatetimeUnit.NPY_FR_GENERIC.value
class TestArrayStrptim... |
275453e1892e5514188bf4bb3d8002149d3431dd00c4d7793eab5172b3420eee | Python | 3,924 | 81 | # Copyright 2024 Xanadu Quantum Technologies 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 agre... |
106597404c73b84d975babd930cfb9d9470c8ba80f16da6ce3ed949f1f12f14f | Python | 3,926 | 98 | import pandas as pd
import numpy as np
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix, classification_report, accur... |
5aba8b67edf309e0ca7d835934fd954adec42060d0cd98dc6bf0aa1b9ea9a7b3 | Python | 3,927 | 115 | # -*- coding: utf-8 -*-
# @File name: t-test_continuous-laser.py
# @Author: Alicia Garrido-Peña
# @Date: 2023-08-04 12:57:08
# @Contact: alicia.garrido@uam.es
# "Copyright (c) 2023 Alicia Garrido-Peña. All Rights Reserved."
# Use of this source code is govern by GPL-3.0 license that
# can be found in the LICENSE fi... |
f9eb77df5cef1d5bbb3d5c0d919960718d5da980a80f2b0600be1df2c8cb7a84 | Python | 3,927 | 116 | # Copyright 2018-2021 Xanadu Quantum Technologies 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... |
1432f99f30bebad3746d8872f5bb087b30fdee8c8e61078928d515b80a6fc6bb | Python | 3,929 | 115 | ''' find_duplicate_slides.py
Find slide codes with mutiple samples in neuronBridge
'''
__version__ = '1.0.0'
import argparse
import collections
from operator import attrgetter
import sys
import jrc_common.jrc_common as JRC
# pylint: disable=broad-exception-caught,logging-not-lazy,logging-fstring-interpolation
# ... |
66bc9d77260fcb37a61f7eea4ae129fdf7ccd26c5a6e469bb894ae959b8eff2e | Python | 3,929 | 180 |
# # import libraries
import pandas as pd
from pandas import DataFrame
import itertools
from nltk.stem.isri import ISRIStemmer
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
#from sklearn import cross_validation# from sklearn.model_selection import train_test_split
from sklearn.model_sel... |
f896dfe38a1ca3044fee7a595537711743cbff8c76d5eb5ba41ed39d4be85cd2 | Python | 3,929 | 132 | # Module: containers.base_container
# Author: Antoni Baum (Yard1) <antoni.baum@protonmail.com>
# License: MIT
import inspect
from typing import Any, Dict, Optional
import pycaret.utils.generic
class BaseContainer:
"""
Base container class, for easier definition of containers. Ensures consistent format
b... |
d08325b7bbf62f9ffb2ba1f9f069a506490ca0dd1c892b9968e6a9e66082e03f | Python | 3,932 | 109 | import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import font_manager
import os
#%%
def get_figures(n_rows,n_cols,figsize=(10,10),sharex=True,sharey=True) -> (plt.figure, plt.axes):
""" Get figure and axes object
args:
n_rows: number of rows
n_cols:... |
61ad79e177710a4f78fd8bc506fc937f65224a3a65bf9447f59b45e51081b1f6 | Python | 3,937 | 125 | """Test lme4 functionality"""
import pathlib
import socket
from dclab.lme4 import rsetup
from shapeout2.gui.main import ShapeOut2
from shapeout2 import session
from shapeout2.gui.compute.comp_lme4 import ComputeSignificance
import pytest
if not (rsetup.has_r() and rsetup.has_lme4()):
pytest.skip(allow_module_lev... |
3db3b00897f1c8772f28a67aae15617543004e2759c0bc08fd239707bbc0d746 | Python | 3,944 | 105 | import pandas as pd
from pathlib import Path
from src.transform import OneHotPD
from src.prep import bin_data
class DataSpec():
def __init__(self, data_file: Path, covarities: list, exclude: list, tracer: str, type: list):
self.data_file = data_file
self.covarities = covarities
self.exclud... |
690ea8b64db27ef2f5c635163e938111dc1bd3f8af26caf2d609d676789a02fa | Python | 3,945 | 126 | import re
import pytest
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametrize(
"to_replace,value,expected",
[
# one-to-one
(4, 1, [1, 2, 3]),
(3, 1, [1, 2, 1]),
# many-to-one
((5, 6), 2, [1, 2, 3]),
((3, 2), 1, [1, 1, 1]),
],
)
def test... |
9f99e160baa555b790b012830564841b825f376011fc4c6079b976ed79052842 | Python | 3,945 | 115 | # Copyright 2025 Xanadu Quantum Technologies 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 agre... |
66f0c51f349ddc981d36719d11674b03613ba50231b174e1ef30624b93c4ca28 | Python | 3,947 | 108 | # This table comes from https://github.com/opendatakosovo/cyrillic-transliteration/blob/master/cyrtranslit/mapping.py,
# from the 'cyrtranslit' module. We originally had to reimplement it because
# 'cyrtranslit' didn't work in Python 3; now it does, but we've made the table
# more robust than the one in cyrtranslit.
SR... |
742548e7206b9ad482a322742c160ea077bcb30bc458f564be5a788b7d4b8265 | Python | 3,949 | 119 | #!/usr/bin/env python
__author__ = 'etseng@pacb.com'
"""
Filter away transcripts that are mono-exonic.
Required input: <input_prefix>.gff, .rep.fq, .abundance.txt
Example:
filter_monoexon.py test.collapsed test.collapsed.nomono
"""
import os, sys
from collections import defaultdict
from csv import DictReader,... |
c4b11917513b8684f6532f9489c3aa7192542c107b2066558d0889b74f894ce1 | Python | 3,949 | 106 | # Copyright (c) 2018-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
import sys, argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import dictionary_corpus
from utils impo... |
96156e4b3aa1f2a92c71cda2a0ccf9ace6180a4dbf45c00c242320d24904163b | Python | 3,950 | 126 | import numpy as np
import random
import os
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.axes_grid1 import make_axes_locatable
import time
# import sklearn.linear_model
# from sklearn.model_selection import train_test_split
# from sklearn.linear_model import Perceptron, LogisticRegression
... |
67f217e7381f352ffa35bbb153c0a4df3c604743f55cd4ab2b26e4dd49279e7f | Python | 3,953 | 137 | """
reading and writing data
"""
# pylint: disable=E1101
from __future__ import absolute_import, print_function, division
import logging
logger = logging.getLogger(__name__)
import os
import numpy as np
import tables
from .. import NcsFile, DefaultFilter
from scipy.io import loadmat
SAMPLES_PER_REC = 512
DEFAULT_MA... |
4512271c2af1c272c9ae7bc038963d942d99014b95485c0af222089870412d63 | Python | 3,955 | 155 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Created by Roberto Preste
from collections import namedtuple
import os
import unittest
from unittest.mock import Mock, patch
from mtoolnote.classes import Field, Variant, Annotator
from mtoolnote.constants import NONHUMAN_HEADERS
DATADIR = os.path.join(os.path.dirname(o... |
7f019293fe4da5fc715a9ae9dc7fa37c4f2a785dc0b7eb94ac1611732ccfdad7 | Python | 3,955 | 139 | import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.transforms as transforms
from pathlib import Path
import sys
sys.path.append('../')
from plotting_functions import *
#create figure
fig, ax = plt.subplots()
#set font
plt.rcParams['font.family'] = 'Gargi'
#point to fi... |
20ad3d80453a9e0432b1492116003c5e61179a0e7506626ee006670bcdb5abc5 | Python | 3,956 | 109 | import numpy as np
import pandas as pd
import pandas._testing as tm
class TestEquals:
def test_dataframe_not_equal(self):
# see GH#28839
df1 = pd.DataFrame({"a": [1, 2], "b": ["s", "d"]})
df2 = pd.DataFrame({"a": ["s", "d"], "b": [1, 2]})
assert df1.equals(df2) is False
def t... |
fb37ec20ece292c21a563216ae0f29c1cebd953a60911cc3174a1500af9ab068 | Python | 3,956 | 139 | import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.transforms as transforms
from pathlib import Path
import sys
#sys.path.append('../')
from plotting_functions import *
#create figure
fig, ax = plt.subplots()
#set font
plt.rcParams['font.family'] = 'Gargi'
#point to f... |
448a337523e8ab761a66dfafb03b27aa82a6abdfcb68b548b4ddef2810791a83 | Python | 3,958 | 100 | import torch
import torch.nn as nn
from egnn_pytorch import EGNN
import numpy as np
vocab = ['ALA', 'ARG', 'ASN', 'ASP', 'CYS', 'GLN', 'GLU', 'GLY', 'HIS', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', '*']
class AbFlex(nn.Module):
def __init__(self, dim, res_dim, n_layer, num_neare... |
cbc17908d35796cf22381b94fd4d04af07d8583bcaf9ee17423b4dbf03a0eb1a | Python | 3,959 | 106 | import pytest
import pandas as pd
class TestTimedeltaIndexRendering:
def test_repr_round_days_non_nano(self):
# GH#55405
# we should get "1 days", not "1 days 00:00:00" with non-nano
tdi = pd.TimedeltaIndex(["1 days"], freq="D").as_unit("s")
result = repr(tdi)
expected = "... |
ce9191675b2e962abcbd30463a72f22bec29bc6c4f27209a88270618f7c88df6 | Python | 3,960 | 116 | #!/usr/bin/env python
'''
Testcases for the neural network prediction
'''
import windseer.utils as utils
import windseer.plotting as plotting
import windseer
import numpy as np
import os
import unittest
windseer_path = os.path.dirname(windseer.__file__)
testdata_folder = os.path.join(windseer_path, 'test', 'testdata... |
94f12be974d7f9dd928ae70ac763ab405c1440dbda9dc841d4898e0f2f5700b1 | Python | 3,961 | 115 | import importlib.resources
import webbrowser
from dclab import lme4
from PyQt6 import uic, QtCore, QtGui, QtWidgets
from .comp_lme4_dataset import LME4Dataset
from .comp_lme4_results import Rlme4ResultsDialog
from ..widgets import ShowWaitCursor
class ComputeSignificance(QtWidgets.QDialog):
def __init__(self, ... |
c0eb661686b866ab353648042fae033519c90835d7395d9bf067e83cb2f5d8d0 | Python | 3,962 | 103 | import datetime
class StimulationState:
def __init__(self):
self.status = None
self.result_id = None
class stimulationOperator:
def __init__(self):
self.messenager = None
self.state = StimulationState()
self.events = ['CTOK',
... |
9c88adf0ad15be3ce4406455b4513663feea88c718f112bab3bd59a1ce8f886c | Python | 3,964 | 95 | """Direct Reconstruction by Adjoint Fourier Transform."""
from collections.abc import Callable
from mrpro.algorithms.reconstruction.Reconstruction import Reconstruction
from mrpro.data.CsmData import CsmData
from mrpro.data.DcfData import DcfData
from mrpro.data.IData import IData
from mrpro.data.KData import KData
f... |
4663b68ddafdce91a6aa8cebb7321294f30c658f1166ec94d8db1cc10696f180 | Python | 3,966 | 95 | """
Created by Jude Wells 2023-04-20
Objective is to create a secondary structure matrix for each protein
1) renumbers the pdb file (1-indexed)
2) runs stride to get secondary structure file
3) parses the secondary structure file to create a matrix of secondary structure
# should take around 3 minutes for 1000 structu... |
5ab544ac414f5344d3d9bb9a31db3949e61e03df48e18bc623ca42f525f9a78f | Python | 3,966 | 114 | from operator import methodcaller
import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeries:
@pytest.mark.parametrize("func", ["rename_axis", "_set_axis_name"])
def test_set_axis_name_mi(self, func):
ser = pd.Series(
[11, 21, 31],
inde... |
eead96d43c199838a66206a4acbd563be5b1cac1819186b44db2e0f078074226 | Python | 3,967 | 95 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 10 00:01:51 2022
@author: Eduardo Castro
"""
from botocore.client import Config
import ibm_boto3
import os
import pandas as pd
import numpy as np
import sys
import json
import logging
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(_... |
96649557c9313191780b38fef80ce634524285c3790959f2b18bd89a842e8435 | Python | 3,968 | 122 | from __future__ import annotations
import json
from typing import TYPE_CHECKING
import pyarrow
from pandas.core.dtypes.dtypes import (
DatetimeTZDtype,
IntervalDtype,
PeriodDtype,
)
from pandas.core.arrays.interval import VALID_CLOSED
if TYPE_CHECKING:
from pandas._typing import IntervalClosedType
... |
8106aa7003d3b4bc5ffc546fe80dfbbf395cd4a3bdbc091ace91967bfe946c17 | Python | 3,971 | 107 | import os
import glob
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
from torch_geometric.data import Data
from ssa import sparrow_search_algorithm
from cnn import CNN
from gnn import SimpleGNN
from cbam impor... |
c302031b0a6404f3ed7e177a7e89763622bd1e7d1bd1061f16b05c6556b0a04b | Python | 3,973 | 136 | """
Test extension array for storing nested data in a pandas container.
The ListArray stores an ndarray of lists.
"""
from __future__ import annotations
import numbers
import string
from typing import TYPE_CHECKING
import numpy as np
from pandas.core.dtypes.base import ExtensionDtype
import pandas as pd
from pand... |
1001d494281a6d5c09dc25180921b2e78789096a2b2b810b13f6aabf2f6a5123 | Python | 3,974 | 109 | from base.surfaceExamples import Sphere, Heart
import os
from base.surfaces import Surface
from base.surfaceSection import Hyperplane, SurfaceSection
from base.surfaceMatching import SurfaceMatchingParam
from base.surfaceToSectionsMatching import SurfaceToSectionsMatching
from base import loggingUtils
import numpy as n... |
c7de8855c69e3825e638e9cbe23f05fdd3b11171624282f54448d035281adf0c | Python | 3,974 | 140 | import warnings
import pytest
from pandas.errors import (
AbstractMethodError,
Pandas4Warning,
Pandas5Warning,
PandasChangeWarning,
PandasDeprecationWarning,
PandasPendingDeprecationWarning,
UndefinedVariableError,
)
import pandas as pd
import pandas._testing as tm
@pytest.mark.parametr... |
b5ae5ad067b1a11b5afc2ece7bf589cc0bb8d74d1cc4240596f3372d59657360 | Python | 3,976 | 128 | import numpy
import scipy.sparse
import matplotlib.pyplot as plt
import bionetwork
import torch
from scipy.linalg import eig
from scipy.sparse.linalg import eigs
import plotting
import pandas
networkSize = 100
deltaSize = numpy.double(1e-10)
initialEig = 0.95
density = 0.1
folder = 'figures/SI Figure 6/'
#Generate r... |
e5b4067323b6c18b1686f310bb085e8871b4ecb6076116462a9debbe509b55ee | Python | 3,976 | 83 | # Copyright 2019 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... |
a1c7c1c89808b55220618a8e0d052b2d09eac85fc70598c1e739ac9eef237544 | Python | 3,978 | 109 | #%%
#Imports
import numpy as np
import os
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from matplotlib.gridspec import GridSpec
import matplotlib.backends.backend_pdf
import seaborn as sns
import pandas as pd
# style specs
matplotlib.rcParams['lines.linewidth'] = 0.5
matplotlib.rcParams['lin... |
4adb19f498e99e624f977fa89eec27ce456444ffae15575da8e4df1bd9004b07 | Python | 3,980 | 124 | """
Tests for DataFrame cumulative operations
See also
--------
tests.series.test_cumulative
"""
import numpy as np
import pytest
from pandas.errors import OutOfBoundsTimedelta
import pandas as pd
import pandas._testing as tm
class TestDataFrameCumulativeOps:
# ------------------------------------------------... |
a384b69fedb67c5776686901fa27e0d78a7ea44113c4297747e7ca765d907b5a | Python | 3,980 | 103 | import time
import numpy as np
import torch
from PyQt5 import QtCore
from kilosort.gui.logger import setup_logger
from kilosort.run_kilosort import (
initialize_ops, compute_preprocessing, compute_drift_correction,
detect_spikes, cluster_spikes, save_sorting
)
logger = setup_logger(__name__)
class Kilo... |
6a19ab87ad87e1cf387eb87164f7bc8f15da3aec8c73c28ae700ef61bbe4d933 | Python | 3,984 | 110 | import pickle
import argparse
import numpy as np
from scipy.integrate import ode
from numpy.random import random
###################################################################
# definition of the system equations
def coupled_lorenz_systems(t, xy, epsilon_12, epsilon_21):
"""
Bidirectionally coupled Lor... |
fede48d4f79566a6ed8ce860f33c304a76407166f0435bf4256ebc4aecb61898 | Python | 3,984 | 118 | from typing import Iterable, List, Literal, Optional, Sequence, Tuple, Union
import matplotlib as mpl
import numpy as np
import seaborn as sns
from anndata import AnnData
from matplotlib import pyplot as plt
def volcano_plot(
adata_cc: AnnData,
figsize: Tuple[int, int] = (10, 6),
font_size: int = 1,
... |
f5e1a4c9f3862b5f36578c298127de62d7a8b9ffd3fc140d2e3d586563c6cebb | Python | 3,986 | 114 | # Copyright (c) 2018-2023, NVIDIA Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this
# list of condit... |
af19d6350380e5aaba5cd8dd9a047f4e026116e9963bd560b2a95ed90f5c1665 | Python | 3,987 | 129 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
def test_nlargest():
a = pd.Series([1, 3, 5, 7, 2, 9, 0, 4, 6, 10])
b = pd.Series(list("a" * 5 + "b" * 5))
gb = a.groupby(b)
r = gb.nlargest(3)
e = pd.Series(
[7, 5, 3, 10, 9, 6],
index=pd.MultiIndex... |
9a5c5fd3637a4db283849a8d12f3a3a759ff74aaad391fe8ef4a9053d8a09167 | Python | 3,988 | 112 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import Sequential, Linear, ReLU
from torch_geometric.nn import GINConv, global_add_pool
from torch_geometric.nn import global_mean_pool as gap, global_max_pool as gmp
# GINConv model
class GINConvNet(torch.nn.Module):
def __init__(sel... |
34154cd5ad4ba711f1c68bd14a671e4b43a425907742b0811ff04966a6f39a2d | Python | 3,991 | 95 | import os
import pysam
def parse_ttmars_res(work_dir):
# samples = ["HG00514", "HG00512", "HG00513", "HG00733", "HG00731", "HG00732", "NA19240", "NA19239", "NA19238"]
samples = ["HG00514", "HG00512", "HG00513"]
ttmars_res = {}
vcf_file = pysam.VariantFile(os.path.join(work_dir, "denovo.sv.vcf"))
... |
ada2a8b7029b2249974e8810c1b31b65487c998d777e06f228bb5f8ff2408788 | Python | 3,992 | 153 | """Test Histogram view."""
# ------------------------------------------------------------------------------
# Imports
# ------------------------------------------------------------------------------
import numpy as np
from phylib.utils import Bunch
from ..histogram import FiringRateView, HistogramView, ISIView, _com... |
d8b5b850925504f63ec7fcccc5ba2ac2587c1287c1cbf668504d9090e5ab79ba | Python | 3,994 | 102 | #!/usr/bin/env python3
"""
liftover.py is used to convert all `*.scheme.bed` primer schemes over to the new `*.primers.bed` format now generated by Primal Scheme.
This is essentially taking the old 5-column format and putting it into a 6-column one that conforms to BED standards.
The new format has the following colu... |
fc441eeec0f2001ab7e0a34977ae5ca01c78416eeddf26802ee5d9a5209db672 | Python | 3,994 | 120 | # MOFTransformer version 2.0.0
import numpy as np
from itertools import combinations
from matplotlib import pyplot as plt
from matplotlib.colors import Normalize
import matplotlib.ticker as mticker
from ase.data import covalent_radii
from moftransformer.assets.colors import cpk_colors
from moftransformer.visual... |
aac715e3839b529ff132f509aedf566c1e3c2f78cc1e0f187e29ccea2c2b44b5 | Python | 3,996 | 133 | import pytest
import pandas as pd
from pandas.core.strings.accessor import StringMethods
_any_string_method = [
("cat", (), {"sep": ","}),
("cat", (pd.Series(list("zyx")),), {"sep": ",", "join": "left"}),
("center", (10,), {}),
("contains", ("a",), {}),
("count", ("a",), {}),
("decode", ("UTF-... |
f5abd2eff8e8aad46ce0dc9947b7c11eb40a89fe8941fdb9b2da856d533c643c | Python | 3,996 | 84 | from terminaltables import SingleTable
import psutil
# Compression rations according to the lvl of resultion. Experty values.
ratio_comp = {-1:3, 0:6, 1:15, 2:15, 3:30}
def display_configuration(param, neurons, n_chunks):
nbytes = param['integrations']*param['n_Iapp']*neurons*param[param['dtype']]
config = [[... |
d434fbf8d619fef3c4121eaf727db3130dec6662aa96dac57847a5b145bfe74f | Python | 3,998 | 122 | #####################################################################################################################
# Date created : 10/21/2022
# Date modified: 10/21/2022
# Purpose : This program is to crate features from pdb (dssp) complementary ss, sa, angle features and relative spetial position of a resi... |
da436d0b03f804db92aaf8a78321bd4c7fde3d6201f25f5389a09f63989c2b81 | Python | 3,998 | 118 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
class TestSeriesRound:
def test_round(self, datetime_series):
datetime_series.index.name = "index_name"
result = datetime_series.round(2)
expected = pd.Series(
np.round(datetime_series.values, 2)... |
9a5865f8a6c92b90e567d5fb856a6166610a19bdf73c38821b3adaa7ccc3fcdb | Python | 4,000 | 84 | #!/usr/bin/env python
#SBATCH -c 2
#SBATCH --mem 32G
#SBATCH --time 5-00:00:00
#SBATCH -J JJJ
#SBATCH -o temp/slurm-%j.out
import os, sys
import numpy as np
import pandas as pd
def read_pairs(pairs_path):
pairs = pd.read_csv(pairs_path, compression='gzip', sep='\t', comment='#', header=None)
pairs.columns = [... |
e9033094ff5a3a4de45293fb905b9149653fd3be684384424293576ffcefab70 | Python | 4,003 | 97 | """Tests for `multimodal_ad.data.augmentation`."""
import numpy as np
from scipy.ndimage import rotate as ndimage_rotate
from multimodal_ad.data.augmentation import (
_CORNER_PATCH_SIZE,
_flip_horizontal,
_flip_vertical,
_rotate_frame,
augment_volume,
)
def test_augment_volume_preserves_shape() ... |
c2f3b4475fa7392b85c5cac12b139d923497cd9bdc1b76b0c3f059853bf4b8f8 | Python | 4,004 | 105 | """Subprocess driver: exercise only the public PeakModel workflow."""
import importlib
import json
import os
from pathlib import Path
import sys
import threading
from types import SimpleNamespace
import numpy as np
from MACS3.Signal.FixWidthTrack import FWTrack
def treatment(kind, two_strands=False):
track = F... |
7be8ee3f388879e835d5604746601aff3562e5f7be36130ab223359125bef8e0 | Python | 4,005 | 123 | import numpy as np
import pytest
import pandas as pd
import pandas._testing as tm
from pandas.api.types import (
infer_dtype,
is_object_dtype,
is_string_dtype,
)
class BaseDtypeTests:
"""Base class for ExtensionDtype classes"""
def test_name(self, dtype):
assert isinstance(dtype.name, st... |
4abaa9154aa6a7358db3882fdccbc4009a41a33c391e9702cef42edb7aad129d | Python | 4,008 | 106 | # -*- coding: utf-8 -*-
import numpy as np
from ..state import State
from .move import Move
__all__ = ["RedBlueMove"]
class RedBlueMove(Move):
"""
An abstract red-blue ensemble move with parallelization as described in
`Foreman-Mackey et al. (2013) <https://arxiv.org/abs/1202.3665>`_.
Args:
... |
531820abd7b1e317dfc8876b23dcf50440f78b628a9c4eae1375b6d5a200662f | Python | 4,010 | 109 | """Local-filesystem ObjectStore driver.
Default dev backend. Stores blobs under ``settings.artifact_dir`` and
returns ``file://`` URIs. The directory tree mirrors the key — so
``key="runs/abc/pipeline.pkl"`` lands at
``<artifact_dir>/runs/abc/pipeline.pkl`` — keeping the on-disk layout
human-debuggable.
"""
from __fu... |
ef9f7166f6e6b62b89ccc831ae4d4a4574751c1b2ed0f595ad4287a65b8f7c3d | Python | 4,010 | 136 | from typing import Tuple, Union, Optional
import os
import nibabel as nib
import torch
import numpy as np
from ..transform import RigidTransform
from ..utils import PathType
def compare_resolution_affine(r1, a1, r2, a2, s1, s2) -> bool:
r1 = np.array(r1)
a1 = np.array(a1)
r2 = np.array(r2)
a2 = np.arr... |
42f95691b4fb8de46b30af3c0971e9c147dc2cb8db948f6d961f1c803e0c735f | Python | 4,011 | 143 | # ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.14.1
# kernelspec:
# display_name: ol-c-kernel
# language: python
# name: ol-c-kernel
# ---
# %% [markdown]
# ## Get adjacency matrix by ... |
bcf106726703fbd1088c2e198ba7db58a19828dc2a954372e8bf7279af7ead68 | Python | 4,012 | 99 | import argparse
import pandas as pd
import json
import csv
import os
from onmt.utils.properties import add_property,mols_from_smiles,condition_convert
from onmt.utils.motif_extration import Motif_Fragment, Scaffold_Fragment, del_mapid
from sklearn.model_selection import train_test_split
from itertools import chain
du... |
40ea423f8fccac0ce6f2527228c72f2de80bb6c534a26c63f9fc0bc744af0cb5 | Python | 4,013 | 107 | """Train a model on a Slurm HPC cluster.
To run the model outside the cluster, simply change the main commands.
"""
import argparse
import os
import pytorch_lightning as pl
import sys
sys.path.append('')
import functions.datasets as datasets
import functions.sgc_resnets as sgc
def float_interval(lower=None, upper... |
041bb57a82802f0724156e243cc496164120204192361f965c687c749391accd | Python | 4,014 | 114 | """Failure debugger — reads a failed Run's error + event tail and suggests fixes.
UX: inline card on `/runs/:id` when `run.status == 'failed'`. The card's
payload is the exact error string + the final slice of the event stream
(where the failure is), so the LLM can tell the user whether it's a data
problem, a config p... |
72fb7bc372f9987c87443b55b8aaf44fe3965140305672e3e826e5dae67f369e | Python | 4,014 | 147 | """
This script performs multi-band SENSE reconstruction
for single-shot EPI acquisition.
Authors:
Zhengguo Tan <zhengguo.tan@gmail.com>
"""
import h5py
import os
import torch
import numpy as np
import sigpy as sp
from sigpy.mri import app, sms
from pathlib import Path
# %%
def MbSenseRecon(kdat, coil, sms_pha... |
8dd139246f55abd63cdc86596e0fa22342a64c032f28f5221954eff90f313b51 | Python | 4,014 | 118 | from io import (
BytesIO,
StringIO,
)
import uuid
import pytest
import pandas as pd
import pandas._testing as tm
def test_compression_roundtrip(compression, temp_file):
df = pd.DataFrame(
[[0.123456, 0.234567, 0.567567], [12.32112, 123123.2, 321321.2]],
index=["A", "B"],
columns=... |
3be604141f946c93124665947e21d952af13061e53ae6d9f08a7921b4aed6426 | Python | 4,018 | 140 | import unittest
from unittest import TestCase
from evcouplings.utils import *
import tempfile
class TestUtilsHelpers(TestCase):
def test_wrap(self):
"""
Test whether string is correctly wrap
"""
out = wrap("Test", width=2)
self.assertEqual("Te\nst", out)
def test_rang... |
64468a027657c4353e00f59997e31827d4e1da4cc3f60d910ac1f94a3da4fcf4 | Python | 4,022 | 163 | """
General calculation functions.
Authors:
Thomas A. Hopf
"""
import numpy as np
def entropy(X, normalize=False):
"""
Calculate entropy of distribution
Parameters
----------
X : np.array
Vector for which entropy will be calculated
normalize:
Rescale entropy to range from ... |
65bb33e0596b3129a07b0788ae14f5d2f318c91e2606a52f187d3855c48918af | Python | 4,024 | 118 | # -*- coding: utf-8 -*-
import numpy as np
from .mh import MHMove
__all__ = ["GaussianMove"]
class GaussianMove(MHMove):
"""A Metropolis step with a Gaussian proposal function.
Args:
cov: The covariance of the proposal function. This can be a scalar,
vector, or matrix and the proposal ... |
8e429396cc888a73dbd966b0010a0355aaae772b8557b1f1304f57af00b4f19d | Python | 4,024 | 108 | import dgl
import torch
import random
import numpy as np
from torch.utils.data.dataloader import DataLoader
from sklearn.model_selection import KFold, StratifiedKFold
def collate(sample):
graphs, labels = map(list,zip(*sample))
batched_graph = dgl.batch(graphs)
batched_graph.set_n_initializer(dgl.init.zer... |
791ebdbbd1ea57819dcafa982caf45d2605874111b1dd31f1a2ea6c76e0da049 | Python | 4,026 | 95 | import sys, os, re, collections
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', 'resource-gcg', 'scripts'))
import tree
from storestate import Sign, StoreState, getArity #, getParentContexts, getRchildContexts
def arityGivenCat(cat):
arity = getArity(cat)
return arity+1 if cat[0]=='N' and not... |
455d632447166f98d00544af3cdf878df26b91803ec3d0a558c1bca03ebdfa23 | Python | 4,029 | 122 | import numpy as np
import pytest
from pandas._libs import lib
import pandas as pd
import pandas._testing as tm
def test_string_array(nullable_string_dtype, any_string_method):
method_name, args, kwargs = any_string_method
data = ["a", "bb", np.nan, "ccc"]
a = pd.Series(data, dtype=object)
b = pd.Se... |
bb7f382905930e6a8c6b1318072d4860ab91fb7aba011e2a770e6a53a10321cc | Python | 4,030 | 138 | """First-run bootstrap routes.
The frontend checks ``GET /api/v1/setup/status`` on load. If
``is_bootstrapped == false``, it redirects to a setup wizard that POSTs to
``/api/v1/setup/bootstrap`` with admin credentials + workspace name. The
bootstrap creates:
- a ``User`` row (superuser, active)
- a ``Workspace`` row
... |
5d8341254dff58a396c2d60b063a61b6096fc901a0355d300817224b4dab10ed | Python | 4,032 | 114 | """Phase 6 cross-process pub/sub for run events.
In Phase 0/1 the event broker (``runs/broker.py``) fans events within
a single Python process via ``asyncio.Queue``. That stops working when
the worker runs in a separate container (Phase 1 ``runs_backend=redis``):
the worker fits a model, emits events to its in-process... |
67045a2c5ec0b411658986fe5dc140f10129251e5bef8ac1ccfda132119a6344 | Python | 4,032 | 138 | # MOFTransformer version 2.2.0
import sys
import warnings
import pytorch_lightning as pl
from moftransformer.database import (
DEFAULT_PMTRANSFORMER_PATH,
DEFAULT_MOFTRANSFORMER_PATH,
)
if pl.__version__ >= "2.0.0":
from pytorch_lightning.trainer.connectors.accelerator_connector import (
... |
0b20e9f6847a40bbe43d6f638fd90db3bdecbd7cb7f9c5a0e43279ee7fcf5924 | Python | 4,033 | 163 | import h5py
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle
import numpy as np
import os
DIR = os.path.dirname(os.path.realpath(__file__))
print('> current directory: ', DIR)
# %% ablation 1: regularization weight
print('> ablation 1')
fig, ax = plt.subplots(1, 3, figsize=(12, 4))
f = h5py.F... |
19ce50669e62abd13af79affed23056f8dba04a1b35fd1469ac9e0ee75a59d4b | Python | 4,035 | 138 | """
Test cases for fold stage of EVCouplings pipline
Currently only tests complex_dock protocol and its called functions
TODO: fix circular import of COMPLEX_CHAIN_NAMES
Author:
Anna G. Green
"""
import unittest
import os
import ruamel.yaml as yaml
from unittest import TestCase
from evcouplings.fold import haddo... |
2f7fc87216853c25156b30eda24eb072f89a05f3dfc6f477043e53cc96b82d2f | Python | 4,036 | 120 | from time import time
import hnswlib
import numpy as np
import queue
class HNSW3:
def __init__(self, mat, M, ef, k, base_step):
self.M = int(M)
self.ef = int(ef)
self.k = int(k)
self.base_step = int(base_step)
self.fit(mat)
self.g = []
def get_base(self, node, m... |
b5006c0c9b5ec1f52ad63abd698d0fbe0cb528bc441483ef36db3917b109511a | Python | 4,036 | 70 | from Environment import *
from Parameter import *
from Analysis.freesia_export_to_BrainRegion import genSingleRegion, genPointsSingleRegion
def get_multi_region(region_color, image_root, atlas_root, Region_root, Points_SingleRegion_root, get_point=False):
region_name = region_color.keys()
color = region_color.... |
f5272be348fe67213acd4a8293cb368684fede9cf08b084e7b51c5024fb9885c | Python | 4,038 | 122 | import gzip
import os
import numpy as np
from utils import mesFlush
import joblib
class PET(object):
__slots__ = [
"chromL", "chromR",
"startL", "startR",
"endL", "endR",
"strandL", "strandR",
"cL", "cR",
"distance"
]
def __init__(self, date):
"""
... |
bb08c6a3792c1794f7a934a484ee965c91c90eda73417c97b026a92449e29cab | Python | 4,041 | 156 | import matplotlib.pyplot as plt
import matplotlib
from matplotlib.colors import LinearSegmentedColormap
import numpy as np
import pandas as pd
import sys
import seaborn as sns; sns.set()
import statistics as stat
import matplotlib.font_manager as mfm
mfm.findSystemFonts(fontpaths=None, fontext='ttf')
sns.set(font_scal... |
d26e679a7a0fe163c1595ebd6ef3c5a5a31651aaf687de56b9427353002f08ba | Python | 4,042 | 105 | 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='checkpoint.pth'):
"""
Args:
patience (int): How long to wait after last time v... |
b65a16db0679df0e182fd3596de7d670e4737b455ae5b07f4f57fe48dfac94c3 | Python | 4,043 | 81 | import pandas as pd
from progressbar import ProgressBar
import cv2
import os
def extract_images(video_path, image_path, cropped=False, max_frames=None, target_class=['COVID', 'Pneumonia', 'Normal'], target_source=['Butterfly', 'GrepMed', 'LITFL', 'PocusAtlas'], target_probe=['convex', 'linear']):
"""
Func... |
17033b206a1f73888e7562841ed1f456b3753c4d45435e9673ed2901dbb7961b | Python | 4,044 | 114 | # Copyright 2024 Xanadu Quantum Technologies 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 agre... |
8964254dd8a154d37d4978aa4fc5d03c9b7e5f1a7493029c544620b4b9b54df0 | Python | 4,046 | 110 | import numpy
import pandas
import matplotlib.pyplot as plt
#Hyper parameters
countCutOf = 2e6
geneCutOf = 5000
ensembl2geneData = pandas.read_csv('filtered/ensemblTable.tsv', sep='\t', low_memory=False)
ensembl2gene = dict(zip(ensembl2geneData['Source'], ensembl2geneData['external_gene_name']))
counts = pandas.read_... |
15286a181c09067f197c466ba565f67601743a123cf6571e6efe2f54a2b9f33b | Python | 4,047 | 99 | """L1 Norm with :math:`C` as :math:`R^2`."""
import torch
from mrpro.operators.Functional import ElementaryProximableFunctional, throw_if_negative_or_complex
class L1NormViewAsReal(ElementaryProximableFunctional):
r"""Functional class for the L1 Norm, where C is identified with :math:`R^2`.
This implements... |
f18d7e1a581f9dc2d9ea3f8f4c07ed6a8eafe5b8ae495546a983ed0a96360734 | Python | 4,048 | 105 | import numpy as np
import matplotlib.pyplot as plt
import sys
import os
from kcsd import sKCSD
from kcsd import sKCSD_utils as utils
import kcsd.validation.plotting_functions as pl
import sKCSD_utils
dt = 0.5
if __name__ == '__main__':
fname_base = "Figure_7"
fig_name = sKCSD_utils.make_fig_names(fname_base + '... |
28fc09bbfebf2d1c06082fd5adfae7bedbda96884c0e2d6a4c80c0aaa5818156 | Python | 4,050 | 116 | import numpy as np
class YOLOV5DataSetConfig:
root_path: str = 'F:/RSI/NWPU'
image_net_dir: str = 'F:/RSI/NWPU/JPEGImages'
# data set root dir
image_size: tuple = (608, 608)
image_shrink_rate: dict = {
'for_s': (8, 8),
'for_m': (16, 16),
'for_l': (32, 32),
}... |
cd6a7d7904c46506aaf8c2477d6f019225d3df0409cd8813a831b86c427de499 | Python | 4,053 | 81 | """
Several methods to automate edits to bids database.
"""
import os
from csv import DictReader
from glob import glob
def load_participants(bids_database):
participants = {}
with open(os.path.join(bids_database, 'participants.tsv'), 'r') as f:
reader = DictReader(f, delimiter='\t')
for row i... |
1b1f48bd3fd45a12455f0a383564e0a93742871e10624543b62e507e673c1c82 | Python | 4,056 | 90 | import numpy as np, matplotlib.pyplot as plt, sys
import pumpprobe as pp, wormdatamodel as wormdm
ds_list = "/projects/LEIFER/francesco/funatlas_list.txt"
req_auto_response = True#"--req-auto-response" in sys.argv
funa = pp.Funatlas.from_datasets(
ds_list,merge_bilateral=True,merge_dorsoventral=False,... |
cc7691217c45c08af7224f7c2a68aba99195a28e3c4ff6126628b8df0a6c7832 | Python | 4,057 | 117 | """
test_insert is specifically for the DataFrame.insert method; not to be
confused with tests with "insert" in their names that are really testing
__setitem__.
"""
import numpy as np
import pytest
from pandas.errors import Pandas4Warning
import pandas as pd
import pandas._testing as tm
class TestDataFrameInsert:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.