RevitPythonShell: Randomization

## Introduction

You can implement randomization in your scripts using the .NET Random class. For example the following code will return a random double number between 0 and 1 in the RevitPythonShell

import System

#declare a random variable
rand = System.Random()

#get the double value
rand.NextDouble()

You can specify a seed value to control the random output

import System

#specify seed
seed = 8

rand = System.Random(seed)
rand.NextDouble()

Custom integer ranges can be supplied by using rand.Next()

import System

seed = 8

#random range
r1 = 0
r2 = 20

rand = System.Random(seed)

#use range variables
rand.Next(r1, r2)

## Random Surface Form

We can create a random free-form surface using a a technique similar to the loft wave example. Instead of a predictable math formula, we will instead use random to create a strange looking surface.

import clr
import math
import System
from Autodesk.Revit.DB import *

app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document

t = Transaction(doc, 'Create random surface form.')

t.Start()

#declare randomization parameters
#random seed
seed = 4

#random range
r1 = 1
r2 = 20

#random
rand = System.Random(seed)

refarrarr = ReferenceArrayArray()

for i in range(0,20):
refptarr = ReferencePointArray()
for j in range(0,20):
x = i * 10
y = j * 10

#get the next random value for z
z = rand.Next(r1,r2)

myXYZ = XYZ(x,y,z)
refPoint = doc.FamilyCreate.NewReferencePoint(myXYZ)
refptarr.Append(refPoint)

crv = doc.FamilyCreate.NewCurveByPoints(refptarr)

refarr = ReferenceArray()
refarr.Append(crv.GeometryCurve.Reference)
refarrarr.Append(refarr)

loft = doc.FamilyCreate.NewLoftForm(True, refarrarr)

t.Commit()

__window__.Close()

## Random Family Parameters

We can also use random values to control family parameters. This code is similar to this instance parameter example. Instead of modifying the 'height' parameter of the boxes using an incrementing variable, the parameter is set using a random variable.

Viola, instant city context!

import clr
import System
from Autodesk.Revit.DB import *

app = __revit__.Application
doc = __revit__.ActiveUIDocument.Document

t = Transaction(doc, 'Change parameters with random values.')

t.Start()

#declare randomization parameters
#random seed
seed = 4

#random range
r1 = 20
r2 = 150

#random
rand = System.Random(seed)

instName = 'BoxFamily'

collector = FilteredElementCollector(doc)
collector.OfCategory(BuiltInCategory.OST_Mass)
collector.OfClass(FamilyInstance)

famtypeitr = collector.GetElementIdIterator()
famtypeitr.Reset()

inc = 1

for item in famtypeitr:
famtypeID = item
faminst = doc.get_Element(famtypeID)

if faminst.Name == instName:
param = faminst.get_Parameter('height')
#set height parameter using random variable
param.Set(rand.Next(r1,r2))

t.Commit()

__window__.Close()

Just for fun we can put the random 'city' into the Vasari wind tunnel… Look! Pretty colors!