'efficient way of equations from table

I have the following table shown in the figure with the first few entries shown below:

n m equation
1 1 0
1 2 dP-41
1 3 2dP-28
2 1 -35
etc

Formulas for suppression of harmonics

I would like to code this up in python such that I can specify a m and n and dP (delta Power) and it will spit out the suppression.

Other than doing a big if then statement, is there a more efficient / pythonic way of doing this?

(this for some RF engineering to calculate spurious responses from mixers: paper here



Solution 1:[1]

Dictionaries to the rescue!

Note that each of the harmonic suppression equations are linear: there is a coefficient, the variable (dP), and a constant -- all equations follow the form y = mx + b.

Therefore, we can implement one generic suppression() function which accepts dP and a coefficient (the m in mx + b) and a constant (the + b).

Then, you can use tuples to map (n, m) pairs to their corresponding suppression equation:

def suppression(dP, *, coef, const):
    return coef * dP + const


LO_RF = {(1, 1): {"coef": 0, "const": 0},
         (1, 2): {"coef": 1, "const": -41},
         (1, 3): {"coef": 2, "const": -28},
         (2, 1): {"coef": 0, "const": -35},
         (2, 2): {"coef": 1, "const": -39},
         (2, 3): {"coef": 2, "const": -44},
         (3, 1): {"coef": 0, "const": -10},
         (3, 2): {"coef": 1, "const": -32},
         (3, 3): {"coef": 2, "const": -18},
         (4, 1): {"coef": 0, "const": -35},
         (4, 2): {"coef": 1, "const": -39},
         (5, 1): {"coef": 0, "const": -14},
         (5, 3): {"coef": 2, "const": -14},
         (6, 1): {"coef": 0, "const": -35},
         (6, 2): {"coef": 1, "const": -39},
         (7, 1): {"coef": 0, "const": -17},
         (7, 3): {"coef": 2, "const": -11}}


def calculate_suppression(*, n, m, dP):
    try:
        return suppression(dP, **LO_RF[(n, m)])
    except KeyError:
        print("Invalid (n, m) pair!")

Demo:

In [3]: calculate_suppression(n=3, m=2, dP=21)
Out[3]: -11

Note that * in a function's signature denotes that arguments after it are keyword-only. This is not necessary, but helps prevent users from putting their arguments in the wrong order -- with keyword-only arguments, order doesn't matter because the value of each argument must be assigned by name (basically, it's very difficult to give an incorrect value for n if you are forced to type n = ...).

The suppression() function does require the keyword args, but it's possible to remove this limitation if you want -- you'll just need to modify some code.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1