# coding: utf-8

"""
    Mixpeek API

    This is the Mixpeek API, providing access to various endpoints for data processing and retrieval.

    The version of the OpenAPI document: 1.3.0
    Contact: info@mixpeek.com
    Generated by OpenAPI Generator (https://openapi-generator.tech)

    Do not edit the class manually.
"""  # noqa: E501


from __future__ import annotations
import pprint
import re  # noqa: F401
import json

from pydantic import BaseModel, ConfigDict, Field, StrictInt, StrictStr, field_validator
from typing import Any, ClassVar, Dict, List, Optional
from typing_extensions import Annotated
from typing import Optional, Set
from typing_extensions import Self

class WeightLearningConfig(BaseModel):
    """
    Configuration for automatic feature weight learning in multi-feature clustering.  When multi_feature_strategy='weighted' and feature_weights is not provided, this configuration controls how optimal weights are automatically learned.  The system tries different weight combinations and picks the one that produces the best clustering quality (measured by silhouette score, etc.).  Examples:     Bayesian optimization (recommended):     {         \"method\": \"bayesian\",         \"max_iterations\": 20,         \"metric\": \"silhouette\",         \"sample_size\": 5000     }      Grid search (exhaustive, limited to 2-3 features):     {         \"method\": \"grid_search\",         \"max_iterations\": 5,         \"metric\": \"silhouette\"     }
    """ # noqa: E501
    method: Optional[StrictStr] = Field(default='bayesian', description="Weight learning method: - bayesian: Gaussian process optimization (recommended, scales to 5+ features) - grid_search: Exhaustive search (limited to 2-3 features, simpler but slower)")
    max_iterations: Optional[Annotated[int, Field(le=100, strict=True, ge=5)]] = Field(default=20, description="Maximum optimization iterations: - grid_search: Number of values to try per feature (total: max_iterations^n_features) - bayesian: Number of weight combinations to evaluate Recommended: 20 for bayesian, 5 for grid_search")
    metric: Optional[StrictStr] = Field(default='silhouette', description="Clustering quality metric to optimize: - silhouette: Measures how similar points are to their cluster vs other clusters (range: [-1, 1], higher is better) - davies_bouldin: Ratio of within-cluster to between-cluster distances (range: [0, ∞], lower is better) - calinski_harabasz: Ratio of between-cluster to within-cluster variance (range: [0, ∞], higher is better) Recommended: silhouette (most general-purpose)")
    sample_size: Optional[Annotated[int, Field(strict=True, ge=100)]] = Field(default=None, description="Optional: Learn weights on a random sample (speeds up large datasets). If provided and dataset has more documents, weights are learned on sample_size random documents, then applied to full dataset. Recommended: 5000 for datasets >10k documents")
    random_state: Optional[StrictInt] = Field(default=42, description="Random seed for reproducibility of weight learning")
    __properties: ClassVar[List[str]] = ["method", "max_iterations", "metric", "sample_size", "random_state"]

    @field_validator('method')
    def method_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['grid_search', 'bayesian']):
            raise ValueError("must be one of enum values ('grid_search', 'bayesian')")
        return value

    @field_validator('metric')
    def metric_validate_enum(cls, value):
        """Validates the enum"""
        if value is None:
            return value

        if value not in set(['silhouette', 'davies_bouldin', 'calinski_harabasz']):
            raise ValueError("must be one of enum values ('silhouette', 'davies_bouldin', 'calinski_harabasz')")
        return value

    model_config = ConfigDict(
        populate_by_name=True,
        validate_assignment=True,
        protected_namespaces=(),
    )


    def to_str(self) -> str:
        """Returns the string representation of the model using alias"""
        return pprint.pformat(self.model_dump(by_alias=True))

    def to_json(self) -> str:
        """Returns the JSON representation of the model using alias"""
        # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead
        return json.dumps(self.to_dict())

    @classmethod
    def from_json(cls, json_str: str) -> Optional[Self]:
        """Create an instance of WeightLearningConfig from a JSON string"""
        return cls.from_dict(json.loads(json_str))

    def to_dict(self) -> Dict[str, Any]:
        """Return the dictionary representation of the model using alias.

        This has the following differences from calling pydantic's
        `self.model_dump(by_alias=True)`:

        * `None` is only added to the output dict for nullable fields that
          were set at model initialization. Other fields with value `None`
          are ignored.
        """
        excluded_fields: Set[str] = set([
        ])

        _dict = self.model_dump(
            by_alias=True,
            exclude=excluded_fields,
            exclude_none=True,
        )
        return _dict

    @classmethod
    def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]:
        """Create an instance of WeightLearningConfig from a dict"""
        if obj is None:
            return None

        if not isinstance(obj, dict):
            return cls.model_validate(obj)

        _obj = cls.model_validate({
            "method": obj.get("method") if obj.get("method") is not None else 'bayesian',
            "max_iterations": obj.get("max_iterations") if obj.get("max_iterations") is not None else 20,
            "metric": obj.get("metric") if obj.get("metric") is not None else 'silhouette',
            "sample_size": obj.get("sample_size"),
            "random_state": obj.get("random_state") if obj.get("random_state") is not None else 42
        })
        return _obj


