From 8dbf6c9c589d12b0b0c5286b3133f96195bad6c0 Mon Sep 17 00:00:00 2001
From: Vanessa Stehr <vanessa.stehr@ptb.de>
Date: Wed, 8 May 2024 12:29:32 +0200
Subject: [PATCH] Refactoring: Rename variables called 'fraction', fix typos

---
 .gitignore             |  3 +-
 README.md              |  2 +-
 src/dsiUnits.py        | 86 +++++++++++++++++++++---------------------
 tests/test_dsiUnits.py |  4 +-
 4 files changed, 48 insertions(+), 47 deletions(-)

diff --git a/.gitignore b/.gitignore
index df30947..ce5cd2c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,2 +1,3 @@
-
+__pycache__
 .idea/
+venv
diff --git a/README.md b/README.md
index d9cc3b3..6700b78 100644
--- a/README.md
+++ b/README.md
@@ -3,7 +3,7 @@
 # D-SI Parser
 
 This library converts D-SI unit strings to Latex.
-And is able to perform math operatins *, / and power with the D-SI units as well as checken weather teh can be converted into each other with scalar multiplication
+And is able to perform math operations *, / and power with the D-SI units as well as checken weather teh can be converted into each other with scalar multiplication
 
 ## Usage
 
diff --git a/src/dsiUnits.py b/src/dsiUnits.py
index 7c59c11..af9ada8 100644
--- a/src/dsiUnits.py
+++ b/src/dsiUnits.py
@@ -26,10 +26,10 @@ import numbers
 def _dsiStrFromNodes(nodeList):
     """Converts a list of nodes to a D-SI string."""
     dsiStr = ""
-    for i, fraction in enumerate(nodeList):
+    for i, unitFraction in enumerate(nodeList):
         if i > 0:
             dsiStr += r"\per"
-        for node in fraction:
+        for node in unitFraction:
             dsiStr += str(node)
     return dsiStr
 
@@ -217,7 +217,7 @@ class dsiUnit:
     """D-SI representation in tree form, also includes validity check and warnings about D-SI string.
        Tree format: list of lists:
            List format:
-           First layer: items of the fraction
+           First layer: items of the unit fraction
            Second layer: nodes containing prefix, unit, power
     """
 
@@ -227,7 +227,7 @@ class dsiUnit:
         Args:
             dsiString (str): the D-SI unit string to be parsed
             optional dsiTree (list): List of lists of nodes as tuples containing (prefix: str,unit: str,exponent: float=1.0,scaleFactor: float = 1.0)
-            like [('metre', 1.0, 1.0), ('second', -1.0, 1.0)] to generate ms^-1 when usign this construction method no str can be given
+            like [('metre', 1.0, 1.0), ('second', -1.0, 1.0)] to generate ms^-1 when using this construction method no str can be given
         """
         # we have got a tree so we dont need to parse the string
         if dsiString == "" and dsiTree != []:
@@ -315,9 +315,9 @@ class dsiUnit:
             return ''.join(superscripts.get(char, char) for char in exp_str)
 
         utf8Array = []
-        for fraction in self.tree:
+        for unitFraction in self.tree:
             fractionUtf8Array = []
-            for node in fraction:
+            for node in unitFraction:
                 # Fetch UTF-8 unit representation
                 unitStr = _dsiUnitsUTF8.get(node.unit, node.unit)
 
@@ -344,9 +344,9 @@ class dsiUnit:
         Converts the entire D-SI tree to its base unit representation.
         """
         baseUnitTree = []
-        for fraction in self.tree:
+        for unitFraction in self.tree:
             baseFraction = []
-            for node in fraction:
+            for node in unitFraction:
                 baseFraction.extend(node.toBaseUnits())
             baseUnitTree.append(baseFraction)
         unconsolidatedTree = dsiUnit(self.dsiString, baseUnitTree, self.warnings, self._latexDefaultWrapper, self._latexDefaultPrefix, self._latexDefaultSuffix)
@@ -354,9 +354,9 @@ class dsiUnit:
         # if kgms True we do a second round but resolve volt ampere mole this round
         if complete:
             baseUnitTree = []
-            for fraction in self.tree:
+            for unitFraction in self.tree:
                 baseFraction = []
-                for node in fraction:
+                for node in unitFraction:
                     baseFraction.extend(node.toBaseUnits(complete=complete))
                 baseUnitTree.append(baseFraction)
             unconsolidatedTree = dsiUnit(self.dsiString, baseUnitTree, self.warnings, self._latexDefaultWrapper,
@@ -434,8 +434,8 @@ class dsiUnit:
                        self._latexDefaultPrefix, self._latexDefaultSuffix)
     def sortTree(self):
         """Sorts each fraction's nodes alphabetically by their units."""
-        for fraction in self.tree:
-            fraction.sort(key=lambda node: node.unit)
+        for unitFraction in self.tree:
+            unitFraction.sort(key=lambda node: node.unit)
     def __eq__(self, other):
         """Checks if two D-SI trees are identical after sorting their nodes alphabetically."""
         if not isinstance(other, dsiUnit):
@@ -449,8 +449,8 @@ class dsiUnit:
         if selfCopy.tree == otherCopy.tree:
             return True
         else:
-            scalfactor,baseunit=selfCopy.isScalablyEqualTo(otherCopy)
-            if scalfactor == 1.0:
+            scaleFactor,baseUnit=selfCopy.isScalablyEqualTo(otherCopy)
+            if scaleFactor == 1.0:
                 return True
             else:
                 return False
@@ -465,27 +465,27 @@ class dsiUnit:
             return (math.nan, None)
 
 
-        sortedself=deepcopy(self)
-        sortedself.sortTree()
-        sortedother=deepcopy(other)
-        sortedother.sortTree()
+        sortedSelf=deepcopy(self)
+        sortedSelf.sortTree()
+        sortedOther=deepcopy(other)
+        sortedOther.sortTree()
         # okay now check if is identical
-        if sortedself.tree == sortedother.tree:
+        if sortedSelf.tree == sortedOther.tree:
             return (1.0,self)
-        scalefactor=1
-        for fracIdx,fraction in enumerate(sortedself.tree):
+        scaleFactor=1
+        for fracIdx,unitFraction in enumerate(sortedSelf.tree):
             try:
-                if len(fraction) != len(sortedother.tree[fracIdx]):
-                    scalefactor=math.nan
+                if len(unitFraction) != len(sortedOther.tree[fracIdx]):
+                    scaleFactor=math.nan
                     break
-                for nodeIDX,node in enumerate(fraction):
-                    scalefactor *= node.isScaled(sortedother.tree[fracIdx][nodeIDX])
+                for nodeIDX,node in enumerate(unitFraction):
+                    scaleFactor *= node.isScaled(sortedOther.tree[fracIdx][nodeIDX])
             except IndexError:
                 # if we get here we have a fraction in one tree that is not in the other in this case we resolve to base units and compare
-                scalefactor=math.nan
+                scaleFactor=math.nan
                 break
-        if not math.isnan(scalefactor):
-            return (scalefactor,self)
+        if not math.isnan(scaleFactor):
+            return (scaleFactor,self)
         # Convert both trees to their base unit representations
         selfBaseUnitTree = self.toBaseUnitTree(complete=complete)
         otherBaseUnitTree = other.toBaseUnitTree(complete=complete)
@@ -493,22 +493,22 @@ class dsiUnit:
         # Sort both trees
         selfBaseUnitTree.sortTree()
         otherBaseUnitTree.sortTree()
-        # Check ifunits match
+        # Check if units match
         if len(selfBaseUnitTree.tree) != len(otherBaseUnitTree.tree):
             return (math.nan, None)
         # Calculate scale factor
         scaleFactor = 1.0
         if len(selfBaseUnitTree.tree) != 1 or len(otherBaseUnitTree.tree) != 1:
-            raise RuntimeError("D-SI tree with more than one fraction cannot be compared. And should not existhere since we consolidatet earlyer")
+            raise RuntimeError("D-SI tree with more than one fraction cannot be compared. And should not exist here since we consolidated earlier")
         for selfNode, otherNode in zip(selfBaseUnitTree.tree[0], otherBaseUnitTree.tree[0]):
             if selfNode.unit != otherNode.unit:
                 return (math.nan, None)
             if float(selfNode.exponent) != float(otherNode.exponent):
                 return (math.nan, None)
             scaleFactor *= otherNode.scaleFactor / selfNode.scaleFactor
-        # reseting scalfactor to 1.0
-        for fraction in selfBaseUnitTree.tree:
-            for node in fraction:
+        # resetting scaleFactor to 1.0
+        for unitFraction in selfBaseUnitTree.tree:
+            for node in unitFraction:
                 node.scaleFactor = 1.0
         return (scaleFactor,selfBaseUnitTree)
 
@@ -536,8 +536,8 @@ class dsiUnit:
         if not isinstance(other, numbers.Real):
             raise TypeError("Exponent must be a real number")
         resultNodeLIst = deepcopy(self.tree)
-        for fraction in resultNodeLIst:
-            for node in fraction:
+        for unitFraction in resultNodeLIst:
+            for node in unitFraction:
                 node.exponent *= other
         resultTree =dsiUnit("", resultNodeLIst, self.warnings, self._latexDefaultWrapper, self._latexDefaultPrefix, self._latexDefaultSuffix)
         resultTree = resultTree.reduceFraction()
@@ -545,13 +545,13 @@ class dsiUnit:
 
     def __mul__(self, other):
         resultNodeLIst=deepcopy(self.tree)
-        for i,fraction in enumerate(other.tree):
+        for i,unitFraction in enumerate(other.tree):
             if i>1:
                 raise RuntimeError("D-SI tree with more than one fraction cannot be multiplied")
             try:
-                resultNodeLIst[i].extend(deepcopy(fraction))
+                resultNodeLIst[i].extend(deepcopy(unitFraction))
             except IndexError:
-                resultNodeLIst.append(deepcopy(fraction))# there was no fraction so we add it
+                resultNodeLIst.append(deepcopy(unitFraction))# there was no fraction so we add it
 
         resultTree =dsiUnit("", resultNodeLIst, self.warnings, self._latexDefaultWrapper, self._latexDefaultPrefix, self._latexDefaultSuffix)
         resultTree = resultTree.reduceFraction()
@@ -636,7 +636,7 @@ class _node:
             List['_node']: List of nodes representing the base units or kg, s, m equivalents.
         """
         # Adjust the scale factor for the prefix
-        prefixScale = _dsiPrefixsScales.get(self.prefix, 1)  # Default to 1 if no prefix
+        prefixScale = _dsiPrefixesScales.get(self.prefix, 1)  # Default to 1 if no prefix
         adjustedScaleFactor = self.scaleFactor * prefixScale
 
         # Convert to base units if it's a derived unit
@@ -678,7 +678,7 @@ class _node:
     def isScaled(self,other):
         """Checks if two nodes are scaled equal."""
         if self.unit == other.unit and self.exponent == other.exponent:
-            return _dsiPrefixsScales[other.prefix]/_dsiPrefixsScales[self.prefix]
+            return _dsiPrefixesScales[other.prefix]/_dsiPrefixesScales[self.prefix]
         else:
             return math.nan
 
@@ -695,7 +695,7 @@ def _warn(message: str, warningClass):
     warnings.warn(message, warningClass)
     return message
 
-def _getClosestStr(unkownStr):
+def _getClosestStr(unknownStr):
     """returns the closest string and type of the given string
 
     Args:
@@ -706,7 +706,7 @@ def _getClosestStr(unkownStr):
         str: type of closest string
     """
     possibleDsiKeys = _dsiPrefixesLatex.keys() | _dsiUnitsLatex.keys() | _dsiKeyWords.keys()
-    closestStr = difflib.get_close_matches(unkownStr, possibleDsiKeys, n=3,cutoff=0.66)
+    closestStr = difflib.get_close_matches(unknownStr, possibleDsiKeys, n=3,cutoff=0.66)
     return closestStr
 # mapping D-SI prefixes to latex
 _dsiPrefixesLatex = {
@@ -733,7 +733,7 @@ _dsiPrefixesLatex = {
 }
 #TODO maybe directlusing the exponents is better
 # mapping D-SI prefixes to scale factors
-_dsiPrefixsScales = {
+_dsiPrefixesScales = {
     'yotta': 1e24,
     'zetta': 1e21,
     'exa': 1e18,
diff --git a/tests/test_dsiUnits.py b/tests/test_dsiUnits.py
index cc893f2..f2898b6 100644
--- a/tests/test_dsiUnits.py
+++ b/tests/test_dsiUnits.py
@@ -134,9 +134,9 @@ def test_wrappers():
     assert parserFull.parse(r'\metre').toLatex() == r'@\mathrm{Prefix}\mathrm{m}\mathrm{Suffix}@'
 
 def test_getClosestMatch():
-    closestMatch = _getClosestStr('\kiilo')
+    closestMatch = _getClosestStr(r'\kiilo')
     assert closestMatch == (['kilo'])
-    closestMatch = _getClosestStr('\mettre')
+    closestMatch = _getClosestStr(r'\mettre')
     assert closestMatch == (['metre'])
     closestMatch = _getClosestStr(r'\ttothe')
     assert closestMatch == (['tothe'])
-- 
GitLab