Add deviation cost and fix a bug in generator