Spanish authorities have declared three days of mourning after two trains collided on a track south of Madrid, killing at least 40 people.