[GIS] Using arcgis.rand() with variables from code block of Calculate Value tool

arcgis-10.2arcgis-desktopmodelbuilderpythonrandom

Within a larger ArcGIS ModelBuilder model I am trying to populate a field in an attribute table with a random number, using Calculate Value. The overall distribution of random numbers needs to follow a Normal distribution. The parameters of that normal distribution (mean and standard deviation) need to be calculated from model variables specified by the user. Is this possible?

The arcgis.rand() function can do what I want and works perfectly if I specify the mean and stdev directly in the Calculate Value expression:

arcgis.rand("Normal 6 2.5") 

If I use model variables directly, it also works:

arcgis.rand("Normal %mean% %stdev%")

However, in some instances I need to do some simple calculations to obtain the parameters from variables the user has entered. For example, they have already entered variables A, B and C, and I need the mean to be A*B and the stdev to be B/C.

I have attempted to do this via the code block:

import random
MN = %A%*%B%
SD = %B%/%C%

and then the expression

arcgis.rand("Normal MN SD")

but this always results in values following the default distribution (mean 0, stdev 1). Troubleshooting shows this happens even if I define the code block variables as simple numbers, suggesting the problem seems to be using code block variables in the expression, not in the definition or calculation of the variables themselves.

My question is: how can I do what I need using arcgis.rand()?

I am open to suggestions of other methods/workflows for achieving what I need, but I am a novice at Python, in case that is not already obvious! I am using ArcGIS Desktop Advanced 10.2.2.

Best Answer

You're using your variable names in a string literal. You can do the following to have the values substituted into the string:

arcgis.rand("Normal {0} {1}".format(MN, SD))

You could also import numpy and use numpy.random.normal(MN, SD, n) to draw a sample of size n from the specified normal distribution. Documentation.

Related Question