Psychology/neurology cannot yet answer such questions. I'd guess it involves combining visualization with muscle memory. Or the problem of visualizing a 1-D string embedded in a 3-D space.
For 95% of the population, it's math.
For me, I don't know how composers do what they do. A heavenly gift, I suppose. There was a time, I spent several weeks trying to compose a melody. I came up with a few ideas, but then fell into the rut of songs I already knew, every time. I found it impossible to clear my mind completely of familiar tunes.
It appears the conversation is drifting...