import random as rd

leafduration = 3 # life time of a leaf
leafold =      2 # age at which a leaf is considered as old
maxorder =     5 # maximum number of branching order
radinc =    0.01 # increment of radius through time

maxduration = lambda order : int(10./(order+1))+3  # life time of an apex
branch_angle = lambda order : 60+30*((maxorder-order)/maxorder) # branching angle
nb_axes = lambda order : rd.randint(3,5)  # number of axe at a ramification
up_angle = lambda t,order : 7        # up angle for lateral branches

# number total of iterations of the system
nbiter = sum([maxduration(o) for o in range(maxorder+1)])

module A # represent trunk apical meristem
module B # represent apical meristem of lateral branches
module L # whorl of leaf
module I # Internode
module T # Meristem ending

Axiom: _(0.1)@GcI(0.5,0.1)A(0,0) 

derivation length: nbiter
production:

A(t,o) :
  if t < maxduration(o):
     # simply produces a metamer and ages the apex
     produce I(1,0.1)L(0,t)A(t+1,o) 
  else:
      # produce a whorl of sympodial branches
      nbaxe = nb_axes(o)
      for i in range(nbaxe):
        nproduce [/(360*i/nbaxe)&(branch_angle(o))B(0,o+1)]
      produce T


B(t,o) :
  if t < maxduration(o):
    # simply produces a metamer and ages the apex
    # reorient smoothly the branch toward the up
    produce ^(up_angle(t,o))I(1,0.1)L(0,t)B(t+1,o)
  else:
    # produce a whorl of sympodial branches
    nbaxe = nb_axes(o)
    for i in range(nbaxe):
      nproduce [/(360*i/nbaxe)&(branch_angle(o))B(0,o+1)]
    produce T

L(t,n) :
  # ages the leaf. If too old, removes
  if t < leafduration :  produce L(t+1,n)
  else:   produce *

# Increment radius of internodes
I(s,r) --> I(s,r+radinc)
_(r) --> _(r+radinc)

homomorphism:

I(a,r) --> F(a,r)
T --> @Ge_(0.05);(3)F(0.5)@O(0.2)

L(t,p) :
    phi = 0 if p % 2 == 0 else 90  # phyllotactic angle
    col = 4 if t >= leafold else 2 # color is chosen according to age
    produce [/(phi)^(120);(col)~l(1)][/(phi)&(120);(col)~l(1)]

endlsystem
###### INITIALISATION ######

__lpy_code_version__ = 1.1

def __initialiseContext__(context):
	context.animation_timestep = 0.153
	context.options.setSelection('Module declaration',1)
__authors__ = 'F. Boudon'
__description__ = 'Leuwenberg architectural model. '
__references__ = 'Halle, 71'
