API Reference

Note that all classes and functions are automatically imported into the top-level package, so referencing via the module is unnecessary.

# Example Usage:
import monaco as mc
sim = mc.Sim

Classes

Sim

class monaco.mc_sim.Sim(name: str, ndraws: int, fcns: dict[SimFunctions, Callable], firstcaseismedian: bool = False, samplemethod: SampleMethod = SampleMethod.SOBOL_RANDOM, seed: int = 2147483648, singlethreaded: bool = True, daskkwargs: dict = {}, verbose: bool = True, debug: bool = False, keepsiminput: bool = True, keepsimrawoutput: bool = True, savesimdata: bool = False, savecasedata: bool = False, resultsdir: str | Path | None = None)[source]

The main Monte Carlo Simulation object.

Parameters:
  • name (str) – The name for the simulation.

  • ndraws (int) – The number of random draws to perform.

  • fcns (dict[monaco.mc_enums.SimFunctions, Callable]) – fcns is a dict with keys SimFunctions.PREPROCESS, RUN, and POSTPROCESS. These point to user-defined functions with certain input and output structures, please see the documentation on how to construct these functions.

  • firstcaseismedian (bool, default: False) – Whether the first case represents the median value.

  • samplemethod (monaco.mc_enums.SampleMethod, default: 'sobol_random') – The random sampling method to use.

  • seed (int, default: np.random.get_state(legacy=False)['state']['key'][0]) – The random number to seed the simulation.

  • singlethreaded (bool, default: False) – Whether to run single threaded rather than using dask.

  • daskkwargs (dict, default: dict()) – Kwargs to pass to the dask Client constructor, see: https://distributed.dask.org/en/stable/api.html#client

  • verbose (bool, default: True) – Whether to print out warning and status messages.

  • debug (bool, default: False) – If False, cases that fail while running will be skipped over. If True, cases that fail will raise an exception.

  • keepsiminput (bool, default: True) – Whether to keep the siminput for each case after running.

  • keepsimrawoutput (bool, default: True) – Whether to keep the simrawoutput for each case after postprocessing.

  • savesimdata (bool, default: True) – Whether to save the simulation data to disk as a .mcsim file.

  • savecasedata (bool, default: True) – Whether to save the full output data for each case to disk as .mccase files.

  • resultsdir (str | pathlib.Path) – The directory to save simulation and case data to. If None, then this defaults to a directory named {name}_results.

rootdir[source]

The directory the simulation was run in.

Type:

pathlib.Path

filepath[source]

The filepath to the simulation .mcsim datafile.

Type:

pathlib.Path

invarseeds[source]

The random seeds for each of the input variables.

Type:

list[int]

outvarseeds[source]

The random seeds for each of the input variables.

Type:

list[int]

caseseeds[source]

The random seeds for each of the cases.

Type:

list[int]

inittime[source]

The timestamp when this simulation object was created.

Type:

datetime.datetime

starttime[source]

The timestamp when the simulation began running.

Type:

datetime.datetime

endtime[source]

The timestamp when the simulation stopped running.

Type:

datetime.datetime

runtime[source]

The length of time it took the simulation to run.

Type:

datetime.timedelta

casespreprocessed[source]

The case numbers which were sucessfully preprocessed.

Type:

set[int]

casesrun[source]

The case numbers which were sucessfully run.

Type:

set[int]

casespostprocessed[source]

The case numbers which were sucessfully postprocessed.

Type:

set[int]

vars[source]

All Variables.

Type:

dict[str, monaco.mc_var.InVar]

invars[source]

The Monte Carlo Input Variables.

Type:

dict[str, monaco.mc_var.InVar]

outvars[source]

The Monte Carlo Output Variables.

Type:

dict[str, monaco.mc_var.OutVar]

constvals[source]

The constant values to pass to each of the cases.

Type:

dict[str, Any]

cases[source]

The Monte Carlo Cases.

Type:

list[monaco.mc_case.Case]

ninvars[source]

The number of input variables.

Type:

int

noutvars[source]

The number of output variables.

Type:

int

corrcoeffs[source]

The correlation coefficients between all of the scalar variables.

Type:

numpy.ndarray

covs[source]

The covariance matrix between all of the scalar variables.

Type:

numpy.ndarray

covvarlist[source]

The names of all the scalar variables.

Type:

list[str]

runsimid[source]

The unique ID for a particular run of this simulation.

Type:

int

ncases[source]

The number of cases.

Type:

int

checkFcnsInput(fcns: dict[SimFunctions, Callable]) None[source]

Check the fcns input dictionary for correctness.

Parameters:

fcns (dict[monaco.mc_enums.SimFunctions, Callable]) – fcns must be a dict with keys SimFunctions.PREPROCESS, RUN, and POSTPROCESS, which point to special user-defined functions.

setFirstCaseMedian(firstcaseismedian: bool) None[source]

Make the first case represent the median expected case or not.

Parameters:

firstcaseismedian (bool) – Whether to make the first case the median case.

initDaskClient()[source]

Initialize the dask distributed client.

addInVar(name: str, dist: rv_discrete | rv_continuous, distkwargs: dict[str, Any], nummap: dict[float, Any] | None = None, seed: int | None = None, datasource: str | None = None) None[source]

Add an input variable to the simulation.

Parameters:
  • name (str) – The name of this variable.

  • dist (scipy.stats.rv_discrete | scipy.stats.rv_continuous) – The statistical distribution to draw from.

  • distkwargs (dict) – The keyword argument pairs for the statistical distribution function.

  • nummap (dict[float, Any], default: None) – A dictionary mapping numbers to nonnumeric values.

  • seed (int) – The random seed for this variable. If None, a seed will be assigned based on the order added.

  • datasource (str, default: None) – If the invals were imported from a file, this is the filepath. If generated through monaco, then None.

addConstVal(name: str, val: Any) None[source]

Add a constant value for all the cases to use.

Parameters:
  • name (str) – Name for this value.

  • val (Any) – The constant value.

setNDraws(ndraws: int) None[source]

Set the number of random draws to perform. Will clear the results.

Parameters:

ndraws (int) – The number of random draws to perform.

drawVars() None[source]

Draw the random values for all the input variables.

runSim(cases: None | int | Iterable[int] = None) None[source]

Run the full simulation.

Parameters:

cases (None | int | Iterable[int]) – The case numbers to run. If None, then all cases are run.

runIncompleteSim() None[source]

Run the full sim, but only the cases which previously failed to preprocess, run, or postprocess.

runSimWorker(casestogenerate: None | int | Iterable[int], casestopreprocess: None | int | Iterable[int], casestorun: None | int | Iterable[int], casestopostprocess: None | int | Iterable[int]) None[source]

The worker function to run the full sim.

Parameters:
  • casestogenerate (None | int | Iterable[int]) – The case numbers to generate. If None, then all cases are generated.

  • casestopreprocess (None | int | Iterable[int]) – The case numbers to preprocess. If None, then all cases are preprocessed.

  • casestorun (None | int | Iterable[int]) – The case numbers to run. If None, then all cases are run.

  • casestopostprocess (None | int | Iterable[int]) – The case numbers to postprocess. If None, then all cases are postprocessed.

genRunSimID() None[source]

Regenerate the unique ID for this simulation run.

genID() int[source]

Generate a unique ID based on the simulation seed, name, and current timestamp.

Returns:

uniqueid – A unique ID.

Return type:

int

genCases(cases: None | int | Iterable[int] = None) None[source]

Generate all the Monte Carlo case objects.

Parameters:

cases (None | int | Iterable[int]) – The case numbers to generate. If None, then all cases are generated.

genCaseSeeds() None[source]

Generate the random seeds for each of the random cases.

executeAllFcns(casestopreprocess: None | int | Iterable[int] = None, casestorun: None | int | Iterable[int] = None, casestopostprocess: None | int | Iterable[int] = None, calledfromrunsim: bool = False)[source]

Preprocess, run, and postprocess all the Monte Carlo cases.

Parameters:
  • casestopreprocess (None | int | Iterable[int]) – The case numbers to preprocess. If None, then all cases are preprocessed.

  • casestorun (None | int | Iterable[int]) – The case numbers to run. If None, then all cases are run.

  • casestopostprocess (None | int | Iterable[int]) – The case numbers to postprocess. If None, then all cases are postprocessed.

  • calledfromrunsim (bool, default: False) – Whether this was called from self.runSim(). If False, a new ID for this simulation run is generated.

preProcessCases(cases: None | int | Iterable[int] = None) None[source]

Preprocess all the Monte Carlo cases.

Parameters:

cases (None | int | Iterable[int]) – The case numbers to preprocess. If None, then all cases are preprocessed.

runCases(cases: None | int | Iterable[int] = None, calledfromrunsim: bool = False) None[source]

Run all the Monte Carlo cases.

Parameters:
  • cases (None | int | Iterable[int]) – The case numbers to run. If None, then all cases are run.

  • calledfromrunsim (bool, default: False) – Whether this was called from self.runSim(). If False, a new ID for this simulation run is generated.

postProcessCases(cases: None | int | Iterable[int] = None) None[source]

Postprocess all the Monte Carlo cases.

Parameters:

cases (None | int | Iterable[int]) – The case numbers to postprocess. If None, then all cases are postprocessed.

genOutVars(datasource: str | None = None) None[source]

Generate the output variables.

Parameters:

datasource (str, default: None) – If the outvals were imported from a file, this is the filepath. If generated through monaco, then None.

scalarOutVars() dict[str, OutVar][source]

Return a dict of just the scalar output variables.

calcSensitivities(outvarnames: None | str | Iterable[str] = None, tol: float = 1e-06, verbose: bool = False) None[source]

Calculate the sensitivity indices for the specified outvars.

Parameters:
  • outvarnames (None | str | Iterable[str] (default: None)) – The outvar names to calculate sensitivity indices for. If None, then calculates sensitivities for all scalar outvars.

  • tol (float, default 1e-6) – The convergence tolerance for scipy’s minimize function acting on the negative log likelihood function.

  • verbose (bool, default False) – Whether to print diagnostic information.

genCovarianceMatrix() None[source]

Generate the covariance matrix and correlation coefficients between all the scalar variables.

corr() tuple[ndarray, list[str]][source]

Generate a correlation matrix between all the scalar variables.

Returns:

(corcoeffs, covvarlist) – corrcoeffs is a correlation matrix between all the scalar input and output variables. covvarlist is a list of all the scalar input and output variables.

Return type:

(numpy.ndarray, list[str])

cov() tuple[ndarray, list[str]][source]

Generate a covariance matrix between all the scalar variables.

Returns:

(covs, covvarlist) – covs is a covariance matrix between all the scalar input and output variables. covvarlist is a list of all the scalar input and output variables.

Return type:

(numpy.ndarray, list[str])

plot(scalarvars: list[InVar | OutVar | str] | None = None, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, fig: Figure | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, tuple[Axes, ...]][source]

Plot all the scalar variables against each other in a grid.

Parameters:
  • scalarvars (list[monaco.mc_var.InVar | monaco.mc_var.OutVar | str]) – The variables to plot. If None, then grabs all the input variables and scalar output variables.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: False) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • fig (matplotlib.figure.Figure, default: None) – The figure handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, axes) – fig is the figure handle for the plot. axes is a tuple of the axes handles for the plots.

Return type:

(matplotlib.figure.Figure, (matplotlib.axes.Axes, …))

clearResults() None[source]

Clear all the simulation results.

reset() None[source]

Completely reset the simulation to the default object state.

downselectCases(cases: None | int | Iterable[int] = None) set[int][source]

Convert the cases input to a set of all the target cases.

Parameters:

cases (None | int | Iterable[int]) – The case numbers to downselect. If None, returns all cases.

Returns:

cases_downselect – A set of all the case numbers to use.

Return type:

set[int]

allCases() set[int][source]

Get a set of the indices for all the cases.

Returns:

allCases – A set of all the case numbers.

Return type:

set[int]

exportVars(vars: dict[str, InVar | OutVar], filename: str | Path | None) Path[source]

Export the nums for the selected to file for use externally.

The format for csv will be:

"vars[0].name", "vars[1].name", "vars[2].name", ...
vars[0].nums[0], vars[1].nums[0], vars[2].nums[0], ...
vars[0].nums[1], vars[1].nums[1], vars[2].nums[1], ...
...

The format for json will be:

{
    "vars[0].name": [vars[0].nums],
    "vars[1].name": [vars[1].nums],
    ...
}
Parameters:
  • vars (dict[str, InVar | OutVar]) – The vars to save to file. Will export the nums, not the vals.

  • filename (Optional[str | pathlib.Path]) – The file to save to. Must be a csv or json. If a str, then will save in the resultsdir.

Returns:

filepath – The filepath the vars were saved to.

Return type:

pathlib.Path

exportInVars(filename: str | Path | None = None) None[source]

Export the drawn nums for all the invars to file for use externally. See monaco.Sim.exportVars docstring for csv and json formatting.

Parameters:

filename (Optional[str | pathlib.Path]) – The file to save to. Must be a csv or json. If a str, then will save in the resultsdir. If None, then will save to ‘{self.name}_invarnums.json’.

exportOutVars(filename: str | Path | None = None) None[source]

Export the nums for all the outvars to file for use externally. See monaco.Sim.exportVars docstring for csv and json formatting.

Parameters:

filename (Optional[str | pathlib.Path]) – The file to save to. Must be a csv or json. If a str, then will save in the resultsdir. If None, then will save to ‘{self.name}_outvarnums.json’.

importVars(filepath: str | Path) tuple[dict[str, list[Any]], Path][source]

Import values from an external file.

The format for csv must be:

"vars[0].name", "vars[1].name", "vars[2].name", ...
vars[0].nums[0], vars[1].nums[0], vars[2].nums[0], ...
vars[0].nums[1], vars[1].nums[1], vars[2].nums[1], ...
...

The format for json must be:

{
    "vars[0].name": [vars[0].nums],
    "vars[1].name": [vars[1].nums],
    ...
}
Parameters:

filepath (str | pathlib.Path) – The file to load from. Must be a csv or json.

Returns:

  • data (dict[str, Any]) – A dictionary where the keys are the variable name and the values are a list of the vals.

  • filepath (pathlib.Path) – The full filepath for the file which was loaded from.

importInVars(filepath: str | Path, dists: list[rv_discrete | rv_continuous] | None = None, distskwargs: list[dict[str, Any]] | None = None, nummaps: list[dict[Any, float]] | None = None) None[source]

Import draws from an external file as InVals. For each of the keyword arguments, they must be the same length as the number of invars. See monaco.Sim.importVars docstring for csv and json formatting.

Parameters:
  • filepath (str | pathlib.Path) – The file to load from. Must be a csv or json.

  • dists (list[rv_discrete | rv_continuous], default: None) – A list of the distribution that was used for the draws. Needed if it is desired to plot the analytical distribution or run a DVARS sensitivity analysis. Note that for discrete distributions, the calcuated percentiles will not likely match the original draws.

  • distskwargs (list[dict[str, Any]], default: None) – A list of the distribution kwargs that were used for the draws. Must be matched with dists above.

  • nummaps (list[dict[Any, float]], default: None) – A list of nummap dicts mapping numbers to nonnumeric values.

importOutVars(filepath: str | Path, nummaps: list[dict[float, Any]] | None = None) None[source]

Import results from an external file as OutVals, convert to OutVars. See monaco.Sim.importVars docstring for csv and json formatting.

Parameters:
  • filepath (str | pathlib.Path) – The file to load from. Must be a csv or json.

  • nummaps (list[dict[float, Any]], default: None) – A list of nummap dicts mapping numbers to nonnumeric values. Note that this is reversed from providing valmaps to OutVals.

saveSimToFile() None[source]

Save the simulation to a .mcsim file

saveCasesToFile(cases: None | int | Iterable[int] = None) None[source]

Save the specified cases to .mccase files.

Parameters:

cases (None | int | Iterable[int]) – The cases to save. If None, save all cases.

loadCases() None[source]

Load the data for cases from file.

findExtraResultsFiles() set[str][source]

Find .mcsim and .mccase files that we don’t expect to see in the results directory.

Returns:

filenames – The extra files.

Return type:

set[str]

removeExtraResultsFiles() None[source]

Delete all unexpected .mcsim and .mccase files in the results directory.

Case

class monaco.mc_case.Case(ncase: int, ismedian: bool, invars: dict[str, InVar], constvals: dict[str, Any] | None = None, keepsiminput: bool = True, keepsimrawoutput: bool = True, seed: int = 2147483648)[source]

Object to hold all the data for a single Monte Carlo case.

Parameters:
  • ncase (int) – The number of this case.

  • ismedian (bool) – Whether this represents the median case.

  • invars (dict[str, monaco.mc_var.InVar]) – A dict pointing to all of the input variables.

  • constvals (dict[str, Any], default: None) – A dict of any constant values common to all cases.

  • keepsiminput (bool, default: True) – Whether to keep the siminput after running.

  • keepsimrawoutput (bool, default: True) – Whether to keep the simrawoutput after postprocessing.

  • seed (int, default: np.random.get_state(legacy=False)['state']['key'][0]) – The random seed to pass to the run function for this case. Not used in as part of any Monte Carlo sampling.

starttime[source]

Timestamp for when this case started running.

Type:

datetime.datetime

endtime[source]

Timestamp for when this case stopped running.

Type:

datetime.datetime

runtime[source]

Total run duration for this case.

Type:

datetime.timedelta

filepath[source]

The filepath for the case data, if saved to disk.

Type:

pathlib.Path

runsimid[source]

The id for the particular sim run this case was run for.

Type:

int

haspreprocessed[source]

Whether this case has been preprocessed.

Type:

bool

hasrun[source]

Whether this case has run the run function.

Type:

bool

haspostprocessed[source]

Whether this case has been postprocessed.

Type:

bool

invals[source]

The input values for this partitcular case.

Type:

dict[str, monaco.mc_val.InVal]

outvals[source]

The output values for this partitcular case.

Type:

dict[str, monaco.mc_val.OutVal]

siminput[source]

The preprocessed inputs provided to the run function for this case.

Type:

tuple[Any]

simrawoutput[source]

The non-postprocessed outputs from the run function for this case.

Type:

tuple[Any]

getInVals() dict[str, InVal][source]

From all the InVar’s, extract the vals for this case.

Returns:

vals – The InVal’s for this case.

Return type:

dict[str, monaco.mc_val.InVal]

getOutVals() dict[str, OutVal][source]

From all the OutVar’s, extract the vals for this case.

Returns:

vals – The OutVal’s for this case.

Return type:

dict[str, monaco.mc_val.OutVal]

addOutVal(name: str, val: Any, split: bool = True, valmap: dict[Any, float] | None = None) None[source]

Generate an OutVal and add it to the dict of outvals.

Parameters:
  • name (str) – The name of the output value.

  • val (Any) – The output value.

  • split (bool) – Whether to split the value into its components.

  • valmap (dict[Any, float], default: None) – A valmap dict mapping nonnumeric values to numbers.

Var

class monaco.mc_var.Var(name: str, ndraws: int, seed: int, firstcaseismedian: bool, datasource: str | None)[source]

Bases: ABC

Abstract base class to hold the data for a Monte Carlo variable.

Parameters:
  • name (str) – The name of this variable.

  • ndraws (int) – The number of random draws.

  • seed (int) – The random seed to use for bootstrapping.

  • firstcaseismedian (bool) – Whether the first case represents the median case.

  • datasource (str) – If the vals were imported from a file, this is the filepath. If generated through monaco, then None.

name[source]

The name of this variable.

Type:

str

ndraws[source]

The number of random draws.

Type:

int

seed[source]

The random seed to use for bootstrapping.

Type:

int

firstcaseismedian[source]

Whether the first case represents the median case.

Type:

bool

datasource[source]

If the vals were imported from a file, this is the filepath. If generated through monaco, then None.

Type:

str

ncases[source]

The number of cases, which is ndraws + 1 if firstcaseismedian and ndraws otherwise.

Type:

int

vals[source]

The values corresponding to the randomly drawn numbers. If valmap is None, then vals == nums.tolist().

Type:

list[Any]

valmap[source]

A dictionary mapping nonnumeric values to numbers (the inverse of nummap).

Type:

dict[Any, float]

nums[source]

The randomly drawn numbers obtained by feeding pcts into dist.

Type:

list[np.ndarray]

nummap[source]

A dictionary mapping numbers to nonnumeric values (the inverse of valmap).

Type:

dict[float, Any]

pcts[source]

The randomly drawn percentiles.

Type:

list[float]

maxdim[source]

The maximum dimension of the values.

Type:

int

isscalar[source]

Whether this is a scalar variable.

Type:

bool

varstats[source]

A list of all the variable statistics for this variable.

Type:

list[moncao.mc_varstat.VarStat]

setFirstCaseMedian(firstcaseismedian: bool) None[source]

Generate val based on the drawn number and the nummap.

Parameters:

firstcaseismedian (bool) – Whether the first case represents a median case.

stats() DescribeResult[source]

Calculates statistics of the variable nums from scipy.stats.describe.

Returns:

stats – A dict with descriptive statistics for the variable nums.

Return type:

DescribeResult

addVarStat(stat: VarStatType | Callable, statkwargs: dict[str, Any] | None = None, bootstrap: bool = False, bootstrap_k: int = 10, conf: float = 0.95, seed: int | None = None, name: str | None = None) None[source]

Add a variable statistic to this variable.

Parameters:
  • stat (monaco.mc_enums.VarStatType | Callable) – The type of variable statistic to add.

  • statkwargs (dict[str, Any]) – Keyword arguments for the specified variable stastistic.

  • seed (int) – The random seed to use for bootstrapping.

  • name (str) – The name of the variable statistic to add.

clearVarStats() None[source]

Remove all the variable statistics for this variable.

plot(vary: InVar | OutVar | None = None, varz: InVar | OutVar | None = None, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '') tuple[Figure, Axes][source]

Plot this variable, against other variables if desired. See monaco.mc_plot.plot() for API details.

class monaco.mc_var.InVar(name: str, ndraws: int, dist: rv_discrete | rv_continuous, distkwargs: dict | None = None, nummap: dict[float, Any] | None = None, samplemethod: SampleMethod = SampleMethod.SOBOL_RANDOM, ninvar: int | None = None, seed: int = 2147483648, firstcaseismedian: bool = False, autodraw: bool = True, datasource: str | None = None)[source]

Bases: Var

A Monte Carlo input variable.

Parameters:
  • name (str) – The name of this variable.

  • ndraws (int) – The number of random draws.

  • dist (scipy.stats.rv_discrete | scipy.stats.rv_continuous) – The statistical distribution to draw from.

  • distkwargs (dict) – The keyword argument pairs for the statistical distribution function.

  • nummap (dict[float, Any], default: None) – A dictionary mapping numbers to nonnumeric values (the inverse of valmap).

  • samplemethod (monaco.mc_enums.SampleMethod, default: 'sobol_random') – The random sampling method to use.

  • ninvar (int) – The number of the input variable this is.

  • seed (int, default: np.random.get_state(legacy=False)['state']['key'][0]) – The random seed for drawing this variable and bootstrapping.

  • firstcaseismedian (bool, default: False) – Whether the first case represents the median case.

  • autodraw (bool, default: True) – Whether to draw the random values when this variable is created.

  • datasource (str, default: None) – If the invals were imported from a file, this is the filepath. If generated through monaco, then None.

isscalar[source]

Whether this is a scalar variable. Alway True for an input variable.

Type:

bool

maxdim[source]

The maximum dimensions of the values. Always 0 for an input variable.

Type:

int

valmap[source]

A dictionary mapping nonnumeric values to numbers (the inverse of nummap).

Type:

dict[Any, float]

pcts[source]

The randomly drawn percentiles.

Type:

list[float]

nums[source]

The randomly drawn numbers obtained by feeding pcts into dist.

Type:

list[np.ndarry]

vals[source]

The values corresponding to the randomly drawn numbers. If valmap is None, then vals == nums.tolist()

Type:

list[Any]

varstats[source]

A list of all the variable statistics for this variable.

Type:

list[moncao.mc_varstat.VarStat]

mapNums() None[source]

Generate vals based on the drawn numbers and the nummap.

genValMap() None[source]

Generate valmap by inverting nummap.

setNDraws(ndraws: int) None[source]

Set the number of random draws.

Parameters:

ndraws (int) – The number of random input draws.

draw(ninvar_max: int | None = None) None[source]

Perform the random draws based on the sampling method and the statistical distribution, and map those draws to values.

Parameters:

ninvar_max (int) – The total number of input variables for the simulation.

getVal(ncase: int) InVal[source]

Get the input value for a specific case.

Parameters:

ncase (int) – The number of the case to get the value for.

Returns:

val – The input value for that case.

Return type:

monaco.mc_val.InVal

getDistMedian() float[source]

Get the median value for the statistical distribution.

Returns:

median – The median value of that distribution.

Return type:

float

getDistMean() float[source]

Get the mean value (also called the expected value) for the statistical distribution.

Returns:

mean – The mean value of that distribution.

Return type:

float

class monaco.mc_var.OutVar(name: str, vals: list[Any], valmap: dict | None = None, ndraws: int | None = None, seed: int = 2147483648, firstcaseismedian: bool = False, datasource: str | None = None)[source]

Bases: Var

A Monte Carlo output variable.

Parameters:
  • name (str) – The name of this value.

  • vals (list[Any]) – The values returned from the simulation.

  • valmap (dict, default: None) – A dictionary mapping nonnumeric values to numbers.

  • ndraws (int) – The number of random draws.

  • seed (int, default: np.random.get_state(legacy=False)['state']['key'][0]) – The random seed for bootstrapping.

  • firstcaseismedian (bool, default: False) – Whether the first case represents the median case.

  • datasource (str, default: None) – If the outvals were imported from a file, this is the filepath. If generated through monaco, then None.

isscalar[source]

Whether this is a scalar variable. Alway True for an input variable.

Type:

bool

maxdim[source]

The maximum dimension of the values. Always 0 for an input variable.

Type:

int

nummap[source]

A dictionary mapping numbers to nonnumeric values (the inverse of valmap).

Type:

dict

nums[source]

The numbers corresponding to the output values. If valmap is None, then nums == list[np.array(vals)].

Type:

list[np.ndarry]

varstats[source]

A list of all the variable statistics for this variable.

Type:

list[moncao.VarStat.VarStat]

genMaxDim() None[source]

Parse the output values to determine the maximum dimension of each of their shapes.

extractValMap() None[source]

Parse the output values and extract a valmap.

genNumMap() None[source]

Generate the nummap by inverting valmap.

mapVals() None[source]

Generate nums by mapping the values with their valmap.

getVal(ncase: int) OutVal[source]

Get the variable value for a specific case.

Parameters:

ncase (int) – The number of the case to get the value for.

Returns:

val – The output value.

Return type:

monaco.mc_val.OutVal

getMedianVal() OutVal[source]

Get the median value for this output variable if firstcaseismedian.

Returns:

val – The median output value.

Return type:

monaco.mc_val.OutVal

split() dict[str, OutVar][source]

Split a multidimentional output variable along its outermost dimension, and generate individual OutVar objects for each index.

Returns:

vars

Return type:

dict[str : monaco.mc_var.OutVar]

plotSensitivities(sensitivities: Sensitivities = Sensitivities.RATIOS, ax: Axes | None = None, title: str = '') tuple[Figure, Axes][source]

Plot the sensitivity indices for this variable. See monaco.mc_plot.plot_sensitivities() for API details.

Val

class monaco.mc_val.Val(name: str, ncase: int, ismedian: bool)[source]

Bases: ABC

Abstract base class to hold the data for a Monte Carlo value.

Parameters:
  • name (str) – The name of this value.

  • ncase (int) – The number of the case for this value.

  • ismedian (bool) – Whether this case represents the median case.

class monaco.mc_val.InVal(name: str, ncase: int, pct: float, num: float, dist: rv_discrete | rv_continuous, nummap: dict[float, Any] | None = None, ismedian: bool = False)[source]

Bases: Val

A Monte Carlo input value.

Parameters:
  • name (str) – The name of this value.

  • ncase (int) – The number of the case for this value.

  • pct (float) – The percentile of the value draw.

  • num (float) – The number corresponding to the statistical percentile draw.

  • dist (scipy.stats.rv_discrete | scipy.stats.rv_continuous) – The statistical distribution that num was drawn from.

  • nummap (dict[float, Any], default: None) – A dictionary mapping numbers to nonnumeric values.

  • ismedian (bool, default: False) – Whether this case represents the median case,

val[source]

The value corresponding to the drawn number. If nummap is None, then this is equal to num.

Type:

Any

isscalar[source]

Whether the value is scalar.

Type:

bool

shape[source]

The shape of the value.

Type:

tuple[int]

valmap[source]

A dictionary mapping nonnumeric values to numbers (the inverse of nummap).

Type:

dict[Any, float]

mapNum() None[source]

Generate val based on the drawn number and the nummap.

genValMap() None[source]

Generate the valmap based on the nummap.

class monaco.mc_val.OutVal(name: str, ncase: int, val: Any, valmap: dict[Any, float] | None = None, ismedian: bool = False)[source]

Bases: Val

A Monte Carlo output value.

Parameters:
  • name (str) – The name of this value.

  • ncase (int) – The number of the case for this value.

  • val (float) – The output value.

  • valmap (dict[Any, float], default: None) – A dictionary mapping nonnumeric values to numbers.

  • ismedian (bool, default: False) – Whether this case represents the median case,

num[source]

A number corresponding to the output value. If valmap is None and val is nonnumeric, then will be an integer as assigned by extractValMap().

Type:

np.array

valmapsource[source]

Either ‘assigned’ or ‘auto’ based on whether a valmap was passed in.

Type:

str

isscalar[source]

Whether the value is scalar.

Type:

bool

shape[source]

The shape of the value.

Type:

tuple[int]

nummap[source]

A dictionary mapping numbers to nonnumeric values (the inverse of valmap).

Type:

dict[float, Any]

convertPandas() None[source]

If the output value is a pandas dataseries or index, convert it to a format we understand.

genShape() None[source]

Calculate the shape of the output value, and whether it is a scalar.

extractValMap() None[source]

Parse the output value and extract a valmap.

mapVal() None[source]

Map the output value to a number or array of numbers.

genNumMap() None[source]

Invert the valmap to get a nummap.

split() dict[str, OutVal][source]

Split a multidimentional output value along its outermost dimension, and generate individual OutVal objects for each index.

Returns:

vals

Return type:

dict[str : monaco.mc_val.OutVal]

VarStat

class monaco.mc_varstat.VarStat(var: Var, stat: str | VarStatType | Callable, statkwargs: dict[str, Any] | None = None, bootstrap: bool = True, bootstrap_k: int = 10, conf: float = 0.95, seed: int = 2147483648, name: str | None = None)[source]

A variable statistic for a Monte Carlo variable.

Parameters:
  • var (monaco.mc_var.Var) – The variable to generate statistics for.

  • stat (monaco.mc_enums.VarStatType | Callable) – The statistic to generate. Can be custom. If custom, must be able to accept an “axis” kwarg for bootstrap vectorization.

  • statkwargs (dict[str:Any]) – The keyword arguments for the variable statistic.

  • bootstrap (bool (default: True)) – Whether to use bootstrapping to generate confidence intervals for the statistic.

  • bootstrap_k (int (default: 10)) – The k’th order statistic to determine the number of bootstrap draws for the given confidence level. Must be >= 1. Set higher for a smoother bootstrap distribution.

  • conf (float (default: 0.95)) – The confidence level for the confidence interval.

  • seed (int (default: np.random.get_state(legacy=False)['state']['key'][0])) – The random seed to use for bootstrapping.

  • name (str) – The name of the variable statistic.

nums[source]

The output of the variable statistic function applied to var.nums

Type:

numpy.ndarray

confidence_interval_low_nums[source]

The nums for the low side of the confidence interval (None if no CI).

Type:

numpy.ndarray

confidence_interval_high_nums[source]

The nums for the high side of the confidence interval (None if no CI).

Type:

numpy.ndarray

vals[source]

The values for the nums as determined by var.nummap

Type:

list[Any]

confidence_interval_low_vals[source]

The values for confidence_interval_low_nums via var.nummap

Type:

list[Any]

confidence_interval_high_vals[source]

The values for confidence_interval_high_nums via var.nummap

Type:

list[Any]

bootstrap_n[source]

The number of bootstrap samples.

Type:

int

Notes

These are the valid stats with their statkwargs

max()

‘max’, no kwargs

min()

‘min’, no kwargs

median()

‘median’, no kwargs

mean()

‘mean’, no kwargs

geomean()

‘geomean’, no kwargs

mode()

‘mode’, no kwargs

variance()

‘variance’, no kwargs

skewness()

‘skewness’, no kwargs

kurtosis()

‘kurtosis’, no kwargs

moment(nint)

‘moment’ n is the n’th moment, n > 0.

percentile(pfloat)

‘percentile’ p is the percentile, 0 < p < 1.

sigma(sigfloat, boundmonaco.mc_enums.StatBound)

‘sigma’ sig is the gaussian sigma value, -inf < sig < inf.

bound is the statistical bound, ether ‘1-sided’ or ‘2-sided’. Default is ‘2-sided’.

gaussianP(pfloat, boundmonaco.mc_enums.StatBound)

‘gaussianP’ p is the percentile, 0 < p < 1.

bound is the statistical bound, ether ‘1-sided’ or ‘2-sided’. Default is ‘2-sided’.

orderstatTI(pfloat, cfloat, boundmonaco.mc_enums.StatBound)

‘orderstatTI’ p is the percentage, 0 < p < 1

c is the confidence, 0 < c < 1. Default is 0.95.

bound is the statistical bound, ether ‘1-sided’, ‘2-sided’, or ‘all’. Default is ‘2-sided’.

orderstatP(pfloat, cfloat, boundmonaco.mc_enums.StatBound)

‘orderstatP’ p is the percentage, 0 < p < 1

c is the confidence, 0 < c < 1. Default is 0.95.

bound is the statistical bound, ether ‘1-sided lower’, ‘1-sided upper’, ‘2-sided’, ‘all’, or ‘nearest’. Default is ‘2-sided’.

genStatsMoment() None[source]

Get the n’th moment about the mean of the variable.

genStatsPercentile() None[source]

Get the value of the variable at the inputted percentile.

genStatsSigma() None[source]

Get the value of the variable at the inputted sigma value, assuming a gaussian distribution.

genStatsGaussianP() None[source]

Get the value of the variable at the inputted percentile value, assuming a gaussian distribution.

sigma(x, sig: float, axis: int | None = None) float[source]

Calculate the sigma value of a normally distributed list of numbers.

Parameters:
  • x (TODO typing) – The numbers to calculate the sigma value for.

  • sig (float) – The sigma value.

  • axis (int (default: None)) – The axis of x to calculate along.

statsFunctionWrapper(x: Any, axis: int | None = None) Any[source]

A wrapper function to allow using a bootstrap function that uses kwargs. Relies on self.fcn and self.fcnkwargs already being set. Note that fcn must accept an axis kwarg if bootstrapping.

Parameters:
  • x (Any) – The input for the function.

  • axis (int (default: None)) – The axis of x to calculate along.

genStatsFunction(fcn: Callable, fcnkwargs: dict[str, Any] | None = None) None[source]

A wrapper function to generate statistics via a generic function.

Parameters:
  • fcn (Callable) – The function used to generate the desired statistics.

  • fcnkwargs (dict[str, Any]) – The keyword arguments for the function.

genStatsOrderStatTI() None[source]

Get the order statistic tolerance interval value of the variable.

genStatsOrderStatP() None[source]

Get the order statistic percentile value of the variable.

checkOrderStatsKWArgs() None[source]

Check the order statistic keyword arguments.

setName(name: str) None[source]

Set the name for this variable statistic.

Parameters:

name (str) – The new name.

Enums

class monaco.mc_enums.SampleMethod(value)[source]

Enum for the possible Monte Carlo sampling methods.

RANDOM = 'random'[source]
SOBOL = 'sobol'[source]
SOBOL_RANDOM = 'sobol_random'[source]
HALTON = 'halton'[source]
HALTON_RANDOM = 'halton_random'[source]
LATIN_HYPERCUBE = 'latin_hypercube'[source]
class monaco.mc_enums.SimFunctions(value)[source]

Enum for the three required user functions.

Notes

The preprocess function must take in only a moncao.mc_case.Case object. It then must return a tuple of the input arguments for the run function. The run function will take in whatever inputs and return whatever outputs. It it recommended to package the outputs into a tuple. The postprocess function must take in as its first argument a moncao.mc_case.Case object, followed by the outputs from the run function. The simulation will attempt to unpack the run function outputs if they are stored in a tuple.

See https://github.com/scottshambaugh/monaco/blob/main/template/template_functions.py for an example of this.

PREPROCESS = 'preprocess'[source]
RUN = 'run'[source]
POSTPROCESS = 'postprocess'[source]
class monaco.mc_enums.StatBound(value)[source]

Enum for possible statistical bounds. Note that not all of these may be valid for a given statistical function.

NEAREST = 'nearest'[source]
BOTH = 'both'[source]
ALL = 'all'[source]
ONESIDED = '1-sided'[source]
TWOSIDED = '2-sided'[source]
ONESIDED_UPPER = '1-sided upper'[source]
ONESIDED_LOWER = '1-sided lower'[source]
class monaco.mc_enums.VarStatType(value)[source]

Enum for the variable statistics functions.

MAX = 'max'[source]
MIN = 'min'[source]
MEDIAN = 'median'[source]
MEAN = 'mean'[source]
GEOMEAN = 'geomean'[source]
MODE = 'mode'[source]
VARIANCE = 'variance'[source]
SKEWNESS = 'skewness'[source]
KURTOSIS = 'kurtosis'[source]
MOMENT = 'moment'[source]
PERCENTILE = 'percentile'[source]
SIGMA = 'sigma'[source]
GAUSSIANP = 'gaussianp'[source]
ORDERSTATTI = 'orderstatti'[source]
ORDERSTATP = 'orderstatp'[source]
class monaco.mc_enums.VarStatSide(value)[source]

Enum for the variable statistics ‘side’ (see documentation for each varstat function).

HIGH = 'high'[source]
LOW = 'low'[source]
BOTH = 'both'[source]
ALL = 'all'[source]
class monaco.mc_enums.PlotOrientation(value)[source]

Enum for the plotting functions orientation.

VERTICAL = 'vertical'[source]
HORIZONTAL = 'horizontal'[source]
class monaco.mc_enums.InVarSpace(value)[source]

Enum for whether to plot invars in number or percentile space.

NUMS = 'nums'[source]
PCTS = 'pcts'[source]
class monaco.mc_enums.Sensitivities(value)[source]

Enum for whether to plot invars in number or percentile space.

INDICES = 'indices'[source]
RATIOS = 'ratios'[source]

Functions

helper_functions

monaco.helper_functions.next_power_of_2(x: int) int[source]

Returns the next power of two greater than or equal to the input.

Parameters:

x (int) – The input number.

Returns:

nextpow2 – The next power of two, nextpow2 >= x.

Return type:

int

monaco.helper_functions.hash_str_repeatable(s: str) int[source]

By default, string hashing in python is randomized. This function returns a repeatable non-randomized hash for strings. See: https://docs.python.org/3/using/cmdline.html#cmdoption-R

Parameters:

s (str) – The string to hash.

Returns:

s_hash – The hash of str.

Return type:

int

monaco.helper_functions.hashable_val(val: Any) Any[source]

For nummap and valmap, we need to use values as keys in a dictionary. This function will return the string representation of a value if that value is not hashable.

Parameters:

val (Any) – The value to hash.

Returns:

hashable_val – A hashable representation of the val.

Return type:

Any

monaco.helper_functions.is_num(val: Any) bool[source]

Type checking function to see if the input is a number.

Parameters:

val (Any) – The value to check.

Returns:

isnum – Returns True if the input is a number, False otherwise.

Return type:

bool

monaco.helper_functions.length(x: Any) int | None[source]

Genericized length function that works on scalars (which have length 1).

Parameters:

x (Any) – The value to check.

Returns:

x_len – The length of the input. If not a sequence or scalar, returns None.

Return type:

int

monaco.helper_functions.get_list(x: Any) list[Any][source]

Converts the input to an iterable list.

Parameters:

x (Any) – The object to convert.

Returns:

x_list – A list conversion of the input.

Return type:

list

monaco.helper_functions.slice_by_index(sequence: Sequence[Any], indices: int | Iterable[int]) list[source]

Returns a slice of a sequence at the specified indices.

Parameters:
  • sequence (Sequence) – The sequence to slice.

  • indices (int | Iterable) – The indices to slice at.

Returns:

slice – A list representing the values of the input sequence at the specified indices.

Return type:

list

monaco.helper_functions.vprint(verbose: bool, *args, **kwargs) None[source]

Print only if verbose is True.

Parameters:
  • verbose (bool) – Flag to determine whether to print something.

  • *args – Must include something to print here!

  • **kwargs – Must include something to print here!

monaco.helper_functions.warn_short_format(message, category, filename, lineno, file=None, line=None) str[source]

Custom warning format for use in vwarn()

monaco.helper_functions.vwarn(verbose: bool, *args, **kwargs) None[source]

Warn only if verbose is True.

Parameters:
  • verbose (bool) – Flag to determine whether to print something.

  • *args – Must include a warning message here!

  • **kwargs – Must include a warning message here!

monaco.helper_functions.vwrite(verbose: bool, *args, **kwargs) None[source]

Perform a tqdm.write() only if verbose is True.

Parameters:
  • verbose (bool) – Flag to determine whether to write something.

  • *args – Must include something to write here!

  • **kwargs – Must include something to write here!

monaco.helper_functions.timeit(fcn: Callable)[source]

Function decorator to print out the function runtime in milliseconds.

Parameters:

fcn (Callable) – Function to time.

monaco.helper_functions.empty_list() list[source]

Sentinel for default arguments being an empty list.

Returns:

empty_list – An empty list.

Return type:

list

monaco.helper_functions.flatten(nested_x: Iterable[Any]) list[Any][source]

Flattens a nested interable into a list with all nested items.

Parameters:

nested_x (Iterable) – Nested iterable.

Returns:

flattened_x – The nested iterable flattened into a list.

Return type:

list

sampling

monaco.mc_sampling.sampling(ndraws: int, method: SampleMethod = SampleMethod.SOBOL_RANDOM, ninvar: int | None = None, ninvar_max: int | None = None, seed: int = 2147483648) ndarray[source]

Draws random samples according to the specified method.

Parameters:
  • ndraws (int) – The number of samples to draw.

  • method (monaco.mc_enums.SampleMethod) – The sample method to use.

  • ninvar (int) – For all but the ‘random’ method, must define which number input variable is being sampled, ninvar >= 1. The ‘sobol’ and ‘sobol_random’ methods must have ninvar <= 21201

  • ninvar_max (int) – The total number of invars, ninvar_max >= ninvar. Used for caching.

  • seed (int, default: np.random.get_state(legacy=False)['state']['key'][0]) – The random seed. Not used in ‘sobol’ or ‘halton’ methods.

Returns:

pcts – The random samples. Each sample is 0 <= pct <= 1.

Return type:

numpy.ndarray

monaco.mc_sampling.cached_pcts(ndraws: int, method: str, ninvar_max: int, scramble: bool, seed: int) ndarray[source]

Wrapper function to cache the qmc draws so that we don’t repeat calculation of lower numbered invars for the higher numbered invars.

Parameters:
  • ndraws (int) – The number of samples to draw.

  • method (monaco.mc_enums.SampleMethod) – The sample method to use.

  • ninvar_max (int) – The total number of invars.

  • scramble (bool) – Whether to scramble the sobol or halton points. Should only be True if method is in {‘sobol_random’, ‘halton_random’}

  • seed (int) – The random seed. Not used in ‘sobol’ or ‘halton’ methods.

Returns:

all_pcts – The random samples. Each sample is 0 <= pct <= 1.

Return type:

numpy.ndarray

plot

monaco.mc_plot.plot(varx: InVar | OutVar, vary: InVar | OutVar = None, varz: InVar | OutVar = None, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Umbrella function to make single plots of a single Monte Carlo variable or pairs or triplets of variables.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar, default: None) – The y variable to plot.

  • varz (monaco.mc_var.InVar | monaco.mc_var.OutVar, default: None) – The z variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: True) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_hist(var: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], cumulative: bool = False, orientation: PlotOrientation = PlotOrientation.VERTICAL, rug_plot: bool = True, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot a histogram of a single variable.

Parameters:
  • var (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • cumulative (bool, default: False) – Whether to plot the histograms as cumulative distribution functions.

  • orientation (monaco.mc_enums.PlotOrientation, default: 'vertical') – The orientation of the histogram. Either ‘vertical’ or ‘horizontal’.

  • rug_plot (bool, default: True) – Whether to plot rug marks.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_cdf(var: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], orientation: PlotOrientation = PlotOrientation.VERTICAL, rug_plot: bool = True, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot a cumulative distribution of a single variable.

Parameters:
  • var (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • orientation (monaco.mc_enums.PlotOrientation, default: 'vertical') – The orientation of the histogram. Either ‘vertical’ or ‘horizontal’.

  • rug_plot (bool, default: True) – Whether to plot rug marks.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_2d_scatter(varx: InVar | OutVar, vary: InVar | OutVar, varz: InVar | OutVar = None, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot a scatter plot of two variables.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The y variable to plot.

  • varz (monaco.mc_var.InVar | monaco.mc_var.OutVar, default: None) – If not None, then sets the values for the underlying contour plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are highlighted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: True) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_2d_line(varx: InVar | OutVar, vary: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot an ensemble of 2D lines for two nonscalar variables.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The y variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are highlighted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_3d_scatter(varx: InVar | OutVar, vary: InVar | OutVar, varz: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot a scatter plot of three variables in 3D space.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The y variable to plot.

  • varz (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The z variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are highlighted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_2p5d_line(varx: InVar | OutVar, vary: InVar | OutVar, varz: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot an ensemble of 2.5D lines for one scalar and two nonscalar variables.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The y variable to plot.

  • varz (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The z variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are highlighted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_3d_line(varx: InVar | OutVar, vary: InVar | OutVar, varz: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot an ensemble of 3D lines for three nonscalar variables.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The y variable to plot.

  • varz (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The z variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are highlighted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_cov_corr(matrix: ndarray, varnames: list[str], ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

Plot either a covariance or correlation matrix.

Parameters:
  • matrix (numpy.ndarray) – The covariance or correlation matrix.

  • varnames (list[str]) – A list of the variable names.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_integration_convergence(outvar: OutVar, dimension: int, volume: float, refval: float = None, conf: float = 0.95, samplemethod: SampleMethod = SampleMethod.RANDOM, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

For a Monte Carlo integration, plot the running integration estimate along with error bars for a given confidence level.

Parameters:
  • outvar (monaco.mc_var.OutVar) – The variable representing the integration estimate.

  • dimension (int) – The number of dimensions over which the integration was performed.

  • volume (float) – The total integration volume.

  • refval (float, default: None) – If known a-priori, the reference value for the integration.

  • conf (float, default: 0.95) – The confidence level for the error estimate. 0.95 corresponds to 95%.

  • samplemethod (monaco.mc_enums.SampleMethod) – The sample method used for integration. Either ‘random’ or ‘sobol’.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_integration_error(outvar: OutVar, dimension: int, volume: float, refval: float, conf: float = 0.95, samplemethod: SampleMethod = SampleMethod.RANDOM, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

For a Monte Carlo integration where the reference value is known, plot the running integration error along with error bounds for a given confidence level.

Parameters:
  • outvar (monaco.mc_var.OutVar) – The variable representing the integration estimate.

  • dimension (int) – The number of dimensions over which the integration was performed.

  • volume (float) – The total integration volume.

  • refval (float) – The reference value for the integration.

  • conf (float, default: 0.95) – The confidence level for the error estimate. 0.95 corresponds to 95%.

  • samplemethod (monaco.mc_enums.SampleMethod) – The sample method used for integration. Either ‘random’ or ‘sobol’.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.plot_sensitivities(outvar: OutVar, sensitivities: Sensitivities = Sensitivities.RATIOS, sort: bool = True, ax: Axes | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, Axes][source]

For a Monte Carlo integration where the reference value is known, plot the running integration error along with error bounds for a given confidence level.

Parameters:
  • outvar (monaco.mc_var.OutVar) – The variable representing the integration estimate.

  • sensitivities (monaco.mc_enums.Sensitivities, default: 'ratios') – The sensitivities to plot. Either ‘ratios’ or ‘indices’.

  • sort (bool, default: True) – Whether to show the sensitivity indices sorted from greatest to least.

  • ax (matplotlib.axes.Axes, default: None) – The axes handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.manage_axis(ax: Axes | None, is3d: bool = False) tuple[Figure, Axes][source]

Set the target axis, either by making a new figure or setting active an existing axis.

Parameters:
  • ax (matplotlib.axes.Axes) – The target axis. If None, a new figure is created.

  • is3d (bool, default: False) – If creating a new figure, whether the plot is a 3D plot.

Returns:

(fig, ax) – fig is the figure handle for the plot. ax is the axes handle for the plot.

Return type:

(matplotlib.figure.Figure, matplotlib.axes.Axes)

monaco.mc_plot.apply_category_labels(ax: Axes, varx: InVar | OutVar | None = None, vary: InVar | OutVar | None = None, varz: InVar | OutVar | None = None) None[source]

For nonnumeric Monte Carlo variables, use the nummap to label the axes.

Parameters:
monaco.mc_plot.get_hist_lim(ax: Axes, orientation: PlotOrientation) tuple[float, float][source]

Get the axis limits for a histogram.

Parameters:
  • ax (matplotlib.axes.Axes) – The target axis.

  • orientation (PlotOrientation) – The orientation of the histogram plot, either ‘vertical’ or ‘horizontal’.

Returns:

lim – Returns the (low, high) limits of the axis.

Return type:

(float, float)

monaco.mc_plot.plot_rug_marks(ax: Axes, orientation: PlotOrientation, nums: Iterable[float]) None[source]

Plot rug marks for a histogram or scatter plot.

Parameters:
  • ax (matplotlib.axes.Axes) – The target axis.

  • orientation (PlotOrientation) – The orientation of the plot, either ‘vertical’ or ‘horizontal’.

  • nums (Iterable[float]) – The numbers to plot the rug marks at.

monaco.mc_plot.plot_2d_cov_ellipse(ax: Axes, varx: InVar | OutVar, vary: InVar | OutVar, p: float) None[source]

Add a covariance ellipse to a 2D scatter plot.

Parameters:
monaco.mc_plot.get_cases(ncases: int, cases: None | int | Iterable[int]) list[int][source]

Parse the cases input for plotting functions. If None, return a list of all the cases. Otherwise, return a list of all the specified cases.

Parameters:
  • ncases (int) – The total number of cases.

  • cases (None | int | Iterable[int]) – The cases to downselect to.

Returns:

cases_list – The cases.

Return type:

list[int]

monaco.mc_plot.manage_invar_space(invar_space: InVarSpace | Iterable[InVarSpace], nvars: int) list[InVarSpace][source]

Parse the invarspace input for plotting functions. If already an iterable of the right length, passes through. If a single value, returns a list of the invarspace of the right length.

Parameters:
  • invar_space (monaco.InVarSpace | Iterable[InVarSpace]) – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • nvars (int) – The length of the list to generate.

Returns:

invar_space_list – A list of length nvars for the desired InVarSpace’s.

Return type:

list[InVarSpace]

monaco.mc_plot.get_plot_points(var: InVar | OutVar, invar_space: InVarSpace) list[float][source]

Get the points to plot based on the invar_space. Returns var.nums, unless var is an InVar and invar_space is ‘pcts’ in which case it returns var.pcts.

Parameters:
  • nvars (InVar | OutVar) – The target variable.

  • invar_space (monaco.InVarSpace) – The space to plot the invars in.

Returns:

plot_points – The points to plot.

Return type:

list[float]

monaco.mc_plot.get_var_steps(var: InVar | OutVar) OutVar[source]

For a 1D variable, get an OutVar that has as values the simulation sets.

Parameters:

var (InVar | OutVar) – The target variable.

Returns:

varsteps – The variable with simulation steps as values.

Return type:

OutVar

multi_plot

monaco.mc_multi_plot.multi_plot(vars: list[InVar | OutVar], cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, fig: Figure | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, tuple[Axes, ...]][source]

Umbrella function to make more complex plots of Monte Carlo variables.

Parameters:
  • vars (list[monaco.mc_var.InVar | monaco.mc_var.OutVar]) – The variables to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: False) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • fig (matplotlib.figure.Figure, default: None) – The figure handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, axes) – fig is the figure handle for the plot. axes is a tuple of the axes handles for the plots.

Return type:

(matplotlib.figure.Figure, (matplotlib.axes.Axes, …))

monaco.mc_multi_plot.multi_plot_2d_scatter_hist(varx: InVar | OutVar, vary: InVar | OutVar, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = True, cov_p: None | float | Iterable[float] = None, cumulative: bool = False, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, fig: Figure | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, tuple[Axes, ...]][source]

Plot two variables against each other with a central scatterplot and two histograms along the x and y axes.

Parameters:
  • varx (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The x variable to plot.

  • vary (monaco.mc_var.InVar | monaco.mc_var.OutVar) – The y variable to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: False) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • cumulative (bool, default: False) – Whether to plot the histograms as cumulative distribution functions.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • fig (matplotlib.figure.Figure, default: None) – The figure handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

  • (fig, (ax1, ax2, ax3)) ((matplotlib.figure.Figure,)

  • (matplotlib.axes.Axes, matplotlib.axes.Axes, matplotlib.axes.Axes)) – fig is the figure handle for the plot. (ax1, ax2, ax3) are the axes handles for the central, y-axis, and x-axis plots, respectively.

monaco.mc_multi_plot.multi_plot_grid_tri(vars: list[InVar | OutVar], cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, cumulative: bool = False, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, fig: Figure | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, tuple[Axes, ...]][source]

Plot multiple variables against each other in a triangular grid. The off-diagonal grid locations show scatterplots of the two corresponding variables. The plots along the diagonal show histograms for the corresponding variables.

Parameters:
  • vars (list[monaco.mc_var.InVar | monaco.mc_var.OutVar]) – The variables to plot.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: False) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • cumulative (bool, default: False) – Whether to plot the histograms as cumulative distribution functions.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • fig (matplotlib.figure.Figure, default: None) – The figure handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, axes) – fig is the figure handle for the plot. axes is a tuple of the axes handles for the plots, starting from the top-left corner and working left-to-right, then top-to-bottom.

Return type:

(matplotlib.figure.Figure, (matplotlib.axes.Axes, …))

monaco.mc_multi_plot.multi_plot_grid_rect(varsx: InVar | OutVar | list[InVar | OutVar], varsy: InVar | OutVar | list[InVar | OutVar] | None = None, cases: None | int | Iterable[int] = None, highlight_cases: None | int | Iterable[int] = [], rug_plot: bool = False, cov_plot: bool = False, cov_p: None | float | Iterable[float] = None, cumulative: bool = False, invar_space: InVarSpace | Iterable[InVarSpace] = InVarSpace.NUMS, fig: Figure | None = None, title: str = '', plotkwargs: dict = {}) tuple[Figure, tuple[Axes, ...]][source]

Plot multiple variables against each other in a rectangual grid. The left column and bottom row show histograms for each variable, and the middle grid locations show the scatter plots between each pari of variables.

Parameters:
  • varsx (monaco.mc_var.InVar | monaco.mc_var.OutVar | list[InVar | OutVar]) – The variables to plot along the X axis.

  • varsy (monaco.mc_var.InVar | monaco.mc_var.OutVar | list[InVar | OutVar]) – The variables to plot along the Y axis.

  • cases (None | int | Iterable[int], default: None) – The cases to plot. If None, then all cases are plotted.

  • highlight_cases (None | int | Iterable[int], default: []) – The cases to highlight. If [], then no cases are highlighted.

  • rug_plot (bool, default: False) – Whether to plot rug marks.

  • cov_plot (bool, default: False) – Whether to plot a covariance ellipse at a certain gaussian percentile level.

  • cov_p (None | float | Iterable[float], default: None) – The gaussian percentiles for the covariance plot.

  • cumulative (bool, default: False) – Whether to plot the histograms as cumulative distribution functions.

  • invar_space (monaco.InVarSpace | Iterable[InVarSpace], default: 'nums') – The space to plot invars in, either ‘nums’ or ‘pcts’. If an iterable, specifies this individually for each of varx, vary, and varz.

  • fig (matplotlib.figure.Figure, default: None) – The figure handle to plot in. If None, a new figure is created.

  • title (str, default: '') – The figure title.

Returns:

(fig, axes) – fig is the figure handle for the plot. axes is a tuple of the axes handles for the plots, starting from the top-left corner and working left-to-right, then top-to-bottom.

Return type:

(matplotlib.figure.Figure, (matplotlib.axes.Axes, …))

monaco.mc_multi_plot.handle_fig(fig: Figure | None) Figure[source]

Set the target figure, either by making a new figure or setting active an existing one.

Parameters:

fig (matplotlib.figure.Figure) – The target figure. If None, a new figure is created.

Returns:

fig – The active figure.

Return type:

matplotlib.figure.Figure

gaussian_statistics

monaco.gaussian_statistics.pct2sig(p: float, bound: StatBound = StatBound.TWOSIDED) float[source]

Converts a percentile to a gaussian sigma value (1-sided), or to the sigma value for which the range (-sigma, +sigma) bounds that percent of the normal distribution (2-sided).

Parameters:
  • p (float) – The percentile to convert, 0 < p < 1.

  • bound (monaco.mc_enums.StatBound) – The statistical bound, either ‘1-sided’ or ‘2-sided’.

Returns:

sig – The gaussian sigma value for the input percentile.

Return type:

float

monaco.gaussian_statistics.sig2pct(sig: float, bound: StatBound = StatBound.TWOSIDED) float[source]

Converts a gaussian sigma value to a percentile (1-sided), or to the percent of the normal distribution bounded by (-sigma, +sigma) (2-sided).

Parameters:
  • sig (float) – The gaussian sigma value to convert.

  • bound (monaco.mc_enums.StatBound) – The statistical bound, either ‘1-sided’ or ‘2-sided’.

Returns:

p – The corresponding percentile or percent, 0 < p < 1.

Return type:

float

monaco.gaussian_statistics.conf_ellipsoid_pct2sig(p: float, df: int) float[source]

Converts a percentile to a sigma value which bounds a df-dimensional gaussian distribution, used in generating confidence ellipsoids. Note that in the 1-D case, np.sqrt(scipy.stats.chi2.ppf(p, df=1)) is equivalent to pct2sig(p >= 0.5, bound = ‘2-sided’) == scipy.stats.norm.ppf(1-(1-p)/2)

Parameters:
  • p (float) – The percentile to convert, 0 < p < 1.

  • df (int) – The degrees of freedom, df > 0.

Returns:

sig – The gaussian sigma value for the input percentile.

Return type:

float

monaco.gaussian_statistics.conf_ellipsoid_sig2pct(sig: float, df: int) float[source]

Converts a sigma value which bounds a df-dimensional gaussian distribution, to a percentil used in generating confidence ellipsoids. Note that in the 1-D case, scipy.stats.chi2.cdf(sig**2, df=1) is equivalent to sig2pct(sig > 0, bound=’2-sided) == 1-(1-scipy.stats.norm.cdf(sig))*2

Parameters:
  • sig (float) – The gaussian sigma value to convert, sig > 0.

  • df (int) – The degrees of freedom, df > 0.

Returns:

p – The corresponding percentile, 0 < p < 1.

Return type:

float

order_statistics

monaco.order_statistics.order_stat_TI_n(k: int, p: float, c: float, nmax: int = 10000000, bound: StatBound = StatBound.TWOSIDED) int[source]

For an Order Statistic Tolerance Interval, find the minimum n from k, p, and c

Notes

This function returns the number of cases n necessary to say that the true result of a measurement x will be bounded by the k’th order statistic with a probability p and confidence c. Variables l and u below indicate lower and upper indices of the order statistic.

For example, if I want to use my 2nd highest measurement as a bound on 99% of all future samples with 90% confidence:

n = order_stat_TI_n(k=2, p=0.99, c=0.90, bound='1-sided') = 389

The 388th value of x when sorted from low to high, or sorted(x)[-2], will bound the upper end of the measurement with P99/90.

‘2-sided’ gives the result for the measurement lying between the k’th lowest and k’th highest measurements. If we run the above function with bound=’2-sided’, then n = 668, and we can say that the true measurement lies between sorted(x)[1] and sorted(x)[-2] with P99/90.

See chapter 5 of Reference [1] for statistical background.

Parameters:
  • k (int) – The k’th order statistic.

  • p (float (0 < p < 1)) – The percent covered by the tolerance interval.

  • c (float (0 < c < 1)) – The confidence of the interval bound.

  • nmax (int, default: 1e7) – The maximum number of draws. Hard limit of 2**1000.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, either ‘1-sided’ or ‘2-sided’.

Returns:

n – The number of samples necessary to meet the constraints.

Return type:

int

References

monaco.order_statistics.order_stat_TI_p(n: int, k: int, c: float, ptol: float = 1e-09, bound: StatBound = StatBound.TWOSIDED) float[source]

For an Order Statistic Tolerance Interval, find the maximum p from n, k, and c.

Parameters:
  • n (int) – The number of samples.

  • k (int) – The k’th order statistic.

  • c (float (0 < c < 1)) – The confidence of the interval bound.

  • ptol (float, default: 1e-9) – The absolute tolerance on determining p.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, either ‘1-sided’ or ‘2-sided’.

Returns:

p – The percent which the tolerance interval covers corresponding to the input constraints.

Return type:

float (0 < p < 1)

monaco.order_statistics.order_stat_TI_k(n: int, p: float, c: float, bound: StatBound = StatBound.TWOSIDED) int[source]

For an Order Statistic Tolerance Interval, find the maximum k from n, p, and c.

Parameters:
  • n (int) – The number of samples.

  • p (float (0 < p < 1)) – The percent covered by the tolerance interval.

  • c (float (0 < c < 1)) – The confidence of the interval bound.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, either ‘1-sided’ or ‘2-sided’.

Returns:

k – The k’th order statistic.

Return type:

int

monaco.order_statistics.order_stat_TI_c(n: int, k: int, p: float, bound: StatBound = StatBound.TWOSIDED) float[source]

For an Order Statistic Tolerance Interval, find the maximum c from n, k, and p.

Parameters:
  • n (int) – The number of samples.

  • k (int) – The k’th order statistic.

  • p (float (0 < p < 1)) – The percent covered by the tolerance interval.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, either ‘1-sided’ or ‘2-sided’.

Returns:

c – The confidence of the interval bound.

Return type:

float (0 < c < 1)

monaco.order_statistics.order_stat_P_n(k: int, P: float, c: float, nmax: int = 10000000, bound: StatBound = StatBound.TWOSIDED) int[source]

Order Statistic Percentile, find minimum n from k, P, and c.

Notes

This function returns the number of cases n necessary to say that the true Pth percentile located at or between indices iPl and iPu of a measurement x will be bounded by the k’th order statistic with confidence c.

For example, if I want to use my 5th nearest measurement as a bound on the 50th Percentile with 90% confidence:

n = order_stat_P_n(k=5, P=0.50, c=0.90, bound='2-sided') = 38
iPl = np.floor(P*(n + 1)) = 19
iPu = np.ceil(P*(n + 1)) = 20

The 19-5 = 14th and 20+5= 25th values of x when sorted from low to high, or [sorted(x)[13], sorted(x)[24]] will bound the 50th percentile with 90% confidence.

‘2-sided’ gives the upper and lower bounds. ‘1-sided lower’ and ‘1-sided upper’ give the respective lower or upper bound of the Pth percentile over the entire rest of the distribution.

See chapter 5 of Reference [2] for statistical background.

Parameters:
  • k (int) – The k’th order statistic.

  • P (float (0 < P < 1)) – The target percentile.

  • c (float (0 < c < 1)) – The confidence of the interval bound.

  • nmax (int, default: 1e7) – The maximum number of draws. Hard limit of 2**1000.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, ‘1-sided upper’, ‘1-sided lower’, or ‘2-sided’.

Returns:

n – The number of samples necessary to meet the constraints.

Return type:

int

References

monaco.order_statistics.order_stat_P_k(n: int, P: float, c: float, bound: StatBound = StatBound.TWOSIDED) int[source]

For an Order Statistic Percentile, find the maximum p from n, k, and c.

Parameters:
  • n (int) – The number of samples.

  • P (float (0 < P < 1)) – The target percentile.

  • c (float (0 < c < 1)) – The confidence of the interval bound.

  • ptol (float, default: 1e-9) – The absolute tolerance on determining p.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, ‘1-sided upper’, ‘1-sided lower’, or ‘2-sided’.

Returns:

k – The k’th order statistic meeting the input constraints.

Return type:

int

monaco.order_statistics.order_stat_P_c(n: int, k: int, P: float, bound: StatBound = StatBound.TWOSIDED) float[source]

For an Order Statistic percentile, find the maximum c from n, k, and P.

Parameters:
  • n (int) – The number of samples.

  • k (int) – The k’th order statistic.

  • P (float (0 < P < 1)) – The target percentile.

  • bound (monaco.mc_enums.StatBound, default: '2-sided') – The statistical bound, ‘1-sided upper’, ‘1-sided lower’, or ‘2-sided’.

Returns:

c – The confidence of the interval bound.

Return type:

float (0 < c < 1)

monaco.order_statistics.EPYP(n: int, l: int, u: int, p: float) float[source]

Estimated Probabiliity for the Y’th Percentile, see Chp. 5.2 of Reference.

Parameters:
  • n (int) – TODO Description

  • l (int) – TODO Description

  • u (int) – TODO Description

  • p (float (0 < p < 1)) – TODO Description

Returns:

c – TODO Description

Return type:

float (0 < c < 1)

monaco.order_statistics.EPTI(n: int, l: int, u: int, p: float) float[source]

Estimated Probabiliity for a Tolerance Interval, see Chp. 5.3 of Reference

Parameters:
  • n (int) – TODO Description

  • l (int) – TODO Description

  • u (int) – TODO Description

  • p (float (0 < p < 1)) – TODO Description

Returns:

c – TODO Description

Return type:

float (0 < c < 1)

monaco.order_statistics.get_iP(n: int, P: float) tuple[int, int, int][source]

Get the index of Percentile (1-based indexing)

Parameters:
  • n (int) – Number of samples

  • P (float (0 < P < 1)) – Target percentile

Returns:

(iPl, iP, iPu) – Lower, closest, and upper index of the percentile.

Return type:

(int, int, int)

monaco.order_statistics.order_stat_var_check(n: int | None = None, l: int | None = None, u: int | None = None, p: float | None = None, k: int | None = None, c: float | None = None, nmax: int | None = None) None[source]

Check the validity of the inputs to the order statistic functions.

integration_statistics

monaco.integration_statistics.integration_error(nums: ndarray, dimension: int, volume: float = 1, conf: float = 0.95, samplemethod: SampleMethod = SampleMethod.RANDOM, runningerror: bool = False) float | ndarray[source]

Returns the bounding integration error for an input array of numbers. This error can be a float point estimate if runningerror == False, or a numpy array showing running error over the samples, to demonstrate convergence. If volume == 1, the error returned is a percent error. Otherwise, the error is absolute over the integration volume.

Parameters:
  • nums (list[float]) – A list of the integration point estimates across the volume.

  • dimension (int) – The number of dimensions in the integration volume, dimension > 0.

  • volume (float) – The integration volume, > 0. If volume == 1 (default), then the error returned is a percentage of the true integration volume.

  • conf (float) – Confidence level of the calculated error. This must be 0 < conf < 1, and should be 0.5 < conf < 1.

  • samplemethod (monaco.mc_enums.SampleMethod) – Monte Carlo sample method. Either ‘random’ (default and bounding), or ‘sobol’. If using a different sample method, use ‘random’ here.

  • runningerror (bool) – If False, returns a point estimate. If True, returns an array containing the running error over all of the integration estimates.

Returns:

error – Either a point estimate of the error if runningerror == False, or an array of the running error if runningerror is True.

Return type:

float | np.ndarray

monaco.integration_statistics.integration_n_from_err(error: float, dimension: int, volume: float, stdev: float, conf: float = 0.95, samplemethod: SampleMethod = SampleMethod.RANDOM) int[source]

Returns the bounding integration error for an input array of numbers. This error can be a float point estimate if runningerror == False, or a numpy array showing running error over the samples, to demonstrate convergence. If volume == 1, the error returned is a percent error. Otherwise, the error is absolute over the integration volume. We generally do not know a-priori what the standard deviation will be, so best practice is to set to the max range of values on the interval, and then calculate a better stdev on a lower number of cases, which can then be subsituted in here to bootleg a more efficient computation. For sobol sampling, remember to round n to the next power of 2 for balance. monaco.helper_functions.next_power_of_2(n) can help with this.

Parameters:
  • error (float) – The target error.

  • dimension (int) – The number of dimensions in the integration volume, dimension > 0.

  • volume (float) – The integration volume, > 0. If volume == 1 (default), then the target error is a percentage of the true integration volume.

  • stdev (float) – The standard deviation of the integration estimates, stdev > 0. We generally do not know this a-priori, so use monaco.integration_statistics.max_stdev to calculate this in that instance. Or, do a limited number of cases to estimate this before performing the full run.

  • conf (float) – Confidence level of the calculated error. This must be 0 < conf < 1, and should be 0.5 < conf < 1.

  • samplemethod (monaco.mc_enums.SampleMethod) – Monte Carlo sample method. Either ‘random’ (default and bounding), or ‘sobol’. If using a different sample method, use ‘random’ here.

Returns:

n – The number of sample points required to meet the target integration error.

Return type:

int

monaco.integration_statistics.integration_args_check(error: float | None, dimension: int, volume: float, stdev: float | None, conf: float, samplemethod: SampleMethod) None[source]

Raises a ValueError if any of the inputs for the integration functions are outside allowable bounds.

Parameters:
  • error (None | float) – error > 0.

  • dimension (int) – dimension > 0.

  • volume (float) – volume > 0.

  • stdev (None | float) – stdev > 0.

  • conf (float) – 0 < conf < 1

  • samplemethod (monaco.mc_enums.SampleMethod) – Either ‘random’ or ‘sobol’.

monaco.integration_statistics.max_variance(low: float, high: float) float[source]

Calculates the maximum possible variance of a list of points that span the range [low, high]. max_variance(0, 1) = 0.25

Parameters:
  • low (float) – The low end of the range.

  • high (float) – The high end of the range.

Returns:

maxvar – The maximum possible variance of a list of points in the input range.

Return type:

float

monaco.integration_statistics.max_stdev(low: float, high: float) float[source]

Calculates the maximum possible variance of a list of points that span the range [low, high]. max_stdev(0, 1) = 0.5

Parameters:
  • low (float) – The low end of the range.

  • high (float) – The high end of the range.

Returns:

maxstd – The maximum possible standard deviation of a list of points in the input range.

Return type:

float