We obtain analytic expressions for the topological partition function of arbitrary N=2 theories in 4d, using modularity, the holomorphic anomaly, and boundary conditions. If a region of asypmotic freedom exists, they specialize to Nekrasov's partition function. For topological string theory on non-compact Calabi-Yau manifolds defined by the anticanonical bundle over del Pezzo surfaces, the partition function counts motivic Donaldson-Thomas invariants related to stable pairs with support on the del Pezzo surface.