dsf-logic-sdk 1.0.3
SDK for DSF Logic API - Conditional Logic Evaluation
Requires Python: >=3.7
Keywords: dsf logic conditional evaluation api sdk

# Adaptive Formula SDK

A cognitive programming framework that replaces complex conditional logic with intelligent, adaptive scoring systems.

## Why Adaptive Formula?

Traditional code filled with nested `if/else` statements becomes unmaintainable as business rules grow. This SDK transforms your decision logic into a **configurable scoring system** that learns and adapts over time, making your code more readable, testable, and scalable.

---

## Working with Real Datasets

### Example: Credit Risk Dataset
```python
import pandas as pd
from adaptive_formula import CognitiveSDK, Field

# Load your data
df = pd.read_csv('credit_data.csv')

# Initialize SDK
sdk = CognitiveSDK()  # or tier='professional' with license

# Configure based on domain knowledge
sdk.configure([
    # High importance for income vs loan ratio
    Field(name='person_income', reference=df['person_income'].median(), 
          importance=3.0, sensitivity=2.5),

    # Critical flag for previous defaults
    Field(name='cb_person_default_on_file', reference=False, 
          importance=5.0, sensitivity=5.0),

    # Moderate importance for employment length
    Field(name='person_emp_length', reference=5.0, 
          importance=2.0, sensitivity=2.0),
])

# Evaluate each application
for idx, row in df.iterrows():
    score = sdk.evaluate(row.to_dict())
    decision = 'Approved' if score > sdk.get_confidence_level() else 'Denied'
    print(f"Application {idx}: {score:.3f} - {decision}")

# Professional tier: Check adapted threshold
if hasattr(sdk, 'get_metrics'):
    metrics = sdk.get_metrics()
    print(f"Optimized confidence level: {metrics['current_confidence_level']:.3f}")
```

### Tips for Production

1. **Reference Values**: Use median/mode from your "good" historical cases
2. **Testing**: Validate with known outcomes before production
3. **Monitoring**: Track score distributions to identify drift
4. **Categorical Encoding**: Convert ordered categories to numbers
5. **Missing Data**: Handle before evaluation (SDK treats None as 0.0 similarity)

---

## Core Benefits

* **🧠 Declarative Configuration:** Define business rules as prioritized fields instead of procedural code
* **⚡ High Performance:** Core engine compiled to C++ using Cython for production-grade speed
* **📊 Adaptive Learning:** Professional and Enterprise tiers automatically adjust decision confidence based on patterns
* **🎯 Nuanced Decisions:** Generate confidence scores (0.0-1.0) instead of binary pass/fail outcomes
* **🔧 Flexible Data Handling:** Support for dictionaries, DataFrames, and NumPy arrays (Premium tiers)

---

## Installation

```bash
pip install dsf-logic-sdk
```

---

## Quick Start

### Community Edition (Free)

```python
from adaptive_formula import CognitiveSDK, Field

# Initialize SDK
sdk = CognitiveSDK()

# Configure validation rules
sdk.configure([
    Field(name='has_verified_email', reference=True, importance=3.0, sensitivity=5.0),
    Field(name='profile_completeness', reference=0.85, importance=2.0, sensitivity=3.0),
    Field(name='country', reference='CO', importance=1.0, sensitivity=1.5),
])

# Evaluate data
user_data = {
    'has_verified_email': True,
    'profile_completeness': 0.85,
    'country': 'CO'
}

score = sdk.evaluate(user_data)
print(f"Validation score: {score:.3f}")

if score > sdk.get_confidence_level():
    print("✅ Approved")
else:
    print("⚠️ Requires review")
```

### Professional Edition

```python
from adaptive_formula import CognitiveSDK, Field

# Initialize with license key
sdk = CognitiveSDK(tier='professional', license_key='PRO-2026-12-31-XXXX-XXXX')

# Configure evaluation rules
sdk.configure([
    Field(name='amount', reference=100.0, importance=3.0, sensitivity=3.5),
    Field(name='location', reference='home', importance=2.0, sensitivity=3.0),
    Field(name='device', reference='known', importance=3.0, sensitivity=4.0),
])

# Professional tier: Process DataFrame rows directly
for idx, row in df.iterrows():
    score = sdk.evaluate(row)  # Accepts Series directly

# Access performance metrics
metrics = sdk.get_metrics()
print(f"Avg score: {metrics['avg_score']:.3f}")
print(f"Adapted confidence: {metrics['current_confidence_level']:.3f}")
```

### Enterprise Edition

```python
from adaptive_formula import CognitiveSDK, Field

# Initialize with enterprise license
sdk = CognitiveSDK(tier='enterprise', license_key='ENT-2026-12-31-XXXX-XXXX')

sdk.configure([
    Field(name='risk_score', reference=30, importance=4.0, sensitivity=3.5),
    Field(name='transaction_volume', reference=5000, importance=3.5, sensitivity=3.0),
    Field(name='account_age', reference=365, importance=2.0, sensitivity=2.0),
])

# Enterprise exclusive: Adjust weight calibration
sdk.set_adjustment_factor(0.4)  # 60% expert weights, 40% algorithm-optimized

# Process evaluations - weights adapt automatically
for transaction in transactions:
    score = sdk.evaluate(transaction)

# Access enhanced metrics with weight evolution
metrics = sdk.get_metrics()
if 'weight_changes' in metrics:
    print("Weight adaptations:")
    for field, change in metrics['weight_changes'].items():
        print(f"  {field}: {change:+.2%} from initial")
```

---

## Hybrid Model Integration

The SDK accepts **any predictive model** as an additional decision factor, creating powerful ensemble systems that combine expert business rules, ML models, statistical analysis, and external data sources.

### ML Model Integration

```python
import joblib
from sklearn.ensemble import RandomForestClassifier
import numpy as np

# Load pre-trained models
credit_model = joblib.load('credit_risk_model.pkl')
behavior_model = joblib.load('user_behavior_classifier.pkl')

# Define hybrid decision factors combining rules + ML models
decision_fields = [
    # Traditional business rules
    Field(name='debt_to_income_ratio', reference=0.3, importance=4.0, sensitivity=3.0),
    Field(name='employment_years', reference=3, importance=3.0, sensitivity=2.0),

    # ML models as decision factors
    Field(name='ml_credit_score', reference=0.8, importance=4.5, sensitivity=3.5),
    Field(name='behavior_risk_score', reference=0.2, importance=3.5, sensitivity=4.0)
]

# Replace complex if/else logic with hybrid scoring
def evaluate_loan_application(applicant_data):
    # Get ML model predictions
    credit_features = [applicant_data['income'], applicant_data['age'], 
                      applicant_data['credit_history_length']]
    ml_credit_prob = credit_model.predict_proba([credit_features])[0][1]

    behavior_features = extract_behavior_features(applicant_data)
    behavior_risk = behavior_model.predict_proba([behavior_features])[0][1]

    # Combine with traditional business rules
    hybrid_data = {
        'debt_to_income_ratio': applicant_data['debt'] / applicant_data['income'],
        'employment_years': applicant_data['employment_years'],
        'ml_credit_score': ml_credit_prob,
        'behavior_risk_score': behavior_risk
    }

    return sdk.evaluate(hybrid_data)

# Before: Complex nested conditions
# if applicant['income'] > 50000:
#     if applicant['debt_ratio'] < 0.4:
#         if credit_model.predict([features])[0] == 1:
#             if behavior_score < 0.3:
#                 return 'approved'
# return 'denied'

# After: Clean, configurable scoring
score = evaluate_loan_application(applicant)
decision = 'approved' if score > 0.75 else 'denied'
```

### External APIs and Statistical Models Integration

```python
import requests
from scipy import stats
import pandas as pd

# External services and statistical models as decision factors
enterprise_fields = [
    # Core business rules
    Field(name='transaction_amount', reference=1000, importance=3.0, sensitivity=2.5),
    Field(name='customer_tier', reference='gold', importance=2.5, sensitivity=2.0),

    # External API services
    Field(name='fraud_api_score', reference=0.1, importance=4.0, sensitivity=4.0),
    Field(name='identity_verification_score', reference=0.9, importance=4.5, sensitivity=3.5),

    # Statistical analysis
    Field(name='spending_pattern_zscore', reference=0.0, importance=3.0, sensitivity=2.0)
]

def advanced_transaction_approval(transaction, user_history):
    # Call external fraud detection API
    fraud_response = requests.post('https://fraud-api.com/check', 
                                  json={'amount': transaction['amount'], 
                                       'merchant': transaction['merchant']})
    fraud_score = fraud_response.json().get('risk_score', 0.5)

    # Identity verification service
    id_response = requests.get(f"https://identity-api.com/verify/{transaction['user_id']}")
    identity_score = id_response.json().get('confidence', 0.0)

    # Statistical analysis of spending patterns
    amounts = [t['amount'] for t in user_history]
    if len(amounts) > 5:
        z_score = stats.zscore([transaction['amount']] + amounts)[0]
        normalized_z = np.tanh(z_score / 2)  # Normalize to -1 to 1 range
    else:
        normalized_z = 0.0

    # Replace complex conditional logic with scoring
    hybrid_data = {
        'transaction_amount': transaction['amount'],
        'customer_tier': transaction['user_tier'],
        'fraud_api_score': fraud_score,
        'identity_verification_score': identity_score,
        'spending_pattern_zscore': normalized_z
    }

    return sdk.evaluate(hybrid_data)

# Before: Unmaintainable nested conditions
# if transaction['amount'] > 10000:
#     fraud_check = call_fraud_api(transaction)
#     if fraud_check['risk'] > 0.3:
#         if user['tier'] != 'platinum':
#             if spending_anomaly_detected(user, transaction):
#                 return block_transaction()
# ... dozens more conditions

# After: Clean, maintainable scoring system
approval_score = advanced_transaction_approval(transaction, user_history)
action = 'approve' if approval_score > 0.7 else 'review' if approval_score > 0.4 else 'block'
```

### Benefits of Hybrid Decision Systems

- **Eliminate complex if/else chains**: Replace procedural logic with declarative configuration
- **Combine multiple intelligence sources**: Expert rules + ML + APIs + statistics in one system
- **Configurable decision weights**: Adjust how much each factor influences the final decision
- **Transparent scoring**: Every decision factor's contribution is visible and auditable
- **Gradual model adoption**: Start with rules, add ML models incrementally
- **Resilient to failures**: If external services fail, other factors compensate automatically

---

## Supported Data Types

### Community Edition
- `dict` with field names

### Professional/Enterprise Edition
Extended support for heterogeneous data:

| Data Type               | Supported |             Reason               |
|-------------------------|-----------|----------------------------------|
| dict                    |     ✅    | Has field names                  |
| pandas DataFrame        |     ✅    | Preserves column names           |
| pandas Series           |     ✅    | Maintains index as names         |
| Objects with attributes |     ✅    | Attributes = field names         |
| numpy arrays            |     ❌    | Arrays don't contain field names |
| lists/tuples            |     ❌    | No field-value mapping           |

**Note**: Arrays/lists are positional structures without field metadata. For Field-based evaluation, use named structures (dict, DataFrame).

```python
# ✅ Correct - has names
data = {'credit_score': 700, 'income': 50000}

# ❌ Incorrect - only values without context
data = [700, 50000]  # Which field is which?
```

---

## API Reference

### CognitiveSDK

Main interface for the Adaptive Formula SDK.

**Methods:**
- `__init__(tier='community', license_key=None)` - Initialize SDK
- `configure(fields)` - Set up evaluation rules
- `evaluate(data)` - Score data against rules (returns 0.0-1.0)
- `get_confidence_level()` - Get current decision confidence level
- `set_confidence_level(value)` - Manually adjust confidence level
- `get_metrics()` - Performance statistics (Professional/Enterprise)
- `set_adjustment_factor(value)` - Set weight calibration factor (Enterprise only)

### Field

Configuration for individual evaluation criteria.

**Parameters:**
- `name` (str): Field identifier
- `reference` (Any): Baseline value for comparison
- `importance` (float): Priority factor (default: 1.0)
- `sensitivity` (float): Strictness factor (default: 1.5)

---

## How It Works

The SDK evaluates your data by comparing each field against its configured reference value. Each field's contribution is adjusted by its **importance** (how much it matters) and **sensitivity** (how strictly it's evaluated). 

The result is a confidence score between 0.0 and 1.0 that represents how well your data aligns with the configured expectations.

### Data Type Behavior

| Data Type           | Comparison Method   | Example                  | Score Impact         |
|---------------------|---------------------|--------------------------|----------------------|
| **Numeric**         | Relative difference | `amount=95` vs ref `100` | ~0.95 (very similar) |
| **String/Category** | Exact match only    | `'rent'` vs ref `'own'`  | 0.3 (different)      |
| **Boolean**         | Binary comparison   | `True` vs ref `False`    | 0.0 (opposite)       |
| **Missing/None**    | Penalized           | `None` vs any ref        | 0.0 (missing)        |

### Calibration Guide

Start with these baseline values and adjust based on your results:

| Importance | Meaning      | Use Case                |
|------------|--------------|-------------------------|
| 1.0 - 2.0  | Nice to have | Secondary indicators    |
| 2.0 - 3.0  | Moderate     | Standard business rules |
| 3.0 - 4.0  | Important    | Key decision factors    |
| 4.0 - 5.0  | Critical     | Must-have requirements  |

| Sensitivity | Meaning     | Use Case                    |
|-------------|-------------|-----------------------------|
| 1.0 - 2.0   | Flexible    | Allow variations            |
| 2.0 - 3.0   | Moderate    | Standard strictness         |
| 3.0 - 4.0   | Strict      | Low tolerance for deviation |
| 4.0 - 5.0   | Very Strict | Near-exact match required   |

**Tip:** Start with (importance=2.0, sensitivity=2.0) for all fields, then adjust based on business requirements.

### Adaptive Learning Details

- **Professional**: Adjusts confidence threshold based on score distributions
- **Enterprise**: Additionally optimizes individual field weights using magnitude-based calibration

---

## Tier Comparison

| Feature                 |  Community |      Professional       |       Enterprise        |
|-------------------------|------------|-------------------------|-------------------------|
| **Evaluations/month**   | Unlimited* |      Unlimited          |       Unlimited         |
| **Data formats**        | Dict only  | Dict, DataFrame, Series | Dict, DataFrame, Series |
| **Adaptive threshold**  |    ❌      |          ✅            |          ✅             |
| **Weight optimization** |    ❌      |          ❌            |          ✅             |
| **Performance metrics** |    ❌      |          ✅            |          ✅    Enhanced |
| **Adjustment factor**   |    ❌      |          ❌            |          ✅             |
| **Support**             |  Community |         Email           |     Priority SLA         |
| **License validity**    |    N/A     |        Annual           |        Annual            |

*Community tier is free for evaluation. Production use requires registration.

---

## Enterprise Features

### Weight Calibration (Enterprise Exclusive)
Enterprise tier automatically calibrates field weights based on data patterns:

```python
# Control the balance between expert and algorithm weights
sdk.set_adjustment_factor(0.3)  # Default: 70% expert, 30% algorithm

# Factor range:
# 0.0 = 100% expert weights (trust configuration)
# 0.5 = 50/50 mix
# 1.0 = 100% algorithm weights (full automation)
```

The algorithm tracks field magnitudes and uses sqrt dampening to prevent extreme values from dominating, then mixes expert and proposed weights according to your adjustment factor.

---

## Use Cases

### Credit Risk Assessment
```python
sdk.configure([
    # Numeric fields - gradual similarity
    Field(name='person_income', reference=50000, importance=4.0, sensitivity=3.0),
    Field(name='loan_percent_income', reference=0.2, importance=5.0, sensitivity=4.0),

    # Categorical fields - exact match scoring
    Field(name='person_home_ownership', reference='own', importance=3.0, sensitivity=2.0),
    Field(name='loan_intent', reference='personal', importance=2.0, sensitivity=2.0),

    # Boolean fields - binary scoring
    Field(name='cb_person_default_on_file', reference=False, importance=5.0, sensitivity=5.0),
])

# Note: For categorical variables with natural ordering (e.g., 'own'>'mortgage'>'rent'),
# consider numeric encoding: own=3, mortgage=2, rent=1
```

### Fraud Detection
```python
sdk.configure([
    Field(name='transaction_amount', reference=100, importance=3.0, sensitivity=3.5),
    Field(name='merchant_location', reference='domestic', importance=2.0, sensitivity=3.0),
    Field(name='time_since_last', reference=3600, importance=2.5, sensitivity=2.0),
])
```

### User Verification
```python
sdk.configure([
    Field(name='email_verified', reference=True, importance=5.0, sensitivity=5.0),
    Field(name='phone_verified', reference=True, importance=4.0, sensitivity=4.0),
    Field(name='documents_uploaded', reference=True, importance=3.0, sensitivity=3.5),
])
```

### Lead Scoring
```python
sdk.configure([
    Field(name='engagement_score', reference=0.5, importance=3.0, sensitivity=2.0),
    Field(name='company_size', reference='medium', importance=2.0, sensitivity=1.5),
    Field(name='budget_range', reference=50000, importance=4.0, sensitivity=3.0),
])
```

---

## Professional & Enterprise Licensing

Professional and Enterprise tiers include:
- Adaptive confidence learning from evaluation patterns
- Real-time performance metrics and insights
- Support for complex data structures
- Production-ready optimization algorithms
- Enterprise: Automatic weight calibration

**To purchase a license:**
- Professional: $299/month or $2,999/year
- Enterprise: Contact for custom pricing
- Email: jaimeajl@hotmail.com

**License format:**
- Professional: `PRO-YYYY-MM-DD-XXXX-XXXX`
- Enterprise: `ENT-YYYY-MM-DD-XXXX-XXXX`

---

## Migration from If/Else

**Before:**
```python
def validate_user(user):
    if not user.get('email_verified'):
        return False
    if user.get('risk_score', 0) > 80:
        return False
    if user.get('country') in ['XX', 'YY']:
        return False
    # ... dozens more conditions
    return True
```

**After:**
```python
sdk = CognitiveSDK()
sdk.configure([
    Field(name='email_verified', reference=True, importance=5.0, sensitivity=5.0),
    Field(name='risk_score', reference=0, importance=3.0, sensitivity=4.0),
    Field(name='country', reference='US', importance=2.0, sensitivity=2.0),
])

score = sdk.evaluate(user)
return score > sdk.get_confidence_level()
```

---

## Frequently Asked Questions

### How do I handle categorical variables with multiple values?
Categorical variables use exact match scoring (1.0 for match, 0.3 for mismatch). For ordered categories (e.g., credit ratings A>B>C), convert to numeric values for gradual similarity.

### Can I train the model with historical labeled data?
The SDK uses unsupervised adaptive learning. It optimizes based on score distributions, not labeled outcomes. For supervised learning, use the scores as features in your ML pipeline.

### How do I determine initial importance and sensitivity values?
Start with baseline (2.0, 2.0) for all fields. Increase importance for business-critical fields. Increase sensitivity when exact matches are required. Test with known cases and adjust.

### What's the difference between importance and sensitivity?
- **Importance**: How much a field contributes to the final score (weight)
- **Sensitivity**: How strictly differences are penalized (tolerance)

### Can I use this with pandas DataFrames?
Professional and Enterprise tiers support DataFrames and Series directly:
```python
# Process entire DataFrame row-by-row
for idx, row in df.iterrows():
    score = sdk.evaluate(row)  # Series handled automatically

# Or individual rows
score = sdk.evaluate(df.iloc[0])  # Single row as Series
```

### How does the adaptive learning work?
- **Professional/Enterprise**: Automatically adjust the confidence threshold based on score distributions after 10+ evaluations
- **Enterprise only**: Additionally optimizes individual field weights based on data magnitudes and patterns

---

## Support

- **Documentation:** https://docs.adaptiveformula.ai
- **Community:** https://github.com/adaptiveformula/sdk/discussions
- **Issues:** https://github.com/adaptiveformula/sdk/issues
- **Professional/Enterprise Support:** jaimeajl@hotmail.com

---

## License

MIT License for Community Edition. Professional and Enterprise editions are subject to commercial licensing terms.

© 2025 Adaptive Formula. Cognitive Programming is a trademark of Adaptive Formula, Inc.