Monte Carlo Simulation

class paransys.MonteCarlo

This class performns Monte Carlo simulations inside Python using ParAnsys as a connection with ANSYS for evaluate FEM models.

It is possible to run Monte Carlo simulations without using ANSYS, just defining the limit state equation and all variables.

This code was made following the ideia of ANSYS being a tool for getting the ultimate load of the structure. This works applying a displacement in the loaded node, and then getting the biggest reaction force on that node, following this way the limit state defined here is ‘R-S’, where R are the values get from ANSYS and S the values generated in Python. It’s also possible to work applying the true load on ANSYS, it’s just necessary to formulate a valid limit state equation.


ATTENTION: When using ANSYS the weight of results from ANSYS variables are determined using the weights of all ANSYS input variables.


To do

  1. When structure has more than one limit state the PDF of sampling distribution is the sum of all limit states sampling distributions vs their sampling weights (h(x) = w1.h1(x) + w2.h2(x) + hi.wi(x)…) It’s already done the division of simulations for each cycle with the limit state weights.

  2. When sampling distribution is different of real distribution Pf is going wrong, so it’s not able to be used, for now.



Class methods:

ANSYS(exec_loc=None, run_location='C:\\Programacao\\_MinhasBibliotecas\\paransys\\docs_sphinx\\ansys_anl\\', jobname='file', nproc=2, override=False, cleardir=False, add_flags='')

If ANSYS will be used it defines ANSYS properties, for initialize the paransys.ANSYS class.

exec_locstr, obligatory

Location of ANSYS executable file.

run_locationstr, optional

ANSYS working directory. Recomended to be a separated directory. Defaults to ansys_anl on current directory.

jobnamestr, optional

ANSYS jobname. Defaults to ‘file’.

nprocint, optional

Number of processors. Defaults to 2.

overridebool, optional

Attempts to delete the .lock file at working directory. It’s useful when ANSYS was interrupted. Defaults to False

cleardirbool, optional

Delete all the files from ANSYS working directory when call the Run command. Defaults to False

add_flagsstr, optional

Additional flags to be called with ANSYS. If it’s an academic version use add_flags=’-aa_r’ Do not use ‘-b -i -o’ Flags can be found at https://www.sharcnet.ca/Software/Ansys/16.2.3/en-us/help/ans_ope/Hlp_G_OPE3_1.html

CreateLimState(equat, weight=1.0, userf=None)

Create and Set a new limit state.*

The number ID of LimitStates are generated automatically starting at 0 for the first.

* Current version supports only one limit state!

ATTENTION: When using ANSYS the weight of results from ANSYS variables are determined using the weights of all ANSYS input variables.

equatstr, obligatory

String with the equation of the limit state. It must be write as a function of defined variables (In and Out).

weightfloat, obligatory only with more than 1 limit state

The weight of current limit state, it determines how the simulations are distributed betwen all the limit states. The sum of all limit states must be 1.00, so, if there is just one limit state it’s weight should be 1.00

userffunction, optional

An user defined function that could be used inside the limit state equation, called inside equat as userf(). Each limit state has it’s own userf, but you can use the same Python function for all limit states. For example, you can create a complex Python function with loops, ifs and whatever for evaluate the R part of your limit state function for a concrete beam. An example is showed after.

First example: if ANSYS returns the maximum load on a truss as variable FxMAX, and applied loads to be tested are (g+q)*sin(theta), where g, q, theta are defined random variables created with CreateVar().

mc.CreateLimState(equat='FxMAX-(g+q)*sin(theta)', weight=1.00)

Note that you can use math expressions as sin(), cos(), tan(), sqrt() from Python math module inside the equation.


Second example: you have a steel bar in tension that hasn’t hardening. It’s stress is a function of (def, fy, E), where def is current deformation, fy is yield stress and E the elastic moduli, you can create inside your code an function like:

def stress(def, fy, E):
        if def > fy/E:
                return fy
        else:
                return def*E

And now defining userf=stress we can:

mc.CreateLimState(equat='userf(def,fy,E)-q', weight=1.00, userf=stress)

where def, fy, E and q are random variables. Note that the function inside the limit state equation should be called as userf() with the parameters from stress.

Or we can do the same using the functions instead of the string:

mc.CreateLimState(equat=stress)
CreateVar(name, distrib, mean, std=0, cv=None, par1=None, par2=None)

Create a Random Variable

If it’s used on ANSYS it need to be told, so after this use:

>>> mc.SetANSYSVar(name)
namestr, obligatory

Name of variable.

distribstr, obligatory

Probabilistic variable distribution type.

For all distributions Mean and Std are related to Normal distribution (the code determines the parameters for the desired distribution).

Available types are: * gaussian (or gauss, normal); * lognormal (or log, logn, ln, lognorm); * gumbel (or gumb, type1); * constant (or const) - Constant value (doesn’t need std).

meanfloat, obligatory

Standard mean of variable values.

stdfloat, optional

Standard deviation of variable. You must define it or cv for variables that aren’t constant, if both (cv and std) declared std will be used.

For LogNormal variables it’s recommend to use CV!

cvfloat, optional

Coeficient of Variation of variable. You must define it or std for variables that aren’t constant, if both (cv and std) declared std will be used.

For LogNormal variables it’s recommend to use CV!

par1 and par2float, optional

Parameters for future implementations.

ExportDataCSV(filename, description=None)

Exports Simulation data to a CSV file.

filenamestr, obligatory

Name of file that will receive the values, doesn’t need the extension “.csv”, it will be placed automatically.

descriptionstr, optional

A string that will be write in the beggining of the file.

GetSolutionControl(thing)

Return values of Monte Carlo solution controllers.

thing: str, obligatory

Control that will be returned. Available things are listed below.

In function of N:
  • ‘N_Pf’ = Probability of failure

  • ‘N_Beta’ = Reliability index

  • ‘N_CVPf’ = CV of Probability of failure

2D numpy array of floats:

Each line has simulation number and requested value on this simulation.

Graph(things, show=True, savefile=False)

Generate graphics of Monte Carlo solution controllers.

Things can be a list of data that will be ploted in the same figure, the figure doesn’t need to be opened, it could be just saved, or just opened.

thingslist of strings, obligatory

List of data that will be ploted in the same figure. Available things are listed below.

showbool, optional

Sinalize if figure should be opened. Defaults to True.

savefilestr/bool, optional

If it’s False doesn’t save anything. If it’s a string it will be used as directory+name that figure will have, it shouldn’t have extension, since it will be SVG. Defaults to False.

With N as horizontal axis:
  • ‘N_Pf’ = Probability of failure

  • ‘N_Beta’ = Reliability index

  • ‘N_CVPf’ = CV of Probability of failure

Info(act=False)

Turn on/off the return of the commands to Python.

actbool, obligatory

True turn On and False turn Off the return of the commands to Python.

Run(Ns, Nmaxcycles, CVPf=0.0, tolAdPt=False)

Run the Monte Carlo simulation.

Nsinteger, obligatory

Number of simulations performed on each cycle. After each cycle the convergence of simualtion is verified. When using Importance Sampling with Adaptive Sampling, after each cycle the new sampling point will be determined.

Nmaxcyclesinteger, obligatory

Maximum number of cycles to be performed, if CVPf is not reached on Nmaxcycles the simulation will be interrupted.

CVPffloat, optional

Target value of Probability Failure Coefficient of Variation, when reached the simulation stops.

tolAdPtfloat or False, optional

Maximum relative tolerance for adaptive sampling point search. If the value is “False” it disable adaptive sampling, simulations will use always the user set point.

Returns a dictionary with:

  • stnumb : integer Status of solution, values can be found after this list.

  • Pf : float Probability of failure.

  • Beta : float Reliability index.

  • CVPf : float Coefficient of Variation of Probability of failure

  • {SamplingPoints} : dictionary of dictionaries Dictionary with sampling points used, or founded in case of adaptive sampling, for each Variable on each Limit State. (SamplingPoints[eachLS][eachVar])

  • cycles : int Number of cycles performed to obtain the solution.

  • distparms : dictionary of dictionaries Return mean (gMean) and standart deviation (gStd) of each limit state function.

Status values:

  • 0: no problem;

  • 1: warning, maximum of cycles reached with no convergence of CVPf;

  • 99: undefined error!

SetANSYSModel(inputname, extrafiles=[], directory='C:\\Programacao\\_MinhasBibliotecas\\paransys\\docs_sphinx')

Set the input script file to be used on ANSYS and extra files that should be copied together. All this files must be in the same directory set in parameter directory.

inputnamestr, obligatory

Name with extension of the script that will be executed in the analysis. The script must be done in function of the INPUT variables defined here, (as parameters of ANSYS), and must define/calculate ANSYS parameters with the results using the names defined here.

extrafileslist of strings, optional

A list of strings containing extra files (with extension) that are necessary to run the script analys, could be an MODEL with the MESH already generated, for example. An example of extrafiles list is: extrafiles = [‘temps.txt’, ‘model1.ans’, ‘file.db’]

directorystr, optional

If the script is not in the current running Python directory you should place the entire location, if it’s in a subdirectory of current directory you can use ‘/dirname/filename.ext’. Defaults to current running Python directory.

SetANSYSOutVar(name)

Defines a parameter/variable from ANSYS APDL script as an variable to return values for Python.

namestr, obligatory

Variable/Parameter name, as defined in APDL script.

SetANSYSVar(name)

Mark a Random variable as ANSYS variable.

ATTENTION: When using ANSYS the weight of results from ANSYS variables are determined using the weights of all ANSYS input variables.

namestr, obligatory

Name of variable.

SetCorrel(var1, var2, correl)

Set the correlation betwen two variables.

The values will be transformed by the Nataf process before running.

var1str, obligatory

First variable name.

var2str, obligatory

Second variable name.

correlfloat, obligatory

Correlation betwen var1 and var2.

SetRandomVarSampl(name, limst, distrib, mean, std=0, cv=None, par1=None, par2=None)

Sets the sampling distribution of a variable to performn Importance Sampling the simulations.

ATTENTION: When using ANSYS the weight of results from ANSYS variables are determined using the weights of all ANSYS input variables.

namestr, obligatory

Name of variable.

limstinteger, obligatory for type=1 with more than 1 limit state

Limit state ID that will use current sampling distribution.

distribstr, obligatory

Probabilistic variable distribution type.

For all distributions Mean and Std are related to Normal distribution (the code determines the parameters for the desired distribution).

Available types are: * gaussian (or gauss, normal); * lognormal (or log, logn, ln, lognorm); * gumbel (or gumb, type1); * constant (or const) - Constant value (doesn’t need std).

meanfloat, obligatory

Standard mean of variable values.

stdfloat, optional

Standard deviation of variable. You must define it or cv for variables that aren’t constant, if both (cv and std) declared std will be used.

For LogNormal variables it’s recommend to use CV!

cvfloat, optional

Coeficient of Variation of variable. You must define it or std for variables that aren’t constant, if both (cv and std) declared std will be used.

For LogNormal variables it’s recommend to use CV!

par1 and par2float, optional

Parameters for future implementations.