ai and S as ndarrays