Object.Hierarchy (object v0.1.2)

Hierarchical Object Composition and Decomposition for OORL framework.

Implements hierarchical planning and object aggregation/decomposition as specified in AAOS section 9. This module enables sophisticated multi-level organization of autonomous objects for complex problem solving.

Core Capabilities

  • Dynamic Composition: Combine multiple objects into higher-level aggregates
  • Strategic Decomposition: Break complex objects into manageable components
  • Hierarchical Planning: Multi-level planning from abstract to concrete
  • Emergent Behavior: Collective capabilities exceeding individual object abilities
  • Adaptive Organization: Dynamic restructuring based on performance feedback

Hierarchy Levels

Objects are organized in abstraction levels:

  • Level 0: Concrete objects with direct environment interaction
  • Level 1: Basic compositions of 2-3 objects
  • Level 2: Complex aggregates with specialized roles
  • Level N: Abstract organizational structures

Composition Strategies

Automatic Composition

  • Rule-based object combination
  • Compatibility scoring and optimization
  • Synergy detection and maximization

Guided Composition

  • Interactive composition with options
  • User-specified requirements and constraints
  • Performance-driven selection

Forced Composition

  • Override compatibility rules when needed
  • Emergency or experimental combinations
  • Rapid prototyping of new structures

Decomposition Strategies

Capability-Based

  • Separate by individual capabilities
  • Maintain functional coherence
  • Enable capability specialization

Functional Decomposition

  • Organize by functional requirements
  • Optimize for task efficiency
  • Support modular development

Resource-Based

  • Separate by resource usage patterns
  • Optimize resource allocation
  • Enable load balancing

Temporal Decomposition

  • Organize by temporal behavior phases
  • Enable pipeline processing
  • Support workflow optimization

Planning Capabilities

Hierarchical planning enables:

  • Multi-Scale Reasoning: Plan at appropriate abstraction levels
  • Efficient Search: Reduce complexity through abstraction
  • Robust Execution: Graceful degradation across levels
  • Adaptive Refinement: Dynamic plan adjustment during execution

Performance Benefits

  • Scalability: Handle systems with hundreds of objects
  • Efficiency: 10-100x faster planning through abstraction
  • Robustness: Fault tolerance through hierarchical redundancy
  • Maintainability: Modular structure enables easy modification

Example Usage

# Create hierarchy with root object
hierarchy = Object.Hierarchy.new("system_coordinator")

# Compose sensor-actuator system
{:ok, updated_hierarchy, composed_spec} = 
  Object.Hierarchy.compose_objects(hierarchy, 
    ["temp_sensor", "motor_actuator"], :automatic)

# Decompose complex AI agent
{:ok, hierarchy, components} = 
  Object.Hierarchy.decompose_object(hierarchy, 
    "complex_ai_agent", :capability_based)

# Perform hierarchical planning
{:ok, plan} = Object.Hierarchy.hierarchical_planning(
  hierarchy, goal, current_state)

Summary

Types

Abstraction level number (higher = more abstract)

Rule for automatically composing objects into higher-level structures.

Condition function for composition rules

Strategy for decomposing complex objects into simpler components.

Unique object identifier string

Specification for an object within the hierarchy.

Coordination protocol identifier

t()

Hierarchical structure containing all levels and organization rules.

Functions

Dynamically adapts the hierarchical structure based on performance.

Composes multiple objects into a higher-level aggregate object.

Manages coordination between objects at different hierarchy levels.

Decomposes a complex object into simpler component objects.

Evaluates the effectiveness of current hierarchical structure.

Performs hierarchical planning across abstraction levels.

Creates a new hierarchical structure with the given root object.

Types

abstraction_level()

@type abstraction_level() :: non_neg_integer()

Abstraction level number (higher = more abstract)

composition_rule()

@type composition_rule() :: %{
  pattern: [atom()],
  result_type: atom(),
  synergy_bonus: float(),
  conditions: [condition()]
}

Rule for automatically composing objects into higher-level structures.

Fields

  • pattern - List of object types that can be composed together
  • result_type - Type of the resulting composed object
  • synergy_bonus - Performance bonus from this composition (0.0-1.0)
  • conditions - Additional conditions that must be met for composition

Example

%{
  pattern: [:sensor, :actuator],
  result_type: :sensor_actuator_system,
  synergy_bonus: 0.3,
  conditions: [&compatible_interfaces?/1]
}

condition()

@type condition() :: ([object_spec()] -> boolean())

Condition function for composition rules

decomposition_strategy()

@type decomposition_strategy() :: %{
  target_type: atom(),
  components: [atom()],
  decomposition_cost: float(),
  success_probability: float()
}

Strategy for decomposing complex objects into simpler components.

Fields

  • target_type - Type of object this strategy can decompose
  • components - Types of components produced by decomposition
  • decomposition_cost - Computational cost of decomposition (0.0-1.0)
  • success_probability - Likelihood of successful decomposition (0.0-1.0)

Example

%{
  target_type: :complex_agent,
  components: [:reasoning_module, :action_module, :perception_module],
  decomposition_cost: 0.2,
  success_probability: 0.8
}

object_id()

@type object_id() :: String.t()

Unique object identifier string

object_spec()

@type object_spec() :: %{
  id: String.t(),
  type: atom(),
  capabilities: [atom()],
  dependencies: [String.t()],
  composition_weight: float()
}

Specification for an object within the hierarchy.

Fields

  • id - Unique object identifier
  • type - Object type/category for composition matching
  • capabilities - List of capabilities this object provides
  • dependencies - List of other objects this object depends on
  • composition_weight - Weight for composition optimization (0.0-1.0)

protocol()

@type protocol() :: :consensus | :delegation | :auction | :hierarchy | atom()

Coordination protocol identifier

t()

@type t() :: %Object.Hierarchy{
  abstraction_mappings: %{required(object_id()) => abstraction_level()},
  composition_rules: [composition_rule()],
  coordination_protocols: [protocol()],
  decomposition_strategies: [decomposition_strategy()],
  hierarchy_levels: %{required(integer()) => [object_spec()]},
  planning_horizon: integer(),
  root_object_id: String.t()
}

Hierarchical structure containing all levels and organization rules.

Fields

  • root_object_id - ID of the root object at the top of the hierarchy
  • hierarchy_levels - Map from level number to objects at that level
  • composition_rules - Rules for automatically combining objects
  • decomposition_strategies - Strategies for breaking down complex objects
  • abstraction_mappings - Map from object ID to its abstraction level
  • planning_horizon - Time horizon for hierarchical planning
  • coordination_protocols - Protocols for inter-level coordination

Level Organization

  • Higher numbers = more abstract levels
  • Level 0 = concrete objects
  • Root object typically at highest level

Functions

adapt_hierarchy(hierarchy, performance_feedback)

Dynamically adapts the hierarchical structure based on performance.

Analyzes performance feedback and automatically restructures or optimizes the hierarchy to improve overall system performance.

Parameters

  • hierarchy - Current hierarchy structure
  • performance_feedback - Performance metrics and observations

Returns

  • {:ok, adapted_hierarchy} - Successfully adapted hierarchy
  • {:error, {:adaptation_failed, reason}} - Adaptation failed

Adaptation Types

  • Restructuring: Major changes to hierarchy organization
  • Optimization: Fine-tuning of existing structure
  • No Change: Structure is already optimal

compose_objects(hierarchy, object_ids, composition_type \\ :automatic)

Composes multiple objects into a higher-level aggregate object.

Combines multiple objects into a single composite object using the specified composition strategy. The composition can be automatic (rule-based), forced (ignore rules), or guided (interactive).

Parameters

  • hierarchy - The hierarchy structure
  • object_ids - List of object IDs to compose
  • composition_type - Composition strategy:
    • :automatic - Use composition rules to find best match
    • :forced - Force composition regardless of rules
    • :guided - Interactive composition with options

Returns

  • {:ok, updated_hierarchy, composed_spec} - Success with new composite object
  • {:error, reason} - Composition failed

Examples

iex> Object.Hierarchy.compose_objects(hierarchy, ["sensor1", "actuator1"], :automatic)
{:ok, updated_hierarchy, %{id: "composed_123", type: :sensor_actuator_system}}

coordinate_hierarchy_levels(hierarchy, coordination_context)

@spec coordinate_hierarchy_levels(t(), map()) ::
  {:ok,
   %{
     coordination_actions: [any()],
     affected_objects: [object_id()],
     performance_impact: %{required(atom()) => float()},
     resource_usage: %{required(atom()) => number()},
     synchronization_points: [DateTime.t()]
   }}
  | {:error, atom()}

Manages coordination between objects at different hierarchy levels.

Identifies and executes coordination tasks needed between objects at different abstraction levels to maintain system coherence and optimal performance. This is essential for multi-level organization.

Parameters

  • hierarchy - The hierarchy structure with all levels and objects
  • coordination_context - Context information for coordination needs:
    • :coordination_type - Type of coordination needed
    • :affected_levels - Hierarchy levels involved
    • :urgency - Priority level for coordination
    • :constraints - Constraints on coordination solutions
    • :performance_requirements - Expected performance outcomes

Returns

  • {:ok, coordination_results} - Successful coordination outcomes:
    • :coordination_actions - Actions taken for coordination
    • :affected_objects - Objects involved in coordination
    • :performance_impact - Impact on system performance
    • :resource_usage - Resources consumed by coordination
    • :synchronization_points - Time points for level synchronization
  • {:error, reason} - Coordination failed:
    • :conflicting_objectives - Irreconcilable goal conflicts
    • :resource_deadlock - Circular resource dependencies
    • :communication_failure - Inter-level communication failed
    • :timeout - Coordination took too long

Coordination Types

Synchronization Coordination

  • Temporal Sync: Align timing across hierarchy levels
  • State Sync: Ensure consistent state across levels
  • Decision Sync: Coordinate decision-making processes

Resource Coordination

  • Allocation: Distribute resources across levels
  • Optimization: Optimize resource usage system-wide
  • Conflict Resolution: Resolve resource conflicts

Information Coordination

  • Flow Management: Control information propagation
  • Aggregation: Combine information from lower levels
  • Dissemination: Distribute decisions to lower levels

Objective Coordination

  • Goal Alignment: Align objectives across levels
  • Priority Resolution: Resolve conflicting priorities
  • Performance Optimization: Optimize collective performance

Examples

# Resource allocation coordination
iex> context = %{
...>   coordination_type: :resource_allocation,
...>   affected_levels: [0, 1, 2],
...>   urgency: :high,
...>   constraints: %{max_disruption: 0.1},
...>   performance_requirements: %{efficiency: 0.9}
...> }
iex> {:ok, results} = Object.Hierarchy.coordinate_hierarchy_levels(
...>   hierarchy, context
...> )
iex> length(results.coordination_actions)
5
iex> results.performance_impact.efficiency_gain
0.15

# Conflict resolution coordination
iex> conflict_context = %{
...>   coordination_type: :conflict_resolution,
...>   affected_levels: [1, 2],
...>   urgency: :critical,
...>   constraints: %{maintain_safety: true}
...> }
iex> {:ok, results} = Object.Hierarchy.coordinate_hierarchy_levels(
...>   hierarchy, conflict_context
...> )
iex> results.affected_objects
["coordinator_1", "team_alpha", "team_beta"]

Coordination Algorithms

Different algorithms for different coordination types:

Consensus-Based

  • Democratic decision making across levels
  • Suitable for collaborative environments
  • Higher coordination overhead but better buy-in

Hierarchical Command

  • Top-down decision propagation
  • Fast coordination but less flexibility
  • Suitable for time-critical situations

Market-Based

  • Auction-based resource allocation
  • Efficient resource utilization
  • Suitable for resource-constrained environments

Negotiation-Based

  • Bilateral and multilateral negotiations
  • Flexible conflict resolution
  • Suitable for autonomous object coordination

Performance Optimization

Coordination is optimized for:

  • Minimal Disruption: Reduce impact on ongoing operations
  • Fast Convergence: Achieve coordination quickly
  • Robust Solutions: Maintain coordination despite failures
  • Resource Efficiency: Minimize coordination overhead

Quality Metrics

Coordination quality measured by:

  • Convergence Time: How quickly coordination is achieved
  • Solution Quality: Optimality of coordination solution
  • Stability: Persistence of coordination over time
  • Adaptability: Ability to adjust to changing conditions

Error Recovery

Coordination failures are handled through:

  • Fallback Protocols: Alternative coordination methods
  • Partial Coordination: Coordinate subsets of objects
  • Graceful Degradation: Maintain partial functionality
  • Retry Mechanisms: Attempt coordination with modified parameters

decompose_object(hierarchy, object_id, decomposition_strategy \\ :capability_based)

Decomposes a complex object into simpler component objects.

Breaks down a complex object into its constituent parts using the specified decomposition strategy.

Parameters

  • hierarchy - The hierarchy structure
  • object_id - ID of object to decompose
  • decomposition_strategy - Strategy to use:
    • :capability_based - Decompose by individual capabilities
    • :functional - Decompose by functional requirements
    • :resource_based - Decompose by resource usage patterns
    • :temporal - Decompose by temporal behavior phases

Returns

  • {:ok, updated_hierarchy, component_specs} - Success with component objects
  • {:error, reason} - Decomposition failed

Examples

iex> Object.Hierarchy.decompose_object(hierarchy, "complex_ai", :capability_based)
{:ok, updated_hierarchy, [%{id: "ai_reasoning"}, %{id: "ai_perception"}]}

evaluate_hierarchy_effectiveness(hierarchy)

@spec evaluate_hierarchy_effectiveness(t()) :: %{
  overall_effectiveness: float(),
  detailed_metrics: %{
    composition_efficiency: float(),
    coordination_overhead: float(),
    emergent_capabilities: [atom()],
    abstraction_quality: float(),
    planning_effectiveness: float()
  },
  recommendations: [String.t()],
  trend_analysis: %{required(atom()) => [float()]},
  bottleneck_identification: [String.t()],
  optimization_opportunities: [
    %{type: atom(), description: String.t(), impact: float()}
  ]
}

Evaluates the effectiveness of current hierarchical structure.

Analyzes multiple dimensions of hierarchy performance to assess how well the current structure supports system objectives. This comprehensive evaluation guides optimization and restructuring decisions.

Parameters

  • hierarchy - The hierarchy to evaluate with all levels and objects

Returns

Comprehensive evaluation map containing:

  • :overall_effectiveness - Aggregate effectiveness score (0.0-1.0)
  • :detailed_metrics - Breakdown by specific performance dimensions
  • :recommendations - Prioritized list of improvement suggestions
  • :trend_analysis - Performance trends over time
  • :bottleneck_identification - Performance limiting factors
  • :optimization_opportunities - Specific areas for improvement

Detailed Metrics

Composition Efficiency (0.0-1.0)

Measures how well objects work together:

  • Synergy Utilization: Actual vs potential synergies
  • Resource Sharing: Efficiency of resource utilization
  • Communication Overhead: Cost of inter-object communication
  • Task Distribution: Balance of workload across objects

Coordination Overhead (0.0-1.0, lower is better)

Measures the cost of maintaining coordination:

  • Message Volume: Communication required for coordination
  • Decision Latency: Time to reach coordinated decisions
  • Conflict Resolution: Effort to resolve conflicts
  • Synchronization Cost: Overhead of maintaining synchronization

Emergent Capabilities (list of capabilities)

Identifies capabilities that emerge from object composition:

  • Novel Behaviors: Behaviors not present in individual objects
  • Enhanced Performance: Performance exceeding sum of parts
  • Robustness Gains: Improved fault tolerance through composition
  • Scalability Benefits: Better scaling characteristics

Abstraction Quality (0.0-1.0)

Evaluates the quality of hierarchical abstraction:

  • Level Coherence: Consistency within each abstraction level
  • Separation Clarity: Clear distinction between levels
  • Information Flow: Efficiency of information across levels
  • Decision Appropriateness: Right decisions at right levels

Planning Effectiveness (0.0-1.0)

Measures planning system performance:

  • Plan Quality: Optimality of generated plans
  • Planning Speed: Time to generate executable plans
  • Adaptation Rate: Speed of replanning when needed
  • Success Rate: Percentage of plans executed successfully

Examples

# Evaluate well-performing hierarchy
iex> evaluation = Object.Hierarchy.evaluate_hierarchy_effectiveness(hierarchy)
iex> evaluation.overall_effectiveness
0.85
iex> evaluation.detailed_metrics.composition_efficiency
0.9
iex> evaluation.emergent_capabilities
[:collective_problem_solving, :distributed_resilience, :adaptive_coordination]

# Identify performance issues
iex> troubled_hierarchy = create_poorly_structured_hierarchy()
iex> evaluation = Object.Hierarchy.evaluate_hierarchy_effectiveness(troubled_hierarchy)
iex> evaluation.overall_effectiveness
0.45
iex> evaluation.recommendations
[
  "Reduce coordination overhead by optimizing communication patterns",
  "Improve abstraction quality by consolidating similar functions",
  "Address bottleneck at level 2 coordinator object"
]

Recommendation Categories

Structural Improvements

  • Hierarchy Reorganization: Restructure levels for better performance
  • Object Redistribution: Move objects between levels
  • Composition Optimization: Form better object combinations
  • Decomposition Adjustments: Break down ineffective compositions

Process Improvements

  • Coordination Protocol Updates: Improve coordination efficiency
  • Planning Algorithm Optimization: Enhance planning performance
  • Communication Pattern Optimization: Reduce message overhead
  • Resource Allocation Improvements: Better resource distribution

Performance Tuning

  • Parameter Adjustments: Fine-tune system parameters
  • Load Balancing: Distribute workload more evenly
  • Caching Strategies: Reduce computational overhead
  • Parallel Processing: Increase concurrency where beneficial

Evaluation Methodology

The evaluation process:

  1. Data Collection: Gather performance metrics from all levels
  2. Metric Calculation: Compute individual performance dimensions
  3. Trend Analysis: Identify performance trends over time
  4. Bottleneck Detection: Find performance limiting factors
  5. Recommendation Generation: Suggest specific improvements
  6. Priority Ranking: Order recommendations by impact and feasibility

Performance Benchmarks

Excellent Performance (0.8-1.0)

  • High composition efficiency
  • Low coordination overhead
  • Strong emergent capabilities
  • Clear abstraction levels

Good Performance (0.6-0.8)

  • Adequate composition efficiency
  • Moderate coordination overhead
  • Some emergent capabilities
  • Generally clear abstractions

Poor Performance (0.0-0.6)

  • Low composition efficiency
  • High coordination overhead
  • Limited emergent capabilities
  • Confused abstraction levels

Continuous Monitoring

Regular evaluation enables:

  • Performance Tracking: Monitor effectiveness over time
  • Early Problem Detection: Identify issues before they become critical
  • Optimization Opportunities: Find ways to improve performance
  • Structural Evolution: Guide hierarchy evolution decisions

hierarchical_planning(hierarchy, goal, current_state)

@spec hierarchical_planning(t(), any(), map()) ::
  {:ok,
   %{
     executable_actions: [any()],
     execution_schedule: %{
       start_time: DateTime.t(),
       total_duration: pos_integer(),
       coordination_points: [DateTime.t()]
     },
     resource_requirements: %{required(atom()) => number()},
     success_probability: float(),
     contingency_plans: [any()],
     coordination_points: [any()]
   }}
  | {:error, {:planning_failed, atom()}}

Performs hierarchical planning across abstraction levels.

Creates a multi-level plan starting from abstract goals and refining down to concrete executable actions. This enables efficient planning for complex scenarios by working at appropriate abstraction levels. The planning process uses hierarchical decomposition to manage complexity.

Parameters

  • hierarchy - The hierarchy structure containing organized objects
  • goal - High-level goal specification to achieve:
    • Can be a simple goal description (string/atom)
    • Or detailed goal map with constraints and preferences
  • current_state - Current system state:
    • Object states and positions
    • Resource availability
    • Environmental conditions

Returns

  • {:ok, executable_plan} - Complete executable plan
  • {:error, {:planning_failed, reason}} - Planning failed due to:
    • :goal_unreachable - Goal cannot be achieved with current resources
    • :insufficient_objects - Not enough objects to complete plan
    • :resource_constraints - Insufficient resources for execution
    • :time_limit_exceeded - Planning took too long

Planning Process

  1. Abstract Planning: Create high-level plan at top abstraction level
  2. Iterative Refinement: Refine plan down through abstraction levels
  3. Concrete Actions: Generate executable actions at level 0
  4. Schedule Creation: Determine timing and coordination requirements
  5. Resource Allocation: Assign resources to plan steps

Plan Structure

The returned executable plan contains:

  • :executable_actions - Sequence of concrete actions for objects
  • :execution_schedule - Timing and coordination information
  • :resource_requirements - Required computational and physical resources
  • :success_probability - Estimated probability of successful completion
  • :contingency_plans - Alternative plans for failure scenarios
  • :coordination_points - Synchronization points between objects

Examples

# Simple goal planning
iex> goal = "optimize system performance"
iex> current_state = %{system_load: 0.7, available_objects: 5}
iex> {:ok, plan} = Object.Hierarchy.hierarchical_planning(
...>   hierarchy, goal, current_state
...> )
iex> length(plan.executable_actions)
12
iex> plan.success_probability
0.85

# Complex goal with constraints
iex> complex_goal = %{
...>   objective: "coordinate rescue operation",
...>   constraints: %{max_time: 300, min_success_rate: 0.9},
...>   preferences: %{minimize_risk: true, maximize_coverage: true}
...> }
iex> {:ok, plan} = Object.Hierarchy.hierarchical_planning(
...>   hierarchy, complex_goal, current_state
...> )
iex> plan.execution_schedule.total_duration
285

Hierarchical Benefits

Hierarchical planning provides:

Computational Efficiency

  • Reduced Search Space: Abstract levels prune irrelevant branches
  • Faster Convergence: High-level structure guides detailed planning
  • Scalable Complexity: Handle large systems efficiently

Plan Quality

  • Global Optimization: Consider system-wide objectives
  • Local Efficiency: Optimize detailed execution at each level
  • Robust Solutions: Multiple abstraction levels provide fallbacks

Adaptive Execution

  • Real-time Refinement: Adjust plans during execution
  • Graceful Degradation: Maintain functionality despite failures
  • Dynamic Replanning: Respond to changing conditions

Planning Algorithms

The planning process uses:

  • Hierarchical Task Networks (HTN): Decompose abstract tasks
  • Forward Search: Explore action sequences from current state
  • Constraint Satisfaction: Respect resource and timing constraints
  • Multi-Objective Optimization: Balance competing objectives

Performance Characteristics

  • Planning Time: O(b^(d/k)) where b=branching, d=depth, k=abstraction factor
  • Memory Usage: Linear with hierarchy size
  • Success Rate: 80-95% for well-structured hierarchies
  • Scalability: Handles 100+ objects across 5+ abstraction levels

new(root_object_id, opts \\ [])

Creates a new hierarchical structure with the given root object.

Initializes a hierarchy with the specified object as the root node, setting up default composition rules, decomposition strategies, and coordination protocols.

Parameters

  • root_object_id - ID of the object to serve as hierarchy root
  • opts - Optional configuration:
    • :composition_rules - Rules for object composition
    • :decomposition_strategies - Strategies for object decomposition
    • :planning_horizon - Planning time horizon (default 10)
    • :protocols - Coordination protocols (default [:consensus, :delegation, :auction])

Returns

New hierarchy structure

Examples

iex> Object.Hierarchy.new("root_obj", planning_horizon: 20)
%Object.Hierarchy{root_object_id: "root_obj", planning_horizon: 20, ...}