From 3789db4aca13d86493990f4d14fcad7bacb66a68 Mon Sep 17 00:00:00 2001
From: Lee McCuller <Lee.McCuller@gmail.com>
Date: Tue, 5 Oct 2021 11:43:41 -0500
Subject: [PATCH] more pep8'ing

---
 .flake8                |  9 +++--
 gwinc/__init__.py      | 20 +++++++-----
 gwinc/noise/quantum.py | 14 ++++----
 gwinc/struct.py        | 74 +++++++++++++++++++++---------------------
 4 files changed, 62 insertions(+), 55 deletions(-)

diff --git a/.flake8 b/.flake8
index 550435c..1ff73d1 100644
--- a/.flake8
+++ b/.flake8
@@ -1,5 +1,10 @@
 
 [flake8]
-#E251: spaces around arguments
-ignore = 
+ignore = E226,E741,E266,W503
 max-line-length = 140
+
+# E226, missing whitespace around arithmetic operator: quantum.py currently needs large changes to avoid this
+# E741, "l" is a bad variable name: Gwinc uses "l" in a few reasonable places
+# E266, Too many leading '#' for block comment: There are some reasonable instances of comments that trigger this
+# W503, binary operator at start of line: This allows using parentheses to break equations
+
diff --git a/gwinc/__init__.py b/gwinc/__init__.py
index 291180a..6e6a8ce 100644
--- a/gwinc/__init__.py
+++ b/gwinc/__init__.py
@@ -27,9 +27,11 @@ logger = logging.getLogger('gwinc')
 
 DEFAULT_FREQ = '5:3000:6000'
 
+
 class InvalidFrequencySpec(Exception):
     pass
 
+
 def freq_from_spec(spec=None):
     """logarithmicly spaced frequency array, based on specification string
 
@@ -122,15 +124,15 @@ def load_budget(name_or_path, freq=None, bname=None):
             inherit_ifo = ifo.get('inherit', None)
             if inherit_ifo is not None:
                 del ifo['inherit']
-                #make the inherited path relative to the loaded path
-                #if it is a yml file
+                # make the inherited path relative to the loaded path
+                # if it is a yml file
                 if os.path.splitext(inherit_ifo)[1] in Struct.STRUCT_EXT:
                     base = os.path.split(path)[0]
                     inherit_ifo = os.path.join(base, inherit_ifo)
 
                 inherit_budget = load_budget(inherit_ifo, freq=freq, bname=bname)
                 pre_ifo = inherit_budget.ifo
-                pre_ifo.update(ifo, overwrite_atoms = False)
+                pre_ifo.update(ifo, overwrite_atoms=False)
                 inherit_budget.update(ifo=pre_ifo)
                 return inherit_budget
             else:
@@ -220,13 +222,15 @@ def gwinc(freq, ifo, source=None, plot=False, PRfixed=True):
         logger.info('Power on BS:            %7.2f W' % pbs)
 
         # coating and substrate thermal load on the ITM
-        PowAbsITM = (pbs/2) * \
-                    np.hstack([(finesse*2/np.pi) * ifo.Optics.ITM.CoatingAbsorption,
-                               (2 * ifo.Materials.MassThickness) * ifo.Optics.ITM.SubstrateAbsorption])
+        PowAbsITM = (
+            (pbs/2)
+            * np.hstack([
+                (finesse*2/np.pi) * ifo.Optics.ITM.CoatingAbsorption,
+                (2 * ifo.Materials.MassThickness) * ifo.Optics.ITM.SubstrateAbsorption])
+        )
 
         logger.info('Thermal load on ITM:    %8.3f W' % sum(PowAbsITM))
-        logger.info('Thermal load on BS:     %8.3f W' %
-                     (ifo.Materials.MassThickness*ifo.Optics.SubstrateAbsorption*pbs))
+        logger.info('Thermal load on BS:     %8.3f W' % (ifo.Materials.MassThickness*ifo.Optics.SubstrateAbsorption*pbs))
         if (ifo.Laser.Power*prfactor != pbs):
             logger.info('Lensing limited input power: %7.2f W' % (pbs/prfactor))
 
diff --git a/gwinc/noise/quantum.py b/gwinc/noise/quantum.py
index d3924b8..9966aa6 100644
--- a/gwinc/noise/quantum.py
+++ b/gwinc/noise/quantum.py
@@ -251,7 +251,7 @@ def shotradSignalRecycled(f, ifo, sustf, power):
     mismatch = mismatch + ifo.TCS.SRCloss        # Mismatch
 
     # BSloss + mismatch has been incorporated into a SRC Loss
-    lambda_SR = 1 - (1 - mismatch) * (1 - bsloss) # SR cavity loss [Power]
+    lambda_SR = 1 - (1 - mismatch) * (1 - bsloss)  # SR cavity loss [Power]
 
     tau = sqrt(ifo.Optics.SRM.Transmittance)     # SRM Transmittance [amplitude]
     rho = sqrt(1 - tau**2)                       # SRM Reflectivity [amplitude]
@@ -355,8 +355,7 @@ def shotradSignalRecycled(f, ifo, sustf, power):
     tau_SEC_ARM = getProdTF(tau_SEC, tau_ARM)
 
     # signal field
-    Msig = tSig * exp(1j * Omega * L / c) * \
-           getProdTF(tau_SEC_ARM, np.array([[np.zeros(nf)], [sqrt(2 * K) / h_SQL]]))
+    Msig = tSig * exp(1j * Omega * L / c) * getProdTF(tau_SEC_ARM, np.array([[np.zeros(nf)], [sqrt(2 * K) / h_SQL]]))
 
     # dark-port input field
     Mifo = rho_SEC
@@ -812,22 +811,21 @@ def sqzFilterCavity(f, Lcav, Ti, Te, Lrt, fdetune, MinR, MinT=1, key='FC'):
     c = const.c
     omega = 2 * pi * f
     wf = 2 * pi * fdetune
-    Phi_p = 2 * (omega-wf)* Lcav / c
-    Phi_m = 2 * (-omega-wf)* Lcav / c
+    Phi_p = 2 * (omega-wf) * Lcav / c
+    Phi_m = 2 * (-omega-wf) * Lcav / c
 
     ephi_p = exp(1j * Phi_p)
     ephi_m = exp(1j * Phi_m)
 
     # cavity gains
-    g_p = 1 / ( 1 - rr * ephi_p)
-    g_m = 1 / ( 1 - rr * ephi_m)
+    g_p = 1 / (1 - rr * ephi_p)
+    g_m = 1 / (1 - rr * ephi_m)
 
     # Reflectivity for vacuum flactuation entering the cavity from
     # the input mirror (check sign)
     r_p = ri - re * Ti * ephi_p * g_p
     r_m = ri - re * Ti * ephi_m * g_m
 
-
     # Transmissivity for vacuum flactuation entering the cavity from
     # the back mirror (check sign)
     t_p = sqrt(Ti * Te * ephi_p) * g_p
diff --git a/gwinc/struct.py b/gwinc/struct.py
index c1645e8..9ca06b6 100644
--- a/gwinc/struct.py
+++ b/gwinc/struct.py
@@ -2,7 +2,6 @@
 """
 
 from collections.abc import Mapping, Sequence, MutableSequence
-#base class for numbers
 from numbers import Number
 
 import os
@@ -19,39 +18,6 @@ from scipy.io.matlab.mio5_params import mat_struct
 assert not issubclass(np.ndarray, Sequence)
 
 
-# HACK: fix loading Number in scientific notation
-#
-# https://stackoverflow.com/questions/30458977/yaml-loads-5e-6-as-string-and-not-a-number
-#
-# An apparent bug in python-yaml prevents it from regognizing
-# scientific notation as a float.  The following is a modified version
-# of the parser that recognize scientific notation appropriately.
-yaml_loader = yaml.SafeLoader
-yaml_loader.add_implicit_resolver(
-    'tag:yaml.org,2002:float',
-    re.compile('''^(?:
-     [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
-    |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
-    |\\.[0-9_]+(?:[eE][-+][0-9]+)?
-    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
-    |[-+]?\\.(?:inf|Inf|INF)
-    |\\.(?:nan|NaN|NAN))$''', re.X),
-    list('-+0123456789.'))
-
-
-def dictlist2recarray(l):
-    def dtype(v):
-        if isinstance(v, int):
-            return float
-        else:
-            return type(v)
-    # get dtypes from first element dict
-    dtypes = [(k, dtype(v)) for k, v in l[0].items()]
-    values = [tuple(el.values()) for el in l]
-    out = np.array(values, dtype=dtypes)
-    return out.view(np.recarray)
-
-
 class Struct(object):
     """Matlab struct-like object
 
@@ -97,7 +63,7 @@ class Struct(object):
         Struct.
 
         """
-        #TODO, should this use the more or less permissive allow_unknown_types?
+        # TODO, should this use the more or less permissive allow_unknown_types?
         self.update(dict(*args, **kwargs), allow_unknown_types=True)
 
     def __getitem__(self, key):
@@ -140,7 +106,7 @@ class Struct(object):
     def update(
             self, other,
             overwrite_atoms=False,
-            clear_test=lambda v : False,
+            clear_test=lambda v: False,
             value_types=(str, Number, np.ndarray),
             allow_unknown_types=True,
     ):
@@ -173,7 +139,7 @@ class Struct(object):
                 else:
                     raise RuntimeError("clear_test deletions not allowed in sequences like lists")
             elif other_v is None:
-                #don't update on None
+                # don't update on None
                 pass
             elif isinstance(other_v, value_types):
                 # other is a value type, not a collection
@@ -555,4 +521,38 @@ class Struct(object):
                 raise IOError("Unknown file type: {}".format(ext))
 
 
+def dictlist2recarray(lst):
+    def dtype(v):
+        if isinstance(v, int):
+            return float
+        else:
+            return type(v)
+    # get dtypes from first element dict
+    dtypes = [(k, dtype(v)) for k, v in lst[0].items()]
+    values = [tuple(el.values()) for el in lst]
+    out = np.array(values, dtype=dtypes)
+    return out.view(np.recarray)
+
+
+# HACK: fix loading Number in scientific notation
+#
+# https://stackoverflow.com/questions/30458977/yaml-loads-5e-6-as-string-and-not-a-number
+#
+# An apparent bug in python-yaml prevents it from regognizing
+# scientific notation as a float.  The following is a modified version
+# of the parser that recognize scientific notation appropriately.
+yaml_loader = yaml.SafeLoader
+yaml_loader.add_implicit_resolver(
+    'tag:yaml.org,2002:float',
+    re.compile('''^(?:
+     [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
+    |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
+    |\\.[0-9_]+(?:[eE][-+][0-9]+)?
+    |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
+    |[-+]?\\.(?:inf|Inf|INF)
+    |\\.(?:nan|NaN|NAN))$''', re.X),
+    list('-+0123456789.'))
+
+
+# add to the registry of mappings, as it is a useful way to write code to normalize between dicts and structs
 Mapping.register(Struct)
-- 
GitLab