### Install metalog-jax using uv Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/getting-started.md Use this command to install the library via uv. ```bash uv pip install metalog-jax ``` -------------------------------- ### Install Dependencies Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Install all project dependencies. This is a crucial step for setting up the development environment and ensuring all necessary libraries are available. ```bash make install ``` -------------------------------- ### Install metalog-jax from source Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Install metalog-jax by cloning the repository and building from source. This method allows for direct contribution and development. ```bash git clone https://github.com/tjefferies/metalog_jax.git cd metalog_jax make install # Install all dependencies ``` -------------------------------- ### Install metalog-jax using pip Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/getting-started.md Use this command to install the library via pip. ```bash pip install metalog-jax ``` -------------------------------- ### Install Metalog JAX Source: https://context7.com/tjefferies/metalog_jax/llms.txt Install Metalog JAX using pip or uv. For GPU support with CUDA 12, use the `[gpu]` extra. ```bash pip install metalog-jax ``` ```bash uv add metalog-jax ``` ```bash pip install "metalog-jax[gpu]" ``` -------------------------------- ### Example Output for Precomputed Quantiles Fit Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/fitting_grids.ipynb This is an example output showing the KS distance and coefficients obtained from fitting a Metalog distribution using precomputed quantiles. ```text Precomputed quantiles fit KS distance: 0.1429 Coefficients: [ 2.11320782e-16 5.82969856e-01 2.37162298e-16 1.05904096e+00 -6.04972876e-16] ``` -------------------------------- ### Install metalog-jax with GPU support Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Install metalog-jax with GPU support, which requires CUDA 12. Note that GPU support is only available on Linux or WSL2. ```bash # pip pip install "metalog-jax[gpu]" # uv uv add "metalog-jax[gpu]" ``` -------------------------------- ### Example of default quantiles array Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb This output shows the structure and values of the default quantiles array used in metalog-jax fitting. ```text Result: Array([0.001 , 0.003 , 0.006 , 0.01 , 0.02 , 0.03 , 0.04 , 0.05 , 0.06 , 0.07 , 0.08 , 0.09 , 0.09999999, 0.11 , 0.12 , 0.13 , 0.14 , 0.14999999, 0.16 , 0.17 , 0.17999999, 0.19 , 0.19999999, 0.21 , 0.22 , 0.22999999, 0.24 , 0.25 , 0.26 , 0.26999998, 0.28 , 0.29 , 0.29999998, 0.31 , 0.32 , 0.32999998, 0.34 , 0.35 , 0.35999998, 0.37 , 0.38 , 0.39 , 0.39999998, 0.41 , 0.42 , 0.42999998, 0.44 , 0.45 , 0.45999998, 0.47 , 0.48 , 0.48999998, 0.5 , 0.51 , 0.52 , 0.53 , 0.53999996, 0.55 , 0.56 , 0.57 , 0.58 , 0.59 , 0.59999996, 0.61 , 0.62 , 0.63 , 0.64 , 0.65 , 0.65999997, 0.66999996, 0.68 , 0.69 , 0.7 , 0.71 , 0.71999997, 0.72999996, 0.74 , 0.75 , 0.76 , 0.77 , 0.78 , 0.78999996, 0.79999995, 0.81 , 0.82 , 0.83 , 0.84 , 0.84999996, 0.85999995, 0.87 , 0.88 , 0.89 , 0.9 , 0.90999997, 0.91999996, 0.93 , 0.94 , 0.95 , 0.96 , 0.96999997, 0.97999996, 0.98999995, 0.994 , 0.997 , 0.999 ], dtype=float32) ``` -------------------------------- ### Get Save Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Displays the documentation for the Metalog.save method, explaining how to serialize the distribution coefficients and parameters to a JSON file. ```python print(Metalog.save.__doc__) ``` -------------------------------- ### Get Load Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Prints the docstring for the Metalog.load method, which describes how to load a serialized metalog distribution from a JSON file. ```python print(Metalog.load.__doc__) ``` -------------------------------- ### Fit a Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Fit a metalog distribution to sample data. This example demonstrates fitting a distribution for response times, which are lower-bounded. ```python import jax.numpy as jnp from metalog_jax.base import MetalogInputData, MetalogParameters from metalog_jax.base import MetalogBoundedness, MetalogFitMethod from metalog_jax.metalog import fit from metalog_jax.utils import DEFAULT_Y # Sample data (e.g., response times in microseconds) response_times = jnp.array([ 45, 52, 58, 61, 67, 72, 78, 85, 93, 102, 115, 128, 145, 167, 195, 238, 312, 456, 623, 892 ]) # Create validated input data data = MetalogInputData.from_values(response_times, DEFAULT_Y, precomputed_quantiles=False) # Configure the metalog (bounded below by 0) params = MetalogParameters( boundedness=MetalogBoundedness.STRICTLY_LOWER_BOUND, lower_bound=0.0, upper_bound=0.0, method=MetalogFitMethod.OLS, num_terms=5, ) # Fit the distribution metalog = fit(data, params) # Analyze your distribution print(f"Median response time: {float(metalog.ppf(jnp.array([0.5]))[0]):.1f} ms") print(f"95th percentile: {float(metalog.ppf(jnp.array([0.95]))[0]):.1f} ms") print(f"99th percentile: {float(metalog.ppf(jnp.array([0.99]))[0]):.1f} ms") ``` -------------------------------- ### Load Previously Saved Metlog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Loads a fitted metalog distribution from a JSON file. This example demonstrates saving a distribution and then loading it back, verifying the loaded coefficients match the original. ```python # load a previously saved metalog with tempfile.TemporaryDirectory() as _tmpdir: _save_path = Path(_tmpdir) / "test_metalog.json" metalog.save(_save_path) loaded_metalog = Metalog.load(_save_path) np.testing.assert_array_almost_equal( np.array(loaded_metalog.a), np.array(metalog.a) ) ``` -------------------------------- ### Build Documentation Live Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Build the documentation and enable live reloading during development. This allows you to see documentation changes in real-time as you edit. ```bash make docs-live ``` -------------------------------- ### Build Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Build the project documentation. This command is useful when you have made changes to docstrings and need to regenerate the documentation. ```bash make docs ``` -------------------------------- ### Verify Equivalence of PPF and Q Methods Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb This snippet demonstrates that the results from `metalog.ppf` and `metalog.q` are numerically identical for the same input probabilities, using `np.testing.assert_allclose` for verification. ```python # results are identical ppf_1 = metalog.ppf(DEFAULT_Y) q = metalog.q(DEFAULT_Y) np.testing.assert_allclose(ppf_1, q) ``` -------------------------------- ### Get Metalog logppf Docstring Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Prints the docstring for the Metalog.logppf function, explaining its arguments and return values. ```python print(Metalog.logppf.__doc__) ``` -------------------------------- ### Get Metalog sf Docstring Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Prints the docstring for the Metalog.sf function, explaining its purpose, arguments, and return values. ```python print(Metalog.sf.__doc__) ``` -------------------------------- ### Initialize MetalogParameters Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Initializes MetalogParameters with specified boundedness, bounds, fitting method, and number of terms. Use this to configure metalog distribution fitting. ```python metalog_params = MetalogParameters( boundedness=MetalogBoundedness.UNBOUNDED, lower_bound=0, upper_bound=1, method=MetalogFitMethod.OLS, num_terms=5, ) ``` -------------------------------- ### Equivalence of ppf and q Methods Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Demonstrates that the `ppf` and `q` methods produce identical results for computing quantiles from a fitted Metalog distribution. ```APIDOC ## Equivalence of ppf and q Methods ### Description This section demonstrates that the `metalog.ppf` and `metalog.q` methods yield identical results when calculating quantiles from a fitted Metalog distribution. ### Method `np.testing.assert_allclose(metalog.ppf(x), metalog.q(x))` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **x** (scalar or array) - Probability values in (0, 1). ### Request Example ```python import numpy as np # Assuming metalog is a fitted Metalog object and DEFAULT_Y is defined ppf_results = metalog.ppf(DEFAULT_Y) q_results = metalog.q(DEFAULT_Y) # Assert that the results are numerically close np.testing.assert_allclose(ppf_results, q_results) print("The results from ppf and q are identical.") ``` ### Response #### Success Response (200) - **Assertion**: The assertion passes, indicating the results are numerically equivalent. #### Response Example ``` The results from ppf and q are identical. ``` ``` -------------------------------- ### Show All Make Targets Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Display a list of all available targets in the Makefile. This command helps in understanding the various development and build tasks supported by the project. ```bash make help ``` -------------------------------- ### Get Plot Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Prints the docstring for the Metalog.plot method, which details how to visualize fitted metalog distributions using Plotly. ```python print(Metalog.plot.__doc__) ``` -------------------------------- ### Clone Repository Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Clone the metalog-jax repository from GitHub. This is the first step to setting up the project locally. ```bash git clone https://github.com/tjefferies/metalog_jax.git ``` -------------------------------- ### Fit Metalog Distribution and Generate Quantiles Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/index.md Demonstrates fitting a Metalog distribution using OLS and generating quantiles. Requires MetalogInputData and MetalogParameters configuration. ```python import jax.numpy as jnp from metalog_jax.base import MetalogInputData, MetalogParameters from metalog_jax.base import MetalogBoundedness, MetalogFitMethod from metalog_jax.metalog import fit # Create validated input data using from_values() raw_data = jnp.array([1.2, 2.3, 2.8, 3.5, 4.1, 5.6]) data = MetalogInputData.from_values( x=raw_data, y=jnp.array([0.1, 0.25, 0.5, 0.75, 0.9, 0.95]), precomputed_quantiles=False # Raw samples, not precomputed quantiles ) # Configure metalog parameters with OLS metalog_params = MetalogParameters( boundedness=MetalogBoundedness.UNBOUNDED, method=MetalogFitMethod.OLS, lower_bound=0.0, upper_bound=0.0, num_terms=5 ) # Fit the metalog distribution m = fit(data, metalog_params) # Generate quantiles quantiles = m.ppf(jnp.array([0.25, 0.5, 0.75])) # Access distribution properties print(f"Mean: {m.mean}, Median: {m.median}, Std: {m.std}") ``` -------------------------------- ### Get Mode of Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Retrieves the mode (most likely value) of the fitted metalog distribution. The mode is found by maximizing the PDF over a grid. ```python # get mode metalog.mode ``` -------------------------------- ### Get Median of Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Retrieves the median of the fitted metalog distribution. The median is calculated exactly using the quantile function (ppf). ```python # get median metalog.median ``` -------------------------------- ### Get Variance of Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Retrieves the estimated variance of the fitted metalog distribution. This value is computed using Monte Carlo sampling. ```python # get variance metalog.var ``` -------------------------------- ### Metalog Distribution API: Quantiles and PDF Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Demonstrates calculating quantiles (inverse CDF) and probability density function (PDF) values for a metalog distribution. Requires importing jax.numpy. ```python import jax.numpy as jnp # Quantile function (inverse CDF) quantiles = metalog.ppf(jnp.array([0.1, 0.25, 0.5, 0.75, 0.9])) # Probability density function pdf_values = metalog.pdf(jnp.array([0.2, 0.4, 0.6, 0.8])) ``` -------------------------------- ### Get Mean of Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Retrieves the estimated mean of the fitted metalog distribution. The mean is computed using Monte Carlo sampling. ```python # get mean metalog.mean ``` -------------------------------- ### Run Quick Tests Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Execute tests for fast iteration without coverage reporting. This is useful during active development for quick feedback on changes. ```bash make test-quick ``` -------------------------------- ### Get Standard Deviation of Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Retrieves the estimated standard deviation of the fitted metalog distribution. Calculated via Monte Carlo sampling. ```python # get standard deviation metalog.std ``` -------------------------------- ### Initialize Metalog Random Variable Parameters Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Initializes parameters for drawing random variables from a fitted metalog distribution. Requires PRNG parameters and the desired sample size. ```python # init metalog RV parameters metalog_rv_params = MetalogRandomVariableParameters( prng_params=uniform_prng_params, size=10 ) ``` -------------------------------- ### Regularized Metalog Fitting with LASSO Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Fit a metalog distribution using LASSO (L1 regularization) for improved stability with noisy data or many terms. This example uses a lambda value of 0.01. ```python from metalog_jax.base import MetalogInputData, MetalogParameters from metalog_jax.base import MetalogBoundedness, MetalogFitMethod from metalog_jax.metalog import fit from metalog_jax.regression import LassoParameters # LASSO (L1 regularization for sparse coefficients) lasso_params = LassoParameters( lam=0.01, # L1 regularization strength learning_rate=1e-3, num_iters=1000, tol=1e-6, momentum=0.9, ) params = MetalogParameters( boundedness=MetalogBoundedness.STRICTLY_LOWER_BOUND, lower_bound=0.0, upper_bound=0.0, method=MetalogFitMethod.Lasso, num_terms=6, ) metalog = fit(data, params, regression_hyperparams=lasso_params) ``` -------------------------------- ### Generate sample data for a single dataset Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/fitting_grids.ipynb Creates sample data from a beta distribution and formats it into a MetalogInputData object for fitting. ```python # Generate sample data from a beta distribution dist_beta = beta(a=2, b=5) samples_beta = dist_beta.rvs(size=200, random_state=42) # Create input data data_single = MetalogInputData.from_values(samples_beta, DEFAULT_Y, False) ``` -------------------------------- ### Sample Random Variates from Metalog Distribution Source: https://context7.com/tjefferies/metalog_jax/llms.txt Generates random samples from a Metalog distribution using specified PRNG parameters and sample size. Visualizes the probability density function (PDF) if Plotly is installed. ```python rv_params = MetalogRandomVariableParameters( prng_params=JaxUniformDistributionParameters(seed=42), size=10000, ) samples = metalog.rvs(rv_params) print(f"Sample mean: {float(jnp.mean(samples)):.2f}") # Visualization (requires Plotly) fig = metalog.plot(MetalogPlotOptions.PDF) # or CDF, SF ``` -------------------------------- ### Change Directory Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Navigate into the cloned metalog-jax directory. This is necessary to run subsequent commands within the project. ```bash cd metalog_jax ``` -------------------------------- ### Loading a Fitted Metalog Distribution Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Illustrates how to load a previously saved metalog distribution from a JSON file. ```APIDOC ## POST /api/metalog/load ### Description Load a fitted metalog distribution from a JSON file. Deserializes the distribution coefficients and parameters from the specified JSON file. ### Method POST ### Endpoint /api/metalog/load ### Parameters #### Request Body - **path** (string) - Required - File path to the JSON file containing the serialized distribution. ### Response #### Success Response (200) - **metalog_instance** (object) - A new instance of the metalog class with loaded coefficients and parameters. #### Response Example { "metalog_instance": "[Loaded Metalog object]" } ``` -------------------------------- ### List MetalogFitMethod Options Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Lists the available members for MetalogFitMethod, showing the regression methods supported for fitting metalog distributions. Use these to set the 'method' parameter. ```python # fit options list(MetalogFitMethod.__members__.keys()) ``` -------------------------------- ### Configure Metalog with Lasso Method Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/getting-started.md Set up Metalog parameters, specifying the Lasso fitting method and regularization hyperparameters. ```python metalog_params = MetalogParameters( boundedness=MetalogBoundedness.UNBOUNDED, method=MetalogFitMethod.Lasso, lower_bound=0.0, upper_bound=0.0, num_terms=9 ) lasso_params = LassoParameters( lam=0.1, # L1 regularization strength learning_rate=0.01, num_iters=500, tol=1e-6, momentum=0.9 ) m = fit(data, metalog_params, regression_hyperparams=lasso_params) ``` -------------------------------- ### Print Metalog Median Method Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Prints the docstring for the Metalog.median property, explaining its exact computation via ppf(0.5). ```python print(Metalog.median.__doc__) ``` -------------------------------- ### Perform 2D Grid Search for Metalog Parameters Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md This snippet demonstrates a 2D grid search over L1 penalties and the number of terms for a single dataset. It initializes data, defines Metalog parameters, and uses `fit_grid` to find the optimal configuration. The best parameters are then identified and printed. ```python import jax.numpy as jnp from metalog_jax.base import MetalogInputData, MetalogParameters from metalog_jax.base import MetalogBoundedness, MetalogFitMethod from metalog_jax.grid_search import fit_grid, find_best_config, extract_metalog from metalog_jax.utils import DEFAULT_Y # Assume 'samples' is a JAX numpy array of data points samples = jnp.array([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) # Example data # Create validated input data data = MetalogInputData.from_values(samples, DEFAULT_Y, precomputed_quantiles=False) params = MetalogParameters( boundedness=MetalogBoundedness.BOUNDED, lower_bound=0.0, upper_bound=1.0, method=MetalogFitMethod.Lasso, num_terms=5, ) # 2D grid search over L1 penalties and num_terms l1_penalties = jnp.array([0.0, 0.01, 0.1]) num_terms_list = [5, 7, 9] result = fit_grid( data.x, data.y, params, l1_penalties=l1_penalties, num_terms=num_terms_list ) # Result shape is (len(l1_penalties), len(num_terms_list)) print(f"Grid shape: {result.ks_dist.shape}") # (3, 3) # Find the best configuration best_idx, best_ks = find_best_config(result.ks_dist) best_l1_idx, best_terms_idx = int(best_idx[0]), int(best_idx[1]) print(f"Best L1 penalty: {float(l1_penalties[best_l1_idx]):.4f}") print(f"Best num_terms: {num_terms_list[best_terms_idx]}") print(f"Best KS distance: {float(best_ks):.4f}") # Extract the best metalog for use best_metalog = extract_metalog(result, best_l1_idx, best_terms_idx) print(f"Median: {float(best_metalog.ppf(jnp.array([0.5]))[0]):.4f}") ``` -------------------------------- ### Format Code Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Automatically format the code according to project conventions. This ensures consistent code style across the repository. ```bash make format ``` -------------------------------- ### Initialize MetalogInputData from raw sample data Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Creates a MetalogInputData object from raw sample data. The `precomputed_quantiles=False` flag tells the object to compute quantiles internally from the provided sample data. ```python # init MetalogInputData object from raw data # MUST use `from_values` - performs validity checks data_1 = MetalogInputData.from_values( x=rvs, y=DEFAULT_Y, precomputed_quantiles=False ) ``` -------------------------------- ### Run Tests with Coverage Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Execute the full test suite with coverage reporting. This is useful for ensuring code quality and identifying areas for improvement. ```bash make test ``` -------------------------------- ### Run Quality Gate Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Execute all quality checks, including formatting, linting, type checking, complexity metrics, tests, license compliance, and security scans. This command mirrors the CI checks and is recommended before pushing changes. ```bash make quality-gate ``` -------------------------------- ### MetalogInputData class documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Documentation for the MetalogInputData class, explaining its role in encapsulating input data for metalog fitting, supporting both pre-computed quantiles and raw data modes, and emphasizing the use of the `from_values` factory method for validation. ```text Output: Container for input data used to fit metalog distributions. This dataclass encapsulates the input data for metalog fitting, supporting two modes: (1) fitting from pre-computed quantiles at specified probability levels, or (2) fitting from raw sample data where quantiles are computed automatically. The mode is controlled by the `precomputed_quantiles` flag, which determines how the `x` array should be interpreted and processed during fitting. **IMPORTANT**: Instances MUST be created using the `from_values()` classmethod. Direct instantiation via `__init__()` is prevented by a `__post_init__` validation that raises `TypeError` if the instance was not created through `from_values()`. Attributes: x: Input data array. The interpretation depends on `precomputed_quantiles`: - If `precomputed_quantiles=True`: Array of quantile values - If `precomputed_quantiles=False`: Array of raw sample data y: Array of probability levels in the open interval (0, 1), sorted in ascending order. precomputed_quantiles: Flag indicating the interpretation of `x`. See Also: MetalogBaseData: Parent class without validation (for advanced use). from_values: Required factory method for creating validated instances. metalog_jax.metalog.fit: Function that uses MetalogInputData for fitting. ``` -------------------------------- ### Cumulative Distribution Function (cdf) Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Provides documentation for the cumulative distribution function (cdf) method. It explains that this function computes P(X <= q) for the fitted Metalog distribution using numerical inversion of the quantile function. It accepts quantile values q and returns corresponding probability values. ```python print(Metalog.cdf.__doc__) ``` -------------------------------- ### Serialization: Dump and Load Metalog from String Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md Shows how to serialize a metalog distribution to a JSON string and deserialize it back into a Metalog object. Includes an assertion to verify equality. ```python from metalog_jax.metalog import Metalog # String serialization json_str = metalog.dumps() loaded2 = Metalog.loads(json_str) assert metalog == loaded == loaded2 ``` -------------------------------- ### Automatic Differentiation with JAX Source: https://github.com/tjefferies/metalog_jax/blob/main/README.md This snippet demonstrates how to use JAX's automatic differentiation capabilities with a Metalog object. It defines a function to calculate quantiles at a given probability and then computes the gradient of this function at the median. ```python import jax # Assume 'metalog' is a fitted Metalog object # Example placeholder for metalog object: class MockMetalog: def ppf(self, prob): return prob * 2 # Simplified linear ppf for demonstration metalog = MockMetalog() # Automatic differentiation def quantile_at(prob): return metalog.ppf(prob) gradient_fn = jax.grad(quantile_at) gradient = gradient_fn(0.5) ``` -------------------------------- ### Metalog PDF Documentation Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Provides documentation for the Metalog.pdf function, explaining its purpose, arguments, return values, and potential exceptions. ```python print(Metalog.pdf.__doc__) ``` -------------------------------- ### Initialize JAX Uniform Distribution Parameters Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Initializes a PRNG parameter object for a JAX uniform distribution using a specified seed. This is a prerequisite for generating samples. ```python # to generate samples from distribution, we first init a PRNG parameter object # below is standard jax PRNG uniform_prng_params = JaxUniformDistributionParameters(seed=42) uniform_prng_params ``` -------------------------------- ### Import necessary libraries for Metalog Grid Search Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/fitting_grids.ipynb Imports JAX, SciPy distributions, and Metalog-specific modules required for grid search operations. ```python import jax.numpy as jnp from scipy.stats import beta, gamma, lognorm, norm, weibull_min from metalog_jax.base import ( MetalogBoundedness, MetalogFitMethod, MetalogInputData, MetalogParameters, ) from metalog_jax.grid_search import find_best_config, fit_grid from metalog_jax.utils import DEFAULT_Y ``` -------------------------------- ### Automatic Differentiation with JAX Source: https://context7.com/tjefferies/metalog_jax/llms.txt Utilize JAX transformations like `grad` and `vmap` on metalog distributions for gradient-based optimization and vectorized computations. Requires fitting a metalog distribution first. ```python import jax import jax.numpy as jnp from metalog_jax.base import MetalogInputData, MetalogParameters from metalog_jax.base import MetalogBoundedness, MetalogFitMethod from metalog_jax.metalog import fit from metalog_jax.utils import DEFAULT_Y # Fit a distribution data_values = jnp.array([2.1, 3.5, 4.2, 5.8, 6.1, 7.3, 8.9, 12.4, 15.2, 18.7]) data = MetalogInputData.from_values(data_values, DEFAULT_Y, precomputed_quantiles=False) params = MetalogParameters( boundedness=MetalogBoundedness.UNBOUNDED, lower_bound=0.0, upper_bound=0.0, method=MetalogFitMethod.OLS, num_terms=5, ) metalog = fit(data, params) # Automatic differentiation of the quantile function def quantile_at(prob): return metalog.ppf(prob)[0] gradient_fn = jax.grad(quantile_at) gradient = gradient_fn(jnp.array(0.5)) print(f"Gradient of PPF at 0.5: {float(gradient):.4f}") # Vectorized evaluation with vmap probs = jnp.array([0.1, 0.25, 0.5, 0.75, 0.9]) vectorized_grad = jax.vmap(gradient_fn) gradients = vectorized_grad(probs) print(f"Gradients at multiple points: {gradients}") ``` -------------------------------- ### Prepare input data for metalog fitting Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Generates sample data from a t-distribution and calculates its quantiles using the default probability levels. This data is then used to initialize a MetalogInputData object. ```python # input data dist = t(df=6, loc=50, scale=5) rvs = jnp.array(dist.rvs(size=1000, random_state=42)) ppf = jnp.array(dist.ppf(DEFAULT_Y)) ``` -------------------------------- ### Prepare Batched Datasets for Metalog Fit Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/fitting_grids.ipynb Generates multiple distributions and stacks them into batched arrays for parallel fitting. Prints the shapes of the batched input data. ```python # Generate multiple distributions (all lower-bounded at 0) dist_lognorm = lognorm(s=0.5, loc=0, scale=1).rvs(size=200, random_state=42) dist_weibull = weibull_min(c=2, scale=2).rvs(size=200, random_state=43) dist_gamma = gamma(a=4, scale=1).rvs(size=200, random_state=44) # Create input data for each data1 = MetalogInputData.from_values(dist_lognorm, DEFAULT_Y, False) data2 = MetalogInputData.from_values(dist_weibull, DEFAULT_Y, False) data3 = MetalogInputData.from_values(dist_gamma, DEFAULT_Y, False) # Stack into batched arrays batched_x = jnp.stack([data1.x, data2.x, data3.x]) batched_y = jnp.stack([data1.y, data2.y, data3.y]) print(f"Batched x shape: {batched_x.shape}") print(f"Batched y shape: {batched_y.shape}") ``` ```text Batched x shape: (3, 105) Batched y shape: (3, 105) ``` -------------------------------- ### Initialize HDR PRNG Parameters Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Initializes parameters for the Hubbard Decision Research Pseudo-Random Number Generator. These parameters seed the random number generation process for simulations. ```python hdr_prng_params = HDRPRNGParameters() ``` -------------------------------- ### List MetalogBoundedness Options Source: https://github.com/tjefferies/metalog_jax/blob/main/docs/source/basic_usage.ipynb Lists the available members for MetalogBoundedness, indicating the types of domain constraints supported. Use these to set the 'boundedness' parameter. ```python # boundedness options list(MetalogBoundedness.__members__.keys()) ``` -------------------------------- ### Fit Bounded and Unbounded Distributions Source: https://context7.com/tjefferies/metalog_jax/llms.txt Use MetalogInputData to create input data and MetalogParameters to specify distribution properties like boundedness, bounds, and fitting method. The fit function returns a fitted Metalog object. ```python import jax.numpy as jnp from metalog_jax.base import MetalogInputData, MetalogParameters from metalog_jax.base import MetalogBoundedness, MetalogFitMethod from metalog_jax.metalog import fit from metalog_jax.utils import DEFAULT_Y # Sample percentage data (bounded between 0 and 100) percentages = jnp.array([5.2, 12.8, 18.5, 25.3, 32.1, 41.7, 52.4, 63.8, 75.2, 88.9]) # Create validated input data data = MetalogInputData.from_values(percentages, DEFAULT_Y, precomputed_quantiles=False) # Fully bounded distribution (0, 100) params_bounded = MetalogParameters( boundedness=MetalogBoundedness.BOUNDED, lower_bound=0.0, upper_bound=100.0, method=MetalogFitMethod.OLS, num_terms=5, ) metalog_bounded = fit(data, params_bounded) # Unbounded distribution for temperature anomalies temp_anomalies = jnp.array([-2.1, -1.3, -0.5, 0.2, 0.8, 1.5, 2.3, 3.1, 4.2, 5.8]) temp_data = MetalogInputData.from_values(temp_anomalies, DEFAULT_Y, precomputed_quantiles=False) params_unbounded = MetalogParameters( boundedness=MetalogBoundedness.UNBOUNDED, lower_bound=0.0, # ignored for unbounded upper_bound=0.0, # ignored for unbounded method=MetalogFitMethod.OLS, num_terms=5, ) metalog_unbounded = fit(temp_data, params_unbounded) print(f"Bounded median: {float(metalog_bounded.ppf(jnp.array([0.5]))[0]):.1f}%") print(f"Unbounded median: {float(metalog_unbounded.ppf(jnp.array([0.5]))[0]):.2f}") ```