Gradient-based optimization of flow through porous media