Created
December 17, 2020 20:52
-
-
Save bodja/849f939139f26411af6b6840aaa45fe6 to your computer and use it in GitHub Desktop.
Calculate antenna length
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import re | |
from fractions import Fraction | |
SPEED_OF_LIGHT = 300000000 # meters/second | |
class Frequency: | |
""" | |
Converts given frequency to Hertz (Hz) | |
frequency = Frequency('5.8GHz') | |
hz = frequency.hz | |
""" | |
si_multiples = { # SI multiples of hertz (Hz) | |
'hz': 1, | |
'dahz': 10 ** 1, | |
'hhz': 10 ** 2, | |
'khz': 10 ** 3, | |
'mhz': 10 ** 6, | |
'ghz': 10 ** 9, | |
'thz': 10 ** 12, | |
'phz': 10 ** 15, | |
'ehz': 10 ** 18, | |
'zhz': 10 ** 21, | |
'yhz': 10 ** 24, | |
} | |
def __init__(self, frequency: str): | |
""" | |
:param frequency: e.g '915MHz' | |
""" | |
match = re.match( | |
rf'(?P<value>\d+(?:\.\d+)?)(?:\s+)?(?P<unit>{"|".join(self.si_multiples)})$', | |
frequency, | |
flags=re.I | |
) | |
if not match: | |
raise ValueError(frequency) | |
try: | |
self.value = int(match.group('value')) | |
except ValueError: | |
self.value = float(match.group('value')) | |
self.unit = match.group('unit') | |
def __str__(self): | |
return f'{self.value}{self.unit}' | |
@property | |
def hz(self): | |
return self.value * self.si_multiples[self.unit.lower()] | |
class Antenna: | |
""" | |
antenna = Antenna(Frequency('5.8 GHz'), '1/4') | |
antenna.length | |
""" | |
def __init__(self, frequency: Frequency, fraction: Fraction): | |
self.frequency = frequency | |
self.fraction = fraction | |
def __str__(self): | |
if self.fraction == Fraction(1, 1): | |
return f'{self.frequency} Full Wavelength Antenna {self.length}mm' | |
return f'{self.frequency} {self.fraction} Wavelength Antenna {self.length}mm' | |
@property | |
def length(self) -> float: | |
""" | |
Antenna length in millimeters (mm) | |
""" | |
return round(SPEED_OF_LIGHT / self.frequency.hz * self.fraction * 100 * 10, 2) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description='Calculate antenna length.') | |
parser.add_argument( | |
'frequency', | |
metavar='frequency', | |
type=Frequency, | |
help='a frequency for antenna length calculation. [e.g. 5.8GHz]' | |
) | |
parser.add_argument( | |
'fraction', | |
metavar='fraction', | |
nargs='*', | |
type=Fraction, | |
default=[Fraction(1, x) for x in range(1, 10)], | |
help='wavelength fraction affects antenna length and efficiency. [e.g. 1/4]', | |
) | |
args = parser.parse_args() | |
for f in args.fraction: | |
antenna = Antenna(args.frequency, f) | |
print(antenna) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment