Skip to content

Added shunt capacitor power factor correction - #9535

Open
Yosef-6 wants to merge 9 commits into
TheAlgorithms:masterfrom
Yosef-6:added-shunt-capacitor-power-factor-correction
Open

Added shunt capacitor power factor correction#9535
Yosef-6 wants to merge 9 commits into
TheAlgorithms:masterfrom
Yosef-6:added-shunt-capacitor-power-factor-correction

Conversation

@Yosef-6

@Yosef-6 Yosef-6 commented Oct 2, 2023

Copy link
Copy Markdown

Describe your change:

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Documentation change?

Checklist:

  • I have read CONTRIBUTING.md.
  • This pull request is all my own work -- I have not plagiarized.
  • I know that pull requests will not be merged if they fail the automated tests.
  • This PR only changes one algorithm file. To ease review, please open separate PRs for separate algorithms.
  • All new Python files are placed inside an existing directory.
  • All filenames are in all lowercase characters with no spaces or dashes.
  • All functions and variable names follow Python naming conventions.
  • All function parameters and return values are annotated with Python type hints.
  • All functions have doctests that pass the automated testing.
  • All new algorithms include at least one URL that points to Wikipedia or another similar explanation.
  • If this pull request resolves one or more open issues then the description above includes the issue number(s) with a closing keyword: "Fixes #ISSUE-NUMBER".

@algorithms-keeper algorithms-keeper Bot added the awaiting reviews This PR is ready to be reviewed label Oct 2, 2023
@algorithms-keeper algorithms-keeper Bot added the tests are failing Do not merge until tests pass label Oct 2, 2023
Yosef-6 and others added 2 commits October 2, 2023 14:41
@algorithms-keeper algorithms-keeper Bot removed the tests are failing Do not merge until tests pass label Oct 2, 2023
@Yosef-6 Yosef-6 closed this Oct 3, 2023
@Yosef-6
Yosef-6 deleted the added-shunt-capacitor-power-factor-correction branch October 3, 2023 20:39
@Yosef-6
Yosef-6 restored the added-shunt-capacitor-power-factor-correction branch October 3, 2023 20:40
@Yosef-6 Yosef-6 reopened this Oct 3, 2023
@Yosef-6 Yosef-6 mentioned this pull request Oct 5, 2023
14 tasks
@rohan472000

Copy link
Copy Markdown
Contributor

Seems correct but can you don't add L and R also with another function, all 3 in a single class???

@Yosef-6

Yosef-6 commented Oct 5, 2023

Copy link
Copy Markdown
Author

Ok but Resistors don't affect reactive power inductors and capacitors do
i will add L and C in one class

@rohan472000

rohan472000 commented Oct 5, 2023

Copy link
Copy Markdown
Contributor

For R, to correct the power factor of a load with an undesired resistance, I think u need to add a parallel shunt resistor, its calculation will involve the real power and resistance.

It's been 2 yrs since I don't touched electrical engineering, so correct me if I goes wrong somewhere.

@Yosef-6

Yosef-6 commented Oct 5, 2023

Copy link
Copy Markdown
Author

Thats possible sir
but power factor correction is needed without affecting the real power absorbed by the load adding a resistor affects amount of power the load absorbs i haven't seen a use case that uses a resistor to correct power factor
so capacitor is used if load is lagging (inductive)
inductors used when the load is leading (capacitive)
in both cases we must approach the pf to unity by adding the respective element(power factor correction) without altering the real power absorbed by the load
i will create an inductor one and add additional examples and checks

@algorithms-keeper algorithms-keeper Bot added tests are failing Do not merge until tests pass and removed tests are failing Do not merge until tests pass labels Oct 6, 2023
@Yosef-6

Yosef-6 commented Oct 6, 2023

Copy link
Copy Markdown
Author

For R, to correct the power factor of a load with an undesired resistance, I think u need to add a parallel shunt resistor, its calculation will involve the real power and resistance.

It's been 2 yrs since I don't touched electrical engineering, so correct me if I goes wrong somewhere.

done

@cclauss

cclauss commented Sep 3, 2026

Copy link
Copy Markdown
Member

@priya-sundaram-dev, your review, please. Is there any code cleanup that we should consider?

@priya-sundaram-dev priya-sundaram-dev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the review request, @cclauss. The math is sound and the doctests (including the ValueError traceback cases) are a nice touch. A few cleanup items, roughly in priority order:

1. Docstring copy-paste bug (should fix). shunt_inductor_power_factor_correction still says "Calculate shunt capacitor...". It should describe the inductor, and ideally state the returned unit (farads for the capacitor, henries for the inductor) plus a one-line note on sign conventions.

2. Heavy duplication (main cleanup opportunity). The two functions are ~90% identical — same validation block and the same four reactive-power lines. That's the thing I'd most want to DRY up. A small private helper keeps each public function to its final formula, e.g.:

def _reactive_power_delta(voltage, frequency, real_power, pf_now, pf_target):
    for pf in (pf_now, pf_target):
        if not isinstance(pf, (int, float)) or not -1 <= pf <= 1:
            raise ValueError("power_factor must be a valid float between -1 and 1.")
    if frequency == 0:
        raise ValueError("frequency is zero dc circuit")
    if voltage == 0:
        raise ValueError("voltage is zero no excitation")
    q_now = (real_power / pf_now) * math.sin(math.acos(pf_now))
    q_target = (real_power / pf_target) * math.sin(math.acos(pf_target))
    return q_now - q_target

Then the capacitor returns delta / (2*pi*f*V**2) and the inductor V**2 / (2*pi*f*delta).

3. Comment style. The mid-function """...""" blocks are string-expression statements, not comments — please switch them to # comments so they don't read as unused expressions.

4. chr/bool edge case. isinstance(True, (int, float)) is True, so pf=True sneaks through as 1. Minor; a bool guard is optional but tidy.

5. Inductor division-by-zero. The inductor formula puts change_reactive_power in the denominator, so pf_now == pf_target raises ZeroDivisionError. Worth an explicit ValueError (or a doctest) since the capacitor version can't hit that.

6. Chained comparison. -1 <= pf <= 1 reads cleaner than the four-way or chain (ruff-friendly too).

None of these are blockers — 1 and 2 are the ones I'd ask for before merge; 3–6 are polish. Happy to push a follow-up commit with the helper extraction if the author would like a hand.

@priya-sundaram-dev priya-sundaram-dev left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed @cclauss — the math is sound (Q = P·(tanφ₁ − tanφ₂), then C = ΔQ/(ω·V²) for the capacitor, L = V²/(ω·ΔQ) for the inductor) and both doctests reproduce. A few cleanups worth making before merge:

  1. Copy-paste docstringshunt_inductor_power_factor_correction's summary still says "Calculate shunt capacitor…". Should read "inductor".

  2. Unguarded division by zerocurrent_apparent_power = real_power / current_power_factor raises ZeroDivisionError when current_power_factor == 0 (a purely reactive load, which is exactly when correction matters most). The -1..1 range check lets 0 through. Suggest rejecting 0 explicitly, e.g. if current_power_factor == 0 or expected_power_factor == 0: raise ValueError("power factor cannot be zero"), with a doctest covering it.

  3. Dead string literals used as comments — the triple-quoted blocks inside each function body ("""The difference between the new and old reactive powers…""") are expression statements, not docstrings (they aren't the first statement). Please convert them to # comments so they don't sit in the compiled code.

  4. Duplication (optional) — the two functions share identical validation + reactive-power computation; only the final return differs. A small private _reactive_power_change(...) helper would remove ~20 duplicated lines, but I'm fine leaving it if you'd rather keep each function self-contained for readability.

Items 1–3 are worth fixing; 4 is a nice-to-have. Nice addition to electronics/ otherwise.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

awaiting reviews This PR is ready to be reviewed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants