A variational approach to niche construction