text stringlengths 185 73.3k | repo stringlengths 7 100 | path stringlengths 4 146 | language stringclasses 7
values | hash stringlengths 16 16 | score float64 7 8.5 | stars int64 0 237k |
|---|---|---|---|---|---|---|
"""Platform for switch integration."""
import logging
from typing import Any
from homeassistant.components.switch import (
SwitchEntity,
SwitchDeviceClass
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import STATE_ON
from homeassistant.core import HomeAssistant
from homeassi... | toscano/hass-autonomic | custom_components/autonomic/switch.py | .py | 4623f5a63f525852 | 7.45 | 7 |
import numpy as np
import pandas as pd
import scanpy as sc
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
import umap
import anndata as ad
import igraph as ig
from palettable.scientific.sequential import LaJolla_20, Batlow_20
from anndata import AnnData
from scipy.sp... | CahanLab/PySingleCellNet | src/pySingleCellNet/plotting/dot.py | .py | 36be88468e2b478d | 7.64 | 18 |
from __future__ import annotations
from typing import Dict, List, Optional
import numpy as np
import pandas as pd
from scipy import sparse
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import pdist
import matplotlib.pyplot as plt
def plot_module_heatmap(
adata,
*,
un... | CahanLab/PySingleCellNet | src/pySingleCellNet/plotting/fancy.py | .py | bc6e225fc6aa37ee | 7.64 | 18 |
import numpy as np
from matplotlib.colors import ListedColormap, to_rgb
import matplotlib.tri as mtri
from scipy.interpolate import griddata
from scipy.ndimage import gaussian_filter
from matplotlib.colors import to_hex
import matplotlib.pyplot as plt
import contextlib
@contextlib.contextmanager
def _temp_plt_axes(fig... | CahanLab/PySingleCellNet | src/pySingleCellNet/plotting/helpers.py | .py | 76c2f5df439dc955 | 7.64 | 18 |
import numpy as np
import pandas as pd
import igraph as ig
from anndata import AnnData
import scanpy as sc
def _add_scn_class_cat(adata: AnnData):
"""Add a new '.obs' column 'SCN_class_cat' to an AnnData object.
The value of 'SCN_class_cat' is taken from `.obs['SCN_class_emp']` when
`.obs['SCN_class_type... | CahanLab/PySingleCellNet | src/pySingleCellNet/tools/categorize.py | .py | 6a1c09704e19f6c3 | 7.64 | 18 |
from __future__ import annotations
from typing import List, Dict, Optional, Sequence, Tuple, Any, Union
import itertools
import numpy as np
import pandas as pd
import scanpy as sc
import anndata as ad
import igraph as ig
def cluster_alot(
adata,
leiden_resolutions: Sequence[float],
prefix: str = "autoc",
... | CahanLab/PySingleCellNet | src/pySingleCellNet/tools/cluster.py | .py | 3b043635603c4fce | 7.64 | 18 |
from __future__ import annotations
from typing import List, Optional, Tuple, Union, Sequence, Dict
import itertools
import numpy as np
import pandas as pd
from scipy.cluster.hierarchy import linkage, fcluster
# (No large dense pairwise matrices; we only compute distances within lenient components)
# ----------------... | CahanLab/PySingleCellNet | src/pySingleCellNet/tools/cluster_cliques.py | .py | 429233d254ac21c8 | 7.64 | 18 |
import numpy as np
import pandas as pd
import scanpy as sc
import anndata as ad
from anndata import AnnData
import warnings
import gseapy as gp
import os
import copy
import igraph as ig
from collections import defaultdict
def deg(
adata: AnnData,
sample_obsvals: list = [], # Impacts the sign of the test stati... | CahanLab/PySingleCellNet | src/pySingleCellNet/tools/comparison.py | .py | 3b844f5428ce2b78 | 7.64 | 18 |
import warnings
import numpy as np
import pandas as pd
import scanpy as sc
import re
import csv
from collections import defaultdict
def create_gene_structure_dict_by_stage(file_path, stage):
"""Create a dictionary mapping structures to lists of genes expressed at a specific stage.
Designed for parsing output ... | CahanLab/PySingleCellNet | src/pySingleCellNet/utils/annotation.py | .py | 491e9860094f982e | 7.64 | 18 |
"""Persistence for trained SCN classifiers.
A trained classifier is a plain dict, and the usual way to share one is to
pickle it. Routing that through `save_classifier` / `load_classifier` gives the
payload a format version -- so the on-disk layout can change without silently
mispredicting -- and gives loading a singl... | CahanLab/PySingleCellNet | src/pySingleCellNet/utils/classifier_io.py | .py | cdc4ec1c6a7f1736 | 7.64 | 18 |
import matplotlib.pyplot as plt
import numpy as np
def get_unique_colors(n_colors):
"""Generate a list of unique colors from the Tab20, Tab20b, and Tab20c colormaps.
Args:
n_colors: The number of unique colors needed.
Returns:
A list of unique colors.
"""
# Get the colormaps
t... | CahanLab/PySingleCellNet | src/pySingleCellNet/utils/colors.py | .py | 901d3281c1ed260d | 7.64 | 18 |
from __future__ import annotations
import numpy as np
import pandas as pd
import scanpy as sc
import anndata as ad
import igraph as ig
def build_knn_graph(correlation_matrix, labels, k=5):
"""Build a k-nearest neighbors (kNN) graph from a correlation matrix.
Args:
correlation_matrix: Square correlatio... | CahanLab/PySingleCellNet | src/pySingleCellNet/utils/knn.py | .py | 41bf74e1cf32fb5c | 7.64 | 18 |
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import AnnData
from scipy.stats import median_abs_deviation
def call_outlier_cells(adata, metric = ["total_counts"], nmads = 5):
"""Determines whether obs[metric] exceeds nmads.
Args:
adata: The input AnnData object containing sin... | CahanLab/PySingleCellNet | src/pySingleCellNet/utils/qc.py | .py | 175f82da6bb6386e | 7.64 | 18 |
"""Session-scoped fixtures for PySingleCellNet tests.
Loads small test data once per session and trains classifier once.
Run `python tests/generate_test_data.py` first to create the fixtures.
"""
import os
import pytest
import scanpy as sc
import numpy as np
DATA_DIR = os.path.join(os.path.dirname(__file__), "data")... | CahanLab/PySingleCellNet | tests/conftest.py | .py | 9145f2c1ce6435b8 | 8.14 | 18 |
#!/usr/bin/env python
"""Generate small test fixtures from the full data files in data/.
Run once from the repo root:
python tests/generate_test_data.py
Creates three small .h5ad files in tests/data/:
- pbmc_ref_small.h5ad (~320 cells, 2000 HVGs)
- pbmc_query_small.h5ad (~500 cells, common genes)
- ... | CahanLab/PySingleCellNet | tests/generate_test_data.py | .py | 3b3c9e5dc5c9dbd9 | 8.14 | 18 |
"""Tests for the categorize pipeline."""
import warnings
import numpy as np
import pandas as pd
import pytest
import scanpy as sc
def _warnings_mentioning(recorded, needle):
"""Messages among `recorded` that mention `needle`."""
return [str(w.message) for w in recorded if needle in str(w.message)]
def tes... | CahanLab/PySingleCellNet | tests/test_categorize.py | .py | f1e7099fc4836139 | 8.14 | 18 |
"""Tests for the quickstart classifier pipeline."""
import numpy as np
import pandas as pd
import pytest
import scanpy as sc
def test_limit_anndata_to_common_genes(pbmc_ref, pbmc_query):
"""After limiting to common genes, var_names should match."""
from pySingleCellNet.utils.adataTools import limit_anndata_t... | CahanLab/PySingleCellNet | tests/test_classifier.py | .py | ded726e19af7563b | 8.14 | 18 |
"""Tests for classifier persistence.
Trained classifiers are normally shared as pickled dicts. Without a save/load
pair there is nowhere to record a format version and nowhere to validate a
loaded object, so a malformed one surfaces as an AttributeError from deep
inside prediction instead of a clear message at load ti... | CahanLab/PySingleCellNet | tests/test_classifier_io.py | .py | aca9e1094f8ffde6 | 7.14 | 18 |
"""Tests for the cluster_alot pipeline."""
import numpy as np
import pandas as pd
import pytest
import scanpy as sc
@pytest.fixture(scope="module")
def clustered_pijuan(pijuan):
"""Prepare and run cluster_alot on the Pijuan dataset."""
from pySingleCellNet.tools.cluster import cluster_alot
ad = pijuan.c... | CahanLab/PySingleCellNet | tests/test_clustering.py | .py | 7796a7ea1258b692 | 8.14 | 18 |
"""Tests for the cell-type relatedness graph travelling with the classifier.
`categorize_classification` splits multi-class cells into Intermediate (the
classes are close in a cell-type graph) and Hybrid (they are not). The graph is
built from the reference, so anyone who receives only a trained classifier
could not r... | CahanLab/PySingleCellNet | tests/test_ct_graph.py | .py | a4617fe3d4ae036b | 8.14 | 18 |
"""Tests for query/classifier gene-overlap reporting.
A classifier gene absent from the query is reindexed to a column of zeros, so
every pair feature involving it collapses to a constant. The forest still
returns confident-looking scores, so the failure is invisible without an
explicit overlap check.
"""
import pyte... | CahanLab/PySingleCellNet | tests/test_gene_overlap.py | .py | 5498fe6e58f0f1e0 | 8.14 | 18 |
"""Tests for gene-pair encoding.
Top-scoring pairs used to be identified only by the string ``f"{a}_{b}"`` and
recovered by splitting on ``_``, so any gene symbol containing an underscore
decoded into fragments that are not genes. Spatial and module-style datasets
name genes that way routinely.
"""
import pickle
imp... | CahanLab/PySingleCellNet | tests/test_gene_pairs.py | .py | 85b7e29b31d69c2f | 8.14 | 18 |
"""Package-level API surface tests."""
import importlib.metadata
import pytest
def test_version_is_exposed():
"""`__version__` is advertised in __all__, so it must actually resolve."""
import pySingleCellNet as cn
assert isinstance(cn.__version__, str)
assert cn.__version__
def test_version_match... | CahanLab/PySingleCellNet | tests/test_package.py | .py | 69eeefc835130505 | 7.14 | 18 |
"""Smoke tests for plotting functions (no-error checks with Agg backend)."""
import matplotlib
matplotlib.use("Agg")
import numpy as np
import pandas as pd
import pytest
import scanpy as sc
def test_heatmap_scores(classified_query):
"""heatmap_scores should run without raising."""
from pySingleCellNet.plott... | CahanLab/PySingleCellNet | tests/test_plotting.py | .py | 6a9f694df740b5d4 | 8.14 | 18 |
"""Tests for the prediction path: densification cost and score stability.
`_scn_predict` used to densify the entire query (n_cells x n_genes) before
subsetting it to the few hundred genes the classifier actually needs, so peak
memory scaled with the dataset rather than with the classifier.
"""
import numpy as np
impo... | CahanLab/PySingleCellNet | tests/test_predict.py | .py | 8ad2f833821a5c5e | 7.14 | 18 |
"""Tests that training the same classifier twice gives the same classifier.
Two independent sources of drift: gene pairs were drawn from the unseeded
`random` module, and the candidate gene lists were de-duplicated through
`set()`, whose iteration order for strings varies with PYTHONHASHSEED. The
second means results ... | CahanLab/PySingleCellNet | tests/test_reproducibility.py | .py | d988b70a5f81adcd | 8.14 | 18 |
"""Tests for utility functions."""
import numpy as np
import pandas as pd
import pytest
import scanpy as sc
def test_rename_cluster_labels(pijuan):
"""rename_cluster_labels should create a new column with short labels."""
from pySingleCellNet.utils.adataTools import rename_cluster_labels
ad = pijuan.cop... | CahanLab/PySingleCellNet | tests/test_utils.py | .py | c1953d34b26b7e94 | 8.14 | 18 |
import numpy
def load_variable_from_file(filepath, variable_names):
"""Load the variable 'variable_name' for a file at filepath
:param filepath: path to the file to read
:type filepath: str
:param variable_names: Name of the variable(s) to read in file
:type variable_names: str or list
:return... | llnl/kosh | examples/some_user_io_functions.py | .py | 0f293100c6b52f1c | 7.5 | 9 |
# Ultra files loader contributed by Josh Kallman 5/6/2020
from .core import KoshLoader
import sys
import os
import numpy
sys.path.append("/usr/gapps/pydv/current") # noqa
class UltraLoader(KoshLoader):
"""Kosh Loader for ultra files"""
types = {"ultra": ["curves", "curves/pydv", "curves/pdv", "pydv", "pdv",
... | llnl/kosh | kosh/loaders/UltraLoader.py | .py | d21843ba80a30141 | 7.5 | 9 |
from __future__ import print_function, division
from .core import KoshLoader
def walk_hdf5(dataset, prefix=""):
"""Walk through hdf5 groups to find all datasets and return their paths
return generator
:param dataset: hdf5 dataset to start walking from
:type dataset: h5py._hl.dataset.Dataset
:param... | llnl/kosh | kosh/loaders/hdf5.py | .py | 498d71b0fd4d87b4 | 7.5 | 9 |
from .core import KoshLoader
class PandasLoader(KoshLoader):
""" Kosh loader to load data using Pandas"""
types = {"pandas/csv": ["DataFrame", ],
"pandas/excel": ["DataFrame", ],
"pandas/pickle": ["DataFrame", ],
"pandas/table": ["DataFrame", ],
"pandas/fwf... | llnl/kosh | kosh/loaders/pandas_loader.py | .py | e4803a50714341cb | 7.5 | 9 |
from .core import KoshLoader
def read_chunk(f, end='\n'):
out = ""
cont = True
while cont:
r = f.read(1).decode()
if r == end:
return out
out += r
class PGMLoader(KoshLoader):
types = {"pgm": ["numpy", ]}
def __init__(self, obj, **kargs):
"""PGMLoader... | llnl/kosh | kosh/loaders/pgm.py | .py | ffc8224bd2538c5e | 7.5 | 9 |
from .core import KoshLoader
class PILLoader(KoshLoader):
types = {"png": ["numpy", "bytes"],
"gif": ["numpy", "bytes"],
"image": ["numpy", "bytes"],
"tiff": ["numpy", "bytes"],
"pil": ["numpy", "bytes"],
"tif": ["numpy", "bytes"]}
def __init__... | llnl/kosh | kosh/loaders/pil.py | .py | 8e86b4fd26632d9a | 7.5 | 9 |
from filelock import FileLock, Timeout
from collections.abc import Generator
import time
import functools
import os
import logging
LOGGER = logging.getLogger()
LOGGER.setLevel(int(os.environ.get('LOCK_STRATEGIES_LOG_LEVEL', 30))) # 30 is logging.WARNING
pid_map = {}
def lock_function(func):
"""
Decorator t... | llnl/kosh | kosh/lock_strategies.py | .py | 584ced0997130e67 | 7.5 | 9 |
from ..exec_graphs import KoshExecutionGraph
from abc import abstractmethod
import hashlib
from kosh import kosh_cache_dir
import os
import functools
class KoshOperator(KoshExecutionGraph):
# TODO something about operator accepting multiple types in (list?)
# For now assuming it is type of first input receive... | llnl/kosh | kosh/operators/core.py | .py | e33c7b3952d9641c | 7.5 | 9 |
def auto_valid(validation):
"""auto_valid converts class type
to their 'isinstance' function in the future other
keyword maybe added to the list
:param validation: class def or type
:type validation: type
:return: isinstance lambda function or validation function
:rtype: function
"""
... | llnl/kosh | kosh/schema.py | .py | e7c90977ba33f93e | 7.5 | 9 |
# this defines Kosh transformers object to augment/filter data from loaders
from abc import ABCMeta, abstractmethod
import hashlib
import os
from ..exec_graphs import KoshExecutionGraph
from kosh import kosh_cache_dir
class KoshTransformer(KoshExecutionGraph):
# Defines which input types it can handle
# and w... | llnl/kosh | kosh/transformers/core.py | .py | afcb10f00adf7a2a | 7.5 | 9 |
from .core import KoshTransformer, kosh_cache_dir
import os
from .utils import get_ids_for_rank, MPIPrint, get_mpi_tools
import time
def make_slices_args(ndims, axis, start, end):
"""given the number of total dimenions return the slice(start, end) at the correct postion for axis
:param ndims: Total number of ... | llnl/kosh | kosh/transformers/npy.py | .py | 1145f46ef0921901 | 7.5 | 9 |
try:
import conduit
has_conduit = True
except ImportError:
has_conduit = False
from .utils import get_ids_for_rank, get_mpi_tools
from .core import KoshTransformer
class SidreFeatureMetrics(KoshTransformer):
"""Numpy-based Metrics
this returns a dictionary of metrics for a feature (sent as input)
... | llnl/kosh | kosh/transformers/sidre.py | .py | df48d9d3e8f5bafb | 7.5 | 9 |
"""Async-capable Typer wrapper used by the Twente Milieu CLI.
Adaptation of the snippet/code from:
- https://github.com/tiangolo/typer/issues/88#issuecomment-1613013597
- https://github.com/argilla-io/argilla/blob/e77ca86c629a492019f230ac55ebde207b280xc9c/src/argilla/cli/typer_ext.py
"""
# Copyright 2021-present, th... | frenck/python-twentemilieu | src/twentemilieu/cli/async_typer.py | .py | 17fda68570bd8357 | 7.45 | 7 |
"""Asynchronous Python client for the Twente Milieu API."""
from __future__ import annotations
import asyncio
import json
import socket
from dataclasses import dataclass, field
from datetime import date, datetime, timedelta
from enum import IntEnum
from typing import Any, Self
from zoneinfo import ZoneInfo
import ai... | frenck/python-twentemilieu | src/twentemilieu/twentemilieu.py | .py | 196fd743490bc480 | 7.45 | 7 |
"""Shared fixtures and helpers for the test suite."""
from __future__ import annotations
import json
from datetime import date
from inspect import signature
from pathlib import Path
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
import aiohttp
import pytest
from aioresponses import core as a... | frenck/python-twentemilieu | tests/conftest.py | .py | 8b821f3750e08e3d | 7.95 | 7 |
"""Tests for `twentemilieu.twentemilieu`."""
from __future__ import annotations
# pylint: disable=protected-access,redefined-outer-name
import socket
from typing import TYPE_CHECKING, Any
from unittest.mock import patch
import aiohttp
import pytest
from aioresponses import aioresponses
from twentemilieu import Twen... | frenck/python-twentemilieu | tests/test_twentemilieu.py | .py | 0393388bbf761ed8 | 7.95 | 7 |
"""Common test fixtures for all Plastron packages"""
from os.path import abspath, dirname
from pathlib import Path
import pytest
import requests
from rdflib import URIRef
import plastron.validation.vocabularies
def pytest_configure(config):
# Set VOCABULARIES_DIR and VOCABULARIES to point to local test files,
... | umd-lib/plastron | conftest.py | .py | 58db98bae8174d1f | 7.95 | 7 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import importlib.metadata
import logging
import logging.config
import os
import sys
from argparse import ArgumentParser, FileType
from argparse import Namespace
from datetime import datetime
from importlib import import_module
from pkgutil import iter_modules
from typing i... | umd-lib/plastron | plastron-cli/src/plastron/cli/__init__.py | .py | a3819f101300c2f2 | 7.45 | 7 |
import logging.config
import os
import re
import yaml
from argparse import ArgumentTypeError, Namespace
from datetime import datetime
from importlib import import_module
from time import sleep
from plastron.client import Client, ClientError
from plastron.cli.commands import BaseCommand
from plastron.client.transaction... | umd-lib/plastron | plastron-cli/src/plastron/cli/commands/load.py | .py | 73b32ca0db8508f3 | 7.45 | 7 |
import argparse
import os
import tempfile
from csv import DictReader
from io import StringIO
from uuid import uuid4
import pytest
from plastron.cli.commands.importcommand import Command
from plastron.jobs import JobConfigError, JobNotFoundError
def test_cannot_resume_without_job_id(plastron_context):
# Verifies... | umd-lib/plastron | plastron-cli/tests/commands/test_importcommand.py | .py | c75e02397619591b | 7.95 | 7 |
import logging
from http import HTTPStatus
from pathlib import Path
from typing import Optional, Any, Callable
from rdflib import Graph
from requests import Session, Response, ConnectionError
from requests.auth import AuthBase
from plastron.client.endpoint import Endpoint
from plastron.client.utils import SessionHead... | umd-lib/plastron | plastron-client/src/plastron/client/base.py | .py | 0dba71c6e6b2f339 | 7.45 | 7 |
from urlobject import URLObject
class Endpoint:
"""Conceptual entry point for a Fedora repository."""
def __init__(self, url: str, default_path: str = '/'):
self.url = URLObject(url)
"""Endpoint URL"""
self.relpath = default_path
"""Default container path"""
if not s... | umd-lib/plastron | plastron-client/src/plastron/client/endpoint.py | .py | 075c7cc80aa17c2f | 7.45 | 7 |
from requests import Response
from plastron.client.base import Client
from plastron.client.endpoint import Endpoint
from plastron.client.utils import SessionHeaderAttribute
class ProxiedClient(Client):
"""HTTP client that behaves as if it were sending reversed proxied requests
to the repository. Takes both t... | umd-lib/plastron | plastron-client/src/plastron/client/proxied.py | .py | e264a54edfb3566c | 7.45 | 7 |
import logging
import os
import threading
from contextlib import contextmanager
from http import HTTPStatus
from typing import Optional, Any
from rdflib import URIRef, Graph
from requests import ConnectionError, Response
from plastron.client.base import Client, ClientError
from plastron.client.endpoint import Endpoin... | umd-lib/plastron | plastron-client/src/plastron/client/transactions.py | .py | ad3a43ae79606cda | 7.45 | 7 |
import logging
import os
from base64 import urlsafe_b64encode
from collections import namedtuple
from typing import NamedTuple
from rdflib import Graph, Literal, URIRef
logger = logging.getLogger(__name__)
OMIT_SERVER_MANAGED_TRIPLES = 'return=representation; omit="http://fedora.info/definitions/v4/repository#Server... | umd-lib/plastron | plastron-client/src/plastron/client/utils.py | .py | d03b447a96219656 | 7.45 | 7 |
#!/usr/bin/env python3
import logging
import subprocess as sp
from pathlib import Path
logging.basicConfig(level=logging.INFO)
OUTPUT_PATH = Path("packages")
def replace_in_file(infile, replacements, outfile=None):
"""Reads in a file, replaces the given data using python formatting and writes back
the resu... | zwicker-group/py-droplets | docs/source/run_autodoc.py | .py | 5a8f357219291387 | 7.57 | 13 |
"""Simple sphinx plug-in that simplifies type information in function signatures."""
import collections
import re
# simple (literal) replacement rules
REPLACEMENTS = collections.OrderedDict(
[
# Remove some unnecessary information in favor of a more compact style
("Dict[KT, VT]", "dict"),
... | zwicker-group/py-droplets | docs/source/sphinx_simplify_typehints.py | .py | 60269fa01ba9325f | 7.57 | 13 |
"""Miscellaneous functions.
.. autosummary::
:nosignatures:
enable_scalar_args
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
from __future__ import annotations
import functools
from collections.abc import Callable
from typing import Any, TypeVar
from pde.tools.misc import number_array
TFunc =... | zwicker-group/py-droplets | droplets/tools/misc.py | .py | 1d726a876c603fe3 | 7.57 | 13 |
"""Module defining classes for tracking droplets in simulations.
.. autosummary::
:nosignatures:
LengthScaleTracker
DropletTracker
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
from __future__ import annotations
import math
from pathlib import Path
from typing import TYPE_CHECKING, Any, Lite... | zwicker-group/py-droplets | droplets/trackers.py | .py | eca1193ce2b89bf6 | 7.57 | 13 |
#!/usr/bin/env python3
from __future__ import annotations
import argparse
import os
import subprocess as sp
import sys
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Sequence
PACKAGE = "droplets" # name of the package that needs to be tested
PACKAGE_PATH ... | zwicker-group/py-droplets | scripts/run_tests.py | .py | 9e3a5aa65db0381c | 8.07 | 13 |
"""This file is used to configure the test environment when running py.test.
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import matplotlib.pyplot as plt
import numpy as np
import pytest
from pde.backends.numba.utils import random_seed
@pytest.fixture(autouse=False, name="rng")
def init_random_numbe... | zwicker-group/py-droplets | tests/conftest.py | .py | 23c682f135201465 | 8.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
import pytest
from pde.grids import UnitGrid
from pde.tools.misc import module_available
from droplets.droplet_tracks import DropletTrack, DropletTrackList
from droplets.droplets import DiffuseDroplet, SphericalDroplet
from droplets.e... | zwicker-group/py-droplets | tests/test_droplet_tracks.py | .py | 95cd9753a5da574e | 8.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
import pytest
from scipy import integrate
from pde.backends.numba.utils import jit
from pde.grids import CartesianGrid, UnitGrid
from pde.tools.misc import module_available
from droplets import droplets
def test_simple_droplet():
... | zwicker-group/py-droplets | tests/test_droplets.py | .py | 0ae7b74ab33c5f76 | 8.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import functools
import logging
import math
import numpy as np
import pytest
from pde import CartesianGrid, MemoryStorage, ScalarField, UnitGrid, VectorField
from pde.tools.misc import module_available
from droplets import DiffuseDroplet, Emulsion, Sph... | zwicker-group/py-droplets | tests/test_emulsion.py | .py | 21b53bda3ff24f4b | 8.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
from __future__ import annotations
import os
import subprocess as sp
import sys
from pathlib import Path
import pytest
from pde.tools.misc import module_available
PACKAGE_PATH = Path(__file__).resolve().parents[1]
EXAMPLES = list((PACKAGE_PATH / "exam... | zwicker-group/py-droplets | tests/test_examples.py | .py | 7fa7d057f669fcd1 | 7.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
import pytest
from numpy.lib.recfunctions import structured_to_unstructured
from pde import ScalarField
from pde.grids import (
CartesianGrid,
CylindricalSymGrid,
PolarSymGrid,
SphericalSymGrid,
UnitGrid,
)
from dr... | zwicker-group/py-droplets | tests/test_image_analysis.py | .py | f5a6729e857b3b8c | 7.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
import pytest
from pde import CahnHilliardPDE, CartesianGrid, DiffusionPDE, ScalarField, UnitGrid
from pde.tools.misc import module_available
from droplets import LengthScaleTracker, SphericalDroplet
from droplets.emulsions import Emu... | zwicker-group/py-droplets | tests/test_trackers.py | .py | 1b2e8337a083ea26 | 8.07 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import numpy as np
from droplets.tools import misc
def test_enable_scalar_args():
"""Test the enable_scalar_args decorator."""
class Test:
@misc.enable_scalar_args
def meth(self, arr):
return arr + 1
t = Test()... | zwicker-group/py-droplets | tests/tools/test_misc.py | .py | 68f9746faff4653a | 7.57 | 13 |
"""
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
import math
import random
import numpy as np
import pytest
from numba import njit
from scipy import integrate
import pde
from droplets.tools import spherical
@pytest.mark.parametrize("dim", [1, 2, 3])
def test_volume_conversion(dim):
"""Tests con... | zwicker-group/py-droplets | tests/tools/test_spherical.py | .py | 7d2d6fb3ff84b323 | 8.07 | 13 |
import re
import os
from . import workspace
from pathlib import Path
class LogFile:
def __init__(self, logging_config=None):
self.logging_config = logging_config
self.folder = None
if self.logging_config is not None:
return
for folder in workspace.get_folders():
... | absszero/LaravelGoto | lib/log_file.py | .py | 8f2d6f701227ba83 | 7.54 | 11 |
import re
from .place import Place
from . import workspace
class Middleware:
def __init__(self, http_kernel=None):
self.http_kernel = http_kernel
if self.http_kernel:
return
for folder in workspace.get_folders():
self.http_kernel = workspace.get_file_content(
... | absszero/LaravelGoto | lib/middleware.py | .py | 7411087f42aca4f6 | 7.54 | 11 |
import sublime
from re import compile
patterns = [
(compile(r"""(controller)\s*\(\s*['"]?([^'")]+)"""), False),
(compile(r"""resource\s*\(\s*['"][^'"]+['"]\s*,\s*(['"]?)([^,'"]+)"""), False),
(compile(r"""namespace\s*\(\s*(['"])\s*([^'"]+)\1"""), True),
(compile(r"""['"]namespace['"]\s*=>\s*(['"])([^'"... | absszero/LaravelGoto | lib/namespace.py | .py | 4f62c16b9bdb45a9 | 7.54 | 11 |
from pathlib import Path
import os
import sublime
mTimes = {}
contents = {}
changes = {}
def is_file(base, filename=None):
fullpath = base
if filename:
fullpath = os.path.join([base, filename])
return os.path.isfile(fullpath)
def is_changed(folder_path, file_path=None):
'''
is the folde... | absszero/LaravelGoto | lib/workspace.py | .py | 75c68c7be443049c | 7.54 | 11 |
from . import unittest
from LaravelGoto.lib.classname import ClassName
class TestClassName(unittest.ViewTestCase):
classname = ClassName()
def test_php_var(self):
place = self.classname.get_place(
'App\\Models\\Score',
"""return $this->hasMany('App\\Mod|els\\Score');"""
... | absszero/LaravelGoto | tests/test_classname.py | .py | 766d4f4f2e49b9ae | 7.04 | 11 |
from . import unittest
from LaravelGoto.lib.livewire import Livewire
class testLivewire(unittest.ViewTestCase):
livewire = Livewire()
def test_blade_tag(self):
place = self.livewire.get_place(
'nav.show-post',
"""<livewire:nav.show-post>""")
self.assertEqual("Nav/ShowP... | absszero/LaravelGoto | tests/test_livewire.py | .py | 36a8926e389d1cef | 7.04 | 11 |
from unittest.mock import patch
from . import unittest
from LaravelGoto.lib.middleware import Middleware
class TestMiddleware(unittest.ViewTestCase):
@patch('LaravelGoto.lib.workspace.get_folders')
def test_all(self, mock_get_folders):
mock_get_folders.return_value = [self.get_test_dir()]
mid... | absszero/LaravelGoto | tests/test_middleware.py | .py | 12e79f02f753d2e7 | 7.04 | 11 |
"""Pandas dataframe extension for ADNI."""
# pylint: disable=R0914
# Third party imports
import logging
from typing import ClassVar, Literal
import pandas as pd
logger = logging.getLogger(__name__)
@pd.api.extensions.register_dataframe_accessor("adni")
class ADNI:
"""Dataframe deals with ADNI data.
This ... | mcsitter/adnipy | src/adnipy/adni.py | .py | dc4898125a010fa0 | 7.6 | 15 |
"""Process ADNI study data with adnipy."""
# Standard library imports
import warnings
from io import StringIO
# Third party imports
import pandas as pd
def read_csv(file: str | StringIO) -> pd.DataFrame:
"""Return a csv file as a pandas.DataFrame.
Recognizes missing values used in the ADNI database.
P... | mcsitter/adnipy | src/adnipy/adnipy.py | .py | 732ed48c3c09ca70 | 7.6 | 15 |
"""Tests for dataframe `adni` extension."""
# pylint: disable=W0621, R0801
# Third party imports
import pandas as pd
import pytest
from adnipy import adni # noqa: F401 pylint: disable=W0611
@pytest.fixture
def test_df() -> pd.DataFrame:
"""Provide sample dataframe for standardized testing."""
columns = [
... | mcsitter/adnipy | tests/test_adni.py | .py | 6aa6808a7483ac80 | 8.1 | 15 |
"""Tests for `adnipy` package."""
# pylint: disable=W0621, R0801
# Standard library imports
import io
from io import StringIO
# Third party imports
import pandas as pd
import pytest
from adnipy import adnipy
@pytest.fixture
def test_df() -> pd.DataFrame:
"""Provide sample dataframe for standardized testing.""... | mcsitter/adnipy | tests/test_adnipy.py | .py | b062b79b01853e4b | 7.1 | 15 |
"""
CriteriaEvaluator facade — public entry for fracture-criteria evaluations.
Envelope, coupled-criterion, and steady-state logic live in sibling modules;
this class holds ``CriteriaConfig`` and delegates.
"""
from __future__ import annotations
import numpy as np
from weac.analysis.analyzer import (
BOUNDARY_D... | 2phi/weac | src/weac/analysis/criteria_evaluator.py | .py | a10b505f851ab0b4 | 7.56 | 12 |
"""
Stress and fracture-toughness envelope evaluations.
"""
from __future__ import annotations
import numpy as np
from weac.components import CriteriaConfig, WeakLayer
from weac.constants import RHO_ICE
__all__ = [
"fracture_toughness_envelope",
"stress_envelope",
]
def fracture_toughness_envelope(
cr... | 2phi/weac | src/weac/analysis/envelopes.py | .py | 1855f2fc192e0f23 | 7.56 | 12 |
"""
Configuration for the WEAC simulation.
These settings control runtime parameters for WEAC.
In general, developers maintain these defaults; end users should see a stable configuration.
We utilize the pydantic library to define the configuration.
Pydantic syntax is for a field:
field_name: type = Field(..., gt=0, d... | 2phi/weac | src/weac/components/config.py | .py | da26c5f68c583603 | 7.56 | 12 |
"""
Mechanical properties of snow-pack layers.
* `Layer` - a regular slab layer (no foundation springs)
* `WeakLayer` - re-exported from `weac.components.weak_layer` for compatibility
"""
from typing import Literal
from pydantic import BaseModel, Field, model_validator
from weac.constants import CB0, CB1, CG0, CG1,... | 2phi/weac | src/weac/components/layer.py | .py | 856a8117eda2da5d | 7.56 | 12 |
"""
This module defines the input data model for the WEAC simulation.
We utilize the pydantic library instead of dataclasses to define the input
data model. The advantages of pydantic are:
1. validate the input data for the WEAC simulation, compared to __post_init__ methods.
2. generate JSON schemas for the input data... | 2phi/weac | src/weac/components/model_input.py | .py | f99824a15c8a1ff9 | 7.56 | 12 |
"""
This module defines the ScenarioConfig class, which contains the configuration for a given scenario.
"""
from typing import Literal, Any, Annotated
from pydantic import (
BaseModel,
Field,
field_validator,
ConfigDict,
PlainSerializer,
WithJsonSchema,
)
import numpy as np
def _serialize_n... | 2phi/weac | src/weac/components/scenario_config.py | .py | 3e52440e56523975 | 7.56 | 12 |
"""
This module defines the Segment class, which represents a segment of the snowpack.
"""
from typing import Annotated
import numpy as np
from pydantic import BaseModel, Field, field_validator, PlainSerializer, WithJsonSchema
from pydantic import ConfigDict
from numpy.typing import NDArray
def _serialize_ndarray(a... | 2phi/weac | src/weac/components/segment.py | .py | 955911022564080a | 7.56 | 12 |
"""
Mechanical properties of the weak layer (Winkler foundation).
"""
from typing import Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field, model_validator
from weac.components.layer import (
_bergfeld_youngs_modulus,
_gerling_youngs_modulus,
_scapozza_youngs_modulus,
)
from we... | 2phi/weac | src/weac/components/weak_layer.py | .py | ee3e17f387d0ea9f | 7.56 | 12 |
"""
This module defines the Scenario class, which encapsulates the physical setup of the model.
"""
import logging
from collections.abc import Sequence
import numpy as np
from weac.components import ScenarioConfig, Segment, SystemType, WeakLayer
from weac.core.slab import Slab
from weac.utils.misc import decompose_t... | 2phi/weac | src/weac/core/scenario.py | .py | 202a7600cbf45ba7 | 7.56 | 12 |
"""
This module defines the Slab class, which represents the snow slab and its properties.
"""
import numpy as np
from weac.components import Layer
from weac.constants import EPS, G_MM_S2
class Slab: # pylint: disable=too-many-instance-attributes,too-few-public-methods
"""
Parameters of all layers assemble... | 2phi/weac | src/weac/core/slab.py | .py | dfef3b3a58c6f91c | 7.56 | 12 |
"""
This module handles the calculation of slab touchdown events.
Handling the touchdown situation in a PST.
"""
import logging
from typing import Literal
from scipy.optimize import brentq
from weac.components.weak_layer import WeakLayer
from weac.components.scenario_config import ScenarioConfig, TouchdownMode
from ... | 2phi/weac | src/weac/core/slab_touchdown.py | .py | edc86ed43f8bc73d | 7.56 | 12 |
"""
This module defines the system model for the WEAC simulation.
The system model is the heart of the WEAC simulation. All data sources
are bundled into the system model. The system model initializes and
calculates all the parameterizations and passes relevant data to the
different components.
We utilize the pydantic... | 2phi/weac | src/weac/core/system_model.py | .py | 4ab83668df4a5d64 | 7.56 | 12 |
"""
This module defines the system model for the WEAC simulation. The system
model is the heart of the WEAC simulation. All data sources are bundled into
the system model. The system model initializes and calculates all the
parameterizations and passes relevant data to the different components.
We utilize the pydantic... | 2phi/weac | src/weac/core/unknown_constants_solver.py | .py | 86f86527d990fcfb | 7.56 | 12 |
"""
This module contains miscellaneous utility functions.
"""
from typing import Literal
import numpy as np
from numpy.typing import NDArray
from weac.components import Layer
from weac.constants import G_MM_S2, LSKI_MM
def decompose_to_xyz(
f: NDArray[np.float64] | float,
phi: NDArray[np.float64] | float,
... | 2phi/weac | src/weac/utils/misc.py | .py | a2268ba5fdc2d710 | 7.56 | 12 |
"""
Snow grain types and hand hardness values.
These values are used in Pydantic models for validation and correspond to the
parameterizations available in `geldsetzer.py`.
"""
from enum import Enum
class GrainType(str, Enum):
"""SnowPilot grain type codes (see `geldsetzer.GRAIN_TYPE`)."""
DF = "DF"
DF... | 2phi/weac | src/weac/utils/snow_types.py | .py | 38a498f0bcdf2b27 | 7.56 | 12 |
"""
Utilizes the snowpylot library to convert a CAAML file to a WEAC ModelInput.
The snowpylot library is used to parse the CAAML file and extract the snowpit.
The snowpit is then converted to a List of WEAC ModelInput.
Based on the different stability tests performed, several scenarios are created.
Each scenario is ... | 2phi/weac | src/weac/utils/snowpilot_parser.py | .py | 080a5a7005f5c040 | 7.56 | 12 |
"""
This module contains tests for the Analyzer class.
"""
# Third party imports
import numpy as np
import pytest
from weac.analysis import Analyzer
from weac.analysis.analyzer import local_segment_grid
from weac.components import (
Config,
Layer,
ScenarioConfig,
Segment,
WeakLayer,
)
from weac.co... | 2phi/weac | tests/analysis/test_analyzer.py | .py | d3757388a8f49484 | 8.06 | 12 |
"""
Data-driven slab A/B comparison tests (hybrid steady state).
Populate ``COMPARISON_CASES`` with A/B setup pairs. Both gates use production
``CriteriaEvaluator.evaluate_SteadyState`` (hybrid).
Tensile ease (shorter ``critical_cut_length`` = easier) follows Steph's tensile
map: cases 1–11 & 21–23 → A easier; 12–15 ... | 2phi/weac | tests/analysis/test_slab_tensile_comparisons.py | .py | 1d367d27a4031907 | 8.06 | 12 |
"""
Unit tests for configuration components.
Tests Config, ScenarioConfig, CriteriaConfig, Segment, and ModelInput validation.
"""
import json
import pytest
from pydantic import ValidationError
from weac.components import (
Config,
CriteriaConfig,
Layer,
ModelInput,
ScenarioConfig,
Segment,
... | 2phi/weac | tests/components/test_configs.py | .py | cfaa8474da610bb5 | 8.06 | 12 |
"""
Unit tests for Layer and WeakLayer components.
Tests validation, automatic property calculations, and edge cases.
"""
import numpy as np
import pytest
from pydantic import ValidationError
from weac.components.layer import (
Layer,
_adam_tensile_strength,
_bergfeld_youngs_modulus,
_gerling_youngs_... | 2phi/weac | tests/components/test_layer.py | .py | 1e1c4283813480ad | 7.06 | 12 |
"""
Unit tests for the Eigensystem class.
Tests system matrix assembly, eigenvalue/eigenvector calculations,
complementary and particular solutions.
"""
import numpy as np
import pytest
from weac.components import Layer, WeakLayer
from weac.core.eigensystem import Eigensystem
from weac.core.slab import Slab
@pytes... | 2phi/weac | tests/core/test_eigensystem.py | .py | 32fd901c325452fe | 8.06 | 12 |
"""
Unit tests for the FieldQuantities class.
Tests displacement calculations, stress calculations, energy release rates,
and other field quantity computations.
"""
import numpy as np
import pytest
from weac.components import Layer, WeakLayer
from weac.core.eigensystem import Eigensystem
from weac.core.field_quantit... | 2phi/weac | tests/core/test_field_quantities.py | .py | cefbff22979a1fa8 | 7.06 | 12 |
"""Top-level package for PyFlexPlot."""
# Standard library
import os
import importlib.metadata
import logging as _logging
import sys as _sys
import warnings as _warnings
from pathlib import Path as _Path
from typing import List as _List
# Third-party
import matplotlib as _mpl
# Local
from .utils.logging import add_l... | MeteoSwiss-APN/pyflexplot | src/pyflexplot/__init__.py | .py | 1f0de481232a7ba3 | 7.6 | 15 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.