Reorganize linear algebra in rate matrix models

This changes the gradient calculation from O(N^5) to O(N^3).