How can I calculate the optimal amount of attack bonus to give up when using Power Attack?

The Power Attack feat lets you sacrifice attack bonus (AB) to increase your damage.

It’s easy to see that you don’t always want to give up the same amount of AB, and that the optimal amount (assuming you’re trying to maximize your expected damage output) depends on multiple factors. Consider the following two degenerate cases where it’s easy to see that the optimal choice differs:

  1. If your opponent’s AC is so much higher than your AB that you will only ever hit them by rolling a natural 20, then you clearly want to sacrifice the maximum possible amount of AB, since it won’t affect your chance to hit at all (5% in any case), and maximizing your Power Attack damage will result in more damage if you do roll the natural 20.
  2. If your foolish DM has granted you the legendary +Graham’s Number Sword of Munchkinry at level 1, then you clearly don’t want to use Power Attack at all (unless you’ll only miss on a natural 1), because your base damage is so high that even a 5% decrease in your chance to hit will utterly dwarf any piddly damage you get from sacrificing your 1 BAB.

In between these silly cases, though, I’m not sure how to determine the best amount of AB to sacrifice when using Power Attack. It’s not even clear to me what information I need to do so, though I think it includes some or all of the following:

  • The attacker’s AB
  • The defender’s AC
  • The attacker’s BAB (because it’s the maximum amount of AB they can subtract)
  • The number of attacks the attacker is making (if they’re making a full attack)
  • The amount of damage the attack(s) will do on hit
  • How much damage the attacker gains per point of sacrificed AB (e.g., 2 points when using a 2-handed weapon instead of 1 point for a 1-handed weapon)
  • Whether the attack could crit, and its crit stats (range/multiplier) if so

Given this sort of info, how can I calculate the amount of AB to sacrifice to Power Attack that maximizes my expected damage output for the round?

A couple notes:

  • I will happily upvote partial solutions (e.g., ones that only apply to a single attack without considering iteratives, or ones that ignore crits for simplicity’s sake)
  • Ignore considerations that require you to know how close to death the defender is. I’m happy with answers that naively maximize the expected value of my damage output against an idealized combat dummy with infinite HP. Accounting for the desire to maximize the probability of dealing lethal damage against low-HP opponents is, I think, too complicated, and beyond the scope of this question.
  • Ignore the Shock Trooper feat for purposes of this question; obviously if you’re giving up AC for damage instead of AB, it’s a risk/reward judgment call, not a case where there’s an objectively optimal value.