🔍 Code Extractor

class AnalysisResult_v1

Maturity: 48

A dataclass that encapsulates results from statistical analysis operations, providing structured storage and serialization capabilities for analysis outputs.

File:
/tf/active/vicechatdev/vice_ai/models.py
Lines:
2075 - 2120
Complexity:
simple

Purpose

AnalysisResult serves as a data container for storing and managing statistical analysis results. It supports multiple result types (summary statistics, test results, plots, tables, interpretations) and provides serialization/deserialization methods for persistence. The class automatically initializes default values for optional fields and handles datetime conversion for storage compatibility.

Source Code

class AnalysisResult:
    """Results from statistical analysis"""
    result_id: str
    session_id: str
    result_type: str  # "summary_stats", "test_result", "plot", "table", "interpretation"
    result_data: Dict[str, Any]
    file_paths: List[str] = None
    metadata: Dict[str, Any] = None
    created_at: datetime = None
    
    def __post_init__(self):
        if self.file_paths is None:
            self.file_paths = []
        if self.metadata is None:
            self.metadata = {}
        if self.created_at is None:
            self.created_at = datetime.now()
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary with proper serialization"""
        return {
            'result_id': self.result_id,
            'session_id': self.session_id,
            'result_type': self.result_type,
            'result_data': self.result_data,
            'file_paths': self.file_paths,
            'metadata': self.metadata,
            'created_at': self.created_at.isoformat() if self.created_at else None
        }
    
    @classmethod
    def from_dict(cls, data: Dict[str, Any]) -> 'AnalysisResult':
        """Create instance from dictionary"""
        result = cls(
            result_id=data['result_id'],
            session_id=data['session_id'],
            result_type=data['result_type'],
            result_data=data.get('result_data', {}),
            file_paths=data.get('file_paths', []),
            metadata=data.get('metadata', {})
        )
        
        if data.get('created_at'):
            result.created_at = datetime.fromisoformat(data['created_at'])
        
        return result

Parameters

Name Type Default Kind
bases - -

Parameter Details

result_id: Unique identifier for this analysis result, typically a UUID string

session_id: Identifier linking this result to a specific analysis session

result_type: Type of analysis result, must be one of: 'summary_stats', 'test_result', 'plot', 'table', or 'interpretation'

result_data: Dictionary containing the actual analysis data/results, structure varies by result_type

file_paths: Optional list of file system paths to associated files (e.g., saved plots). Defaults to empty list if not provided

metadata: Optional dictionary for storing additional contextual information about the result. Defaults to empty dict if not provided

created_at: Timestamp when the result was created. Automatically set to current datetime if not provided

Return Value

Instantiation returns an AnalysisResult object with all specified attributes. The to_dict() method returns a dictionary representation with datetime converted to ISO format string. The from_dict() class method returns a new AnalysisResult instance reconstructed from a dictionary.

Class Interface

Methods

__post_init__(self) -> None

Purpose: Initializes default values for optional attributes after dataclass initialization

Returns: None - modifies instance attributes in place

to_dict(self) -> Dict[str, Any]

Purpose: Converts the AnalysisResult instance to a dictionary with proper serialization of datetime objects

Returns: Dictionary containing all instance attributes with created_at converted to ISO format string

from_dict(cls, data: Dict[str, Any]) -> AnalysisResult

Purpose: Class method that creates an AnalysisResult instance from a dictionary representation

Parameters:

  • data: Dictionary containing serialized AnalysisResult data, must include result_id, session_id, and result_type keys

Returns: New AnalysisResult instance with attributes populated from the dictionary, including datetime conversion from ISO format

Attributes

Name Type Description Scope
result_id str Unique identifier for this analysis result instance
session_id str Identifier linking this result to a specific analysis session instance
result_type str Type of analysis result: 'summary_stats', 'test_result', 'plot', 'table', or 'interpretation' instance
result_data Dict[str, Any] Dictionary containing the actual analysis data and results instance
file_paths List[str] List of file system paths to associated files (e.g., saved plots), defaults to empty list instance
metadata Dict[str, Any] Additional contextual information about the result, defaults to empty dictionary instance
created_at datetime Timestamp when the result was created, automatically set to current time if not provided instance

Dependencies

  • datetime
  • typing
  • dataclasses

Required Imports

from datetime import datetime
from typing import List, Dict, Any
from dataclasses import dataclass

Usage Example

from datetime import datetime
from typing import List, Dict, Any
from dataclasses import dataclass
import uuid

# Create a new analysis result
result = AnalysisResult(
    result_id=str(uuid.uuid4()),
    session_id='session_123',
    result_type='summary_stats',
    result_data={'mean': 45.2, 'std': 12.3, 'count': 100},
    file_paths=['/path/to/plot.png'],
    metadata={'analyst': 'John Doe', 'dataset': 'sales_data'}
)

# Access attributes
print(result.result_type)  # 'summary_stats'
print(result.created_at)   # datetime object

# Serialize to dictionary
result_dict = result.to_dict()
print(result_dict['created_at'])  # ISO format string

# Deserialize from dictionary
restored_result = AnalysisResult.from_dict(result_dict)
print(restored_result.result_id)  # Original UUID

Best Practices

  • Always provide a unique result_id (use uuid.uuid4() for generation) to avoid conflicts
  • Use one of the predefined result_type values: 'summary_stats', 'test_result', 'plot', 'table', or 'interpretation'
  • The result_data dictionary structure should be consistent for each result_type to facilitate downstream processing
  • When persisting to databases or JSON, use to_dict() method to ensure proper datetime serialization
  • When reconstructing from storage, use the from_dict() class method to maintain proper type conversion
  • File paths in file_paths should be absolute paths or relative to a known base directory
  • The class is immutable after creation (dataclass without frozen=True), but attributes can be modified if needed
  • created_at is automatically set during __post_init__, so manual setting is only needed when reconstructing from storage
  • Metadata dictionary is useful for storing analysis parameters, data source information, or processing notes

Related Versions

Other versions of this component:

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class AnalysisResult 94.0% similar

    A dataclass that encapsulates the results from statistical analysis operations, including metadata, file paths, and timestamps.

    From: /tf/active/vicechatdev/vice_ai/smartstat_models.py
  • class MultiPageAnalysisResult 68.4% similar

    A dataclass that encapsulates the complete results of analyzing a multi-page document, including individual page analyses, document summary, combined response, and processing statistics.

    From: /tf/active/vicechatdev/e-ink-llm/multi_page_llm_handler.py
  • class AnalysisRequest 68.0% similar

    A dataclass that encapsulates an analysis request combining data retrieval requirements and statistical analysis specifications.

    From: /tf/active/vicechatdev/full_smartstat/enhanced_sql_workflow.py
  • class AnnotationResult 66.0% similar

    A dataclass that encapsulates the results of an annotation detection process on PDF documents, containing detected annotations, processing statistics, and a summary.

    From: /tf/active/vicechatdev/e-ink-llm/annotation_detector.py
← Back to Browse