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
"""Circle plot class.""" import numpy as np from rnavigate import data, plots class Circle(plots.Plot): """Create a circle plot. Parameters ---------- num_samples : int Number of samples to plot. **kwargs Keyword arguments passed to :class:`rnavigate.plots.Plot`. Attributes...
Weeks-UNC/RNAvigate
rnavigate/plots/circle.py
.py
41dd788216c31bdb
7.62
16
"""Plot distance histograms.""" import numpy as np from rnavigate import data, plots class DistHist(plots.Plot): """Create a distance histogram plot. Parameters ---------- num_samples : int Number of samples to plot. **kwargs Keyword arguments passed to :class:`rnavigate.plots.P...
Weeks-UNC/RNAvigate
rnavigate/plots/disthist.py
.py
0e7719a3840d2566
7.62
16
import numpy as np from matplotlib.collections import PatchCollection from matplotlib.patches import Path, PathPatch from rnavigate import styles def plot_interactions_circle(ax, seq_circle, interactions): """Plot interactions on a circle plot. Parameters ---------- ax : matplotlib.axes.Axes ...
Weeks-UNC/RNAvigate
rnavigate/plots/functions/circle.py
.py
1ca991ce89d1ff10
7.62
16
import matplotlib.collections as mp_collections import matplotlib.colors as mp_colors import matplotlib.patches as mp_patches import numpy as np from rnavigate import data, plots def get_contrasting_colors(colors): """Get contrasting colors for a list of colors. Returns a list of "k" (black) or "w" (white) ...
Weeks-UNC/RNAvigate
rnavigate/plots/functions/functions.py
.py
7406181a04a4553e
7.62
16
import matplotlib.collections as mp_collections import matplotlib.patches as mp_patches import numpy as np from scipy.spatial.distance import cdist from rnavigate import data, plots, styles # Secondary structure diagram ploting functions def plot_structure_ss(ax, structure, colors): """Plot the structure of a se...
Weeks-UNC/RNAvigate
rnavigate/plots/functions/ss.py
.py
b7a71ce447186443
7.62
16
"""Heatmap plot class.""" import numpy as np import seaborn as sns from matplotlib.colors import LinearSegmentedColormap from rnavigate import data, plots class Heatmap(plots.Plot): """Create a heatmap plot. Parameters ---------- num_samples : int Number of samples to plot. structure : ...
Weeks-UNC/RNAvigate
rnavigate/plots/heatmap.py
.py
1238d931569bbaa3
7.62
16
"""Plot linear regression scatter plots.""" import numpy as np import seaborn as sns from scipy import stats from rnavigate import plots class LinReg(plots.Plot): """Plot a linear regression scatter plot, pairwise, between profiles. Parameters ---------- num_samples : int Number of samples ...
Weeks-UNC/RNAvigate
rnavigate/plots/linreg.py
.py
07e38677f13a4086
7.62
16
"""Module for plotting 3Dmol.js viewers""" import matplotlib.colors as mpc import py3Dmol from rnavigate import plots class Mol(plots.Plot): def __init__( self, num_samples, pdb, width=400, height=400, background_alpha=1, rotation=None, orientation...
Weeks-UNC/RNAvigate
rnavigate/plots/mol.py
.py
79f0084df6c10603
7.62
16
"""Plot nucleotide distribution of a profile.""" import numpy as np import seaborn as sns from rnavigate import plots, styles class NucleotideDistribution(plots.Plot): """Plot nucleotide distribution of a profile. Parameters ---------- num_samples : int Number of samples to plot. sharex...
Weeks-UNC/RNAvigate
rnavigate/plots/ntdist.py
.py
62cfe1674dd8df78
7.62
16
import math from abc import ABC, abstractmethod import matplotlib.pyplot as plt class Plot(ABC): """Abstract base class for plots. Parameters ---------- num_samples : int Number of samples to plot. rows : int, optional Number of rows in the plot. cols : int, optional ...
Weeks-UNC/RNAvigate
rnavigate/plots/plots.py
.py
e3e197dea0b3ba02
7.62
16
import seaborn as sns from rnavigate import plots, styles class Profile(plots.Plot): """Plot per-nucleotide measurements as colored bars. Parameters ---------- num_samples : int Number of samples to plot. nt_length : int Length of the nucleotide sequence. region : tuple of in...
Weeks-UNC/RNAvigate
rnavigate/plots/profile.py
.py
ba8892d14c748a44
7.62
16
import numpy as np import pandas as pd import seaborn as sns from rnavigate import plots class QC(plots.Plot): """Plot QC data from log files. Parameters ---------- num_samples : int Number of samples to plot. Attributes ---------- fig : matplotlib.figure.Figure Figure o...
Weeks-UNC/RNAvigate
rnavigate/plots/qc.py
.py
fd86e69a428124db
7.62
16
from sklearn.metrics import auc, roc_curve from rnavigate import plots class ROC(plots.Plot): """Plot ROC curves. Parameters ---------- num_samples : int Number of samples to plot. **kwargs Keyword arguments passed to `rnavigate.plots.Plot`. Attributes ---------- fig...
Weeks-UNC/RNAvigate
rnavigate/plots/roc.py
.py
edb0a809a7a950ae
7.62
16
import seaborn as sns from rnavigate import plots, styles class Skyline(plots.Plot): """Plot per-nucleotide measurements as stepped line graphs (skyline plots). Parameters ---------- num_samples : int Number of samples to plot. nt_length : int Length of the nucleotide sequence. ...
Weeks-UNC/RNAvigate
rnavigate/plots/skyline.py
.py
cec839e701013a90
7.62
16
import numpy as np from matplotlib.patches import Rectangle from rnavigate import plots from rnavigate.styles import bg_color, dc_color, rx_color class SM(plots.Plot): """Plot classic ShapeMapper plots. Parameters ---------- nt_length : int Length of the nucleotide sequence. region : tup...
Weeks-UNC/RNAvigate
rnavigate/plots/sm.py
.py
17c325e003b042fd
7.62
16
"""The RNAvigate Sample object for parsing, assigning, and organizing data.""" from rnavigate import data from rnavigate.data_loading import create_data class Sample: """Loads and organizes RNA structural data for use with plotting functions. The Sample class stores all of the relevant experimental and comp...
Weeks-UNC/RNAvigate
rnavigate/rnavigate.py
.py
b8589886f0b9267e
7.62
16
# Copyright (c) 2022 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/conftest.py
.py
c70c7ad01c3b6168
8.04
11
# Copyright (c) 2023 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/multi_thread_logging/fixture/test_thread_logging_fixture.py
.py
990566831bf3690f
8.04
11
# Copyright (c) 2022 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/multi_thread_logging/logger_bypass/conftest.py
.py
9d972a4c7865898b
7.04
11
# Copyright (c) 2023 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/multi_thread_logging/thread/test_thread_logging_thread_patch.py
.py
0965d21eefb55301
8.04
11
# Copyright (c) 2022 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/test_nested_steps.py
.py
11066e78b2862c9b
8.04
11
# Copyright (c) 2022 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/test_nested_steps_ui.py
.py
46c16ba76f7b709d
8.04
11
# Copyright (c) 2022 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/test_skipped.py
.py
fedd02e611bd28d1
8.04
11
# Copyright (c) 2022 https://reportportal.io . # 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 agr...
reportportal/examples-python
pytest/tests/ui/web.py
.py
5ab47415e3fcecc7
7.04
11
# Copyright 2018 Google LLC # # 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 to in writing, ...
googleapis/docuploader
docuploader/credentials.py
.py
93e380a469db8802
7.65
19
# Copyright 2018 Google LLC # # 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 to in writing, ...
googleapis/docuploader
docuploader/tar.py
.py
bb4c169495421635
7.65
19
# Copyright 2019 Google LLC # # 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 to in writing, ...
googleapis/docuploader
tests/test_tar.py
.py
c51cc2f0a37f720f
7.15
19
"""FASTQ parsing and adapter counting primitives.""" from collections import Counter from collections.abc import Iterable, Iterator, Sequence from itertools import islice class FastqFormatError(ValueError): """Raised when an input stream does not contain complete FASTQ records.""" def parse_fastq(stream: Itera...
MOMA-AUH/guessadapt
src/guessadapt/core.py
.py
da45971cd08294c1
7.45
7
from contextlib import AbstractContextManager from functools import lru_cache from json import JSONDecodeError, dumps, loads from pathlib import Path from textwrap import TextWrapper from typing import ( IO, Any, Callable, Dict, Generator, List, Optional, Sequence, Tuple, Union, ...
lumapps/lumapps-sdk
lumapps/api/base_client.py
.py
5d75108febd293b0
7.45
7
from typing import Any, Dict, Optional, Union import httpx from lumapps.api.base_client import BaseClient from lumapps.api.errors import BaseClientError def create_new_media( client: BaseClient, file_data_or_path: Union[bytes, str], doc_path: str, filename: str, mimetype: str, is_shared: boo...
lumapps/lumapps-sdk
lumapps/api/helpers/medias.py
.py
aa67ec8f51ca48fb
7.45
7
import json from typing import Any, Dict import httpx import jwt from lumapps.api.decorators import retry_on_http_status_error from lumapps.api.errors import ( LumAppsJWTClaimsError, LumAppsJwtCustomError, LumAppsJwtHeaderError, LumAppsJwtInvalidClaimError, LumAppsJwtTokenExpiredError, ) JWKS_URL...
lumapps/lumapps-sdk
lumapps/api/lumapps_jwt.py
.py
22c3c6b2739fa74d
7.45
7
#py3 import numpy as np import copy import time import logging logging.basicConfig(level=logging.DEBUG, format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s', datefmt='%a, %d %b %Y %H:%M:%S', filemode='a') grid = [ [0...
fooSynaptic/NLP-utils
Coding/Dijkstra_Floyd.py
.py
596cc267fce08747
7.42
6
# source from leetcode from time import time xrange = range def permuteUnique(nums, verbose = False): ans = [[]] for n in nums: new_ans = [] for l in ans: for i in xrange(len(l)+1): new_ans.append(l[:i]+[n]+l[i:]) if verbose: print("Before handle du...
fooSynaptic/NLP-utils
Coding/permutation.py
.py
dbde78ce584a0f89
7.42
6
''' Single case is one of the programing style, we employed single case to hadle classes with only one instance. For different position in code we can reach the only one object instance with the gurantee of Single case mode. In the case the instance not exists, the pattern will build a new instance, if exists, it wil...
fooSynaptic/NLP-utils
Coding/single_Case.py
.py
24355177e6111211
7.42
6
# encoding=utf-8 # /usr/bin/python3 from bs4 import BeautifulSoup as bs import bs4 import re import numpy as np """Implementation tools... """ def tokenfeatures(word): """ Obsevation state features """ features = [] ### features.append("token==" + word) ### mid = len(word)//2 if mid...
fooSynaptic/NLP-utils
ML/PGM/CRF/crfSpellChecking/utils.py
.py
6a3d24e73b272ff0
7.42
6
# encoding=utf-8 # /usr/bin/python3 """crf implementation from scratch""" import numpy as np from collections import defaultdict from numpy import empty, zeros, ones, log, exp, add, int32 from numpy.random import uniform from utils import * import os import random random.seed(1234) from sklearn.externals import jobl...
fooSynaptic/NLP-utils
ML/PGM/CRF/crf_from_scratch/models.py
.py
ffe72e38d230e835
7.42
6
# encoding=utf-8 # /usr/bin/python3 from bs4 import BeautifulSoup as bs import bs4 import re import numpy as np """Implementation tools... """ def tokenfeatures(word): """ Obsevation state features """ features = [] ### 1 features.append("token==" + word) ### 2 mid = len(word)//2 if ...
fooSynaptic/NLP-utils
ML/PGM/CRF/crf_from_scratch/utils.py
.py
9923b312b799a1d7
7.42
6
# encoding = utf-8 # /usr/bin/python3 ''' This program implemented the vertibi algorithm inference while have - 1. The state-state transition matrix - 2. The state-observation transition matrix - 3. Initial state - ref: https://zhuanlan.zhihu.com/p/63087935 ''' __author__ = 'fooSynaptic' import numpy as np def ...
fooSynaptic/NLP-utils
ML/Vivid_veterbi.py
.py
fe75ba668a696abe
7.42
6
''' Implementation for the Monte_carlo algorithms in chaper 4 of AI handbook - ref: http://www.huaxiaozhuan.com/%E6%95%B0%E5%AD%A6%E5%9F%BA%E7%A1%80/chapters/4_monte_carlo.html ''' from math import pi import numpy as np import random from random import randint from collections import Counter from scipy import stats im...
fooSynaptic/NLP-utils
ML/hands_on_handbooks_from_scratch/Chp_4_monte_carlo.py
.py
b1c807aa4dde48f2
7.42
6
# encoding = utf-8 # /usr/bin/python3 """ ## IBM translation model 整个目标是通过EM算法学习IBM model中的transition prob参数, 通过EM算法,可以在迭代统计平行语料的过程中,不断计算概率 t(e|f) 的似然概率, 并更新到参数中,以达到学习整个参数中最大alignment对应最大概率的目的. - ref: http://www.cs.columbia.edu/~mcollins/courses/nlp2011/notes/ibm12.pdf """ import numpy as np from time import time fr...
fooSynaptic/NLP-utils
ML/machineTranslation/SMT/IBM_translationModel.py
.py
0319d42ab6891062
7.42
6
# encoding = utf - 8 # /usr/bin/python3 """The initial parameter of W can influence the iteration steps heavily.""" import numpy as np import random import matplotlib.pyplot as plt import time from optimizer import * import os num_inputs = 2 num_examples = 1000 true_w = [22.5, -43.3] true_b = 54.2 features = np.ran...
fooSynaptic/NLP-utils
ML/regression/linearRegression.py
.py
68b985fce90e1414
7.42
6
# encoding = utf-8 # /usr/bin/python3 states = ('Rainy', 'Sunny') observations = ('walk', 'shop', 'clean') start_probability = {'Rainy': 0.6, 'Sunny': 0.4} transition_probability = { 'Rainy' : {'Rainy': 0.7, 'Sunny': 0.3}, 'Sunny' : {'Rainy': 0.4, 'Sunny': 0.6}, } emission_probability = { 'Rai...
fooSynaptic/NLP-utils
ML/veterbi.py
.py
1b2de5f78972a799
7.42
6
""" NLP_utils Coding 模块性能测试 对比: 编辑距离、字符串匹配、LDA、Seq2Seq、词云 """ import time import sys import os import numpy as np from typing import List, Tuple # 添加项目路径 sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) class BenchmarkResult: """基准测试结果""" def __init__(self, name: str, nlp_utils_time: float,...
fooSynaptic/NLP-utils
benchmark/coding_benchmark.py
.py
53240b40015b095d
7.42
6
""" 运行所有 benchmark 并生成报告 """ import sys import os import json from datetime import datetime # 导入测试模块 sys.path.insert(0, os.path.dirname(__file__)) try: from coding_benchmark import run_all_benchmarks as run_coding from ml_benchmark import benchmark_all_ml as run_ml except ImportError as e: print(f"Error ...
fooSynaptic/NLP-utils
benchmark/run_all.py
.py
1d81d1381ead7174
7.42
6
"""A set of functions for calculating typical cluster parameters. Todo: error treatment here could be made more bayesian """ from typing import Optional from astropy.coordinates import SkyCoord import numpy as np import pandas as pd from .constants import mas_per_yr_to_rad_per_s, pc_to_m, deg_to_rad def _handle_r...
emilyhunt/ocelot
src/ocelot/calculate/calculate.py
.py
5e77fff229029d59
7.57
13
"""Generic calculation utilities used across the module.""" import numpy as np from numpy.typing import ArrayLike, NDArray from typing import Optional, Union from ocelot.util.check import _check_matching_lengths_of_non_nones from scipy.stats import directional_stats def _weighted_standard_deviation(x: ArrayLike, weig...
emilyhunt/ocelot
src/ocelot/calculate/generic.py
.py
3c035ab8c3a0e747
7.57
13
"""Different methods for calculating the center of a cluster in spherical coordinates. (This is actually oddly difficult, thanks to how spheres work. Damn spheres.) """ import numpy as np from numpy.typing import ArrayLike from ocelot.calculate.generic import spherical_mean def mean_position( longitudes: ArrayL...
emilyhunt/ocelot
src/ocelot/calculate/position.py
.py
109877737573221f
7.57
13
"""A number of functions for pre-processing data before clustering can begin.""" from typing import Literal import numpy as np import pandas as pd import healpy from sklearn.preprocessing import RobustScaler, StandardScaler from astropy.coordinates import SkyCoord from astropy import units as u from scipy.optimize i...
emilyhunt/ocelot
src/ocelot/cluster/preprocess.py
.py
02230e8b93b43fa7
7.57
13
"""Functions for re-sampling Gaia data within errors.""" import numpy as np import pandas as pd from typing import Sequence, Literal from ocelot.util.stats import vectorized_multivariate_normal_rvs def resample_gaia_astrometry( data_gaia: pd.DataFrame, n_resamples: int = 1, suffixes: Sequence[str] | None...
emilyhunt/ocelot
src/ocelot/cluster/resample.py
.py
ec405ac3b9613ab7
7.57
13
"""Set of functions for reading in isochrones from their downloaded formats and processing them into useful spaces.""" from pathlib import Path from typing import Union, Optional, List import numpy as np import pandas as pd from astropy.io import ascii def read_parsec( file_location: Union[Path, List[Path], str...
emilyhunt/ocelot
src/ocelot/isochrone/io.py
.py
24b0a4c622cdcfb9
7.57
13
import numpy as np from scipy.interpolate import RegularGridInterpolator from ocelot.model.binaries._base import BaseBinaryStarModelWithEccentricities from imf.distributions import BrokenPowerLaw, PowerLaw class MoeDiStefanoMultiplicityRelation(BaseBinaryStarModelWithEccentricities): def __init__(self) -> None: ...
emilyhunt/ocelot
src/ocelot/model/binaries/moe_distefano_17.py
.py
bee51a6955f62c08
7.57
13
import numpy as np from numpy.typing import ArrayLike from abc import ABC, abstractmethod class BaseDifferentialReddeningModel(ABC): accepts_random_seed = False # Class attribute for whether or not a given model needs a seed in __init__ def extinction( self, x: ArrayLike, y: ArrayLik...
emilyhunt/ocelot
src/ocelot/model/differential_reddening/_base.py
.py
baeb372cc9ee3c01
7.57
13
"""This file contains an implementation of the King+1962 empirical star cluster model: https://ui.adsabs.harvard.edu/abs/1962AJ.....67..471K/abstract In addition, some of the equations from the paper are also implemented directly as methods in this file. """ import numpy as np from numba import jit from ._base impor...
emilyhunt/ocelot
src/ocelot/model/distribution/king62.py
.py
f696c7c4289f3893
7.57
13
"""Functions common to many different observation classes.""" from __future__ import annotations import pandas as pd from astropy.coordinates import SkyCoord from astropy.units import Quantity import ocelot.model.observation import ocelot.simulate.cluster def calculate_separation(primary: pd.DataFrame, secondary: pd...
emilyhunt/ocelot
src/ocelot/model/observation/common.py
.py
01abf2fbd8f253b8
7.57
13
"""Main class defining an observation made with Gaia DR3.""" from __future__ import annotations from ocelot.model.observation._base import ( BaseObservation, BaseSelectionFunction, ) import ocelot.simulate.cluster from scipy.interpolate import interp1d import numpy as np import pandas as pd from numpy.typing i...
emilyhunt/ocelot
src/ocelot/model/observation/gaia/gaia_dr3.py
.py
44c9d3a3d1ed7cd6
7.57
13
"""A generic subsample selection function class that can be used on many different surveys. """ import numpy as np import pandas as pd from ocelot.model.observation._base import BaseSelectionFunction from scipy.interpolate import interp1d from ocelot.util.stats import variable_bin_histogram from ocelot.util.stats impo...
emilyhunt/ocelot
src/ocelot/model/observation/subsample_selection.py
.py
cd238e9a2131f9c9
7.57
13
"""Functions for dealing with astrometry-related things.""" from __future__ import annotations # Necessary to type hint without cyclic import import numpy as np from ocelot.util.random import unit_vectors import ocelot.simulate.cluster from astropy.coordinates import SkyCoord, CartesianRepresentation, CartesianDiffer...
emilyhunt/ocelot
src/ocelot/simulate/astrometry.py
.py
3f7f54663c9aa053
7.57
13
"""Methods to pair stars randomly picked from the IMF into binaries.""" from __future__ import annotations import numpy as np from ocelot.model.binaries import ( BaseBinaryStarModelWithPeriods, BaseBinaryStarModelWithEccentricities, ) import ocelot.simulate.cluster from numba import jit def make_binaries(clu...
emilyhunt/ocelot
src/ocelot/simulate/binaries.py
.py
53308185bb5e0fb6
7.57
13
""" Created on 2024-01-21 @author: wf """ from pyparsing import ( Group, Literal, OneOrMore, Optional, Suppress, Word, alphanums, alphas, restOfLine, ) class DocstringParser: """ A Python docstring parser. """ def __init__(self): # Define basic elements ...
WolfgangFahl/pyLoDStorage
lodstorage/docstring_parser.py
.py
7670a16d2ca9c795
7.57
13
""" duckdb_query.py DuckDB backend for pyLoDStorage. Created on 2026-02-21 @author: wf """ import logging from typing import Any, Generator import duckdb from lodstorage.query import Endpoint class DuckDBQuery: """ A class to manage and execute DuckDB queries. Attributes: path (str): path t...
WolfgangFahl/pyLoDStorage
lodstorage/duckdb_query.py
.py
64526e736e3c786e
7.57
13
""" Created on 2025-12-01 @author: wf """ import logging import traceback class ExceptionHandler: """ handle exceptions """ @classmethod def handle(cls, msg: str, ex: Exception, debug: bool = False): """Centralized exception logging (non-fatal). Args: msg: context m...
WolfgangFahl/pyLoDStorage
lodstorage/exception_handler.py
.py
7b92a5666b01e2b6
7.57
13
""" Created on 2024-01-28 @author: wf """ from dataclasses import field from typing import Dict, List, Optional, Type from basemkit.yamlable import lod_storable from rdflib.namespace import XSD @lod_storable class Slot: """ Represents a slot in the LinkML schema, equivalent to a field or property. """ ...
WolfgangFahl/pyLoDStorage
lodstorage/linkml.py
.py
a889418042de49e3
7.57
13
""" Created on 2024-01-21 @author: wf """ from collections.abc import Iterable, Mapping from dataclasses import fields, is_dataclass from typing import Union from lodstorage.docstring_parser import DocstringParser from lodstorage.linkml import Class, PythonTypes, Schema, Slot class LinkMLGen: """ Class for...
WolfgangFahl/pyLoDStorage
lodstorage/linkml_gen.py
.py
bc48a8bafbf72e9c
7.57
13
""" Created on 2021-01-31 @author: wf """ class LOD(object): """ list of Dict aka Table """ def __init__(self, name): """ Constructor """ self.name = name pass @staticmethod def getFields(listOfDicts, sampleCount: int = None): """ Extr...
WolfgangFahl/pyLoDStorage
lodstorage/lod.py
.py
9d889f8d31b369b9
7.57
13
""" Created on 2022-06-20 see https://github.com/tyleradams/json-toolkit https://stackoverflow.com/questions/36021526/converting-an-array-dict-to-xml-in-python @author: tyleradams @author: wf """ from xml.dom.minidom import parseString from dicttoxml2 import dicttoxml class Lod2Xml: """ convert a ...
WolfgangFahl/pyLoDStorage
lodstorage/lod2xml.py
.py
13768bdeaf1e5ba4
7.57
13
""" Created 2021 @author: wf """ import csv import io from typing import Any, Dict, List from lodstorage.lod import LOD class CSV: """ helper for converting data in csv format to list of dicts (LoD) and vice versa """ _instance = None def __new__(cls, dialect: str = "excel", quoting: int = cs...
WolfgangFahl/pyLoDStorage
lodstorage/lod_csv.py
.py
53af09ad453166e9
7.57
13
""" Created on 2024-09-12 @author: wf """ from typing import Dict, List, Optional from lodstorage.query import EndpointManager, Query, QueryManager from lodstorage.sql_backend import SQLBackend, get_sql_backend from lodstorage.yaml_path import YamlPath class MultiLanguageQueryManager: """ Query manager for...
WolfgangFahl/pyLoDStorage
lodstorage/multilang_querymanager.py
.py
fb0b19509fc865d4
7.57
13
""" Created on 2020-08-21 @author: wf """ # redudant copy # original is at # https://github.com/WolfgangFahl/py-3rdparty-mediawiki/blob/master/wikibot/mwTable.py class MediaWikiTable(object): """ helper for https://www.mediawiki.org/wiki/Help:Tables """ def __init__( self, wikiTable=True, c...
WolfgangFahl/pyLoDStorage
lodstorage/mwTable.py
.py
a3346830b5f50fbf
7.57
13
""" mysql.py: MySQL and MariaDB support """ import logging from typing import Any, Dict, Generator, List import pymysql from lodstorage.query import Endpoint class MySqlQuery: """ A class to manage and execute mySQL queries with optional debugging. Attributes: endpoint_info (Endpoint): endpo...
WolfgangFahl/pyLoDStorage
lodstorage/mysql.py
.py
166d4b9bbcb07596
7.57
13
""" Created on 2026-07-22 NPQ-FakeSparql: serve named parameterized queries (NPQs) over the SPARQL protocol - without any SPARQL engine behind them. The technology stays hidden; only input parameters and output variables are relevant (see the snapquery EKAW2024 paper). The NPQ name lives in the URL path, input paramet...
WolfgangFahl/pyLoDStorage
lodstorage/npq_endpoint.py
.py
b8e6300a064edc4c
7.57
13
""" Created on 2024-05-06 @author: wf """ import argparse import re from dataclasses import field from typing import Dict, List, Optional from basemkit.yamlable import lod_storable @lod_storable class Param: """ a parameter (input or output) for a query """ name: str type: str # python type ...
WolfgangFahl/pyLoDStorage
lodstorage/params.py
.py
1aad7eb070e12da5
7.57
13
""" Created on 2020-07-05 @author: wf """ import os from collections import Counter import matplotlib.pyplot as plt import numpy as np class Plot(object): """ create Plot based on counters see https://stackoverflow.com/questions/19198920/using-counter-in-python-to-build-histogram """ def __ini...
WolfgangFahl/pyLoDStorage
lodstorage/plot.py
.py
0261c23a50e20542
7.57
13
""" postgresql.py: PostgreSQL support """ import logging from typing import Any, Dict, Generator, List import psycopg2 import psycopg2.extras from lodstorage.query import Endpoint class PostgreSqlQuery: """ A class to manage and execute PostgreSQL queries with optional debugging. Attributes: ...
WolfgangFahl/pyLoDStorage
lodstorage/postgresql.py
.py
18fa1b5c4fd08b0c
7.57
13
""" Created on 2025-06-04 @author: wf """ import os from dataclasses import dataclass, field from typing import ClassVar, Dict, List, Optional from basemkit.yamlable import lod_storable from lodstorage.yaml_path import YamlPath @dataclass class PrefixConfig: """ Configuration for SPARQL prefixes """ ...
WolfgangFahl/pyLoDStorage
lodstorage/prefix_config.py
.py
d12f5116d161f1e8
7.57
13
""" Created on 2024-03-02 @author: wf """ import re class Prefixes: """ Handles the generation of standard SPARQL prefix declarations for queries. This utility class simplifies the inclusion of common prefixes used in SPARQL queries by providing a method to generate the necessary PREFIX lines based ...
WolfgangFahl/pyLoDStorage
lodstorage/prefixes.py
.py
864211258b994bbf
7.57
13
""" Created on 2022-11-18 @author: wf """ import time class Profiler: """ simple profiler """ def __init__(self, msg, profile=True, with_start: bool = True): """ construct me with the given msg and profile active flag Args: msg(str): the message to show if profi...
WolfgangFahl/pyLoDStorage
lodstorage/profiler.py
.py
f2ccf585d94a85d0
7.57
13
""" Created on 2024-08-21 @author: wf """ import json from argparse import ArgumentParser, Namespace from pathlib import Path from typing import Any, Dict, List from lodstorage.lod2xml import Lod2Xml from lodstorage.lod_csv import CSV from lodstorage.params import Params, StoreDictKeyPair from lodstorage.query impor...
WolfgangFahl/pyLoDStorage
lodstorage/query_cmd.py
.py
002350f2b60c002f
7.57
13
""" Created on 2022-02-13 @author: wf """ import logging import os import re import sys import traceback import urllib.parse from argparse import ArgumentParser, RawDescriptionHelpFormatter import requests from lodstorage.prefix_config import PrefixConfigs from lodstorage.query import Endpoint, EndpointManager, For...
WolfgangFahl/pyLoDStorage
lodstorage/querymain.py
.py
bca080682c82da88
7.57
13
""" Created on 2024-08-24 @author: wf """ from functools import wraps from ratelimit import limits, sleep_and_retry class RateLimiter: """ Wrap the @limits decorator in a new decorator """ def __init__(self, calls_per_minute: int = None): if calls_per_minute is None: calls_per_...
WolfgangFahl/pyLoDStorage
lodstorage/rate_limiter.py
.py
f1d8797b6a85a20d
7.57
13
""" Created on 2025-06-01 @author: wf """ from enum import Enum from SPARQLWrapper import JSON, N3, RDF, TURTLE class RdfFormat(Enum): """ RDF serialization formats with MIME types, file extensions, and SPARQLWrapper constants. """ TURTLE = ("turtle", "text/turtle", ".ttl", TURTLE) RDF_XML = (...
WolfgangFahl/pyLoDStorage
lodstorage/rdf_format.py
.py
1f06e3324af5e35d
7.57
13
""" Created on 2024-01-21 @author: wf """ import json import urllib.request from dataclasses import field from datetime import date from typing import Any, Dict, List, Optional from basemkit.yamlable import DateConvert, lod_storable from slugify import slugify @lod_storable class Royal: """ Represents a me...
WolfgangFahl/pyLoDStorage
lodstorage/sample2.py
.py
3e263f72b757f537
7.57
13
""" Created on 2021-01-26 @author: wf """ from collections import Counter class SchemaManager( object, ): """ a manager for schemas """ def __init__(self, schemaDefs=None, baseUrl: str = None): """ constructor Args: schemaDefs(dict): a dictionary of s...
WolfgangFahl/pyLoDStorage
lodstorage/schema.py
.py
153f3bf07ac15822
7.57
13
""" sql_backend.py Unified SQL backend abstraction for pyLoDStorage. Defines the SQLBackend Protocol (duck-typed interface) and the get_sql_backend() factory that resolves the correct backend from an endpoint descriptor, hiding the jdbc:mysql, jdbc:duckdb, and jdbc:postgresql routing details from all call sites. Cre...
WolfgangFahl/pyLoDStorage
lodstorage/sql_backend.py
.py
632ee6029bc827cd
7.57
13
""" Created on 2024-08-24 @author: wf """ import datetime import logging import sqlite3 class DatetimeAdapter: """Class for converting date and time formats with optional lenient error handling.""" def __init__(self, lenient: bool = False): """Initialize with optional lenient error handling.""" ...
WolfgangFahl/pyLoDStorage
lodstorage/sqlite_api.py
.py
1494c921f6450f13
7.57
13
""" Created on 2020-08-29 @author: wf """ import os from enum import Enum from pathlib import Path class StoreMode(Enum): """ possible supported storage modes """ JSONPICKLE = 1 # JSON Pickle JSON = 2 SQL = 3 SPARQL = 4 YAML = 5 class StorageConfig(object): """ a storage ...
WolfgangFahl/pyLoDStorage
lodstorage/storageconfig.py
.py
ff12f51e8e4da83e
7.57
13
""" Created on 2023-12-27 @author: wf """ from dataclasses import dataclass, field from typing import Any, Dict, List, Optional from tabulate import tabulate @dataclass class SyncPair: """ A class to represent a pair of data sources for synchronization. Attributes: title (str): The ti...
WolfgangFahl/pyLoDStorage
lodstorage/sync.py
.py
364679ce23791992
7.57
13
""" Created on 2021-06-13 @author: wf """ from tabulate import tabulate class TabulateCounter(object): """ helper for tabulating Counters """ def __init__(self, counter): """ Constructor """ self.counter = counter def mostCommonTable( self, headers=["#",...
WolfgangFahl/pyLoDStorage
lodstorage/tabulateCounter.py
.py
a8b0147eb7cd9721
7.57
13
""" Created on 2025-11-23 @author: wf """ class ActionStats: """Helper class to track success rates of actions.""" def __init__(self): self.success_count = 0 self.total_count = 0 self.current = None def add(self, is_success: bool): """adds a single result.""" sel...
WolfgangFahl/pyLoDStorage
tests/action_stats.py
.py
f10433a637a61184
8.07
13
""" Created on 2021-08-19 @author: wf """ import getpass import os import time from unittest import TestCase class Basetest(TestCase): """ base test case """ def setUp(self, debug=False, profile=True): """ setUp test environment """ TestCase.setUp(self) self....
WolfgangFahl/pyLoDStorage
tests/basetest.py
.py
c1ac81ffcf1005b8
8.07
13
""" Created on 2025-11-23 @author: wf """ import os from lodstorage.query import EndpointManager from tests.basetest import Basetest class EndpointTest(Basetest): """ base class for endpoint tests """ def setUp(self, debug=False, profile=True): Basetest.setUp(self, debug=debug, profile=pro...
WolfgangFahl/pyLoDStorage
tests/endpoint_test.py
.py
441545b3a46bc689
8.07
13
""" Created on 2020-07-05 @author: wf """ import unittest from lodstorage.plot import Plot from tests.basetest import Basetest class TestPlot(Basetest): """ test the Plot helper class """ def testPlot(self): """test a plot based on a Counter""" valueList = ["A", "B", "A", "C", "A",...
WolfgangFahl/pyLoDStorage
tests/test_Plot.py
.py
0173c37b5cbea00d
8.07
13
"""Cross-validate a multi-task neural network on the Gaultois targets.""" # %% import os import numpy as np import pandas as pd import torch from sklearn.model_selection import KFold from torch import nn from torch.utils.data import DataLoader from thermo.bnn.torch_dropout import Normalized from thermo.data import d...
janosh/thermo
notebooks/multitask/cross_val.py
.py
a0d28cb381e54cd1
7.64
18
"""Train an ensemble of multi-task neural networks on the Gaultois targets.""" # %% import torch from torch import nn from torch.utils.data import DataLoader from thermo.bnn.torch_dropout import GaultoisData from thermo.plots import plot_output from thermo.utils import ROOT # %% head = lambda: nn.Sequential( nn...
janosh/thermo
notebooks/multitask/ensemble.py
.py
a20b26a8556e2a1e
7.64
18
"""Bayesian neural network building blocks: priors, likelihoods and nets.""" import itertools from collections.abc import Callable from functools import partial from typing import Any import tensorflow as tf import tensorflow_probability as tfp def dense(inputs, w, b, activation=tf.identity) -> tf.Tensor: """Ap...
janosh/thermo
thermo/bnn/__init__.py
.py
724ea0582d43ac35
7.64
18
"""Hamiltonian Monte Carlo sampling and prediction for BNNs.""" from typing import Any import tensorflow as tf import tensorflow_probability as tfp from thermo.bnn import build_net, chunks, target_log_prob_fn_factory def pre_train_nn(x_train, y_train, nodes_per_layer, epochs=100) -> tuple: """Pre-train NN to g...
janosh/thermo
thermo/bnn/hmc.py
.py
a427158bb093dcce
7.64
18
"""Maximum a posteriori (MAP) training and prediction for BNNs.""" import numpy as np import tensorflow as tf from thermo import bnn def get_map_trace( target_log_prob_fn, state, n_iter=1000, save_every=10, callbacks=() ) -> tuple[list, list]: """Run Adam to maximize target_log_prob_fn, returning a trace of...
janosh/thermo
thermo/bnn/map.py
.py
c7766325a6fb3900
7.64
18
"""TensorFlow Monte Carlo dropout model with uncertainty estimation.""" from typing import Any import tensorflow as tf from thermo.utils.decorators import timed class Dropout(tf.keras.layers.Layer): """Always-on dropout layer. Disregards the training flag set to true in model.fit() and false in model.predi...
janosh/thermo
thermo/bnn/tf_dropout.py
.py
90c3edeafa5d1932
7.64
18
"""PyTorch Monte Carlo dropout model with uncertainty estimation.""" from collections.abc import Callable, Sequence from datetime import UTC, datetime from typing import Any import numpy as np import torch from pandas import DataFrame from torch import nn from torch.utils.data import DataLoader, Dataset from torch.ut...
janosh/thermo
thermo/bnn/torch_dropout.py
.py
a19d8b913d1a9392
7.64
18
"""Correlation-based candidate selection and random baselines.""" from random import shuffle import numpy as np def rand_obj_val_avr(corr_mat: np.ndarray, n_select: int, n_repeats: int = 50) -> float: """Simulates the random baseline for the discrete constrained optimization problem of finding the n_select ...
janosh/thermo
thermo/correlation.py
.py
27d4985d2e27e8d3
7.64
18
"""Load the Gaultois thermoelectrics database and screening dataset.""" from __future__ import annotations from typing import TYPE_CHECKING from pandas import DataFrame, read_csv from thermo.utils import ROOT if TYPE_CHECKING: from collections.abc import Sequence def to_type(df: DataFrame, dtype: str = "flo...
janosh/thermo
thermo/data/load.py
.py
eeabe25591dd1938
7.64
18