Skip to main content

earth-external-fitness

A Python SDK for connecting custom local or remote compute resources to Genetic Algorithm (GA) experiments on the Earth Platform.

This SDK abstracts the infrastructure of authentication, heartbeat management, and population polling, allowing you to focus strictly on implementing your fitness calculation logic.

Key Features

  • State-Aware Polling: Automatically adjusts polling frequency based on the experiment's lifecycle (Initializing -> Running -> Completed).
  • Asynchronous Heartbeats: Maintains the active status of your worker to prevent experiment abortion by the platform.
  • Queue-Based Distribution: Efficiently fetches individuals and distributes them for concurrent or parallel processing.
  • Production Ready: Built-in token authentication against the Earth API (/api/auth/login), with automatic use of the rotating refresh token so long-running workers stay signed in.
  • Graceful Termination: Automatically shuts down when the experiment reaches a terminal state (Completed, Aborted, Error, or Paused).

Installation

uv add earth-external-fitness
# OR
pip install earth-external-fitness

Basic Usage

The most common way to use the SDK is via an async loop.

import asyncio
from earth_external_fitness import EarthExternalFitnessSDK, EarthSDKSettings, FitnessCalculationResult

async def main():
    # 1. Configure settings directly
    settings = EarthSDKSettings(
        gateway_url="https://earth.evolution.inc/api/external-fitness",
        username="your_username",
        password="your_password"
    )
    
    async with EarthExternalFitnessSDK(settings) as sdk:
        # 2. If no experiment_id is provided, interactively pick one from active runs
        if not settings.experiment_id:
            await sdk.select_experiment()
        
        # 3. Start the background infrastructure (heartbeats and polling)
        await sdk.start()
        
        # 4. Iterate over tasks and submit results as they become available
        async for individual in sdk.tasks():
            print(f"Calculating fitness for individual {individual.individual_id}")
            
            # Implementation of your computation logic
            result = FitnessCalculationResult(score=42.0)
            
            await sdk.submit_result(individual.individual_id, result)

if __name__ == "__main__":
    asyncio.run(main())

Advanced Usage: Parallelism with ProcessPoolExecutor

For CPU-intensive fitness calculations, use a ProcessPoolExecutor to utilize multiple cores while the SDK handles communication in the main async event loop.

import asyncio
import concurrent.futures
from earth_external_fitness import EarthExternalFitnessSDK, EarthSDKSettings, FitnessCalculationResult

def heavy_fitness_calc(chromosome):
    """
    CPU-bound calculation running in a separate process.
    """
    # ... perform complex scientific compute ...
    return 10.5  # Return the score

async def main():
    settings = EarthSDKSettings(
        gateway_url="https://earth.evolution.inc/api/external-fitness",
        experiment_id="your-experiment-uuid"
    )
    
    # Initialize a Process Pool for parallel compute
    with concurrent.futures.ProcessPoolExecutor(max_workers=4) as pool:
        loop = asyncio.get_running_loop()
        
        async with EarthExternalFitnessSDK(settings) as sdk:
            await sdk.start()
            
            tasks = set()
            
            async for individual in sdk.tasks():
                # Schedule the CPU-bound task in the process pool
                fut = loop.run_in_executor(pool, heavy_fitness_calc, individual.chromosome)
                
                # Wrap the submission in an async task to keep the loop moving
                async def handle_and_submit(ind_id, calculation_future):
                    try:
                        score = await calculation_future
                        result = FitnessCalculationResult(score=score)
                        await sdk.submit_result(ind_id, result)
                    except Exception as e:
                        # Report local failure back to the platform
                        await sdk.submit_result(ind_id, error=str(e))

                t = asyncio.create_task(handle_and_submit(individual.individual_id, fut))
                tasks.add(t)
                t.add_done_callback(tasks.discard)

            # Ensure all final results are submitted before exiting
            if tasks:
                await asyncio.gather(*tasks)

if __name__ == "__main__":
    asyncio.run(main())

Configuration (Environment Variables)

Settings can be managed via environment variables prefixed with EARTH_:

Variable Description Default
EARTH_BASE_URL Base API URL https://earth.evolution.inc
EARTH_USERNAME Platform username None
EARTH_PASSWORD Platform password None
EARTH_TOTP_CODE TOTP code, only for accounts with time-based MFA None
EARTH_EXPERIMENT_ID Target Experiment UUID None
EARTH_HEARTBEAT_INTERVAL Seconds between pings 60
EARTH_TOKEN_REFRESH_MARGIN Seconds before expiry to refresh the token 60
EARTH_AUTH_RATE_LIMIT_PER_MINUTE Client-side cap on auth calls per minute (0 disables) 10
EARTH_AUTH_URL Login endpoint {base_url}/api/auth/login
EARTH_REFRESH_URL Token refresh endpoint {base_url}/api/auth/refresh

Authentication

The SDK signs in with POST /api/auth/login (JSON username / password, plus totp_code when the account has time-based MFA) and sends the returned access_token as Authorization: Bearer <token> on every platform call.

Shortly before the token expires it calls POST /api/auth/refresh. Refresh tokens are rotated, so the token returned there replaces the previous one; if a refresh is rejected the SDK falls back to a full login. Both endpoints are rate limited to roughly 10 requests per minute, so the SDK throttles its own auth calls, honours Retry-After on 429, and treats a 401 as terminal rather than retrying credentials that cannot succeed.

A 401 means either the username/password are wrong or the token has expired or been revoked; the SDK raises EarthAuthError in that case.

from earth_external_fitness import EarthAuthError

try:
    await client.start()
except EarthAuthError as e:
    print(f"Check EARTH_USERNAME / EARTH_PASSWORD: {e}")

Note on MFA: a TOTP code is valid for about 30 seconds, so EARTH_TOTP_CODE can only serve the initial login. Staying signed in afterwards relies on the refresh token.

Metadata

Release files for earth-external-fitness 0.0.7

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for earth-external-fitness 0.0.7
File Size Uploaded Provenance Actions
earth_external_fitness-0.0.7.tar.gz 28.7 kB Without provenance Details for earth_external_fitness-0.0.7.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for earth-external-fitness 0.0.7
File Interpreter ABI Platform Actions
earth_external_fitness-0.0.7-py3-none-any.whl Python 3 none any Details for earth_external_fitness-0.0.7-py3-none-any.whl

Total release size: 41.5 kB

Release files / earth_external_fitness-0.0.7.tar.gz

Download URL earth_external_fitness-0.0.7.tar.gz
Size 28.7 kB
Tags Source
SHA-256 checksum
How to use checksums
56a6f485f4676be992e10ba012403ac9875b571b00e428308cd10b2333262604
BLAKE2b-256 checksum
How to use checksums
e92ca474714faf312b691cb87fa51d9ac929dbdd7e69bccbcd792cac6b303291
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Release files / earth_external_fitness-0.0.7-py3-none-any.whl

Download URL earth_external_fitness-0.0.7-py3-none-any.whl
Size 12.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3b2ce456c34be106fb2d374fd906e03c3ffd645fc5bfc989f85f11023af96de1
BLAKE2b-256 checksum
How to use checksums
699ece6a7419bcb0692fce93cb5364e8ec2797795d40d29e435d582dad547f7a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.14

Security for earth-external-fitness 0.0.7

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page