Skip to content
melhzyPublic

About

Part of the ADAM Project

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

51 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

SeedHash: MD5-Based Deterministic Random Seed Generator

Python Version R Version License: MIT Tests

SeedHash is a library for generating deterministic random seeds from string inputs using MD5 hashing. Available in both Python and R, it's perfect for creating reproducible experiments, simulations, and any scenario where you need consistent random number generation across different runs.

πŸ“ Repository Structure

seedhash/
β”œβ”€β”€ Python/              # Python implementation
β”‚   β”œβ”€β”€ seedhash/        # Python package
β”‚   β”œβ”€β”€ examples/        # Python examples
β”‚   └── README.md        # Python documentation
β”‚
β”œβ”€β”€ R/                   # R implementation  
β”‚   β”œβ”€β”€ R/               # R package source
β”‚   β”œβ”€β”€ tests/           # R tests
β”‚   β”œβ”€β”€ examples/        # R examples
β”‚   └── README.md        # R documentation
β”‚
β”œβ”€β”€ PYTHON_TO_R_GUIDE.md # Conversion guide for developers
└── README.md            # This file

Features

  • 🎯 Deterministic: Same input string always produces the same sequence of random numbers
  • πŸ”§ Configurable: Customize the range of generated random numbers
  • βœ… Type-Safe: Comprehensive error handling and input validation
  • πŸ“¦ Lightweight: Minimal dependencies (Python: none, R: R6 + digest)
  • πŸš€ Easy to Use: Simple, intuitive API
  • πŸ”„ Cross-Language: Available in both Python and R
  • 🎲 4 Sampling Methods: Simple, Stratified, Cluster, and Systematic random sampling
  • πŸ§ͺ ML Integration: Experiment tracking with hierarchical seed management
  • πŸ–₯️ Multi-GPU Ready: Seeds PyTorch the same way on one GPU, several GPUs, or several nodes (torchrun, SLURM, MPI)

Installation

Python

# From GitHub
pip install git+https://github.com/melhzy/seedhash.git#subdirectory=Python

# From local directory
cd Python
pip install .

See Python/README.md for detailed instructions.

R

# Recommended: Using pak
install.packages("pak", repos = "https://r-lib.github.io/p/pak/stable/")
pak::pkg_install("github::melhzy/seedhash/R")

# Alternative: Using devtools
devtools::install_github("melhzy/seedhash", subdir = "R")

See R/INSTALL.md for detailed instructions.

Quick Start

Python

from seedhash import SeedHashGenerator

# Create a generator with an input string
generator = SeedHashGenerator("my_experiment_name")

# Generate 10 random seeds
seeds = generator.generate_seeds(10)
print(seeds)

# Get the MD5 hash
print(generator.get_hash())

R

library(seedhash)

# Create a generator
generator <- SeedHashGenerator$new("my_experiment_name")

# Generate 10 random seeds
seeds <- generator$generate_seeds(10)
print(seeds)

# Get the MD5 hash
cat(generator$get_hash(), "\n")

Usage Examples

Basic Usage

from seedhash import SeedHashGenerator

# Initialize with a string
gen = SeedHashGenerator("Shalini")

# Generate 10 random seeds (default range: 0 to 2^31-1)
random_seeds = gen.generate_seeds(10)
print(f"Generated seeds: {random_seeds}")

# Get the underlying hash
print(f"MD5 Hash: {gen.get_hash()}")
print(f"Seed number: {gen.seed_number}")

Custom Range

from seedhash import SeedHashGenerator

# Custom range for random numbers
gen = SeedHashGenerator(
    input_string="experiment_42",
    min_value=100,
    max_value=1000
)

# Generate 5 seeds in the range [100, 1000]
seeds = gen.generate_seeds(5)
print(f"Seeds in range [100, 1000]: {seeds}")

Error Handling

from seedhash import SeedHashGenerator

# The library includes comprehensive error checking
try:
    # Empty string raises ValueError
    gen = SeedHashGenerator("")
except ValueError as e:
    print(f"Error: {e}")

try:
    # Invalid range raises ValueError
    gen = SeedHashGenerator("test", min_value=100, max_value=50)
except ValueError as e:
    print(f"Error: {e}")

try:
    # Non-positive count raises ValueError
    gen = SeedHashGenerator("test")
    seeds = gen.generate_seeds(0)
except ValueError as e:
    print(f"Error: {e}")

Reproducibility Demo

from seedhash import SeedHashGenerator

# Same input always produces same output
gen1 = SeedHashGenerator("experiment_1")
seeds1 = gen1.generate_seeds(5)

gen2 = SeedHashGenerator("experiment_1")
seeds2 = gen2.generate_seeds(5)

assert seeds1 == seeds2  # Always True!
print(f"Reproducible: {seeds1} == {seeds2}")

API Reference

SeedHashGenerator

Constructor

SeedHashGenerator(input_string, min_value=None, max_value=None)

Parameters:

  • input_string (str): The string to hash for seed generation
  • min_value (int, optional): Minimum value for random number range. Default: 0
  • max_value (int, optional): Maximum value for random number range. Default: 2^31 - 1

Raises:

  • TypeError: If input_string is not a string or range values are not integers
  • ValueError: If input_string is empty or min_value >= max_value

Methods

generate_seeds(count)

Generate a list of random seed numbers.

Parameters:

  • count (int): The number of random seeds to generate

Returns:

  • List[int]: A list of random integers within the specified range

Raises:

  • TypeError: If count is not an integer
  • ValueError: If count is not positive
get_hash()

Get the MD5 hash of the input string.

Returns:

  • str: The MD5 hash as a hexadecimal string

Attributes

  • input_string (str): The input string used for seed generation
  • min_value (int): Minimum value for random numbers
  • max_value (int): Maximum value for random numbers
  • seed_number (int): The integer seed derived from the input string

Use Cases

Machine Learning Experiments

from seedhash import SeedHashGenerator

# Reproducible train/test splits
experiment_name = "model_v1_baseline"
gen = SeedHashGenerator(experiment_name)
seeds = gen.generate_seeds(5)  # For different folds

for i, seed in enumerate(seeds):
    print(f"Fold {i+1} seed: {seed}")
    # Use seed for train_test_split, model initialization, etc.

Monte Carlo Simulations

from seedhash import SeedHashGenerator

# Reproducible simulation runs
simulation_id = "monte_carlo_sim_2025"
gen = SeedHashGenerator(simulation_id, min_value=1, max_value=10000)

# Generate seeds for parallel simulation runs
num_simulations = 100
simulation_seeds = gen.generate_seeds(num_simulations)

Data Sampling

from seedhash import SeedHashGenerator
import random

# Reproducible data sampling
dataset_version = "dataset_v2.1"
gen = SeedHashGenerator(dataset_version)
sample_seed = gen.generate_seeds(1)[0]

random.seed(sample_seed)

Advanced Features

🎲 4 Random Sampling Techniques

SeedHash includes 4 scientifically-backed sampling methods for systematic seed generation:

from seedhash import SeedSampler

sampler = SeedSampler(master_seed=42)

# 1. Simple Random Sampling - Pure randomness
simple = sampler.simple_random_sampling(n_samples=10, seed_range=(0, 1000))

# 2. Stratified Random Sampling - Balanced coverage
stratified = sampler.stratified_random_sampling(
    n_samples=25, seed_range=(0, 1000), n_strata=5
)

# 3. Cluster Random Sampling - Grouped seeds
cluster = sampler.cluster_random_sampling(
    n_samples=20, seed_range=(0, 1000), n_clusters=4
)

# 4. Systematic Random Sampling - Even intervals
systematic = sampler.systematic_random_sampling(n_samples=15, seed_range=(0, 1000))

πŸ“– Full Sampling Methods Documentation β†’

πŸ§ͺ Hierarchical Seed Management & Experiment Tracking

from seedhash import SeedExperimentManager
import numpy as np

# Create experiment manager
manager = SeedExperimentManager("my_ml_project")

# Generate hierarchical seeds: master β†’ seeds β†’ sub-seeds
hierarchy = manager.generate_seed_hierarchy(
    n_seeds=10,
    n_sub_seeds=5,
    max_depth=2,
    sampling_method="stratified"  # Use any of the 4 methods
)

# Track experiments
for seed in hierarchy[1]:
    # Run your experiment
    np.random.seed(seed)
    accuracy = 0.8 + np.random.rand() * 0.15
    
    # Record results
    manager.add_experiment_result(
        seed=seed,
        ml_task="classification",
        metrics={"accuracy": accuracy, "f1_score": 0.85},
        sampling_method="stratified"
    )

# Export to DataFrame
df = manager.get_results_dataframe()
df.to_csv('experiment_results.csv')

πŸ“– Full Documentation | πŸ““ Jupyter Tutorials

Project Structure

Python/
β”œβ”€β”€ seedhash/
β”‚   β”œβ”€β”€ __init__.py          # Package initialization
β”‚   β”œβ”€β”€ core.py              # Core SeedHashGenerator class
β”‚   └── experiment.py        # Experiment tracking
β”œβ”€β”€ examples/
β”‚   β”œβ”€β”€ demo.py              # Usage examples
β”‚   β”œβ”€β”€ hierarchical_sampling.py
β”‚   β”œβ”€β”€ deep_learning_seeding.py
β”‚   β”œβ”€β”€ distributed_seeding.py  # Multi-GPU / multi-node
β”‚   └── advanced_ml_paradigms.py
β”œβ”€β”€ setup.py                 # Setup configuration
β”œβ”€β”€ pyproject.toml           # Modern Python packaging
β”œβ”€β”€ requirements.txt         # Dependencies
└── README.md                # Python documentation

R/
β”œβ”€β”€ R/
β”‚   └── seedhash.R           # R package implementation
β”œβ”€β”€ man/                     # R documentation
β”œβ”€β”€ tests/
β”‚   β”œβ”€β”€ testthat.R           # testthat entry point
β”‚   └── testthat/
β”‚       └── test-seedhash.R  # R tests
β”œβ”€β”€ examples/
β”‚   └── example_usage.R
β”œβ”€β”€ DESCRIPTION              # R package metadata
└── README.md                # R documentation

Root files:
β”œβ”€β”€ paper.md                 # JOSS paper
β”œβ”€β”€ paper.bib                # References
β”œβ”€β”€ CONTRIBUTING.md          # Contribution guidelines
β”œβ”€β”€ CODE_OF_CONDUCT.md       # Code of conduct
β”œβ”€β”€ LICENSE                  # MIT License
└── README.md                # This file

Development

Running Tests

# Python: install in development mode, then run the tests from the repository root
pip install -e "Python[experiment]" pytest
pytest test_*.py -v

# R: install the package, then run its testthat suite
R CMD INSTALL R
Rscript -e 'testthat::test_dir("R/tests/testthat", package = "seedhash", load_package = "installed")'

Building the Package

# Install build tools
pip install build

# Build the package
python -m build

# This creates dist/seedhash-0.1.0.tar.gz and dist/seedhash-0.1.0-whl

Publishing to PyPI

# Install twine
pip install twine

# Upload to PyPI
twine upload dist/*

Contributing

We welcome contributions from the community! Please see our Contributing Guidelines for details on:

  • Reporting bugs and suggesting enhancements
  • Development setup for Python and R
  • Coding standards and testing requirements
  • Pull request process

Please also read our Code of Conduct before contributing.

Quick Start for Contributors

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes following our coding standards
  4. Add tests for new functionality
  5. Ensure all tests pass
  6. Commit your changes (git commit -m 'Add some amazing feature')
  7. Push to the branch (git push origin feature/amazing-feature)
  8. Open a Pull Request

For questions, please open an issue on GitHub.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Author

Ziyuan Huang

Citation

If you use SeedHash in your research or project, please consider citing it:

BibTeX

@software{huang2025seedhash,
  author    = {Ziyuan Huang},
  title     = {{SeedHash}: {MD5}-Based Deterministic Random Seed Generator},
  year      = {2025},
  month     = oct,
  publisher = {Zenodo},
  version   = {0.1.0},
  doi       = {10.5281/zenodo.17495331},
  url       = {https://github.com/melhzy/seedhash}
}

APA Style

Huang, Z. (2025). SeedHash: MD5-based deterministic random seed generator 
(Version 0.1.0) [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.17495331

Chicago Style

Huang, Ziyuan. 2025. "SeedHash: MD5-Based Deterministic Random Seed Generator." 
Version 0.1.0. Zenodo. https://doi.org/10.5281/zenodo.17495331.

Changelog

v0.1.0 (2025-10-29)

  • Initial release
  • Core SeedHashGenerator class
  • MD5-based seed generation
  • Configurable random number ranges
  • Comprehensive error handling
  • Full documentation and examples

Acknowledgments

  • Inspired by the need for reproducible random number generation in scientific computing
  • Built with Python's standard library for maximum compatibility

Reference


Note: This library uses MD5 hashing for seed generation. MD5 is suitable for non-cryptographic purposes like seed generation. Do not use this library for cryptographic or security-sensitive applications.

About

Part of the ADAM Project

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages