Index: palm/trunk/SCRIPTS/palm_csd
===================================================================
--- palm/trunk/SCRIPTS/palm_csd	(revision 3628)
+++ palm/trunk/SCRIPTS/palm_csd	(revision 3629)
@@ -25,9 +25,8 @@
 # -----------------
 # $Id$
+# Added canopy generator calls. Some improvements
+# 
+# 3567 2018-11-27 13:59:21Z maronga
 # Initial revisions
-#
-#
-# 
-#
 #
 # Description:
@@ -38,8 +37,4 @@
 # @Author Bjoern Maronga (maronga@muk.uni-hannover.de)
 #
-# @todo Remove high vegetation on demand
-# @todo Add vegetation_pars (LAI)
-# @todo Add building_pars (green roofs)
-# @todo Add LAD and BAD arrays (canopy generator)
 # @todo Make input files optional
 # @todo Allow for ASCII input of terrain height and building height
@@ -49,4 +44,5 @@
 from palm_csd_files.palm_csd_netcdf_interface import *
 from palm_csd_files.palm_csd_tools import *
+from palm_csd_files.palm_csd_canopy_generator import *
 import numpy as np
 
@@ -71,6 +67,4 @@
       print ("Error. No configuration file " + input_config + " found.")
       raise SystemExit   
-   else:
-      print(os.path.isfile(input_config))
 
    config.read(input_config)
@@ -79,6 +73,13 @@
 #  Definition of settings
    global settings_filename_out
-   global settings_lai_season
    global settings_bridge_width
+   global settings_lai_roof_intensive
+   global settings_lai_roof_extensive
+   global settings_season
+   global settings_lai_low_default
+   global settings_lai_high_default
+   global settings_patch_height_default
+   global settings_lai_alpha
+   global settings_lai_beta
    global ndomains
 
@@ -113,9 +114,11 @@
    global domain_dz
    global domain_3d
-   global domain_hv
-   global domain_cg
+   global domain_high_vegetation
    global domain_ip
    global domain_za
    global domain_parent
+   global domain_green_roofs
+   global domain_street_trees
+   global domain_canopy_patches
 
 #  Definition of input data parameters
@@ -137,4 +140,5 @@
    global input_file_building_type
    global input_file_building_type
+   global input_file_lai  
    global input_file_vegetation_type
    global input_file_vegetation_height
@@ -144,5 +148,10 @@
    global input_file_street_crossings
    global input_file_soil_type
-
+   global input_file_vegetation_on_roofs
+   global input_file_tree_crown_diameter
+   global input_file_tree_height
+   global input_file_tree_trunk_diameter
+   global input_file_tree_type
+   global input_file_patch_height
 
    global zt_all
@@ -150,6 +159,13 @@
 
    settings_filename_out = "default"
-   settings_lai_season = "summer"
    settings_bridge_width = 3.0
+   settings_lai_roof_intensive = 0.5
+   settings_lai_roof_extensive = 1.0
+   settings_season = "summer"
+   settings_lai_high_default = 6.0
+   settings_lai_low_default = 1.0
+   settings_patch_height_default = 10.0
+   settings_lai_alpha = 5.0
+   settings_lai_beta = 3.0
    ndomains = 0
 
@@ -181,9 +197,11 @@
    domain_dz = []
    domain_3d = []
-   domain_hv = []
-   domain_cg = []
+   domain_high_vegetation = []
    domain_ip = []
    domain_za = []
    domain_parent = []
+   domain_green_roofs = []
+   domain_street_trees = []
+   domain_canopy_patches = []
 
    zt_min = 0.0
@@ -206,4 +224,5 @@
    input_file_bridges_id = []   
    input_file_building_type = []
+   input_file_lai = []
    input_file_vegetation_type = []
    input_file_vegetation_height = []   
@@ -213,5 +232,10 @@
    input_file_street_crossings = []     
    input_file_soil_type = []
-
+   input_file_vegetation_on_roofs = []
+   input_file_tree_crown_diameter = []
+   input_file_tree_height = []
+   input_file_tree_trunk_diameter = []
+   input_file_tree_type = []
+   input_file_patch_height = []
    
 # Load all user parameters from config file
@@ -240,7 +264,14 @@
       if ( read_tmp == 'settings' ):
          settings_filename_out = config.get(read_tmp, 'filename_out')
-         settings_lai_season = config.get(read_tmp, 'lai_season') 
-         settings_bridge_width = float(config.get(read_tmp, 'bridge_width'))      
- 
+         settings_lai_roof_intensive = config.get(read_tmp, 'lai_roof_intensive')
+         settings_lai_roof_extensive = config.get(read_tmp, 'lai_roof_extensive') 
+         settings_bridge_width = float(config.get(read_tmp, 'bridge_width'))   
+         settings_season = config.get(read_tmp, 'season')   
+         settings_lai_high_default = float(config.get(read_tmp, 'lai_high_vegetation_default'))
+         settings_lai_low_default = float(config.get(read_tmp, 'lai_low_vegetation_default'))         
+         settings_patch_height_default = float(config.get(read_tmp, 'patch_height_default'))  
+         settings_lai_alpha = float(config.get(read_tmp, 'lai_alpha')) 
+         settings_lai_beta = float(config.get(read_tmp, 'lai_beta')) 
+
       if ( read_tmp.split("_")[0] == 'domain' ):
          ndomains = ndomains + 1
@@ -251,6 +282,6 @@
          domain_dz.append(float(config.get(read_tmp, 'dz')))       
          domain_3d.append(config.getboolean(read_tmp, 'buildings_3d'))
-         domain_hv.append(config.getboolean(read_tmp, 'allow_high_vegetation'))
-         domain_cg.append(config.getboolean(read_tmp, 'generate_vegetation_patches'))       
+         domain_high_vegetation.append(config.getboolean(read_tmp, 'allow_high_vegetation'))
+         domain_canopy_patches.append(config.getboolean(read_tmp, 'generate_vegetation_patches'))       
          domain_ip.append(config.getboolean(read_tmp, 'interpolate_terrain'))
          domain_za.append(config.getboolean(read_tmp, 'use_palm_z_axis')) 
@@ -265,5 +296,7 @@
          domain_x1.append(int(floor(float(config.get(read_tmp, 'origin_x'))/float(config.get(read_tmp, 'pixel_size'))) + int(config.get(read_tmp, 'nx'))))
          domain_y1.append(int(floor(float(config.get(read_tmp, 'origin_y'))/float(config.get(read_tmp, 'pixel_size'))) + int(config.get(read_tmp, 'ny'))))
-
+         domain_green_roofs.append(config.getboolean(read_tmp, 'vegetation_on_roofs')) 
+         domain_street_trees.append(config.getboolean(read_tmp, 'street_trees')) 
+         
       if ( read_tmp.split("_")[0] == 'input' ):
          input_names.append(read_tmp.split("_")[1])
@@ -280,5 +313,6 @@
          input_file_building_id.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_building_id'))  
          input_file_bridges_id.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_bridges_id')) 
-         input_file_building_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_building_type'))  
+         input_file_building_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_building_type'))
+         input_file_lai.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_lai'))         
          input_file_vegetation_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_vegetation_type')) 
          input_file_vegetation_height.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_vegetation_height'))          
@@ -286,5 +320,11 @@
          input_file_water_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_water_type'))
          input_file_street_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_street_type'))    
-         input_file_street_crossings.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_street_crossings'))  
+         input_file_street_crossings.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_street_crossings')) 
+         input_file_patch_height.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_patch_height')) 
+         input_file_tree_crown_diameter.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_tree_crown_diameter'))  
+         input_file_tree_height.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_tree_height'))  
+         input_file_tree_trunk_diameter.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_tree_trunk_diameter'))  
+         input_file_tree_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_tree_type'))  
+         input_file_vegetation_on_roofs.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_vegetation_on_roofs'))           
          #input_file_soil_type.append(config.get(read_tmp, 'path') + "/" + config.get(read_tmp, 'file_soil_type'))    
    return 0
@@ -317,5 +357,12 @@
    "street_crossings": "b",     
    "soil_type": "b",
-   "surface_fraction": "f4"
+   "surface_fraction": "f4",
+   "building_pars": "f4",
+   "vegetation_pars": "f4",
+   "tree_data": "f4",
+   "tree_type": "b",
+   "nbuilding_pars": "i",
+   "nvegetation_pars": "i",
+   "zlad": "f4"
    }
 
@@ -340,5 +387,9 @@
    "street_crossings": np.byte(-127),   
    "soil_type": np.byte(-127),
-   "surface_fraction": float(-9999.0)
+   "surface_fraction": float(-9999.0),
+   "building_pars": float(-9999.0),
+   "vegetation_pars": float(-9999.0),
+   "tree_data": float(-9999.0),
+   "tree_type": np.byte(-127)
    }
 
@@ -363,5 +414,9 @@
    "street_crossings": 0,    
    "soil_type": 1,
-   "surface_fraction": float(0.0)
+   "surface_fraction": float(0.0),
+   "buildings_pars": float(-9999.0),
+   "tree_data": float(-9999.0),
+   "tree_type": 0,
+   "vegetation_pars": float(-9999.0)   
    }
   
@@ -606,5 +661,5 @@
 
 
-      del bridges_2d, bridges_id, building_id
+      del bridges_2d, bridges_id, building_id, buildings_2d
 
 
@@ -684,6 +739,6 @@
    vegetation_height = nc_read_from_file_2d(input_file_vegetation_height[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i])   
          
-   vegetation_type = np.where((vegetation_height != fillvalues["vegetation_height"]) & (vegetation_height == 0.0) & ((vegetation_type == 4) | (vegetation_type == 7) | (vegetation_type == 17)), 3, vegetation_type)
-   vegetation_height = np.where((vegetation_height != fillvalues["vegetation_height"]) & (vegetation_height == 0.0) & ((vegetation_type == 4) | (vegetation_type == 7) | (vegetation_type == 17)), fillvalues["vegetation_height"],vegetation_height)
+   vegetation_type = np.where((vegetation_height != fillvalues["vegetation_height"]) & (vegetation_height == 0.0) & ((vegetation_type == 4) | (vegetation_type == 5) | (vegetation_type == 6) |(vegetation_type == 7) | (vegetation_type == 17) | (vegetation_type == 18)), 3, vegetation_type)
+   vegetation_height = np.where((vegetation_height != fillvalues["vegetation_height"]) & (vegetation_height == 0.0) & ((vegetation_type == 4) | (vegetation_type == 5) | (vegetation_type == 6) |(vegetation_type == 7) | (vegetation_type == 17) | (vegetation_type == 18)), fillvalues["vegetation_height"],vegetation_height)
 
 
@@ -720,7 +775,6 @@
    del soil_type
 
-
-
-
+   del x
+   del y
 
 #  pixels with bridges get building_type = 7 = bridge. This does not change the _type setting for the under-bridge
@@ -737,5 +791,5 @@
          del bridges_2d
 
-# Read/Write street type and street crossings
+# Read/write street type and street crossings
 for i in range(0,ndomains):  
 
@@ -763,2 +817,203 @@
    nc_write_attribute(filename[i], 'street_crossings', 'grid_mapping', 'E_UTM N_UTM lon lat')   
    del street_crossings
+
+
+# Read/write vegetation on roofs
+for i in range(0,ndomains):  
+   if domain_green_roofs[i]: 
+      green_roofs = nc_read_from_file_2d(input_file_vegetation_on_roofs[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i])   
+      buildings_2d = nc_read_from_file_2d_all(filename[i], 'buildings_2d') 
+
+
+      x = nc_read_from_file_2d_all(filename[i], 'x')
+      y = nc_read_from_file_2d_all(filename[i], 'y')  
+      nbuilding_pars = np.arange(0,46)
+      building_pars = np.ones((len(nbuilding_pars),len(y),len(x)))
+      building_pars[:,:,:] = fillvalues["building_pars"]
+
+#     assign green fraction on roofs
+      building_pars[3,:,:] = np.where( (buildings_2d != fillvalues["buildings_2d"] ) & ( green_roofs != fillvalues["building_pars"] ),1.0,fillvalues["building_pars"])
+
+#     assign leaf area index for vegetation on roofs
+      building_pars[4,:,:] = np.where( ( buildings_2d != fillvalues["buildings_2d"] ) & ( green_roofs == 1.0 ),settings_lai_roof_intensive,fillvalues["building_pars"])
+      building_pars[4,:,:] = np.where( ( buildings_2d != fillvalues["buildings_2d"] ) & ( green_roofs == 2.0 ),settings_lai_roof_extensive,building_pars[4,:,:])
+   
+   
+      nc_write_dimension(filename[i], 'nbuilding_pars', nbuilding_pars, datatypes["nbuilding_pars"]) 
+      nc_write_to_file_3d(filename[i], 'building_pars', building_pars, datatypes["building_pars"],'nbuilding_pars','y','x',fillvalues["building_pars"]) 
+      nc_write_attribute(filename[i], 'building_pars', 'long_name', 'building_pars')
+      nc_write_attribute(filename[i], 'building_pars', 'units', '')
+      nc_write_attribute(filename[i], 'building_pars', 'res_orig', domain_px[i])  
+      nc_write_attribute(filename[i], 'building_pars', 'coordinates', 'E_UTM N_UTM lon lat') 
+      nc_write_attribute(filename[i], 'building_pars', 'grid_mapping', 'E_UTM N_UTM lon lat')   
+         
+      del building_pars, buildings_2d, x, y
+
+
+# Read tree data and create LAD and BAD arrays using the canopy generator
+for i in range(0,ndomains):  
+   if domain_street_trees[i]: 
+      lai = nc_read_from_file_2d(input_file_lai[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i])   
+      
+      
+#     Save lai data as default for low and high vegetation
+      lai_low = lai
+      lai_high = lai
+      
+      x = nc_read_from_file_2d_all(filename[i], 'x')
+      y = nc_read_from_file_2d_all(filename[i], 'y')  
+      nvegetation_pars = np.arange(0,11)
+      vegetation_pars = np.ones((len(nvegetation_pars),len(y),len(x)))
+      vegetation_pars[:,:,:] = fillvalues["vegetation_pars"]  
+      
+      vegetation_pars[1,:,:] = lai
+      
+
+#     Write out first version of LAI. Will later be overwritten.
+      nc_write_dimension(filename[i], 'nvegetation_pars', nvegetation_pars, datatypes["nvegetation_pars"]) 
+      nc_write_to_file_3d(filename[i], 'vegetation_pars', vegetation_pars, datatypes["vegetation_pars"],'nvegetation_pars','y','x',fillvalues["vegetation_pars"]) 
+      nc_write_attribute(filename[i], 'vegetation_pars', 'long_name', 'vegetation_pars')
+      nc_write_attribute(filename[i], 'vegetation_pars', 'units', '')
+      nc_write_attribute(filename[i], 'vegetation_pars', 'res_orig', domain_px[i])  
+      nc_write_attribute(filename[i], 'vegetation_pars', 'coordinates', 'E_UTM N_UTM lon lat') 
+      nc_write_attribute(filename[i], 'vegetation_pars', 'grid_mapping', 'E_UTM N_UTM lon lat')   
+
+
+#     Read all tree parameters from file
+      tree_height = nc_read_from_file_2d(input_file_tree_height[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i])   
+      tree_crown_diameter = nc_read_from_file_2d(input_file_tree_crown_diameter[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i])   
+      tree_trunk_diameter = nc_read_from_file_2d(input_file_tree_trunk_diameter[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i])         
+      tree_type = nc_read_from_file_2d(input_file_tree_type[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i]) 
+      patch_height = nc_read_from_file_2d(input_file_patch_height[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i]) 
+      
+#     Remove missing values from the data. Reasonable values will be set by the tree generator    
+      tree_height = np.where( (tree_height == 0.0) | (tree_height == -1.0) ,fillvalues["tree_data"],tree_height)
+      tree_crown_diameter = np.where( (tree_crown_diameter == 0.0) | (tree_crown_diameter == -1.0) ,fillvalues["tree_data"],tree_crown_diameter)
+      tree_trunk_diameter = np.where( (tree_trunk_diameter == 0.0) | (tree_trunk_diameter == -1.0) ,fillvalues["tree_data"],tree_trunk_diameter)
+      tree_type = np.where( (tree_type == 0.0) | (tree_type == -1.0) ,fillvalues["tree_data"],tree_type)
+      patch_height = np.where( patch_height == -1.0 ,fillvalues["tree_data"],patch_height)     
+
+#     Convert trunk diameter from cm to m
+      tree_trunk_diameter = np.where(tree_trunk_diameter != fillvalues["tree_data"], tree_trunk_diameter * 0.01,tree_trunk_diameter)
+
+
+#     Temporarily change missing value for tree_type
+      tree_type = np.where( (tree_type == fillvalues["tree_type"]),fillvalues["tree_data"],tree_type)    
+
+#     Compare patch height array with vegetation type and correct accordingly
+      vegetation_type = nc_read_from_file_2d_all(filename[i], 'vegetation_type') 
+
+
+#     For zero-height patches, set vegetation_type to short grass and remove these pixels from the patch height array
+      vegetation_type = np.where( (patch_height == 0.0) & ( (vegetation_type == 4) | (vegetation_type == 5) | (vegetation_type == 6) |(vegetation_type == 7) | (vegetation_type == 17) | (vegetation_type == 18) ),3,vegetation_type)
+      patch_type = np.where( (patch_height == 0.0) & ( (vegetation_type == 4) | (vegetation_type == 5) | (vegetation_type == 6) |(vegetation_type == 7) | (vegetation_type == 17) | (vegetation_type == 18) ),fillvalues["tree_data"],patch_height)      
+      nc_overwrite_to_file_2d(filename[i], 'vegetation_type', vegetation_type)  
+
+      max_tree_height = max(tree_height.flatten())
+      max_patch_height = max(patch_height.flatten())
+      
+      if ( (max_tree_height != fillvalues["tree_data"]) | (max_patch_height == fillvalues["tree_data"]) ):
+           
+         lad, bad, tree_ids, zlad = generate_single_tree_lad(x,y,domain_dz[i],max_tree_height,max_patch_height,tree_type,tree_height,tree_crown_diameter,tree_trunk_diameter,lai,settings_season,fillvalues["tree_data"])
+  
+  
+#        Remove LAD volumes that are inside buildings
+         buildings_2d = nc_read_from_file_2d_all(filename[i], 'buildings_2d') 
+         for k in range(0,len(zlad)-1):
+  
+            lad[k,:,:] = np.where(buildings_2d == fillvalues["buildings_2d"],lad[k,:,:],fillvalues["tree_data"])
+            bad[k,:,:] = np.where(buildings_2d == fillvalues["buildings_2d"],bad[k,:,:],fillvalues["tree_data"])
+            tree_ids[k,:,:] = np.where(buildings_2d == fillvalues["buildings_2d"],tree_ids[k,:,:],fillvalues["tree_data"])      
+  
+  
+         nc_write_dimension(filename[i], 'zlad', zlad, datatypes["tree_data"]) 
+         nc_write_to_file_3d(filename[i], 'lad', lad, datatypes["tree_data"],'zlad','y','x',fillvalues["tree_data"]) 
+         nc_write_attribute(filename[i], 'lad', 'long_name', 'leaf area density')
+         nc_write_attribute(filename[i], 'lad', 'units', '')
+         nc_write_attribute(filename[i], 'lad', 'res_orig', domain_px[i])  
+         nc_write_attribute(filename[i], 'lad', 'coordinates', 'E_UTM N_UTM lon lat') 
+         nc_write_attribute(filename[i], 'lad', 'grid_mapping', 'E_UTM N_UTM lon lat') 
+  
+         nc_write_to_file_3d(filename[i], 'bad', bad, datatypes["tree_data"],'zlad','y','x',fillvalues["tree_data"]) 
+         nc_write_attribute(filename[i], 'bad', 'long_name', 'basal area density')
+         nc_write_attribute(filename[i], 'bad', 'units', '')
+         nc_write_attribute(filename[i], 'bad', 'res_orig', domain_px[i])  
+         nc_write_attribute(filename[i], 'bad', 'coordinates', 'E_UTM N_UTM lon lat') 
+         nc_write_attribute(filename[i], 'bad', 'grid_mapping', 'E_UTM N_UTM lon lat')
+            
+         nc_write_to_file_3d(filename[i], 'tree_id', tree_ids, datatypes["tree_data"],'zlad','y','x',fillvalues["tree_data"]) 
+         nc_write_attribute(filename[i], 'tree_id', 'long_name', 'tree id')
+         nc_write_attribute(filename[i], 'tree_id', 'units', '')
+         nc_write_attribute(filename[i], 'tree_id', 'res_orig', domain_px[i])  
+         nc_write_attribute(filename[i], 'tree_id', 'coordinates', 'E_UTM N_UTM lon lat') 
+         nc_write_attribute(filename[i], 'tree_id', 'grid_mapping', 'E_UTM N_UTM lon lat')           
+            
+         del buildings_2d, lai, lad, bad, tree_ids, zlad
+
+      del vegetation_pars, tree_height, tree_crown_diameter, tree_trunk_diameter, tree_type, patch_height, vegetation_type, x, y
+
+
+# Create vegetation patches for locations with high vegetation type
+for i in range(0,ndomains):  
+   if domain_canopy_patches[i]: 
+
+#     Load vegetation_type and lad array (at level z = 0) for re-processing
+      vegetation_type = nc_read_from_file_2d_all(filename[i], 'vegetation_type') 
+      lad = nc_read_from_file_3d_all(filename[i], 'lad') 
+      patch_height = nc_read_from_file_2d(input_file_patch_height[ii[i]], 'Band1', domain_x0[i], domain_x1[i], domain_y0[i], domain_y1[i]) 
+      vegetation_pars = nc_read_from_file_3d_all(filename[i], 'vegetation_pars') 
+      lai = vegetation_pars[1,:,:]
+
+#     For all pixels where the LAD array does not contains a street tree and for which a high vegetation was set and for which a patch height is either missing of larger than one grid spacing
+#     the lai_high is reset to a low vegetation value
+      lai_high = np.where( (lad[0,:,:] == fillvalues["tree_data"]) & ( ( (vegetation_type == 4) | (vegetation_type == 5) | (vegetation_type == 6) |(vegetation_type == 7) | (vegetation_type == 17) | (vegetation_type == 18) ) & ( (patch_height == fillvalues["tree_data"]) | (patch_height >= domain_dz[i])) ),settings_lai_low_default,fillvalues["tree_data"])
+
+#     For all pixels where lai_high is set but no lai is available, set the default high vegetation lai TODO: check if this makes sense bacauce lai_high = lai anway?!
+      lai_high = np.where( (lai_high != fillvalues["tree_data"]) & (lai == fillvalues["tree_data"]), settings_lai_high_default, lai_high)
+
+#     Define a patch height whereever it is missing, but where a high vegetation LAI was set
+      patch_height = np.where ( (lai_high != fillvalues["tree_data"]) & (patch_height == fillvalues["tree_data"]), settings_patch_height_default, patch_height)
+
+#     Remove pixels where street trees were already set
+      patch_height = np.where ( (lad[0,:,:] != fillvalues["tree_data"]), fillvalues["tree_data"], patch_height)
+
+#     For missing LAI values, set either the high vegetation default or the low vegetation default    
+      lai_high = np.where( (patch_height > 2.0) & (lai_high == fillvalues["tree_data"]),settings_lai_high_default,lai_high)
+      lai_high = np.where( (patch_height <= 2.0) & (lai_high == fillvalues["tree_data"]),settings_lai_low_default,lai_high)
+    
+    
+      if ( max(patch_height.flatten()) >= (2.0 * domain_dz[i]) ):
+         print("    start calculating LAD (this might take some time)") 
+         lad_patch, patch_nz, status = process_patch(domain_dz[i],patch_height,lai_high,settings_lai_alpha,settings_lai_beta)
+
+         lad[0:patch_nz+1,:,:] = np.where( (lad[0:patch_nz+1,:,:] == fillvalues["tree_data"]),lad_patch[0:patch_nz+1,:,:], lad[0:patch_nz+1,:,:] )
+
+#     Remove high vegetation wherever it is replaced by a leaf area density. This should effectively remove all high vegetation pixels
+      vegetation_type = np.where((lad[0,:,:] != fillvalues["tree_data"]) & (vegetation_type != fillvalues["vegetation_type"]),3,vegetation_type)
+  
+ 
+#     If desired, remove all high vegetation. TODO: check if this is still necessary
+      if domain_high_vegetation[i]:
+         vegetation_type = np.where((vegetation_type != fillvalues["vegetation_type"]) & ( (vegetation_type == 4) | (vegetation_type == 5) | (vegetation_type == 6) |(vegetation_type == 7) | (vegetation_type == 17) | (vegetation_type == 18) ),3,vegetation_type)   
+
+  
+#     Remove LAI from pixels where a LAD was set
+      lai_low = np.where( (lad[0,:,:] == fillvalues["tree_data"]), lai,fillvalues["tree_data"])
+    
+#     Fill low vegetation pixels without LAI set with default value
+      lai_low = np.where( (lai == fillvalues["tree_data"]) & (vegetation_type != fillvalues["vegetation_type"] ), settings_lai_low_default, lai)
+
+    
+#     Overwrite lai in vegetation_parameters  
+
+      vegetation_pars[1,:,:] = lai_low
+      nc_overwrite_to_file_3d(filename[i], 'vegetation_pars', vegetation_pars) 
+
+#     Overwrite lad array
+      nc_overwrite_to_file_3d(filename[i], 'lad', lad) 
+      
+#     Overwrite vegetation_type
+      nc_overwrite_to_file_2d(filename[i], 'vegetation_type', vegetation_type)   
+      
+      
+      del vegetation_type, lad, lai, patch_height, vegetation_pars
Index: palm/trunk/SCRIPTS/palm_csd_files/palm_csd_canopy_generator.py
===================================================================
--- palm/trunk/SCRIPTS/palm_csd_files/palm_csd_canopy_generator.py	(revision 3629)
+++ palm/trunk/SCRIPTS/palm_csd_files/palm_csd_canopy_generator.py	(revision 3629)
@@ -0,0 +1,552 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+#--------------------------------------------------------------------------------#
+# This file is part of the PALM model system.
+#
+# PALM is free software: you can redistribute it and/or modify it under the terms
+# of the GNU General Public License as published by the Free Software Foundation,
+# either version 3 of the License, or (at your option) any later version.
+#
+# PALM is distributed in the hope that it will be useful, but WITHOUT ANY
+# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License along with
+# PALM. If not, see <http://www.gnu.org/licenses/>.
+#
+# Copyright 1997-2018  Leibniz Universitaet Hannover
+#--------------------------------------------------------------------------------#
+#
+# Current revisions:
+# -----------------
+# 
+# 
+# Former revisions:
+# -----------------
+# $Id$
+# Initial revision
+# 
+# Description:
+# ------------
+# Canopy generator routines for creating 3D leaf and basal area densities for 
+# single trees and tree patches
+#
+# @Author Bjoern Maronga (maronga@muk.uni-hannover.de)
+#------------------------------------------------------------------------------#
+import numpy as np
+import math
+import scipy.integrate as integrate
+
+def generate_single_tree_lad(x,y,dz,max_tree_height,max_patch_height,tree_type,tree_height,tree_dia,trunk_dia,tree_lai,season,fill):
+
+
+#  Step 1: Create arrays for storing the data
+   max_canopy_height = max( max_tree_height,max_patch_height )
+ 
+   zlad = np.arange(0,math.floor(max_canopy_height/dz)*dz+2*dz,dz)
+   zlad[1:] = zlad[1:] - 0.5 * dz
+
+   lad = np.ones((len(zlad),len(y),len(x)))
+   lad[:,:,:] = fill
+
+   bad = np.ones((len(zlad),len(y),len(x)))
+   bad[:,:,:] = fill
+   
+   ids = np.ones((len(zlad),len(y),len(x)))
+   ids[:,:,:] = fill 
+   
+
+#  Calculating the number of trees in the arrays and a boolean array storing the location of trees which is used for convenience in the following loop environment   
+   number_of_trees_array = np.where( (tree_type.flatten() != fill) | (tree_dia.flatten() != fill) | (trunk_dia.flatten() != fill),1.0,fill)
+   number_of_trees = len( number_of_trees_array[number_of_trees_array == 1.0] )
+   dx = x[1] - x[0]
+       
+   valid_pixels = np.where( (tree_type[:,:] != fill) | (tree_dia[:,:] != fill) | (trunk_dia[:,:] != fill),True,False)
+   
+#  For each tree, create a small 3d array containing the LAD field for the individual tree
+   print("Start generating " +  str(number_of_trees) + " trees...")
+   tree_id_counter = 0
+   if (number_of_trees > 0):
+      for i in range(0,len(x)-1):
+         for j in range(0,len(y)-1):
+            if valid_pixels[j,i]:
+               tree_id_counter = tree_id_counter + 1
+               print("   Processing tree No " +  str(tree_id_counter) + " ...", end="")
+
+               lad_loc, bad_loc, x_loc, y_loc, z_loc, status = process_single_tree(dx,dz,tree_type[j,i],tree_height[j,i],tree_lai[j,i],tree_dia[j,i],trunk_dia[j,i],season)
+               if ( np.any(lad_loc) != fill ):
+ 
+#                 Calculate the position of the local 3d tree array within the full domain in order to achieve correct mapping and cutting off at the edges of the full domain
+                  lad_loc_nx = int(len(x_loc) / 2)
+                  lad_loc_ny = int(len(y_loc) / 2)
+                  lad_loc_nz = int(len(z_loc))
+                             
+                  odd_x = int(len(x_loc) % 2)
+                  odd_y = int(len(y_loc) % 2)
+               
+                  ind_l_x  = max(0,(i-lad_loc_nx))
+                  ind_l_y  = max(0,(j-lad_loc_ny))
+                  ind_r_x  = min(len(x)-1,i+lad_loc_nx-1+odd_x)
+                  ind_r_y  = min(len(y)-1,j+lad_loc_ny-1+odd_y)
+               
+                  out_l_x = ind_l_x - (i-lad_loc_nx)
+                  out_l_y = ind_l_y - (j-lad_loc_ny)
+                  out_r_x = len(x_loc)-1 + ind_r_x - (i+lad_loc_nx-1+odd_x)
+                  out_r_y = len(y_loc)-1 + ind_r_y - (j+lad_loc_ny-1+odd_y)               
+   
+
+                  lad[0:lad_loc_nz,ind_l_y:ind_r_y+1,ind_l_x:ind_r_x+1] = np.where(lad_loc[0:lad_loc_nz,out_l_y:out_r_y+1,out_l_x:out_r_x+1] != fill,lad_loc[0:lad_loc_nz,out_l_y:out_r_y+1,out_l_x:out_r_x+1],lad[0:lad_loc_nz,ind_l_y:ind_r_y+1,ind_l_x:ind_r_x+1]) 
+                  bad[0:lad_loc_nz,ind_l_y:ind_r_y+1,ind_l_x:ind_r_x+1] = np.where(bad_loc[0:lad_loc_nz,out_l_y:out_r_y+1,out_l_x:out_r_x+1] != fill,bad_loc[0:lad_loc_nz,out_l_y:out_r_y+1,out_l_x:out_r_x+1],bad[0:lad_loc_nz,ind_l_y:ind_r_y+1,ind_l_x:ind_r_x+1]) 
+                  ids[0:lad_loc_nz,ind_l_y:ind_r_y+1,ind_l_x:ind_r_x+1] = np.where(lad_loc[0:lad_loc_nz,out_l_y:out_r_y+1,out_l_x:out_r_x+1] != fill,tree_id_counter,ids[0:lad_loc_nz,ind_l_y:ind_r_y+1,ind_l_x:ind_r_x+1]) 
+
+
+                  if ( status == 0 ):
+                     status_char = " ok."
+                  else:
+                     status_char = " skipped."
+                  print(status_char)
+
+               del lad_loc, x_loc, y_loc, z_loc, status
+   return lad, bad, ids, zlad
+
+
+def process_single_tree(dx,dz,tree_type,tree_height,tree_lai,tree_dia,trunk_dia,season):
+
+#  Set some parameters
+   sphere_extinction = 0.6
+   cone_extinction = 0.2
+   ml_n_low = 0.5
+   ml_n_high = 6.0
+    
+#  Populate look up table for tree species and their properties
+#  #1 Tree shapes were manually lookep up.
+#  #2 Crown h/w ratio - missing
+#  #3 Crown diameter based on Berlin tree statistics
+#  #4 Tree height based on Berlin tree statistics
+#  #5 Tree LAI summer - missing
+#  #6 Tree LAI winter - missing
+#  #7 Height of lad maximum - missing
+#  #8 Ratio LAD/BAD - missing
+#  #9 Trunk diameter at breast height from Berlin 
+   default_trees = []
+                                                #1   #2   #3   #4    #5   #6   #7   #8     #9
+   default_trees.append(tree("Default",         1.0, 1.0, 4.0, 12.0, 2.0, 0.1, 0.6, 0.025, 0.35)) 
+   default_trees.append(tree("Abies",           3.0, 1.0, 4.0, 12.0, 2.0, 0.1, 0.6, 0.025, 0.80)) 
+   default_trees.append(tree("Acer",            1.0, 1.0, 7.0, 12.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Aesculus",        1.0, 1.0, 7.0, 12.0, 2.0, 0.1, 0.6, 0.025, 1.00))
+   default_trees.append(tree("Ailanthus",       1.0, 1.0, 8.5, 13.5, 2.0, 0.1, 0.6, 0.025, 1.30))
+   default_trees.append(tree("Alnus",           3.0, 1.0, 6.0, 16.0, 2.0, 0.1, 0.6, 0.025, 1.20))
+   default_trees.append(tree("Amelanchier",     1.0, 1.0, 3.0,  4.0, 2.0, 0.1, 0.6, 0.025, 1.20))
+   default_trees.append(tree("Betula",          1.0, 1.0, 6.0, 14.0, 2.0, 0.1, 0.6, 0.025, 0.30))
+   default_trees.append(tree("Buxus",           1.0, 1.0, 4.0,  4.0, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Calocedrus",      3.0, 1.0, 5.0, 10.0, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Caragana",        1.0, 1.0, 3.5,  6.0, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Carpinus",        1.0, 1.0, 6.0, 10.0, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Carya",           1.0, 1.0, 5.0, 17.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Castanea",        1.0, 1.0, 4.5,  7.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Catalpa",         1.0, 1.0, 5.5,  6.5, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Cedrus",          1.0, 1.0, 8.0, 13.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Celtis",          1.0, 1.0, 6.0,  9.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Cercidiphyllum",  1.0, 1.0, 3.0,  6.5, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Cercis",          1.0, 1.0, 2.5,  7.5, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Chamaecyparis",   5.0, 1.0, 3.5,  9.0, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Cladrastis",      1.0, 1.0, 5.0, 10.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Cornus",          1.0, 1.0, 4.5,  6.5, 2.0, 0.1, 0.6, 0.025, 1.20))
+   default_trees.append(tree("Corylus",         1.0, 1.0, 5.0,  9.0, 2.0, 0.1, 0.6, 0.025, 0.40))
+   default_trees.append(tree("Cotinus",         1.0, 1.0, 4.0,  4.0, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Crataegus",       3.0, 1.0, 3.5,  6.0, 2.0, 0.1, 0.6, 0.025, 1.40))
+   default_trees.append(tree("Cryptomeria",     3.0, 1.0, 5.0, 10.0, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Cupressocyparis", 3.0, 1.0, 3.0,  8.0, 2.0, 0.1, 0.6, 0.025, 0.40))
+   default_trees.append(tree("Cupressus",       3.0, 1.0, 5.0,  7.0, 2.0, 0.1, 0.6, 0.025, 0.40))
+   default_trees.append(tree("Cydonia",         1.0, 1.0, 2.0,  3.0, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Davidia",         1.0, 1.0,10.0, 14.0, 2.0, 0.1, 0.6, 0.025, 0.40))
+   default_trees.append(tree("Elaeagnus",       1.0, 1.0, 6.5,  6.0, 2.0, 0.1, 0.6, 0.025, 1.20))
+   default_trees.append(tree("Euodia",          1.0, 1.0, 4.5,  6.0, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Euonymus",        1.0, 1.0, 4.5,  6.0, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Fagus",           1.0, 1.0,10.0, 12.5, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Fraxinus",        1.0, 1.0, 5.5, 10.5, 2.0, 0.1, 0.6, 0.025, 1.60))
+   default_trees.append(tree("Ginkgo",          3.0, 1.0, 4.0,  8.5, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Gleditsia",       1.0, 1.0, 6.5, 10.5, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Gymnocladus",     1.0, 1.0, 5.5, 10.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Hippophae",       1.0, 1.0, 9.5,  8.5, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Ilex",            1.0, 1.0, 4.0,  7.5, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Juglans",         1.0, 1.0, 7.0,  9.0, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Juniperus",       5.0, 1.0, 3.0,  7.0, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Koelreuteria",    1.0, 1.0, 3.5,  5.5, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Laburnum",        1.0, 1.0, 3.0,  6.0, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Larix",           3.0, 1.0, 7.0, 16.5, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Ligustrum",       1.0, 1.0, 3.0,  6.0, 2.0, 0.1, 0.6, 0.025, 1.10))
+   default_trees.append(tree("Liquidambar",     3.0, 1.0, 3.0,  7.0, 2.0, 0.1, 0.6, 0.025, 0.30))
+   default_trees.append(tree("Liriodendron",    3.0, 1.0, 4.5,  9.5, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Lonicera",        1.0, 1.0, 7.0,  9.0, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Magnolia",        1.0, 1.0, 3.0,  5.0, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Malus",           1.0, 1.0, 4.5,  5.0, 2.0, 0.1, 0.6, 0.025, 0.30))
+   default_trees.append(tree("Metasequoia",     5.0, 1.0, 4.5, 12.0, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Morus",           1.0, 1.0, 7.5, 11.5, 2.0, 0.1, 0.6, 0.025, 1.00))
+   default_trees.append(tree("Ostrya",          1.0, 1.0, 2.0,  6.0, 2.0, 0.1, 0.6, 0.025, 1.00))
+   default_trees.append(tree("Parrotia",        1.0, 1.0, 7.0,  7.0, 2.0, 0.1, 0.6, 0.025, 0.30))
+   default_trees.append(tree("Paulownia",       1.0, 1.0, 4.0,  8.0, 2.0, 0.1, 0.6, 0.025, 0.40))
+   default_trees.append(tree("Phellodendron",   1.0, 1.0,13.5, 13.5, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Picea",           3.0, 1.0, 3.0, 13.0, 2.0, 0.1, 0.6, 0.025, 0.90))
+   default_trees.append(tree("Pinus",           3.0, 1.0, 6.0, 16.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Platanus",        1.0, 1.0,10.0, 14.5, 2.0, 0.1, 0.6, 0.025, 1.10))
+   default_trees.append(tree("Populus",         1.0, 1.0, 9.0, 20.0, 2.0, 0.1, 0.6, 0.025, 1.40))
+   default_trees.append(tree("Prunus",          1.0, 1.0, 5.0,  7.0, 2.0, 0.1, 0.6, 0.025, 1.60))
+   default_trees.append(tree("Pseudotsuga",     3.0, 1.0, 6.0, 17.5, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Ptelea",          1.0, 1.0, 5.0,  4.0, 2.0, 0.1, 0.6, 0.025, 1.10))
+   default_trees.append(tree("Pterocaria",      1.0, 1.0,10.0, 12.0, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Pterocarya",      1.0, 1.0,11.5, 14.5, 2.0, 0.1, 0.6, 0.025, 1.60))
+   default_trees.append(tree("Pyrus",           3.0, 1.0, 3.0,  6.0, 2.0, 0.1, 0.6, 0.025, 1.80))
+   default_trees.append(tree("Quercus",         1.0, 1.0, 8.0, 14.0, 3.1, 0.1, 0.6, 0.025, 0.40)) #
+   default_trees.append(tree("Rhamnus",         1.0, 1.0, 4.5,  4.5, 2.0, 0.1, 0.6, 0.025, 1.30))
+   default_trees.append(tree("Rhus",            1.0, 1.0, 7.0,  5.5, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Robinia",         1.0, 1.0, 4.5, 13.5, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Salix",           1.0, 1.0, 7.0, 14.0, 2.0, 0.1, 0.6, 0.025, 1.10))
+   default_trees.append(tree("Sambucus",        1.0, 1.0, 8.0,  6.0, 2.0, 0.1, 0.6, 0.025, 1.40))
+   default_trees.append(tree("Sasa",            1.0, 1.0,10.0, 25.0, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Sequoiadendron",  5.0, 1.0, 5.5, 10.5, 2.0, 0.1, 0.6, 0.025, 1.60))
+   default_trees.append(tree("Sophora",         1.0, 1.0, 7.5, 10.0, 2.0, 0.1, 0.6, 0.025, 1.40))
+   default_trees.append(tree("Sorbus",          1.0, 1.0, 4.0,  7.0, 2.0, 0.1, 0.6, 0.025, 1.10))
+   default_trees.append(tree("Syringa",         1.0, 1.0, 4.5,  5.0, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Tamarix",         1.0, 1.0, 6.0,  7.0, 2.0, 0.1, 0.6, 0.025, 0.50))
+   default_trees.append(tree("Taxodium",        5.0, 1.0, 6.0, 16.5, 2.0, 0.1, 0.6, 0.025, 0.60))
+   default_trees.append(tree("Taxus",           2.0, 1.0, 5.0,  7.5, 2.0, 0.1, 0.6, 0.025, 1.50))
+   default_trees.append(tree("Thuja",           3.0, 1.0, 3.5,  9.0, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Tilia",           3.0, 1.0, 7.0, 12.5, 2.0, 0.1, 0.6, 0.025, 0.70))
+   default_trees.append(tree("Tsuga",           3.0, 1.0, 6.0, 10.5, 2.0, 0.1, 0.6, 0.025, 1.10))
+   default_trees.append(tree("Ulmus",           1.0, 1.0, 7.5, 14.0, 2.0, 0.1, 0.6, 0.025, 0.80))
+   default_trees.append(tree("Zelkova",         1.0, 1.0, 4.0,  5.5, 2.0, 0.1, 0.6, 0.025, 1.20))
+   default_trees.append(tree("Zenobia",         1.0, 1.0, 5.0,  5.0, 2.0, 0.1, 0.6, 0.025, 0.40))
+   
+#  Define fill values
+   fillvalues = {
+   "tree_data": float(-9999.0),
+   }
+   
+   
+#  Check for missing data in the input and set default values if needed
+   if ( tree_type == fillvalues["tree_data"] ):
+      tree_type = int(0)
+   else:
+      tree_type = int(tree_type)
+
+   if ( tree_height == fillvalues["tree_data"] ):
+      tree_height = default_trees[tree_type].height
+      
+   if ( tree_lai == fillvalues["tree_data"] ):
+      if (season == "summer"):
+         tree_lai = default_trees[tree_type].lai_summer
+      else:
+         tree_lai = default_trees[tree_type].lai_winter      
+
+   if ( tree_dia == fillvalues["tree_data"] ):
+      tree_dia = default_trees[tree_type].diameter
+      
+   if ( trunk_dia == fillvalues["tree_data"] ):
+      trunk_dia = default_trees[tree_type].dbh   
+ 
+ 
+#  Assign values that are not defined as user input from lookup table
+   tree_shape          = default_trees[tree_type].shape
+   tree_ratio          = default_trees[tree_type].ratio
+   lad_max_height      = default_trees[tree_type].lad_max_height
+   bad_scale           = default_trees[tree_type].bad_scale
+
+   #print("Tree input parameters:")
+   #print("----------------------")
+   #print("type:           " + str(default_trees[tree_type].species) )
+   #print("height:         " + str(tree_height))
+   #print("lai:            " + str(tree_lai))
+   #print("crown diameter: " + str(tree_dia))
+   #print("trunk diameter: " + str(trunk_dia))
+   #print("shape: " + str(tree_shape))
+   #print("height/width: " + str(tree_ratio))
+
+#  Calculate crown height and height of the crown center
+   crown_height   = tree_ratio * tree_dia
+   if ( crown_height > tree_height ):
+      crown_height = tree_height
+
+   crown_center   = tree_height - crown_height * 0.5
+
+
+#  Calculate height of maximum LAD
+   z_lad_max = lad_max_height * tree_height
+   
+#  Calculate the maximum LAD after Lalic and Mihailovic (2004)
+   lad_max_part_1 = integrate.quad(lambda z: ( ( tree_height - z_lad_max ) / ( tree_height - z ) ) ** (ml_n_high) * np.exp( ml_n_high * (1.0 - ( tree_height - z_lad_max ) / ( tree_height - z ) ) ), 0.0, z_lad_max)
+   lad_max_part_2 = integrate.quad(lambda z: ( ( tree_height - z_lad_max ) / ( tree_height - z ) ) ** (ml_n_low) * np.exp( ml_n_low * (1.0 - ( tree_height - z_lad_max ) / ( tree_height - z ) ) ), z_lad_max, tree_height)
+   
+   lad_max = tree_lai / (lad_max_part_1[0] + lad_max_part_2[0])
+
+   
+   
+#  Define position of tree and its output domain
+   nx = int(tree_dia / dx) + 2
+   nz = int(tree_height / dz) + 2
+    
+#  Add one grid point if diameter is an odd value    
+   if ( (tree_dia % 2.0) != 0.0 ):
+      nx = nx + 1
+
+
+#  Create local domain of the tree's LAD
+   x = np.arange(0,nx*dx,dx)
+   x[:] = x[:] - 0.5 * dx
+   y = x
+
+   z = np.arange(0,nz*dz,dz)
+   z[1:] = z[1:] - 0.5 * dz
+
+
+#  Define center of the tree position inside the local LAD domain
+   tree_location_x = x[nx/2]
+   tree_location_y = y[nx/2]
+
+
+#  Calculate LAD profile after Lalic and Mihailovic (2004). Will be later used for normalization
+   lad_profile     =  np.arange(0,nz,1.0)
+   lad_profile[:]  = 0.0
+
+   for k in range(1,nz-1):
+       if ( (z[k] > 0.0) & (z[k] < z_lad_max) ):
+          n = ml_n_high
+       else:
+          n = ml_n_low
+     
+       lad_profile[k] =  lad_max * ( ( tree_height - z_lad_max ) / ( tree_height - z[k] ) ) ** (n) * np.exp( n * (1.0 - ( tree_height - z_lad_max ) / ( tree_height - z[k] ) ) )
+
+#  Create lad array and populate according to the specific tree shape. This is still experimental
+   lad_loc = np.ones((nz,nx,nx))
+   lad_loc[:,:,:] = fillvalues["tree_data"]
+   bad_loc = np.copy(lad_loc)
+
+
+#  For very small trees, no LAD is calculated
+   if ( tree_height <=  (0.5*dz) ):
+        print("    Shallow tree found. Action: ignore.")
+        return lad_loc, bad_loc, x, y, z, 1
+   
+   
+#  Branch for spheres and ellipsoids. A symmetric LAD sphere is created assuming an LAD extinction towards the center of the tree, representing the effect of sunlight extinction and thus
+#  less leaf mass inside the tree crown. Extinction coefficients are experimental.
+   if ( tree_shape == 1 ):
+      for i in range(0,nx-1):
+         for j in range(0,nx-1):
+            for k in range(0,nz):
+               r_test = np.sqrt( (x[i] - tree_location_x)**(2)/(tree_dia * 0.5)**(2) + (y[j] - tree_location_y)**(2)/(tree_dia * 0.5)**2 + (z[k] - crown_center)**(2)/(crown_height * 0.5)**(2))
+               if ( r_test <= 1.0 ):
+                  lad_loc[k,j,i] = lad_max * np.exp( - sphere_extinction * (1.0 - r_test) )  
+               else:
+                  lad_loc[k,j,i] = fillvalues["tree_data"]
+
+            if ( np.any( lad_loc[:,j,i] != fillvalues["tree_data"]) ):
+               lad_loc[0,j,i] = 0.0
+
+
+#  Branch for cylinder shapes
+   if ( tree_shape == 2 ):
+      k_min = int((crown_center - crown_height * 0.5) / dz)
+      k_max = int((crown_center + crown_height * 0.5) / dz)
+      for i in range(0,nx-1):
+         for j in range(0,nx-1):
+            for k in range(k_min,k_max):
+               r_test = np.sqrt( (x[i] - tree_location_x)**(2)/(tree_dia * 0.5)**(2) + (y[j] - tree_location_y)**(2)/(tree_dia * 0.5)**(2))
+               if ( r_test <= 1.0 ):
+                  r_test3 = np.sqrt( (z[k] - crown_center)**(2)/(crown_height * 0.5)**(2))
+                  lad_loc[k,j,i] = lad_max * np.exp ( - sphere_extinction * (1.0 - max(r_test,r_test3) ) )                 
+               else:
+                  lad_loc[k,j,i] = fillvalues["tree_data"]
+
+            if ( np.any( lad_loc[:,j,i] != fillvalues["tree_data"]) ):
+               lad_loc[0,j,i] = 0.0
+
+#  Branch for cone shapes
+   if ( tree_shape == 3 ):
+      k_min = int((crown_center - crown_height * 0.5) / dz)
+      k_max = int((crown_center + crown_height * 0.5) / dz)
+      for i in range(0,nx-1):
+         for j in range(0,nx-1):
+            for k in range(k_min,k_max):
+               k_rel = k - k_min
+               r_test = (x[i] - tree_location_x)**(2) + (y[j] - tree_location_y)**(2) - ( (tree_dia * 0.5)**(2) / crown_height**(2) ) * ( z[k_rel] - crown_height)**(2)
+               if ( r_test <= 0.0 ):
+                  r_test2 = np.sqrt( (x[i] - tree_location_x)**(2)/(tree_dia * 0.5)**(2) + (y[j] - tree_location_y)**(2)/(tree_dia * 0.5)**(2))
+                  r_test3 = np.sqrt( (z[k] - crown_center)**(2)/(crown_height * 0.5)**(2))
+                  lad_loc[k,j,i] = lad_max * np.exp ( - cone_extinction * (1.0 - max((r_test+1.0),r_test2,r_test3)) )         
+               else:
+                  lad_loc[k,j,i] = fillvalues["tree_data"]
+
+            if ( np.any( lad_loc[:,j,i] != fillvalues["tree_data"]) ):
+               lad_loc[0,j,i] = 0.0
+ 
+#  Branch for inverted cone shapes. TODO: what is r_test2 and r_test3 used for? Debugging needed!
+   if ( tree_shape == 4 ):
+      k_min = int((crown_center - crown_height * 0.5) / dz)
+      k_max = int((crown_center + crown_height * 0.5) / dz)
+      for i in range(0,nx-1):
+         for j in range(0,nx-1):
+            for k in range(k_min,k_max):
+               k_rel = k_max - k
+               r_test = (x[i] - tree_location_x)**(2) + (y[j] - tree_location_y)**(2) - ( (tree_dia * 0.5)**(2) / crown_height**(2) ) * ( z[k_rel] - crown_height)**(2)
+               if ( r_test <= 0.0 ):
+                  r_test2 = np.sqrt( (x[i] - tree_location_x)**(2)/(tree_dia * 0.5)**(2) + (y[j] - tree_location_y)**(2)/(tree_dia * 0.5)**(2))
+                  r_test3 = np.sqrt( (z[k] - crown_center)**(2)/(crown_height * 0.5)**(2))
+                  lad_loc[k,j,i] = lad_max * np.exp ( - cone_extinction * ( - r_test ) )         
+               else:
+                  lad_loc[k,j,i] = fillvalues["tree_data"]
+
+            if ( np.any( lad_loc[:,j,i] != fillvalues["tree_data"]) ):
+               lad_loc[0,j,i] = 0.0
+ 
+ 
+#  Branch for paraboloid shapes
+   if ( tree_shape == 5 ):
+      k_min = int((crown_center - crown_height * 0.5) / dz)
+      k_max = int((crown_center + crown_height * 0.5) / dz)
+      for i in range(0,nx-1):
+         for j in range(0,nx-1):
+            for k in range(k_min,k_max):
+               k_rel = k - k_min
+               r_test = ((x[i] - tree_location_x)**(2) + (y[j] - tree_location_y)**(2)) * crown_height / (tree_dia * 0.5)**(2) - z[k_rel]
+               if ( r_test <= 0.0 ):
+                   lad_loc[k,j,i] = lad_max * np.exp ( - cone_extinction * (- r_test) )                
+               else:
+                  lad_loc[k,j,i] = fillvalues["tree_data"]
+
+            if ( np.any( lad_loc[:,j,i] != fillvalues["tree_data"]) ):
+               lad_loc[0,j,i] = 0.0
+ 
+ 
+ 
+#  Branch for inverted paraboloid shapes
+   if ( tree_shape == 6 ):
+      k_min = int((crown_center - crown_height * 0.5) / dz)
+      k_max = int((crown_center + crown_height * 0.5) / dz)
+      for i in range(0,nx-1):
+         for j in range(0,nx-1):
+            for k in range(k_min,k_max):
+               k_rel = k_max - k
+               r_test = ((x[i] - tree_location_x)**(2) + (y[j] - tree_location_y)**(2)) * crown_height / (tree_dia * 0.5)**(2) - z[k_rel]
+               if ( r_test <= 0.0 ):
+                   lad_loc[k,j,i] = lad_max * np.exp ( - cone_extinction * (- r_test) )                
+               else:
+                  lad_loc[k,j,i] = fillvalues["tree_data"]
+
+            if ( np.any( lad_loc[:,j,i] != fillvalues["tree_data"]) ):
+               lad_loc[0,j,i] = 0.0 
+ 
+ 
+#  Normalize the LAD profile so that the vertically integrated Lalic and Mihailovic (2004) is reproduced by the LAD array. Deactivated for now.
+   #for i in range(0,nx-1):
+      #for j in range(0,nx-1):
+         #lad_clean = np.where(lad_loc[:,j,i] == fillvalues["tree_data"],0.0,lad_loc[:,j,i])
+         #lai_from_int = integrate.simps (lad_clean, z)
+         #print(lai_from_int)
+         #for k in range(0,nz):
+            #if ( np.any(lad_loc[k,j,i] > 0.0) ):  
+               #lad_loc[k,j,i] = np.where((lad_loc[k,j,i] != fillvalues["tree_data"]),lad_loc[k,j,i] / lai_from_int * lad_profile[k],lad_loc[k,j,i])
+
+
+#  Dreate BAD array and populate
+   bad_loc = np.where(lad_loc != fillvalues["tree_data"],lad_loc*0.01,lad_loc)
+   
+
+#  Overwrite grid cells that are occupied by the tree trunk
+   radius = trunk_dia * 0.5
+   for i in range(0,nx-1):
+      for j in range(0,nx-1):
+         for k in range(0,nz):
+            if ( z[k] <= crown_center ):
+               r_test = np.sqrt( (x[i] - tree_location_x)**(2) + (y[j] - tree_location_y)**(2)  )
+               if ( r_test <= radius ):
+                  bad_loc[k,j,i] = 1.0
+               if ( (r_test == 0.0) & (trunk_dia <= dx) ):
+                   bad_loc[k,j,i] = radius**(2) * 3.14159265359
+
+   return lad_loc, bad_loc, x, y, z, 0
+
+
+def process_patch(dz,patch_height,patch_lai,alpha,beta):
+   
+#  Define fill values
+   fillvalues = {
+   "tree_data": float(-9999.0),
+   "pch_index": int(-9999),
+   }
+
+   phdz = patch_height[:,:] / dz
+   pch_index = np.where( (patch_height[:,:] != fillvalues["tree_data"]),phdz.astype(int)+1,int(-1))    
+   pch_index = np.where( (pch_index[:,:] == 0) ,fillvalues["pch_index"],pch_index[:,:])
+   pch_index = np.where( (pch_index[:,:] == -1) ,0,pch_index[:,:])
+
+   max_canopy_height = max(patch_height.flatten())
+
+   z = np.arange(0,math.floor(max_canopy_height/dz)*dz+2*dz,dz)
+   
+   z[1:] = z[1:] - 0.5 * dz
+
+   nz = len(z)
+   ny = len(patch_height[:,0])
+   nx = len(patch_height[0,:])
+
+   pre_lad = np.ones((nz))
+   pre_lad[:] = 0.0
+   lad_loc = np.ones( (nz,ny,nx) )
+   lad_loc[:,:,:] = fillvalues["tree_data"]
+    
+   for i in range(0,nx-1):
+      for j in range(0,ny-1):
+          int_bpdf = 0.0
+          if ( (patch_height[j,i] != fillvalues["tree_data"]) & (patch_height[j,i] >= (0.5*dz)) ):
+             for k in range(0,pch_index[j,i]):
+                int_bpdf = int_bpdf + ( ( ( z[k] / patch_height[j,i] )**( alpha - 1 ) ) * ( ( 1.0 - ( z[k] / patch_height[j,i] ) )**(beta - 1 ) ) * ( dz / patch_height[j,i] ) )
+
+             for k in range(0,pch_index[j,i]):
+                pre_lad[k] =  patch_lai[j,i] * ( ( ( dz*k / patch_height[j,i] )**( alpha - 1.0 ) ) * ( ( 1.0 - ( dz*k / patch_height[j,i] ) )**(beta - 1.0 ) ) / int_bpdf ) / patch_height[j,i]
+
+             lad_loc[0,j,i] = pre_lad[0]
+             
+             for k in range(0,pch_index[j,i]):            
+                lad_loc[k,j,i] = 0.5 * ( pre_lad[k-1] + pre_lad[k] )
+
+   return lad_loc, nz, 0
+
+
+# CLASS TREE
+#
+# Default tree geometrical parameters:
+#
+# species: name of the tree type 
+#
+# shape: defines the general shape of the tree and can be one of the following types:
+# 1.0 sphere or ellipsoid
+# 2.0 cylinder
+# 3.0 cone
+# 4.0 inverted cone
+# 5.0 paraboloid (rounded cone)
+# 6.0 inverted paraboloid (invertes rounded cone)
+#  
+# ratio:  ratio of maximum crown height to the maximum crown diameter
+# diameter: default crown diameter (m)
+# height:   default total height of the tree including trunk (m)
+# lai_summer: default leaf area index fully leafed
+# lai_winter: default winter-teim leaf area index
+# lad_max: default maximum leaf area density (m2/m3)
+# lad_max_height: default height where the leaf area density is maximum relative to total tree height
+# bad_scale: ratio of basal area in the crown area to the leaf area
+# dbh: default trunk diameter at breast height (1.4 m) (m)
+#
+#
+class tree:
+    def __init__(self, species, shape, ratio, diameter, height, lai_summer, lai_winter, lad_max_height, bad_scale, dbh): 
+       self.species = species
+       self.shape = shape
+       self.ratio = ratio
+       self.diameter = diameter
+       self.height = height
+       self.lai_summer = lai_summer
+       self.lai_winter = lai_winter
+       self.lad_max_height = lad_max_height
+       self.bad_scale = bad_scale
+       self.dbh = dbh    
Index: palm/trunk/SCRIPTS/palm_csd_files/palm_csd_netcdf_interface.py
===================================================================
--- palm/trunk/SCRIPTS/palm_csd_files/palm_csd_netcdf_interface.py	(revision 3628)
+++ palm/trunk/SCRIPTS/palm_csd_files/palm_csd_netcdf_interface.py	(revision 3629)
@@ -25,9 +25,8 @@
 # -----------------
 # $Id$
+# Some new routines
+# 
+# 3567 2018-11-27 13:59:21Z maronga
 # Initial revisions
-#
-#
-# 
-#
 #
 # Description:
@@ -76,4 +75,23 @@
    nc_file = Dataset(filename, "r+", format="NETCDF4")
    tmp_array = np.array(nc_file.variables[varname][:][:], dtype=type(nc_file.variables[varname]))
+
+   return tmp_array
+
+def nc_read_from_file_3d_all(filename, varname):
+
+
+   import numpy as np
+   import sys
+   
+   try:
+      f = open(filename)
+      f.close()
+#      print("Load: " + filename + ".")
+   except FileNotFoundError:
+      print("Error: " + filename + ". No such file. Aborting...")
+      sys.exit(1)
+   
+   nc_file = Dataset(filename, "r+", format="NETCDF4")
+   tmp_array = np.array(nc_file.variables[varname][:][:][:], dtype=type(nc_file.variables[varname]))
 
    return tmp_array
@@ -212,4 +230,22 @@
    return 0
 
+def nc_overwrite_to_file_3d(filename,varname,array):
+
+   try:
+      f =  Dataset(filename, "a", format="NETCDF4")
+      #print("Opened: " + filename + ".")
+   except FileNotFoundError:
+      print("Error. Could not open file: " + filename + ". Aborting...")
+      sys.exit(1)
+
+   print("Writing array " + varname + " to file...")
+   
+   temp = f.variables[varname]
+   temp[:,:,:] = array
+   
+   f.close()
+
+   return 0
+
 def nc_write_to_file_3d(filename,varname,array,datatype,dimname1,dimname2,dimname3,fillvalue):
 
