src.pydasa.analysis.simulation ============================== .. py:module:: src.pydasa.analysis.simulation .. autoapi-nested-parse:: Module simulation.py =========================================== Module for Monte Carlo Simulation execution and analysis in *PyDASA*. This module provides the MonteCarlo class for performing Monte Carlo simulations on dimensionless coefficients derived from dimensional analysis. Classes: **MonteCarlo**: Performs Monte Carlo simulations on dimensionless coefficients. *IMPORTANT:* Based on the theory from: # H.Gorter, *Dimensionalanalyse: Eine Theoririe der physikalischen Dimensionen mit Anwendungen* Classes ------- .. autoapisummary:: src.pydasa.analysis.simulation.MonteCarlo Module Contents --------------- .. py:class:: MonteCarlo Bases: :py:obj:`pydasa.core.basic.Foundation`, :py:obj:`pydasa.elements.specs.numerical.BoundsSpecs` **MonteCarlo** class for stochastic analysis in *PyDASA*. Performs Monte Carlo simulations on dimensionless coefficients to analyze the coefficient's distribution and sensitivity to input parameter variations. :param Foundation: Foundation class for validation of symbols and frameworks. :param BoundsSpecs: Value bounds for statistical properties (mean, median, dev, min, max). .. attribute:: # Core Identification .. attribute:: name User-friendly name of the Monte Carlo simulation. :type: str .. attribute:: description Brief summary of the simulation. :type: str .. attribute:: _idx Index/precedence of the simulation. :type: int .. attribute:: _sym Symbol representation (LaTeX or alphanumeric). :type: str .. attribute:: _alias Python-compatible alias for use in code. :type: str .. attribute:: _fwk Frameworks context (PHYSICAL, COMPUTATION, SOFTWARE, CUSTOM). :type: str .. attribute:: _cat Category of analysis (SYM, NUM, HYB). :type: str .. attribute:: # Coefficient and Expression Management .. attribute:: _coefficient Coefficient for the simulation. :type: Optional[Coefficient] .. attribute:: _pi_expr LaTeX expression to analyze. :type: str .. attribute:: _sym_func Sympy function of the simulation. :type: Callable .. attribute:: _exe_func Executable function for numerical evaluation. :type: Callable .. attribute:: # Variable Management .. attribute:: _variables Variable symbols in the expression. :type: Dict[str, Variable] .. attribute:: _symbols Python symbols for the variables. :type: Dict[str, Any] .. attribute:: _aliases Variable aliases for use in code. :type: Dict[str, Any] .. attribute:: _latex_to_py Mapping from LaTeX to Python variable names. :type: Dict[str, str] .. attribute:: _py_to_latex Mapping from Python to LaTeX variable names. :type: Dict[str, str] .. attribute:: # Simulation Configuration .. attribute:: _experiments Number of simulation experiments to run. Default is -1. :type: int .. attribute:: _distributions Variable sampling distributions. :type: Dict[str, Dict[str, Any]] .. attribute:: _simul_cache Working sampled values cache. :type: Dict[str, NDArray[np.float64]] .. attribute:: # Results and Input data .. attribute:: _data Input data dictionary mapping variable names to arrays. :type: Dict[str, NDArray[np.float64]] .. attribute:: _results Raw simulation results. :type: Optional[np.ndarray] .. attribute:: # Statistics (inherited from BoundsSpecs _mean, _median, _dev, _min, _max) .. attribute:: _mean Mean value of simulation results. :type: float .. attribute:: _median Median value of simulation results. :type: float .. attribute:: _dev Standard deviation of simulation results. :type: float .. attribute:: _min Minimum value in simulation results. :type: float .. attribute:: _max Maximum value in simulation results. :type: float .. attribute:: _count Number of valid simulation results (MonteCarlo-specific). :type: int .. attribute:: _statistics Statistical summary. :type: Optional[Dict[str, float]] .. py:attribute:: _name :type: str :value: '' User-friendly name of the Monte Carlo simulation. .. py:attribute:: description :type: str :value: '' Brief summary of the simulation. .. py:attribute:: _idx :type: int :value: -1 Index/precedence of the simulation. .. py:attribute:: _sym :type: str :value: '' Symbol representation (LaTeX or alphanumeric). .. py:attribute:: _alias :type: str :value: '' Python-compatible alias for use in code. .. py:attribute:: _fwk :type: str :value: 'PHYSICAL' Frameworks context (PHYSICAL, COMPUTATION, SOFTWARE, CUSTOM). .. py:attribute:: _cat :type: str :value: 'DIST' Category of analysis (DIST, DATA). .. py:attribute:: _coefficient :type: pydasa.dimensional.buckingham.Coefficient Coefficient for the simulation. .. py:attribute:: _pi_expr :type: Optional[str] :value: None LaTeX expression to analyze. .. py:attribute:: _sym_func :type: Optional[Union[sympy.Expr, sympy.Basic]] :value: None Sympy expression object for the coefficient (Mul, Add, Pow, Symbol, etc.). .. py:attribute:: _exe_func :type: Optional[Callable[Ellipsis, Union[float, numpy.ndarray]]] :value: None Compiled executable function for evaluation of the coefficient. .. py:attribute:: _variables :type: Dict[str, pydasa.elements.parameter.Variable] Dictionary of variables in the expression. .. py:attribute:: _symbols :type: Dict[str, sympy.Symbol] Map from variable names (strings) to sympy Symbols. .. py:attribute:: _aliases :type: Dict[str, sympy.Symbol] Map from Variable aliases to sympy Symbols. .. py:attribute:: _latex_to_py :type: Dict[str, str] Map from LaTeX symbols to Python-compatible names. .. py:attribute:: _py_to_latex :type: Dict[str, str] Map from Python-compatible names to LaTeX symbols. .. py:attribute:: _var_symbols :type: List[str] :value: [] List of variable names extracted from expression. .. py:attribute:: _experiments :type: int :value: -1 Number of simulation iterations to run. .. py:attribute:: _distributions :type: Dict[str, Dict[str, Any]] Variable sampling distributions and specifications that includes: - 'dtype': Distribution type name. - 'params': Distribution parameters (mean, std_dev, etc.). - 'func': Function for sampling, usually in Lambda format. - 'depends': List of variables this variable depends on. .. py:attribute:: _dependencies :type: Dict[str, List[str]] Variable dependencies for simulations. .. py:attribute:: _simul_cache :type: Dict[str, numpy.typing.NDArray[numpy.float64]] Working sampled values during each simulation iteration. Memory cache. .. py:attribute:: _data :type: Dict[str, numpy.typing.NDArray[numpy.float64]] Input data dictionary mapping variable names to their value arrays. .. py:attribute:: _results :type: numpy.typing.NDArray[numpy.float64] Raw simulation results. .. py:attribute:: _mean :type: Optional[float] Mean value of simulation results. .. py:attribute:: _median :type: Optional[float] Median value of simulation results. .. py:attribute:: _dev :type: Optional[float] Standard deviation of simulation results. .. py:attribute:: _min :type: Optional[float] Minimum value in simulation results. .. py:attribute:: _max :type: Optional[float] Maximum value in simulation results. .. py:attribute:: _count :type: int :value: -1 Number of valid simulation results. .. py:attribute:: _statistics :type: Optional[Dict[str, Union[float, int, None]]] :value: None Statistical summary of the Monte Carlo simulation results. .. py:method:: _validate_dist(value, field_name) *_validate_dist()* Custom validator to ensure all distributions have callable 'func'. :param value: The distributions dictionary to validate. :param field_name: Name of the field being validated. :raises ValueError: If distributions don't have callable 'func' functions. .. py:method:: _validate_readiness() *_validate_readiness()* Checks if the simulation can be performed. :raises ValueError: If the simulation is not ready due to missing variables, executable function, or invalid number of iterations. .. py:method:: set_coefficient(coef) *set_coefficient()* Configure analysis from a coefficient. :param coef: Dimensionless coefficient to analyze. :type coef: Coefficient :raises ValueError: If the coefficient doesn't have a valid expression. .. py:method:: _collect_dataset(vars) *_collect_dataset()* Consolidate dataset from all variables for 'DATA' simulation mode. :param vars: Dictionary of variables to collect data from. :type vars: Dict[str, Variable] :returns: Dictionary mapping variable symbols to their data arrays. :rtype: Dict[str, NDArray[np.float64]] :raises ValueError: If variables have no data. :raises ValueError: If variables have inconsistent lengths. .. py:method:: _generate_dataset(vars) *_generate_dataset()* Generate dataset by sampling from variable distributions for 'DIST' mode. :param vars: Dictionary of variables to generate samples for. :type vars: Dict[str, Variable] :returns: Dictionary mapping variable symbols to sampled arrays. :rtype: Dict[str, NDArray[np.float64]] :raises ValueError: If sampling fails or encounters errors. .. py:method:: _parse_expression(expr) *_parse_expression()* Parse the LaTeX expression into a sympy function. :param expr: LaTeX expression to parse. :type expr: str :raises ValueError: If the expression cannot be parsed. .. py:method:: _generate_sample(var, memory) *_generate_sample()* Generate a sample for a given variable. :param var: The variable to generate a sample for. :type var: Variable :param memory: The current iteration values. :type memory: Dict[str, float] :returns: The generated sample. :rtype: float .. py:method:: run(iters = None, mode = SimulationMode.DIST) *run()* Execute the Monte Carlo simulation. :param iters: Number of iterations to run. If None, uses _experiments. :type iters: int, optional :param mode: Simulation mode. Either 'DIST' to sample from distributions, or 'DATA' to use pre-existing Variable._data. Defaults to 'DIST'. :type mode: str | SimulationMode, optional :raises ValueError: If simulation is not ready or encounters errors during execution. .. py:method:: _reset_memory() *_reset_memory()* Reset results and inputs arrays. .. py:method:: _reset_statistics() *_reset_statistics()* Reset all statistical attributes to default values. .. py:method:: _calculate_statistics() *_calculate_statistics()* Calculate statistical properties of simulation results. .. py:method:: get_confidence_interval(conf = 0.95) *get_confidence_interval()* Calculate the confidence interval. :param conf: Confidence level for the interval. Defaults to 0.95. :type conf: float, optional :raises ValueError: If no results are available or if the confidence level is invalid. :returns: Lower and upper bounds of the confidence interval. :rtype: Tuple[float, float] .. py:method:: _validate_cache_locations(var_syms, idx) *_validate_cache_locations()* Check if cache locations are valid for variable(s) at the iteration. :param var_syms: Variable symbol(s) to check. :type var_syms: Union[str, List[str]] :param idx: Iteration index to check. :type idx: int :returns: True if all cache locations are valid (including NaN placeholders), False otherwise. :rtype: bool .. py:method:: _get_cached_value(var_sym, idx) *_get_cached_value()* Retrieve cached value for variable at the iteration. :param var_sym: Variable symbol. :type var_sym: str :param idx: Iteration index. :type idx: int :returns: Cached value if valid, None otherwise. :rtype: Optional[float] .. py:method:: _set_cached_value(var_sym, idx, val) *_set_cached_value()* Store value in cache for variable at the iteration. :param var_sym: Variable symbol. :type var_sym: str :param idx: Iteration index. :type idx: int :param val: Value to cache. It can be a normal number (float) or a memory cache correction (dict). :type val: Union[float, Dict] :raises ValueError: If cache location is invalid. .. py:method:: extract_results() *extract_results()* Extract simulation results. :returns: Dictionary containing simulation results. :rtype: Dict[str, NDArray[np.float64]] .. py:property:: variables :type: Dict[str, pydasa.elements.parameter.Variable] *variables* Get the variables involved in the simulation. :returns: Dictionary of variable symbols and Variable objects. :rtype: Dict[str, Variable] .. py:property:: coefficient :type: Optional[pydasa.dimensional.buckingham.Coefficient] *coefficient* Get the coefficient associated with the simulation. :returns: The associated Coefficient object, or None. :rtype: Optional[Coefficient] .. py:property:: results :type: numpy.typing.NDArray[numpy.float64] *results* Raw simulation results. :returns: Copy of the simulation results. :rtype: NDArray[np.float64] :raises ValueError: If no results are available. .. py:property:: data :type: Dict[str, numpy.typing.NDArray[numpy.float64]] *data* Get the input data dictionary. :returns: Copy of input data mapping variable names to arrays. :rtype: Dict[str, NDArray[np.float64]] :raises ValueError: If no data is available. .. py:property:: statistics :type: Dict[str, Union[float, int, None]] *statistics* Get the statistical analysis of simulation results. :raises ValueError: If no results are available. :returns: Dictionary containing statistical properties. :rtype: Dict[str, Union[float, int, None]] .. py:property:: experiments :type: int *experiments* Number of simulation experiments. :returns: Current number of experiments. :rtype: int .. py:property:: distributions :type: Dict[str, Dict[str, Any]] *distributions* Get the variable distributions. :returns: Current variable distributions. :rtype: Dict[str, Dict[str, Any]] .. py:property:: dependencies :type: Dict[str, List[str]] *dependencies* Get variable dependencies. :returns: Dictionary of variable dependencies. :rtype: Dict[str, List[str]] .. py:property:: cat :type: str *mode* Get simulation execution category. :returns: Current simulation category (DIST or DATA). :rtype: str .. py:property:: count :type: int *count* Number of valid simulation results. :returns: Result count. :rtype: int :raises ValueError: If no results are available. .. py:property:: summary :type: Dict[str, Union[float, int, None]] *summary* Get the statistical analysis of simulation results. :returns: Dictionary containing statistical properties. It returns NaN values and -1 count if simulation hasn't run yet. :rtype: Dict[str, Union[float, int, None]] .. py:method:: clear() *clear()* Reset all attributes to default values. .. py:method:: to_dict() *to_dict()* Convert simulation to dictionary representation. .. py:method:: from_dict(data) :classmethod: *from_dict()* Create simulation from dictionary representation. :param data: Dictionary representation. :type data: Dict[str, Any] :returns: New simulation instance. :rtype: MonteCarlo