Your code has an inner loop, down inside several levels of nested functions, that runs hundreds or thousands of times. The inner loop calls several global functions, and it references some variables defined in the outer functions or globally.
Each of these references is triggering several name lookups because of the nested functions. It’s slowing down your code, but profilers don’t show what the problem is, and it isn’t obvious from looking at the code that there’s a problem!
Investigate every name that appears in your innermost loop, and figure out how many name lookups it requires. Reduce the number of name lookups by caching object references locally or using fewer nested functions.
Put these together, and you can get a lot of name lookups.