Merge pull request #91 from mihtjel/feature/sloppy_parser

sloppy SI parsing to allow common human errors
pull/98/head
mihtjel 2019-11-16 09:55:31 +01:00 zatwierdzone przez GitHub
commit 9ee9f2db8c
Nie znaleziono w bazie danych klucza dla tego podpisu
ID klucza GPG: 4AEE18F83AFDEB23
2 zmienionych plików z 58 dodań i 91 usunięć

Wyświetl plik

@ -15,6 +15,7 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import collections
import math
from numbers import Number
from typing import List
from NanoVNASaver.SITools import Value, Format
@ -33,7 +34,7 @@ class RFTools:
return re50, im50
@staticmethod
def gain(data: Datapoint):
def gain(data: Datapoint) -> float:
# re50, im50 = normalize50(data)
# Calculate the gain / reflection coefficient
# mag = math.sqrt((re50 - 50) * (re50 - 50) + im50 * im50) / \
@ -43,8 +44,7 @@ class RFTools:
mag = math.sqrt(data.re**2 + data.im**2)
if mag > 0:
return 20 * math.log10(mag)
else:
return 0
return 0
@staticmethod
def qualityFactor(data: Datapoint):
@ -73,7 +73,7 @@ class RFTools:
return "- pF"
capacitance = 1 / (freq * 2 * math.pi * im50)
return str(Value(-capacitance, "F", Format(max_nr_digits=5, space_str=" ")))
@staticmethod
def inductanceEquivalent(im50, freq) -> str:
if freq == 0:
@ -82,85 +82,54 @@ class RFTools:
return str(Value(inductance, "H", Format(max_nr_digits=5, space_str=" ")))
@staticmethod
def formatFrequency(freq):
return str(Value(freq, "Hz", Format(max_nr_digits=6)))
def formatFrequency(freq: Number) -> str:
return str(Value(freq, "Hz"))
@staticmethod
def formatShortFrequency(freq):
def formatShortFrequency(freq: Number) -> str:
return str(Value(freq, "Hz", Format(max_nr_digits=4)))
@staticmethod
def formatSweepFrequency(freq: int,
mindigits: int = 2,
appendHz: bool = True,
insertSpace: bool = False,
countDot: bool = True,
assumeInfinity: bool = True) -> str:
""" Format frequency with SI prefixes
mindigits count refers to the number of decimal place digits
that will be shown, padded with zeroes if needed.
"""
freqstr = str(freq)
freqlen = len(freqstr)
# sanity checks
if freqlen > 15:
if assumeInfinity:
return "\N{INFINITY}"
raise ValueError("Frequency too big. More than 15 digits!")
if freq < 1:
return " - " + (" " if insertSpace else "") + ("Hz" if appendHz else "")
si_index = (freqlen - 1) // 3
dot_pos = freqlen % 3 or 3
intfstr = freqstr[:dot_pos]
decfstr = freqstr[dot_pos:]
nzdecfstr = decfstr.rstrip('0')
if si_index != 0:
while len(nzdecfstr) < mindigits:
nzdecfstr += '0'
freqstr = intfstr + ("." if len(nzdecfstr) > 0 else "") + nzdecfstr
return freqstr + (" " if insertSpace else "") + PREFIXES[si_index] + ("Hz" if appendHz else "")
def formatSweepFrequency(freq: Number) -> str:
return str(Value(freq, "Hz", Format(max_nr_digits=5)))
@staticmethod
def parseFrequency(freq: str) -> int:
parser = Value(0, "Hz")
parser = Value(0, "Hz", Format(parse_sloppy_unit=True, parse_sloppy_kilo=True))
try:
return round(parser.parse(freq))
except (ValueError, IndexError):
return -1
@staticmethod
def phaseAngle(data: Datapoint):
def phaseAngle(data: Datapoint) -> float:
re = data.re
im = data.im
return math.degrees(math.atan2(im, re))
@staticmethod
def phaseAngleRadians(data: Datapoint):
def phaseAngleRadians(data: Datapoint) -> float:
re = data.re
im = data.im
return math.atan2(im, re)
@staticmethod
def clamp_int(value: int, min: int, max: int) -> int:
assert min <= max
if value < min:
return min
if value > max:
return max
return value
@staticmethod
def groupDelay(data: List[Datapoint], index: int) -> float:
if index == 0:
angle0 = RFTools.phaseAngleRadians(data[0])
angle1 = RFTools.phaseAngleRadians(data[1])
freq0 = data[0].freq
freq1 = data[1].freq
elif index == len(data) - 1:
angle0 = RFTools.phaseAngleRadians(data[-2])
angle1 = RFTools.phaseAngleRadians(data[-1])
freq0 = data[-2].freq
freq1 = data[-1].freq
else:
angle0 = RFTools.phaseAngleRadians(data[index-1])
angle1 = RFTools.phaseAngleRadians(data[index+1])
freq0 = data[index-1].freq
freq1 = data[index+1].freq
index0 = RFTools.clamp_int(index - 1, 0, len(data) - 1)
index1 = RFTools.clamp_int(index + 1, 0, len(data) - 1)
angle0 = RFTools.phaseAngleRadians(data[index0])
angle1 = RFTools.phaseAngleRadians(data[index1])
freq0 = data[index0].freq
freq1 = data[index1].freq
delta_angle = (angle1 - angle0)
if abs(delta_angle) > math.tau:
if delta_angle > 0:

Wyświetl plik

@ -15,45 +15,35 @@
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import math
from typing import NamedTuple
from numbers import Number
PREFIXES = ("y", "z", "a", "f", "p", "n", "µ", "m",
"", "k", "M", "G", "T", "P", "E", "Z", "Y")
class Format(object):
def __init__(self,
max_nr_digits: int = 6,
fix_decimals: bool = False,
space_str: str = "",
assume_infinity: bool = True,
min_offset: int = -8,
max_offset: int = 8):
assert(min_offset >= -8 and max_offset <= 8 and min_offset < max_offset)
self.max_nr_digits = max_nr_digits
self.fix_decimals = fix_decimals
self.space_str = space_str
self.assume_infinity = assume_infinity
self.min_offset = min_offset
self.max_offset = max_offset
def __repr__(self):
return (f"{self.__class__.__name__}("
f"{self.max_nr_digits}, {self.fix_decimals}, "
f"'{self.space_str}', {self.assume_infinity}, "
f"{self.min_offset}, {self.max_offset})")
class Format(NamedTuple):
max_nr_digits: int = 6
fix_decimals: bool = False
space_str: str = ""
assume_infinity: bool = True
min_offset: int = -8
max_offset: int = 8
parse_sloppy_unit: bool = False
parse_sloppy_kilo: bool = False
class Value(object):
class Value():
def __init__(self, value: Number = 0, unit: str = "", fmt=Format()):
assert 3 <= fmt.max_nr_digits <= 27
assert -8 <= fmt.min_offset <= fmt.max_offset <= 8
self.value = value
self._unit = unit
self.fmt = fmt
def __repr__(self):
def __repr__(self) -> str:
return f"{self.__class__.__name__}({self.value}, '{self._unit}', {self.fmt})"
def __str__(self):
def __str__(self) -> str:
fmt = self.fmt
if fmt.assume_infinity and abs(self.value) >= 10 ** ((fmt.max_offset + 1) * 3):
return ("-" if self.value < 0 else "") + "\N{INFINITY}" + fmt.space_str + self._unit
@ -85,22 +75,30 @@ class Value(object):
return result + fmt.space_str + PREFIXES[offset + 8] + self._unit
def parse(self, value: str):
def parse(self, value: str) -> float:
value = value.replace(" ", "") # Ignore spaces
if self._unit and value.endswith(self._unit) or value.lower().endswith(self._unit.lower()): # strip unit
if self._unit and (
value.endswith(self._unit) or
(self.fmt.parse_sloppy_unit and
value.lower().endswith(self._unit.lower()))): # strip unit
value = value[:-len(self._unit)]
factor = 1
if self.fmt.parse_sloppy_kilo and value[-1] == "K": # fix for e.g. KHz
value = value[:-1] + "k"
if value[-1] in PREFIXES:
factor = 10 ** ((PREFIXES.index(value[-1]) - 8) * 3)
value = value[:-1]
elif value[-1] == 'K':
# Fix for the very common KHz
factor = 10 ** ((PREFIXES.index(value[-1].lower()) - 8) * 3)
value = value[:-1]
self.value = float(value) * factor
if self.fmt.assume_infinity and value == "\N{INFINITY}":
self.value = math.inf
elif self.fmt.assume_infinity and value == "-\N{INFINITY}":
self.value = -math.inf
else:
self.value = float(value) * factor
return self.value
@property
def unit(self):
def unit(self) -> str:
return self._unit