added support for custom distance matrix to gradients