Skip to content

Lattice Sun and Shadow

This script generates an interpolated sun and shadow lattice. To do this the script imports a sunpath from ladybug.

This Sunpath takes as input a longtitude and latitude over which to take the sun information. Based on the capacity of your hardware, or the size of the lattice over which to calculate

For each voxel it casts a ray towards the sunpath. Because of the context arround the building, this ray could be blocked- the voxel does not receive light from this sunray. For all the voxels that have received light, it then casts the ray from the voxel to the sun backwards, to check whether it blocks sun (casts a shadow) from the context.

As an input it takes a low_res and highres_lattice and a Sunpath and as output it generates a high_res and low_res lightvalue

0. Initialization

Importing all necessary libraries and specifying the inputs

import os
import topogenesis as tg
import pyvista as pv
import trimesh as tm
import numpy as np
from ladybug.sunpath import Sunpath
from scipy.interpolate import RegularGridInterpolator

1. Import Meshes (context + envelope)

1.1. Load Meshes

#loading envelope and context from obj 
envelope_path = os.path.relpath('../data/compulsory_envelope.obj')
context_path = os.path.relpath('../data/immediate_context.obj')

# load the mesh from file
envelope_mesh = tm.load(envelope_path)
context_mesh = tm.load(context_path)

# Check if the mesh is watertight
print(envelope_mesh.is_watertight)
print(context_mesh.is_watertight)

1.2. Visualize Meshes (with pyvista)

# convert mesh to pv_mesh
def tri_to_pv(tri_mesh):
    faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3)
    pv_mesh = pv.PolyData(tri_mesh.vertices, faces)
    return pv_mesh

# initiating the plotter
p = pv.Plotter(notebook=True)

# adding the meshes
p.add_mesh(tri_to_pv(envelope_mesh), color='#abd8ff')
p.add_mesh(tri_to_pv(context_mesh), color='#aaaaaa')

# plotting
p.show(use_ipyvtk=True)

2. Import Lattice (envelope)

2.1. Load the Envelope Lattice

# loading the lattice from csv
lattice_path = os.path.relpath('../data/voxelized_envelope_lowres.csv')
envelope_lattice = tg.lattice_from_csv(lattice_path)

#setting the full lattice 
full_lattice = envelope_lattice * 0 + 1

# loading the lattice from csv
lattice_path = os.path.relpath('../data/voxelized_envelope_highres.csv')
avail_lattice_highres = tg.lattice_from_csv(lattice_path)

2.2. Visualize the Context Mesh + Envelope Lattice

# convert mesh to pv_mesh
def tri_to_pv(tri_mesh):
    faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3)
    pv_mesh = pv.PolyData(tri_mesh.vertices, faces)
    return pv_mesh

# initiating the plotter
p = pv.Plotter(notebook=True)

# fast visualization of the lattice
envelope_lattice.fast_vis(p)

# adding the meshes
p.add_mesh(tri_to_pv(context_mesh), color='#aaaaaa')

# plotting
p.show(use_ipyvtk=True)

3. Sun Vectors

3.1. Compute Sun Vectors

# initiate sunpath
sp = Sunpath(longitude=4.3571, latitude=52.0116)

# defening sun hours
hoys = []
sun_vectors = []
day_multiples = 90
for d in range(365):
    if d%day_multiples==0:
        for h in range(24):
            i = d*24 + h
            # compute the sun object
            sun = sp.calculate_sun_from_hoy(i)
            # extract the sun vector
            sun_vector = sun.sun_vector.to_array()
            # Removing the sun vectors under the horizon 
            if sun_vector[2] < 0.0:
                hoys.append(i)
                sun_vectors.append(sun_vector)

sun_vectors = np.array(sun_vectors)
# compute the rotation matrix 
Rz = tm.transformations.rotation_matrix(np.radians(36.324), [0,0,1])
# Rotate the sun vectors to match the site rotation
sun_vectors = tm.transform_points(sun_vectors, Rz)
print(sun_vectors.shape)
# convert mesh to pv_mesh
def tri_to_pv(tri_mesh):
    faces = np.pad(tri_mesh.faces, ((0, 0),(1,0)), 'constant', constant_values=3)
    pv_mesh = pv.PolyData(tri_mesh.vertices, faces)
    return pv_mesh

# initiating the plotter
p = pv.Plotter(notebook=True)

# fast visualization of the lattice
envelope_lattice.fast_vis(p)

# adding the meshes
p.add_mesh(tri_to_pv(context_mesh), color='#aaaaaa')

# add the sun locations, color orange
p.add_points( - sun_vectors * 300, color='#ffa500')

# plotting
p.show(use_ipyvtk=True)

4. Compute Intersection of Sun Rays with Context Mesh

4.1. Preparing the List of Ray Directions and Origins

# constructing the sun direction from the sun vectors in a numpy array
sun_dirs = -np.array(sun_vectors)

# exract the centroids of the envelope voxels
full_lattice = envelope_lattice * 0 + 1
vox_cens = full_lattice.centroids

# shoot towards all sun vectors from all voxel centroids
ray_dir = []
ray_src = []
for v_cen in vox_cens:
    for s_dir in sun_dirs:
        ray_dir.append(s_dir)
        ray_src.append(v_cen)

# converting the list of directions and sources to numpy array
ray_dir = np.array(ray_dir)
ray_src = np.array(ray_src)

print("number of voxels to shoot rays from :",vox_cens.shape)
print("number of rays per each voxel :",sun_dirs.shape)
print("number of rays to be shooted :",ray_src.shape)

4.2. Computing the Intersection

# computing the intersections of rays with the context mesh from voxel centroid towards sun 
f_tri_id, f_ray_id = context_mesh.ray.intersects_id(ray_origins=ray_src, ray_directions=ray_dir, multiple_hits=False)
# computing the intersections of rays with the context mesh from voxel centroid backwards to context 
b_tri_id, b_ray_id = context_mesh.ray.intersects_id(ray_origins=ray_src, ray_directions=-ray_dir, multiple_hits=False)

5. Aggregate Simulation Result in the Sun Access Lattice and shadow access lattice

# initializing the hits list full of zeros
f_hits = [0]*len(ray_dir)
b_hits = [0]*len(ray_dir)

for id in f_ray_id:
    f_hits[id] = 1

for id in b_ray_id:
    if not f_hits[id]:
        b_hits[id] = 1

calculating the sun_access and shadow

# initiating the sun and vox list
sun_count = len(sun_dirs)
vox_count = len(vox_cens)

# initiating the list of ratio
vox_sun_acc = []
# iterate over the voxels
for v_id in range(vox_count):
    # counter for the intersection
    int_count = 0
    # iterate over the sun rays
    for s_id in range(sun_count):
        # computing the ray id from voxel id and sun id
        r_id = s_id + v_id * sun_count 

        # summing the intersections
        int_count += f_hits[r_id]

    # computing the percentage of the rays that DID NOT have an intersection
    sun_access =   1 - int_count/sun_count

    # add the ratio to list
    vox_sun_acc.append(sun_access)


# hits = np.array(hits)
vox_sun_acc = np.array(vox_sun_acc)
# initiating the list of ratio
vox_shadowing = []

# iterate over the voxels
for v_id in range(vox_count):
    # counter for the intersection
    int_count = 0
    # iterate over the sun rays
    for s_id in range(sun_count):
        # computing the ray id from voxel id and sun id
        r_id = s_id + v_id * sun_count 

        # summing the intersections
        int_count += b_hits[r_id]

    # computing the percentage of the rays that DID NOT have an intersection 
    shadowing =  int_count/sun_count

    # add the ratio to list
    vox_shadowing.append(shadowing)

vox_shadowing = np.array(vox_shadowing)

5.2. Store shadow access information in a Lattice

# getting the condition of all voxels: are they inside the envelope or not
env_all_vox = full_lattice.flatten()

# all voxels cast shadow access
all_vox_shad_cast = []

# v_id: voxel id in the list of only interior voxels
v_id = 0

# for all the voxels, place the interiority condition of each voxel in "vox_in"
for vox_in in env_all_vox:
    if vox_in == True:
        # read its value of sun access and append it to the list of all voxel sun access
        all_vox_shad_cast.append(vox_shadowing[v_id])
        # add one to the voxel id so the next time we read the next voxel
        v_id += 1 
    else:
        # add 0.0 for its sun access
        all_vox_shad_cast.append(0.0)

# convert to array
shadcast_array = np.array(all_vox_shad_cast)

# reshape to lattice shape
shadcast_array = shadcast_array.reshape(envelope_lattice.shape)

# convert to lattice
shadcast_lattice = tg.to_lattice(shadcast_array, envelope_lattice)


print(shadcast_lattice.shape)

5.2.1 Store sun access information in a Lattice

# getting the condition of all voxels: are they inside the envelop or not
env_all_vox = full_lattice.flatten()

# all voxels sun access
all_vox_sunacc = []

# v_id: voxel id in the list of only interior voxels
v_id = 0

# for all the voxels, place the interiority condition of each voxel in "vox_in"
for vox_in in env_all_vox:
    if vox_in == True:
        # read its value of sun access and append it to the list of all voxel sun access
        all_vox_sunacc.append(vox_sun_acc[v_id])
        # add one to the voxel id so the next time we read the next voxel
        v_id += 1 
    else:
        # add 0.0 for its sun access
        all_vox_sunacc.append(0.0)

# convert to array
sunacc_array = np.array(all_vox_sunacc)

# reshape to lattice shape
sunacc_array = sunacc_array.reshape(envelope_lattice.shape)

# convert to lattice
sunacc_lattice = tg.to_lattice(sunacc_array, envelope_lattice)


print(sunacc_lattice.shape)

5.2. shadow lattice information

# initiating the plotter
p = pv.Plotter(notebook=True)

vis_lattice = shadcast_lattice
# Create the spatial reference
grid = pv.UniformGrid()

# Set the grid dimensions: shape because we want to inject our values
grid.dimensions = vis_lattice.shape
# The bottom left corner of the data set
grid.origin = vis_lattice.minbound
# These are the cell sizes along each axis
grid.spacing = vis_lattice.unit

# Add the data values to the cell data
grid.point_arrays["Shadow Casting"] = vis_lattice.flatten(order="F")  # Flatten the Lattice

# adding the meshes
p.add_mesh(tri_to_pv(context_mesh), opacity=0.1, style='wireframe')

# adding the volume
opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5
p.add_volume(grid, cmap="coolwarm", clim=[0., 1.0],opacity=opacity, shade=True)

# plotting
p.show(use_ipyvtk=True)

5.2.1 sun lattice information

# initiating the plotter
p = pv.Plotter(notebook=True)

vis_lattice = sunacc_lattice
# Create the spatial reference
grid = pv.UniformGrid()

# Set the grid dimensions: shape because we want to inject our values
grid.dimensions = vis_lattice.shape
# The bottom left corner of the data set
grid.origin = vis_lattice.minbound
# These are the cell sizes along each axis
grid.spacing = vis_lattice.unit

# Add the data values to the cell data
grid.point_arrays["Sun Access"] = vis_lattice.flatten(order="F") 

# adding the meshes
p.add_mesh(tri_to_pv(context_mesh), opacity=0.1, style='wireframe')

# adding the volume
opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5
p.add_volume(grid, cmap="coolwarm", clim=[0., 1.0],opacity=opacity, shade=True)

# plotting
p.show(use_ipyvtk=True)

5.3. Interpolation

def interpolate(info_lowres, base_highres):
    # line spaces
    x_space = np.linspace(info_lowres.minbound[0], info_lowres.maxbound[0],info_lowres.shape[0])
    y_space = np.linspace(info_lowres.minbound[1], info_lowres.maxbound[1],info_lowres.shape[1])
    z_space = np.linspace(info_lowres.minbound[2], info_lowres.maxbound[2],info_lowres.shape[2])

    # interpolation function
    interpolating_function = RegularGridInterpolator((x_space, y_space, z_space), info_lowres, bounds_error=False, fill_value=None)

    # high_res lattice
    envelope_lattice = base_highres + 1

    # sample points
    sample_points = envelope_lattice.centroids

    # interpolation
    interpolated_values = interpolating_function(sample_points)

    # lattice construction
    info_highres = tg.to_lattice(interpolated_values.reshape(base_highres.shape), base_highres)

    # nulling the unavailable cells
    info_highres *= base_highres

    return info_highres
#interpolation the shadow_access to highres
shad_acc_highres = interpolate(shadcast_lattice, avail_lattice_highres)
#interpolation the sun_access to highres
sun_acc_highres = interpolate(sunacc_lattice, avail_lattice_highres)

5.3. Visualize the sun and shadow access lattice

# initiating the plotter
p = pv.Plotter(notebook=True)

vis_lattice = shad_acc_highres
# Create the spatial reference
grid = pv.UniformGrid()

# Set the grid dimensions: shape because we want to inject our values
grid.dimensions = vis_lattice.shape
# The bottom left corner of the data set
grid.origin = vis_lattice.minbound
# These are the cell sizes along each axis
grid.spacing = vis_lattice.unit

# Add the data values to the cell data
grid.point_arrays["Shadow Casting"] = vis_lattice.flatten(order="F")  # Flatten the Lattice

# adding the meshes
p.add_mesh(tri_to_pv(context_mesh), opacity=0.1, style='wireframe')

# adding the volume
opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5
p.add_volume(grid, cmap="coolwarm", clim=[0., 1.0],opacity=opacity, shade=True)

# plotting
p.show(use_ipyvtk=True)
# initiating the plotter
p = pv.Plotter(notebook=True)

vis_lattice = sun_acc_highres
# Create the spatial reference
grid = pv.UniformGrid()

# Set the grid dimensions: shape because we want to inject our values
grid.dimensions = vis_lattice.shape
# The bottom left corner of the data set
grid.origin = vis_lattice.minbound
# These are the cell sizes along each axis
grid.spacing = vis_lattice.unit

# Add the data values to the cell data
grid.point_arrays["Sun Access"] = vis_lattice.flatten(order="F")  # Flatten the Lattice

# adding the meshes
p.add_mesh(tri_to_pv(context_mesh), opacity=0.1, style='wireframe')

# adding the volume
opacity = np.array([0,0.6,0.6,0.6,0.6,0.6,0.6])*1.5
p.add_volume(grid, cmap="coolwarm", clim=[0., 1.0],opacity=opacity, shade=True)

# plotting
p.show(use_ipyvtk=True)

6. Save Sun Access Lattice into a CSV

# save the shadow access latice to csv
csv_path = os.path.relpath('../data/shadow_access_highres.csv')
shad_acc_highres.to_csv(csv_path)
# save the sun access latice to csv
csv_path = os.path.relpath('../data/sun_access_highres.csv')
sun_acc_highres.to_csv(csv_path)

Credits

__author__ = "Shervin Azadi and Pirouz Nourian"
__editor__ = 'Siebren Meines'
__license__ = "MIT"
__version__ = "1.0"
__url__ = "https://github.com/shervinazadi/spatial_computing_workshops"
__summary__ = "Interpolation of sun and shadow"