Documentation

Docs/API Deployment

ExoBengal API - Cerebrium Deployment

A production-ready machine learning API for exoplanet detection deployed on Cerebrium cloud platform.

🚀 Live API Endpoint

https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api/

✅ Live and operational

Overview

ExoBengal API provides serverless ML inference with automatic scaling, making it easy to serve exoplanet detection models to users worldwide.

Features

  • Multiple ML Models: Random Forest, Decision Tree, KNN, and CNN
  • Earth Similarity Index: Automatic ESI calculation for planet predictions
  • Auto-scaling: Scales from 0-3 replicas based on demand
  • Fast Response: 10-second cooldown for quick scaling
  • Error Resilience: Continues with other models if one fails
  • Model Selection: Choose specific models or run all

Available Models

ModelTypeDescription
random_forestEnsemble LearningRandom Forest Classifier for robust predictions
decision_treeTree-based LearningDecision Tree for interpretable results
knnInstance-based LearningKNN with ESI calculation
cnnDeep LearningCNN for complex pattern recognition

API Endpoints

Base URL

https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api/
EndpointMethodDescription
/predictPOSTMain prediction endpoint
/health_checkPOSTHealth status check
/get_model_infoPOSTGet model information
/initPOSTInitialize models manually

Usage Examples

1. Health Check

curl -X POST "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api/health_check" \
  -H "Content-Type: application/json" \
  -d '{}'

2. Get Model Information

curl -X POST "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api/get_model_info" \
  -H "Content-Type: application/json" \
  -d '{}'

3. Predict with All Models

curl -X POST "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "period": 365.0,
    "prad": 1.0,
    "teq": 288.0,
    "srad": 1.0,
    "slog_g": 4.44,
    "steff": 5778.0,
    "impact": 0.1,
    "duration": 5.0,
    "depth": 100.0
  }'

4. Predict with Specific Models

curl -X POST "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api/predict" \
  -H "Content-Type: application/json" \
  -d '{
    "period": 365.0,
    "prad": 1.0,
    "teq": 288.0,
    "srad": 1.0,
    "slog_g": 4.44,
    "steff": 5778.0,
    "impact": 0.1,
    "duration": 5.0,
    "depth": 100.0,
    "models": ["random_forest", "cnn"]
  }'

5. Python Request Examples

import requests
import json

# API Configuration
BASE_URL = "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api"
HEADERS = {"Content-Type": "application/json"}

def check_health():
    """Check API health status"""
    response = requests.post(f"{BASE_URL}/health_check", headers=HEADERS, json={})
    return response.json()

def get_model_info():
    """Get information about available models"""
    response = requests.post(f"{BASE_URL}/get_model_info", headers=HEADERS, json={})
    return response.json()

def predict_all_models(planet_data):
    """Make prediction with all models"""
    response = requests.post(f"{BASE_URL}/predict", headers=HEADERS, json=planet_data)
    return response.json()

def predict_specific_models(planet_data, models):
    """Make prediction with specific models"""
    planet_data["models"] = models
    response = requests.post(f"{BASE_URL}/predict", headers=HEADERS, json=planet_data)
    return response.json()

# Example usage
if __name__ == "__main__":
    # Earth-like planet data
    earth_data = {
        "period": 365.0,
        "prad": 1.0,
        "teq": 288.0,
        "srad": 1.0,
        "slog_g": 4.44,
        "steff": 5778.0,
        "impact": 0.1,
        "duration": 5.0,
        "depth": 100.0
    }
    
    # Check health
    health = check_health()
    print("Health:", health)
    
    # Get model info
    models = get_model_info()
    print("Models:", models)
    
    # Predict with all models
    result = predict_all_models(earth_data)
    print("All models prediction:", result)
    
    # Predict with specific models
    specific_result = predict_specific_models(earth_data, ["random_forest", "cnn"])
    print("Specific models prediction:", specific_result)

6. JavaScript Request Examples

// API Configuration
const BASE_URL = "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api";
const HEADERS = {"Content-Type": "application/json"};

async function checkHealth() {
    const response = await fetch(`${BASE_URL}/health_check`, {
        method: 'POST',
        headers: HEADERS,
        body: JSON.stringify({})
    });
    return await response.json();
}

async function getModelInfo() {
    const response = await fetch(`${BASE_URL}/get_model_info`, {
        method: 'POST',
        headers: HEADERS,
        body: JSON.stringify({})
    });
    return await response.json();
}

async function predictAllModels(planetData) {
    const response = await fetch(`${BASE_URL}/predict`, {
        method: 'POST',
        headers: HEADERS,
        body: JSON.stringify(planetData)
    });
    return await response.json();
}

async function predictSpecificModels(planetData, models) {
    const data = {...planetData, models};
    const response = await fetch(`${BASE_URL}/predict`, {
        method: 'POST',
        headers: HEADERS,
        body: JSON.stringify(data)
    });
    return await response.json();
}

async function runExamples() {
    // Earth-like planet data
    const earthData = {
        period: 365.0,
        prad: 1.0,
        teq: 288.0,
        srad: 1.0,
        slog_g: 4.44,
        steff: 5778.0,
        impact: 0.1,
        duration: 5.0,
        depth: 100.0
    };
    
    try {
        // Check health
        const health = await checkHealth();
        console.log("Health:", health);
        
        // Get model info
        const models = await getModelInfo();
        console.log("Models:", models);
        
        // Predict with all models
        const result = await predictAllModels(earthData);
        console.log("All models prediction:", result);
        
        // Predict with specific models
        const specificResult = await predictSpecificModels(earthData, ["random_forest", "cnn"]);
        console.log("Specific models prediction:", specificResult);
        
    } catch (error) {
        console.error("Error:", error);
    }
}

// Run examples
runExamples();

// Export for Node.js modules
if (typeof module !== 'undefined' && module.exports) {
    module.exports = {
        checkHealth,
        getModelInfo,
        predictAllModels,
        predictSpecificModels
    };
}

Hot Jupiter Detection Example

Hot Jupiters are gas giant planets that orbit very close to their host stars, typically with orbital periods of 1-10 days and high equilibrium temperatures. Here's how to detect them using the ExoBengal API:

Python Example

import requests
import json

# API Configuration
BASE_URL = "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api"
HEADERS = {"Content-Type": "application/json"}

def detect_hot_jupiter():
    """Detect a Hot Jupiter using typical parameters"""
    # Hot Jupiter characteristics:
    # - Short orbital period (1-10 days)
    # - Large radius (8-15 Earth radii)
    # - High equilibrium temperature (1000-2000K)
    # - Close to star (small stellar radius)
    
    hot_jupiter_data = {
        "period": 3.5,        # 3.5 days orbital period
        "prad": 11.0,         # 11 Earth radii (Jupiter-like)
        "teq": 1500.0,        # 1500K equilibrium temperature
        "srad": 1.2,          # Stellar radius
        "slog_g": 4.5,         # Stellar surface gravity
        "steff": 6000,        # Stellar temperature
        "impact": 0.3,        # Impact parameter
        "duration": 2.5,      # Transit duration (hours)
        "depth": 5000.0       # Deep transit (ppm)
    }
    
    response = requests.post(f"{BASE_URL}/predict", headers=HEADERS, json=hot_jupiter_data)
    result = response.json()
    
    print("Hot Jupiter Detection Results:")
    print(f"Status: {result.get('status', 'unknown')}")
    
    if 'result' in result:
        for model, prediction in result['result'].items():
            if model != 'ESI':
                print(f"{model}: {'Exoplanet' if prediction['prediction'] == 1 else 'Not Exoplanet'} (confidence: {prediction['probability']:.2%})")
        
        if 'ESI' in result['result']:
            print(f"Earth Similarity Index: {result['result']['ESI']:.3f}")
    
    return result

# Run the detection
if __name__ == "__main__":
    result = detect_hot_jupiter()

JavaScript Example

// Hot Jupiter Detection with JavaScript
const BASE_URL = "https://api.aws.us-east-1.cerebrium.ai/v4/p-e08fc93f/exobengal-api";

async function detectHotJupiter() {
    // Hot Jupiter characteristics
    const hotJupiterData = {
        period: 3.5,        // 3.5 days orbital period
        prad: 11.0,         // 11 Earth radii (Jupiter-like)
        teq: 1500.0,        // 1500K equilibrium temperature
        srad: 1.2,          // Stellar radius
        slog_g: 4.5,        // Stellar surface gravity
        steff: 6000,        // Stellar temperature
        impact: 0.3,        // Impact parameter
        duration: 2.5,      // Transit duration (hours)
        depth: 5000.0       // Deep transit (ppm)
    };
    
    try {
        const response = await fetch(`${BASE_URL}/predict`, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(hotJupiterData)
        });
        
        const result = await response.json();
        
        console.log("Hot Jupiter Detection Results:");
        console.log(`Status: ${result.status || 'unknown'}`);
        
        if (result.result) {
            Object.entries(result.result).forEach(([model, prediction]) => {
                if (model !== 'ESI') {
                    const classification = prediction.prediction === 1 ? 'Exoplanet' : 'Not Exoplanet';
                    console.log(`${model}: ${classification} (confidence: ${(prediction.probability * 100).toFixed(2)}%)`);
                }
            });
            
            if (result.result.ESI) {
                console.log(`Earth Similarity Index: ${result.result.ESI.toFixed(3)}`);
            }
        }
        
        return result;
        
    } catch (error) {
        console.error("Error detecting Hot Jupiter:", error);
        throw error;
    }
}

// Run the detection
detectHotJupiter()
    .then(result => console.log("Detection completed:", result))
    .catch(error => console.error("Detection failed:", error));

Understanding Hot Jupiter Parameters

ParameterHot Jupiter ValueExplanation
period1-10 daysVery short orbital period due to proximity to star
prad8-15 Earth radiiGas giant size, similar to Jupiter
teq1000-2000KHigh temperature from stellar proximity
depth1000-10000 ppmDeep transit due to large planet size
duration1-5 hoursShort transit duration due to fast orbit

🌡️ Hot Jupiter Characteristics

  • • Orbital periods typically 1-10 days (vs. Earth's 365 days)
  • • Equilibrium temperatures often exceed 1000K due to stellar proximity
  • • Gas giant composition with radii 8-15 times Earth's radius
  • • Deep transit signals (1000-10000 ppm) due to large size
  • • Short transit durations due to high orbital velocity

Input Parameters

ParameterTypeRequiredDescriptionExample
periodfloatRequiredOrbital period (days)365.0
pradfloatRequiredPlanet radius (Earth radii)1.0
teqfloatRequiredEquilibrium temperature (Kelvin)288.0
sradfloatRequiredStellar radius (solar radii)1.0
slog_gfloatRequiredStellar surface gravity (log scale)4.44
stefffloatRequiredStellar effective temperature (Kelvin)5778.0
impactfloatRequiredImpact parameter0.1
durationfloatRequiredTransit duration (hours)5.0
depthfloatRequiredTransit depth (ppm)100.0
modelsarrayOptionalSpecific models to run["random_forest", "cnn"]

Available Model Options: 'random_forest', 'decision_tree', 'knn', 'cnn'

Response Format

Successful Prediction Response

{
  "run_id": "abc123-def456-ghi789",
  "result": {
    "random_forest": {
      "prediction": 1,
      "probability": 0.95
    },
    "decision_tree": {
      "prediction": 1,
      "probability": 0.88
    },
    "knn": {
      "prediction": 1,
      "probability": 0.92
    },
    "cnn": {
      "prediction": 1,
      "probability": 0.89
    },
    "ESI": 0.987
  },
  "input_data": {
    "period": 365.0,
    "prad": 1.0,
    "teq": 288.0,
    "srad": 1.0,
    "slog_g": 4.44,
    "steff": 5778.0,
    "impact": 0.1,
    "duration": 5.0,
    "depth": 100.0
  },
  "models_executed": ["random_forest", "decision_tree", "knn", "cnn"],
  "status": "success",
  "run_time_ms": 245
}

ESI Calculation

The Earth Similarity Index (ESI) provides a measure of how Earth-like an exoplanet is:

  • Range: 0.0 to 1.0
  • 1.0: Perfect Earth-like conditions
  • 0.0: Completely unlike Earth
  • Formula: Based on planet radius and equilibrium temperature

Error Handling

Missing Parameters Error

{
  "error": "Missing required parameters",
  "details": "The following parameters are required: period, prad, teq, srad, slog_g, steff, impact, duration, depth",
  "status": "error"
}

Invalid Model Error

{
  "error": "Invalid model specified",
  "details": "Model 'invalid_model' not found. Available models: random_forest, decision_tree, knn, cnn",
  "status": "error"
}

Model Execution Error

{
  "error": "Model execution failed",
  "details": "Random Forest model failed to execute: Model file not found",
  "status": "error",
  "failed_models": ["random_forest"]
}

Initialization Error

{
  "error": "Model initialization failed",
  "details": "Unable to load model files from storage",
  "status": "error"
}

Deployment Configuration

Hardware Specifications

  • CPU: 2.0 cores
  • Memory: 4.0 GB
  • Compute: CPU (AWS)
  • Python: 3.10
  • Base Image: python:3.10-bookworm

Auto-scaling Settings

  • Min Replicas: 0 (scales to zero when idle)
  • Max Replicas: 3
  • Cooldown: 10 seconds
  • Concurrency: 1 request per replica
  • Metric: Concurrency utilization

Model Files

  • Random Forest Classifier (.pkl)
  • Decision Tree Classifier (.pkl)
  • CNN Model (.h5)
  • KNN Model (.pkl)
  • Feature Scaler (.pkl)
  • Data Imputer (.pkl)

Performance

  • Cold Start: ~10-15 seconds (model loading)
  • Warm Response: ~100-500ms
  • Scaling: Automatic based on traffic
  • Availability: 99.9% uptime on Cerebrium
  • Throughput: Up to 3 concurrent requests (max replicas)

Common Issues

  • Missing Parameters: Ensure all required fields are included
  • Invalid Models: Check model names in the models array
  • Cold Start Delays: First request after idle period takes longer
  • Type Errors: Ensure numeric values are properly formatted

Use Cases

  • Exoplanet Research: Classify newly discovered celestial objects
  • Educational Tools: Demonstrate ML in astronomy
  • Space Missions: Quick assessment of potential targets
  • Comparative Analysis: Test different detection algorithms
  • Habitability Studies: Use ESI calculations for astrobiology

Additional Resources

🚀 Start exploring the universe with ExoBengal API!

Deployed with love on Cerebrium Cloud Platform

Interstellar
Background Music
30%