diff --git a/doc/Makefile b/doc/Makefile index 09aff0b..a2f40ca 100644 --- a/doc/Makefile +++ b/doc/Makefile @@ -47,7 +47,7 @@ help: api: - $(SPHINXBUILDAPI) -f -o source/api -T -H 'PyTurbSim API' ../pyts/ + $(SPHINXBUILDAPI) -f -T -H 'PyTurbSim API' -o source/api ../pyts/ ../pyts/gui # $(SPHINXBUILDAPI) -f -o source/api -T -H 'PyTS Plot API' ../pyts_plot/ clean: diff --git a/doc/source/code-framework.rst b/doc/source/code-framework.rst index e383f1c..f37d807 100644 --- a/doc/source/code-framework.rst +++ b/doc/source/code-framework.rst @@ -30,7 +30,8 @@ code and its use. The primary components of this framework are: stress profile models. d) :mod:`pyts.cohereModels`, contains the spatial coherence models. - More details on model packages can be found in the :ref:`model-info` section. + + More details on model packages can be found in the :ref:`model-info` section. 3) The :mod:`pyts.io` package supports reading and writing of TurbSim input (.inp) and output files (e.g. .bl, .wnd, etc.). diff --git a/doc/source/conf.py b/doc/source/conf.py index 3be64de..f12659d 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -63,7 +63,7 @@ # General information about the project. project = ver.__prog_name__ -copyright = u'2014, National Renewable Energy Lab' +copyright = u'2018, National Renewable Energy Lab' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -91,7 +91,7 @@ # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. -exclude_patterns = [] +exclude_patterns = ['pyts/gui/'] # The reST default role (used for this markup: `text`) to use for all documents. # default_role = None diff --git a/doc/source/usage.rst b/doc/source/usage.rst index 9877b80..1300283 100644 --- a/doc/source/usage.rst +++ b/doc/source/usage.rst @@ -30,8 +30,8 @@ command line do:: Alternatively, this mode can be used from an interactive python shell by doing:: - >>> from pyts.runInput.main import readConfig, run, write - >>> config = readConfig('TurbSim.inp') + >>> from pyts.runInput.main import readInput, run, write + >>> config = readInput('TurbSim.inp') >>> tsdat = run(config) >>> write(tsdat, config, 'TurbSim') @@ -51,6 +51,7 @@ the statistics of |pyts| output explicitly. This api is the core interface of |pyts| (the other two are wrappers). As a starting point for using this interface checkout the :doc:`API documentation `. Or start navigating the api interactively by importing it:: + import pyts.api as pyts More specifically, the :file:`examples/api.py` file includes an @@ -58,20 +59,6 @@ overview of how to begin using |pyts|. The contents of that file is: .. literalinclude:: ../../examples/api.py -3) Graphical user interface (GUI) ---------------------------------- - -The GUI was developed for reading and writing TurbSim input files. -The gui was designed to help new users of TurbSim in understanding -and writing input files. The gui can be used to run |pyts| or -|ots| (if an |ots| executable can be found in path). -'gTurbSim' can be run from a command line in the |pyts| -directory:: - - $ python gTurbSim.py TurbSim.inp - -The source code for this mode is contained in the :mod:`.pyts.gui` package. - Reading output files -------------------- diff --git a/docs/.buildinfo b/docs/.buildinfo index 2b96498..48e506c 100644 --- a/docs/.buildinfo +++ b/docs/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: f3dcb6ff76ded42a9421f678f2620724 +config: 48e95e86a0231fc25b40451d00c9e8c3 tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/_images/plotting.png b/docs/_images/plotting.png index c2b763d..ee424a2 100644 Binary files a/docs/_images/plotting.png and b/docs/_images/plotting.png differ diff --git a/docs/_images/plotting2.png b/docs/_images/plotting2.png index 34c4004..5a46e88 100644 Binary files a/docs/_images/plotting2.png and b/docs/_images/plotting2.png differ diff --git a/docs/_modules/index.html b/docs/_modules/index.html index 914b2a7..f4c63fb 100644 --- a/docs/_modules/index.html +++ b/docs/_modules/index.html @@ -1,37 +1,39 @@ + - - - Overview: module code — PyTurbSim 0.4.7 documentation - + Overview: module code — PyTurbSim 0.4.8 documentation - - + - + + + + - + - + +
@@ -93,14 +95,11 @@

Related Topics

@@ -108,11 +107,11 @@

Quick search

diff --git a/docs/_modules/pyts/base.html b/docs/_modules/pyts/base.html index 0290d22..2a92c64 100644 --- a/docs/_modules/pyts/base.html +++ b/docs/_modules/pyts/base.html @@ -1,38 +1,39 @@ + - - - pyts.base — PyTurbSim 0.4.7 documentation - + pyts.base — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.base

-"""
+"""
 This is the 'base' module for the PyTurbSim program.
 
 This module:
@@ -55,65 +56,65 @@ 

Source code for pyts.base

  d) Defines several abstract base classes.
 
 """
-from . import pyts_numpy as np
-from numpy import float32, complex64
-from .misc import lowPrimeFact_near
-from os import path
+from . import pyts_numpy as np
+from numpy import float32, complex64
+from .misc import lowPrimeFact_near
+from os import path
 try:
-    from .tslib import tslib  # The file tslib.so contains the module 'tslib'.
+    from .tslib import tslib  # The file tslib.so contains the module 'tslib'.
 except ImportError:
-    print """
-    ***Warning***: 'tslib' did not load correctly.  pyTurbSim
-    will produce accurate results, but MUCH less efficiently.
-    Consider compiling the tslib to improve performance.
-    """
-    tslib = None
+    print """
+    ***Warning***: 'tslib' did not load correctly.  pyTurbSim
+    will produce accurate results, but MUCH less efficiently.
+    Consider compiling the tslib to improve performance.
+    """
+    tslib = None
 
-dbg = None
-#import dbg
+dbg = None
+#import dbg
 
-tsroot = path.realpath(__file__).replace("\\", "/").rsplit('/', 1)[0] + '/'
-userroot = path.expanduser('~')
+tsroot = path.realpath(__file__).replace("\\", "/").rsplit('/', 1)[0] + '/'
+userroot = path.expanduser('~')
 
 ts_float = float32
 ts_complex = complex64
-#ts_float={'dtype':np.float32,'order':'F'}
-#ts_complex={'dtype':np.complex64,'order':'F'}
+#ts_float={'dtype':np.float32,'order':'F'}
+#ts_complex={'dtype':np.complex64,'order':'F'}
 
 
 
[docs]class statObj(float): - def __new__(self, dat, ubar=None): - return float.__new__(self, dat.mean()) + def __new__(self, dat, ubar=None): + return float.__new__(self, dat.mean()) @property def mean(self): return self - def __init__(self, dat, ubar=None): + def __init__(self, dat, ubar=None): self.max = dat.max() self.min = dat.min() self.sigma = np.std(dat) - if ubar is None: + if ubar is None: ubar = self.mean self.ti = (self.sigma / ubar) * 100 def __repr__(self,): - return '<statObj mean: %0.2f, min: %0.2f, max: %0.2f>' % (self.mean, self.min, self.max) + return '<statObj mean: %0.2f, min: %0.2f, max: %0.2f>' % (self.mean, self.min, self.max)
+ -
[docs]class tsBaseObj(object): """ An abstract, base object, that contains the component (u,v,w) information for derived classes. """ - comp_name = ['u', 'v', 'w'] + comp_name = ['u', 'v', 'w'] n_comp = len(comp_name) - comp = range(n_comp) + comp = range(n_comp)
+ -
[docs]class calcObj(tsBaseObj): """ @@ -125,23 +126,23 @@

Source code for pyts.base

     output 'statistics' of that class. In other words: profObj,
     specObj, stressObj, and cohereObj all derive from this class.
     """
-    _alias0 = ['u', 'v', 'w']
+    _alias0 = ['u', 'v', 'w']
 
     def __getitem__(self, ind):
         if ind in self._alias0:
             ind = self._alias0.index(ind)
-        if hasattr(self, '_alias1') and ind in self._alias1:
+        if hasattr(self, '_alias1') and ind in self._alias1:
             ind = self._alias1.index(ind)
         return self.array[ind]
 
     def __setitem__(self, ind, val):
         if ind in self._alias0:
             ind = self._alias0.index(ind)
-        if hasattr(self, '_alias1') and ind in self._alias1:
+        if hasattr(self, '_alias1') and ind in self._alias1:
             ind = self._alias1.index(ind)
-        self.array[ind] = val
+        self.array[ind] = val
+ -
[docs]class gridProps(tsBaseObj): """ @@ -179,9 +180,9 @@

Source code for pyts.base

 
     @property
     def dt(self,):
-        return self.grid.dt
+        return self.grid.dt
+ -
def _parse_inputs(n, l, d, plus_one=1): """ Parse inputs that describe a grid dimension. @@ -216,26 +217,26 @@

Source code for pyts.base

     value of `d` is disregaurded and computed from `n` and `l`.
 
     """
-    if (n is None) + (l is None) + (d is None) > 1:
-        raise Exception('Invalid inputs to Grid Initialization.')
-    if n is None:
+    if (n is None) + (l is None) + (d is None) > 1:
+        raise Exception('Invalid inputs to Grid Initialization.')
+    if n is None:
         d = ts_float(d)
         n = int(l / d) + plus_one
         l = (n - plus_one) * d
-    elif l is None:
+    elif l is None:
         d = ts_float(d)
         l = (n - plus_one) * d
-    else:  # Always override d if the other two are specified.
+    else:  # Always override d if the other two are specified.
         l = ts_float(l)
         d = l / (n - plus_one)
     return n, l, d
 
 
-
[docs]def tsGrid(center=None, ny=None, nz=None, - width=None, height=None, dy=None, dz=None, - nt=None, time_sec=None, time_min=None, dt=None, time_sec_out=None, - findClose_nt_lowPrimeFactors=True, prime_max=31, - clockwise=True): +
[docs]def tsGrid(center=None, ny=None, nz=None, + width=None, height=None, dy=None, dz=None, + nt=None, time_sec=None, time_min=None, dt=None, time_sec_out=None, + findClose_nt_lowPrimeFactors=True, prime_max=31, + clockwise=True): """ Create a TurbSim grid. @@ -281,15 +282,15 @@

Source code for pyts.base

 
     """
     out = gridObj()
-    if center is None:
+    if center is None:
         raise TypeError(
-            "tsGrid objects require that the height of the grid center \
-            (input parameter 'center') be specified.")
-    if time_sec is None and time_min is not None:
+            "tsGrid objects require that the height of the grid center \
+            (input parameter 'center') be specified.")
+    if time_sec is None and time_min is not None:
         time_sec = time_min * 60.
-    if time_sec_out is None and time_sec is not None:
+    if time_sec_out is None and time_sec is not None:
         time_sec_out = time_sec
-    if not (time_sec_out is None or time_sec is None):
+    if not (time_sec_out is None or time_sec is None):
         time_sec = max(time_sec_out, time_sec)
     n_y, width, dy = _parse_inputs(ny, width, dy)
     n_z, height, dz = _parse_inputs(nz, height, dz)
@@ -299,22 +300,22 @@ 

Source code for pyts.base

                                dz, dtype=ts_float)
 
     out.n_t, out.time_sec, out.dt = _parse_inputs(nt, time_sec, dt, plus_one=0)
-    if time_sec_out is None:
+    if time_sec_out is None:
         time_sec_out = out.time_sec
     (out.n_t_out,
      time_sec_out,
-     junk) = _parse_inputs(None,
+     junk) = _parse_inputs(None,
                            time_sec_out,
                            dt, plus_one=0)
 
     if findClose_nt_lowPrimeFactors:
         out.n_t = lowPrimeFact_near(out.n_t, nmin=out.n_t_out, pmax=prime_max)
         out.n_t, out.time_sec, junk = _parse_inputs(
-            out.n_t, None, out.dt, plus_one=0)
-    out.f = np.arange(out.n_f, dtype=ts_float) * out.df + out.df  # !!!CHECKTHIS
-    return out
+            out.n_t, None, out.dt, plus_one=0)
+    out.f = np.arange(out.n_f, dtype=ts_float) * out.df + out.df  # !!!CHECKTHIS
+    return out
+ -
[docs]class gridObj(tsBaseObj): """ @@ -331,22 +332,22 @@

Source code for pyts.base

     2) Irregular grids are not yet supported.
 
     """
-    clockwise = True
-    n_tower = 0  # This is a placeholder.
+    clockwise = True
+    n_tower = 0  # This is a placeholder.
 
     def __getitem__(self, ind):
-        if hasattr(ind, '__len__'):
+        if hasattr(ind, '__len__'):
             if len(ind) == 1:
                 iy = ind[0]
-                iz = slice(None)
+                iz = slice(None)
             elif len(ind) == 2:
                 iy, iz = ind
             else:
                 raise Exception(
-                    "Indices for accessing grids must have len==1 or 2.")
+                    "Indices for accessing grids must have len==1 or 2.")
         else:
             iy = ind
-            iz = slice(None)
+            iz = slice(None)
         out = type(self)()
         out.n_t = self.n_t
         out.n_t_out = self.n_t_out
@@ -358,9 +359,9 @@ 

Source code for pyts.base

         return out
 
     def __repr__(self,):
-        return ('<TurbSim Grid:%5.1fm high x %0.1fm wide grid  (%d x %d points)'
-                ', centered at %0.1fm.\n              %5.1fsec simulation, dt=%0.1fsec '
-                '(%d timesteps).>' % (self.height, self.width,
+        return ('<TurbSim Grid:%5.1fm high x %0.1fm wide grid  (%d x %d points)'
+                ', centered at %0.1fm.\n              %5.1fsec simulation, dt=%0.1fsec '
+                '(%d timesteps).>' % (self.height, self.width,
                                       self.n_z, self.n_y,
                                       self.center, self.time_sec,
                                       self.dt, self.n_t))
@@ -447,23 +448,23 @@ 

Source code for pyts.base

         returned by :attr:`sub2ind`).
 
         """
-        if not hasattr(ii, '__len__'):
+        if not hasattr(ii, '__len__'):
             ii = self.ind2sub(ii)
-        if not hasattr(jj, '__len__'):
+        if not hasattr(jj, '__len__'):
             jj = self.ind2sub(jj)
         return np.sqrt((self.y[ii[1]] - self.y[jj[1]]) ** ts_float(2) +
-                       (self.z[ii[0]] - self.z[jj[0]]) ** ts_float(2))
-
+ (self.z[ii[0]] - self.z[jj[0]]) ** ts_float(2))
+ @property def zhub(self,): """ The height of the hub. """ - if not hasattr(self, '_zhub'): + if not hasattr(self, '_zhub'): self._zhub = self.center return self._zhub - @zhub.setter + @zhub.setter def zhub(self, val): self._zhub = val @@ -476,50 +477,50 @@

Source code for pyts.base

         """
         return min(self.width, self.height)
 
-    ## def ind2sub(self,ind):
-    ##     """
-    ##     Return the subscripts (iz,iy) corresponding to the
-    ##     `flattened' index *ind* (column-order) for this grid.
-    ##     """
-    ##     iy=ind/self.n_z
-    ##     if iy>=self.n_y:
-    ##         raise IndexError('Index beyond range of grid.')
-    ##     iz=np.mod(ind,self.n_z)
-    ##     return (iz,iy)
-
-    ## def sub2ind(self,subs):
-    ##     """
-    ##     Return the `flattened' index (column-order) corresponding
-    ##     to the subscript *subs* (iz,iy) for this grid.
-    ##     """
-    ##     return subs[1]*self.n_z+subs[0]
-
-    ## def flatten(self,arr):
-    ##     """
-    ##     Reshape an array so that the z-y grid points are
-    ##     one-dimension of the array (for Cholesky factorization).
-    ##     """
-    ##     if arr.ndim>2 and arr.shape[0]==3 and
-    ##     arr.shape[1]==self.n_z and arr.shape[2]==self.n_y:
-    ##         shp=[3,self.n_p]+list(arr.shape[3:])
-    ##     elif arr.shape[0]==self.n_z and arr.shape[1]==self.n_y:
-    ##         shp=[self.n_p]+list(arr.shape[2:])
-    ##     else:
-    ##         raise ValueError('The array shape does not match this grid.')
-    ##     return arr.reshape(shp,order='F')
-
-    ## def reshape(self,arr):
-    ##     """
-    ##     Reshape the array *arr* so that its z-y grid points are
-    ##     two-dimensions of the array (after Cholesky factorization).
-    ##     """
-    ##     if arr.shape[0]==3 and arr.shape[1]==self.n_p:
-    ##         shp=[3,self.n_z,self.n_y]+list(arr.shape[2:])
-    ##     elif arr.shape[0]==self.n_p:
-    ##         shp=[self.n_z,self.n_y]+list(arr.shape[1:])
-    ##     else:
-    ##         raise ValueError('The array shape does not match this grid.')
-    ##     return arr.reshape(shp,order='F')
+    ## def ind2sub(self,ind):
+    ##     """
+    ##     Return the subscripts (iz,iy) corresponding to the
+    ##     `flattened' index *ind* (column-order) for this grid.
+    ##     """
+    ##     iy=ind/self.n_z
+    ##     if iy>=self.n_y:
+    ##         raise IndexError('Index beyond range of grid.')
+    ##     iz=np.mod(ind,self.n_z)
+    ##     return (iz,iy)
+
+    ## def sub2ind(self,subs):
+    ##     """
+    ##     Return the `flattened' index (column-order) corresponding
+    ##     to the subscript *subs* (iz,iy) for this grid.
+    ##     """
+    ##     return subs[1]*self.n_z+subs[0]
+
+    ## def flatten(self,arr):
+    ##     """
+    ##     Reshape an array so that the z-y grid points are
+    ##     one-dimension of the array (for Cholesky factorization).
+    ##     """
+    ##     if arr.ndim>2 and arr.shape[0]==3 and
+    ##     arr.shape[1]==self.n_z and arr.shape[2]==self.n_y:
+    ##         shp=[3,self.n_p]+list(arr.shape[3:])
+    ##     elif arr.shape[0]==self.n_z and arr.shape[1]==self.n_y:
+    ##         shp=[self.n_p]+list(arr.shape[2:])
+    ##     else:
+    ##         raise ValueError('The array shape does not match this grid.')
+    ##     return arr.reshape(shp,order='F')
+
+    ## def reshape(self,arr):
+    ##     """
+    ##     Reshape the array *arr* so that its z-y grid points are
+    ##     two-dimensions of the array (after Cholesky factorization).
+    ##     """
+    ##     if arr.shape[0]==3 and arr.shape[1]==self.n_p:
+    ##         shp=[3,self.n_z,self.n_y]+list(arr.shape[2:])
+    ##     elif arr.shape[0]==self.n_p:
+    ##         shp=[self.n_z,self.n_y]+list(arr.shape[1:])
+    ##     else:
+    ##         raise ValueError('The array shape does not match this grid.')
+    ##     return arr.reshape(shp,order='F')
 
 
[docs] def ind2sub(self, ind): """ @@ -528,10 +529,10 @@

Source code for pyts.base

         """
         iz = ind / self.n_y
         if iz >= self.n_z:
-            raise IndexError('Index beyond range of grid.')
+            raise IndexError('Index beyond range of grid.')
         iy = np.mod(ind, self.n_y)
-        return (iz, iy)
-
+ return (iz, iy)
+
[docs] def sub2ind(self, subs): """ Return the 'flattened' index (row/C-order) corresponding to @@ -541,8 +542,8 @@

Source code for pyts.base

             subs = (self.n_z + subs[0], subs[1])
         if subs[1] < 0:
             subs = (subs[0], self.n_y + subs[1])
-        return subs[0] * self.n_y + subs[1]
-
+ return subs[0] * self.n_y + subs[1]
+
[docs] def flatten(self, arr): """ Reshape `arr` so that the z-y grid points are one-dimension @@ -558,9 +559,9 @@

Source code for pyts.base

         elif arr.shape[0] == self.n_z and arr.shape[1] == self.n_y:
             shp = [self.n_p] + list(arr.shape[2:])
         else:
-            raise ValueError('The array shape does not match this grid.')
-        return arr.reshape(shp, order='C')
-
+ raise ValueError('The array shape does not match this grid.') + return arr.reshape(shp, order='C')
+
[docs] def reshape(self, arr): """ Reshape `arr` so that its z-y grid points are two-dimensions @@ -571,10 +572,10 @@

Source code for pyts.base

         elif arr.shape[0] == self.n_p:
             shp = [self.n_z, self.n_y] + list(arr.shape[1:])
         else:
-            raise ValueError('The array shape does not match this grid.')
-        return arr.reshape(shp, order='C')
+            raise ValueError('The array shape does not match this grid.')
+        return arr.reshape(shp, order='C')
+ -
[docs]class modelBase(tsBaseObj): """ @@ -584,12 +585,12 @@

Source code for pyts.base

     @property
     def model_name(self,):
         """The model name is the class definition name"""
-        return str(self.__class__).rsplit('.', 1)[-1].rstrip("'>")
+        return str(self.__class__).rsplit('.', 1)[-1].rstrip("'>")
 
     @property
     def model_desc(self,):
         """The model description is the first line of the docstring."""
-        return self.__doc__.splitlines()[0].rstrip('.')
+        return self.__doc__.splitlines()[0].rstrip('.')
 
     @property
     def parameters(self,):
@@ -600,10 +601,10 @@ 

Source code for pyts.base

         This functionality is not yet implemented, and this is a
         placeholder for now.
         """
-        return dict(self.__dict__)
+        return dict(self.__dict__)
 
     def _sumfile_string(self, tsrun, ):
-        return "## No '_sumfile_string' defined for %s ##\n" % (str(self.__class__))
+ return "## No '_sumfile_string' defined for %s ##\n" % (str(self.__class__))
@@ -622,14 +623,11 @@

Related Topics

@@ -637,11 +635,11 @@

Quick search

diff --git a/docs/_modules/pyts/cohereModels/base.html b/docs/_modules/pyts/cohereModels/base.html index 2d97f40..481dbae 100644 --- a/docs/_modules/pyts/cohereModels/base.html +++ b/docs/_modules/pyts/cohereModels/base.html @@ -1,38 +1,39 @@ + - - - pyts.cohereModels.base — PyTurbSim 0.4.7 documentation - + pyts.cohereModels.base — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.cohereModels.base

-"""
+"""
 This is the coherence package's base module.
 
 The coherence models work somewhat different than other packages. In
@@ -57,8 +58,9 @@ 

Source code for pyts.cohereModels.base

 the grid.
 
 """
-from ..base import gridProps, modelBase, np, ts_float, ts_complex, tslib, dbg, calcObj
-from numpy.linalg import cholesky
+# tslib and dbg are needed externally
+from ..base import gridProps, modelBase, np, ts_float, ts_complex, calcObj
+from numpy.linalg import cholesky
 
 
 
[docs]class cohereObj(gridProps, calcObj): @@ -98,24 +100,24 @@

Source code for pyts.cohereModels.base

         Avoid accessing this property on PyTurbSim runs involving many
         grid-points or timesteps.
         """
-        if not hasattr(self, '_array'):
+        if not hasattr(self, '_array'):
             self._array = np.empty((self.n_comp,
                                     self.n_p,
                                     self.n_p,
                                     self.n_f),
-                                   dtype=ts_complex, order='F')
+                                   dtype=ts_complex, order='F')
 
             for icomp in range(3):
                 for ff in range(self.n_f):
                     for ii, jj in self._iter_inds():
-                        self._array[icomp, ii, jj] = self._array[icomp, jj, ii] = self.calcCoh(self.grid.f, icomp, ii, jj)
+                        self._array[icomp, ii, jj] = self._array[icomp, jj, ii] = self.calcCoh(self.grid.f, icomp, ii, jj)  # nopep8
         return self._array
 
-    @array.setter
+    @array.setter
     def array(self, val):
         self._array = val
 
-    @array.deleter
+    @array.deleter
     def array(self,):
         del self._array
 
@@ -124,7 +126,7 @@ 

Source code for pyts.cohereModels.base

         self.prof = tsrun.prof
         self.spec = tsrun.spec
         self.stress = tsrun.stress
-        self.ncore = tsrun.ncore # This is used by tslib.
+        self.ncore = tsrun.ncore  # This is used by tslib.
 
     def _iter_inds(self,):
         """
@@ -167,43 +169,49 @@ 

Source code for pyts.cohereModels.base

         calcCoh : computes the coherence for individual grid-point pairs.
 
         """
-        out = np.zeros((self.n_comp, self.n_p, self.n_f), dtype=ts_complex, order='F')
-        tmp = np.empty((self.n_p, self.n_p), dtype=ts_float, order='F')
+        out = np.zeros((self.n_comp, self.n_p, self.n_f),
+                       dtype=ts_complex, order='F')
+        tmp = np.empty((self.n_p, self.n_p),
+                       dtype=ts_float, order='F')
         for icomp in range(3):
             for ff in range(self.n_f):
                 for ii, jj in self._iter_inds():
                     if ii == jj:
                         tmp[ii, ii] = 1
                     else:
-                        tmp[ii, jj] = tmp[jj, ii] = self.calcCoh(self.grid.f[ff], icomp, ii, jj)
+                        tmp[ii, jj] = tmp[jj, ii] = self.calcCoh(
+                            self.grid.f[ff],
+                            icomp, ii, jj)
                 tmp[:] = cholesky(tmp)
-                ## print tmp
-                ## print (tmp*phases[icomp,:,ff]).shape
-                out[icomp,:, ff] = (tmp*phases[icomp,:, ff]).sum(-1)
-        return out
-
+ out[icomp, :, ff] = (tmp * phases[icomp, :, ff]).sum(-1) + return out
+
[docs] def calcCoh(self, f, comp, ii, jj): """ - THIS IS A PLACEHOLDER METHOD WHICH SHOULD BE OVER-WRITTEN FOR ALL SUB-CLASSES - OF cohereModelBase. THIS METHOD ONLY RAISES AN ERROR. + THIS IS A PLACEHOLDER METHOD WHICH SHOULD BE OVER-WRITTEN FOR + ALL SUB-CLASSES OF cohereModelBase. THIS METHOD ONLY RAISES AN + ERROR. - A functioning version of this method (i.e. in a subclass of cohereModelBase) - should return the a length-n_f vector that is the coherence between point - `ii`=(iz,iy) and `jj`=(jz,jy) for velocity component `comp`. + A functioning version of this method (i.e. in a subclass of + cohereModelBase) should return the a length-n_f vector that is + the coherence between point `ii`=(iz,iy) and `jj`=(jz,jy) for + velocity component `comp`. Parameters ---------- cohi : A 'coherence calculator' instance (for the given tsrun). - comp : an integer (0,1,2) indicating the velocity component for which to - compute the coherence. - ii,jj : Two-integer elements indicating the grid-points between which to - calculate the coherence. For example, ii=(1,3),jj=(2,3) + comp : an integer (0,1,2) indicating the velocity component + for which to compute the coherence. + ii,jj : Two-integer elements indicating the grid-points + between which to calculate the coherence. For + example, ii=(1,3),jj=(2,3) """ raise Exception( - 'Subclasses of cohereObj must overwrite the calcCoh method or redfine the calc_phases method.') + 'Subclasses of cohereObj must overwrite the ' + 'calcCoh method or redfine the calc_phases method.')
+ -
[docs]class cohereUser(cohereObj): """ @@ -241,13 +249,13 @@

Source code for pyts.cohereModels.base

         be defined explicitly for all sub-classes of cohereModelBase.
 
         """
-        tmp = np.empty((self.n_p, self.n_p), dtype=ts_float, order='F')
+        tmp = np.empty((self.n_p, self.n_p), dtype=ts_float, order='F')
         for ff in np.range(self.n_f):
-            tmp[:] = cholesky(self.array[comp,:,:, ff])
+            tmp[:] = cholesky(self.array[comp, :, :, ff])
             for ii in range(self.n_p):
-                coh[ii, ff] = (tmp*phases[:, ff]).sum(-1)
+                coh[ii, ff] = (tmp * phases[:, ff]).sum(-1) 
+ -
[docs]class cohereModelBase(modelBase, gridProps): """ @@ -270,14 +278,15 @@

Source code for pyts.cohereModels.base

     Where tsr is a 'tsrun' object.
 
     """
-    cohereObj = cohereObj  # This needs to be set to the appropriate
-                           # 'coherence object' for each model.
+    cohereObj = cohereObj  # This needs to be set to the appropriate
+                           # 'coherence object' for each model.
 
 
[docs] def __call__(self, tsrun): """ - Calculate the coherence matrix for TurbSim run `tsrun` according to this - coherence model. The grid, profile and spectrum (tsrun.grid, tsrun.prof, - tsrun.spec) must already be defined for the tsrun. + Calculate the coherence matrix for TurbSim run `tsrun` + according to this coherence model. The grid, profile and + spectrum (tsrun.grid, tsrun.prof, tsrun.spec) must already be + defined for the tsrun. Parameters ---------- @@ -290,9 +299,10 @@

Source code for pyts.cohereModels.base

         cohi=thisCohereModel(tsrun)
 
         The coherence instance is either an array of the full
-        cross-spectral matrix (3 x n_p x n_p x n_f), or a 'calculator' that returns
-        the components of that array. Either way, the components of the cross-spectral
-        matrix (csm) can be obtained from
+        cross-spectral matrix (3 x n_p x n_p x n_f), or a 'calculator'
+        that returns the components of that array. Either way, the
+        components of the cross-spectral matrix (csm) can be obtained
+        from
 
         csm_u=cohi[0]
         csm_v=cohi[1]
@@ -300,7 +310,7 @@ 

Source code for pyts.cohereModels.base

 
         """
         out = self.cohereObj(tsrun)
-        if hasattr(self, 'set_coefs'):
+        if hasattr(self, 'set_coefs'):
             self.set_coefs(out)
         return out
@@ -321,14 +331,11 @@

Related Topics

@@ -336,11 +343,11 @@

Quick search

diff --git a/docs/_modules/pyts/cohereModels/main.html b/docs/_modules/pyts/cohereModels/main.html index 98e7fc1..b3b168c 100644 --- a/docs/_modules/pyts/cohereModels/main.html +++ b/docs/_modules/pyts/cohereModels/main.html @@ -1,38 +1,39 @@ + - - - pyts.cohereModels.main — PyTurbSim 0.4.7 documentation - + pyts.cohereModels.main — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,13 +41,14 @@

Source code for pyts.cohereModels.main

-"""
+"""
 This module defines two coherence models:
 nwtc - The NWTC 'non-IEC' coherence model.
 iec  - The IEC coherence model.
 """
-from .base import cohereModelBase, np, ts_float, tslib, dbg, cohereObj, ts_complex
-from ..misc import Lambda
+from .base import cohereModelBase, np, ts_float, cohereObj, ts_complex
+from ..base import tslib, dbg
+from ..misc import Lambda
 
 
 
[docs]class cohereObjNone(cohereObj): @@ -57,21 +59,21 @@

Source code for pyts.cohereModels.main

     """
 
 
[docs] def calc_phases(self, phases): - return phases -
+ return phases
+
[docs] def calcCoh(self, f, comp, ii, jj): - return 0 * f + return 0 * f
+ -
[docs]class none(cohereModelBase): """ This is a 'dummy' coherence model that forces the coherence to zero. """ - cohereObj = cohereObjNone + cohereObj = cohereObjNone
+ -
[docs]class cohereObjNWTC(cohereObj):
[docs] def calc_phases(self, phases): @@ -103,9 +105,9 @@

Source code for pyts.cohereModels.main

         calcCoh : computes the coherence for individual grid-point pairs.
 
         """
-        if tslib is not None:
-            tmp = np.zeros((self.n_p, self.n_f), dtype=ts_complex, order='F')
-            u = self.grid.flatten(self.prof.u).copy(order='F')
+        if tslib is not None:
+            tmp = np.zeros((self.n_p, self.n_f), dtype=ts_complex, order='F')
+            u = self.grid.flatten(self.prof.u).copy(order='F')
             for icomp in range(3):
                 tmp[:] = phases[icomp]
                 tslib.nonieccoh(tmp, self.grid.f,
@@ -115,8 +117,8 @@ 

Source code for pyts.cohereModels.main

                 phases[icomp] = tmp
         else:
             phases = cohereObj.calc_phases(self, phases)
-        return phases
-
+ return phases
+
[docs] def calcCoh(self, f, comp, ii, jj): """ The base function for calculating coherence for non-IEC @@ -133,14 +135,14 @@

Source code for pyts.cohereModels.main

         two = ts_float(2)
         zm = (self.grid.z[ii[0]] + self.grid.z[jj[0]]) / two
         um = (self.prof.u[ii] + self.prof.u[jj]) / two
-        #print zm
-        #print self.grid.z[1],self.grid.y[1],r,um,(r/zm)**self.CohExp,self.grid.f[9]
-        #print 'junk',self.a[comp],self.b[comp]
-        #print -self.a[0]*r*np.sqrt((self.grid.f[9]/um)**2+(self.b[comp])**2)
+        #print zm
+        #print self.grid.z[1],self.grid.y[1],r,um,(r/zm)**self.CohExp,self.grid.f[9]
+        #print 'junk',self.a[comp],self.b[comp]
+        #print -self.a[0]*r*np.sqrt((self.grid.f[9]/um)**2+(self.b[comp])**2)
         return np.exp(-self.a[comp] * (r / zm) ** self.CohExp *
-                      np.sqrt((f * r / um) ** two + (self.b[comp] * r) ** two))
+                      np.sqrt((f * r / um) ** two + (self.b[comp] * r) ** two))
+ -
[docs]class nwtc(cohereModelBase): """NWTC coherence model. @@ -183,11 +185,11 @@

Source code for pyts.cohereModels.main

     CohExp is the 'coherence exponent' input parameter (default is 0).
 
     """
-    __doc__ += cohereModelBase.__doc__
+    __doc__ += cohereModelBase.__doc__
 
-    cohereObj = cohereObjNWTC  # This must be defined for each coherence model.
+    cohereObj = cohereObjNWTC  # This must be defined for each coherence model.
 
-    def __init__(self, a=[None, None, None], b=[0., 0., 0.], CohExp=0.0):
+    def __init__(self, a=[None, None, None], b=[0., 0., 0.], CohExp=0.0):
         """
         Create a NWTC 'non-IEC' coherence model.
 
@@ -205,25 +207,25 @@ 

Source code for pyts.cohereModels.main

             velocity component.  Each element defaults to 0.
         CohExp :  float, optional
         """
-        if CohExp is None:
+        if CohExp is None:
             self.CohExp = 0.0
         else:
             self.CohExp = CohExp
         self.a = a
         self.b = np.array(b, dtype=ts_float)
         if dbg:
-            #self.timer=dbg.timer('tslib-cohNWTC')
-            self.timer = dbg.timer('roll')
+            #self.timer=dbg.timer('tslib-cohNWTC')
+            self.timer = dbg.timer('roll')
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Coherence model used                             =  {dat.model_desc}
-        Coherence Exponent                               =  {dat.CohExp:0.2f}
-        Coherence decrements (IncDec):
-           U (a, b)                                      =  ({coh.a[0]:0.2f}, {coh.b[0]:0.2f})
-           V (a, b)                                      =  ({coh.a[1]:0.2f}, {coh.b[1]:0.2f})
-           W (a, b)                                      =  ({coh.a[2]:0.2f}, {coh.b[2]:0.2f})
-        """
+        sumstring_format = """
+        Coherence model used                             =  {dat.model_desc}
+        Coherence Exponent                               =  {dat.CohExp:0.2f}
+        Coherence decrements (IncDec):
+           U (a, b)                                      =  ({coh.a[0]:0.2f}, {coh.b[0]:0.2f})
+           V (a, b)                                      =  ({coh.a[1]:0.2f}, {coh.b[1]:0.2f})
+           W (a, b)                                      =  ({coh.a[2]:0.2f}, {coh.b[2]:0.2f})
+        """
         return sumstring_format.format(dat=self, coh=tsrun.cohere, )
 
 
[docs] def set_coefs(self, cohereObj): @@ -234,20 +236,20 @@

Source code for pyts.cohereModels.main

         cohereObj.CohExp = self.CohExp
         cohereObj.b = self.b
         cohereObj.a = np.empty((3), dtype=ts_float)
-        if self.a[0] is None:
+        if self.a[0] is None:
             cohereObj.a[0] = cohereObj.prof.uhub
         else:
             cohereObj.a[0] = self.a[0]
-        if self.a[1] is None:
+        if self.a[1] is None:
             cohereObj.a[1] = 0.75 * cohereObj.a[0]
         else:
             cohereObj.a[1] = self.a[1]
-        if self.a[2] is None:
+        if self.a[2] is None:
             cohereObj.a[2] = 0.75 * cohereObj.a[0]
         else:
-            cohereObj.a[2] = self.a[2]
+            cohereObj.a[2] = self.a[2]
+ -
[docs]class cohereObjIEC(cohereObj):
[docs] def calcCoh(self, f, comp, ii, jj): @@ -283,8 +285,8 @@

Source code for pyts.cohereModels.main

             return np.exp(-self.a * np.sqrt((f * r / self.prof.uhub) ** 2
                                             + (0.12 * r / self.Lc) ** 2))
         else:
-            return 0
-
+ return 0
+
[docs] def calc_phases(self, phases): """ Compute and set the full cross-coherence matrix for component @@ -294,8 +296,8 @@

Source code for pyts.cohereModels.main

         the IEC model.
 
         """
-        if tslib is not None:
-            out = phases[0].copy(order='F')
+        if tslib is not None:
+            out = phases[0].copy(order='F')
             tslib.ieccoh(out, self.grid.f,
                          self.y, self.z, self.prof.uhub,
                          self.a, self.Lc,
@@ -303,9 +305,9 @@ 

Source code for pyts.cohereModels.main

             phases[0] = out
             return phases
         else:
-            return cohereObj.calc_phases(self, phases)
+            return cohereObj.calc_phases(self, phases)
+ -
[docs]class iec(cohereModelBase): """IEC coherence model. @@ -346,7 +348,7 @@

Source code for pyts.cohereModels.main

     Lc = 5.67*min(60m,HubHt)
 
     """
-    __doc__ += cohereModelBase.__doc__
+    __doc__ += cohereModelBase.__doc__
 
     cohereObj = cohereObjIEC
 
@@ -359,22 +361,22 @@ 

Source code for pyts.cohereModels.main

     def __init__(self, IECedition=3, ):
         self.IECedition = IECedition
         if IECedition <= 2:
-            # The Lambda function includes a factor of 0.7 (_Lfactor*0.7=2.45).
+            # The Lambda function includes a factor of 0.7 (_Lfactor*0.7=2.45).
             self._Lfactor = 3.5
             self.a = 8.8
-        else:  # 3rd edition IEC standard:
-            # The Lambda function includes a factor of 0.7 (_Lfactor*0.7=5.67)
+        else:  # 3rd edition IEC standard:
+            # The Lambda function includes a factor of 0.7 (_Lfactor*0.7=5.67)
             self._Lfactor = 8.1
             self.a = 12.
         if dbg:
-            self.timer = dbg.timer('tslib-cohIEC')
+            self.timer = dbg.timer('tslib-cohIEC')
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Coherence model used                             =  {dat.model_desc}
-        IEC Edition                                      =  {dat.IECedition:d}
-        Coherence length scale parameter                 =  {L:0.2f} [m]
-        """
+        sumstring_format = """
+        Coherence model used                             =  {dat.model_desc}
+        IEC Edition                                      =  {dat.IECedition:d}
+        Coherence length scale parameter                 =  {L:0.2f} [m]
+        """
         return sumstring_format.format(dat=self, L=self._L(tsrun.grid.zhub))
 
 
[docs] def set_coefs(self, cohereObj): @@ -402,14 +404,11 @@

Related Topics

@@ -417,11 +416,11 @@

Quick search

diff --git a/docs/_modules/pyts/dbg.html b/docs/_modules/pyts/dbg.html index ae25842..19df5d2 100644 --- a/docs/_modules/pyts/dbg.html +++ b/docs/_modules/pyts/dbg.html @@ -1,38 +1,39 @@ + - - - pyts.dbg — PyTurbSim 0.4.7 documentation - + pyts.dbg — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.dbg

-"""
+"""
 This is the PyTurbSim debug package. It contains debugging tools
 specifically valuable to PyTurbSim.
 """
@@ -54,23 +55,23 @@ 

Source code for pyts.dbg

     A timer class for tracking 'real' time (rather than CPU time).
     """
 
-    def __init__(self, label='NONE'):
+    def __init__(self, label='NONE'):
         self.tnew = 0.
         self.total = 0.
         self.label = label
 
 
[docs] def start(self,): - self.tnew = time.time() -
+ self.tnew = time.time()
+
[docs] def reset(self,): self.total = 0. - self.start() -
+ self.start()
+
[docs] def stop(self,): - self.total += time.time() - self.tnew -
+ self.total += time.time() - self.tnew
+ def __repr__(self): - return "So far the *%s* timer has clocked %0.3f seconds." % (self.label, self.total)
+ return "So far the *%s* timer has clocked %0.3f seconds." % (self.label, self.total)
@@ -89,14 +90,11 @@

Related Topics

@@ -104,11 +102,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/base.html b/docs/_modules/pyts/io/base.html index e0dc4cd..58a7247 100644 --- a/docs/_modules/pyts/io/base.html +++ b/docs/_modules/pyts/io/base.html @@ -1,38 +1,39 @@ + - - - pyts.io.base — PyTurbSim 0.4.7 documentation - + pyts.io.base — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,26 +41,26 @@

Source code for pyts.io.base

-"""
+"""
 A base module for the io package.
 """
 
-# This defines the 'endianness' for reading/writing binary files in PyTurbSim.
-e = '<'
-from os.path import isfile
+# This defines the 'endianness' for reading/writing binary files in PyTurbSim.
+e = '<'
+from os.path import isfile
 
 
-
[docs]def convname(fname, extension=None): +
[docs]def convname(fname, extension=None): """ Change the file extension. """ - if extension is None: + if extension is None: return fname - if extension != '' and not extension.startswith('.'): - extension = '.' + extension - return fname.rsplit('.', 1)[0] + extension + if extension != '' and not extension.startswith('.'): + extension = '.' + extension + return fname.rsplit('.', 1)[0] + extension
+ -
[docs]def checkname(fname, extensions=[]): """Test whether fname exists. @@ -69,15 +70,15 @@

Source code for pyts.io.base

     """
     if isfile(fname):
         return fname
-    if isinstance(extensions, basestring):
-        # If extensions is a string make it a single-element list.
+    if isinstance(extensions, basestring):
+        # If extensions is a string make it a single-element list.
         extensions = [extensions]
     for e in extensions:
         fnm = convname(fname, e)
         if isfile(fnm):
             return fnm
-    raise IOError("No such file or directory: '%s', and no "
-                  "files found with specified extensions." % fname)
+ raise IOError("No such file or directory: '%s', and no " + "files found with specified extensions." % fname)
@@ -96,14 +97,11 @@

Related Topics

@@ -111,11 +109,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/formatter.html b/docs/_modules/pyts/io/formatter.html index 2de0ee1..2c05326 100644 --- a/docs/_modules/pyts/io/formatter.html +++ b/docs/_modules/pyts/io/formatter.html @@ -1,38 +1,39 @@ + - - - pyts.io.formatter — PyTurbSim 0.4.7 documentation - + pyts.io.formatter — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,12 +41,12 @@

Source code for pyts.io.formatter

-from string import Formatter
+from string import Formatter
 
 
 
[docs]class SuperFormatter(Formatter): - r""" + r""" SuperFormatter adds the following capabilities: 1. Initialize with a template string, and the :meth:`__call__` method uses @@ -124,86 +125,86 @@

Source code for pyts.io.formatter

 
     """
 
-    format_prfx = ''
-    default_format_prfx = ''
-    allow_sloppy = False
+    format_prfx = ''
+    default_format_prfx = ''
+    allow_sloppy = False
 
     def __init__(self, template):
-        # Override the base methods to initialize the formatter with
-        # the template string.
+        # Override the base methods to initialize the formatter with
+        # the template string.
         self.template = template
 
 
[docs] def __call__(self, *args, **kwargs): - r""" + r""" Format the template string with `*args` and `**kwargs`. """ - return self.format(self.template, *args, **kwargs) -
+ return self.format(self.template, *args, **kwargs)
+ def __iter__(self,): return self.parse(self.template)
[docs] def get_value(self, key, args, kwargs): key = key.rstrip() self._current_name = key - if isinstance(key, (int, long)): + if isinstance(key, (int, long)): return args[key] else: try: return kwargs[key] except KeyError: - return None -
+ return None
+ def _fail(self): if self.allow_sloppy: - return '??SOME JUNK??' + return '??SOME JUNK??' else: - # This _current_name business is a DIRTY HACK. - raise KeyError("'%s' not specified and no default " - "value found in template." % self._current_name) + # This _current_name business is a DIRTY HACK. + raise KeyError("'%s' not specified and no default " + "value found in template." % self._current_name) def _format_default(self, default_val): - return format(default_val, self.default_format_prfx + 's') + return format(default_val, self.default_format_prfx + 's')
[docs] def format_field(self, value, format_spec): - format_spec = format_spec.rstrip() # Strip trailing spaces - default_val = None - if '/' in format_spec: - format_spec, default_val = format_spec.split('/', 1) - # set the default value if there is no input - if value is None: + format_spec = format_spec.rstrip() # Strip trailing spaces + default_val = None + if '/' in format_spec: + format_spec, default_val = format_spec.split('/', 1) + # set the default value if there is no input + if value is None: return self._format_default(default_val) - elif value is None: + elif value is None: return self._fail() - if '|' in format_spec: - format_spec = format_spec.split('|') + if '|' in format_spec: + format_spec = format_spec.split('|') else: format_spec = [format_spec] for form in format_spec: - formtail = None - if '(' in form and form.endswith(')'): - form, formtail = form.split('(', 1) + formtail = None + if '(' in form and form.endswith(')'): + form, formtail = form.split('(', 1) formtail = formtail[:-1] try: - if hasattr(self, '_format_' + form): - if formtail is None: - return getattr(self, '_format_' + form)(value) + if hasattr(self, '_format_' + form): + if formtail is None: + return getattr(self, '_format_' + form)(value) else: - return getattr(self, '_format_' + form)(value, + return getattr(self, '_format_' + form)(value, formtail) - if form in ["b", "c", "d", "e", "E", - "f", "F", "g", "G", "n", - "o", "s", "x", "X", "%", '']: + if form in ["b", "c", "d", "e", "E", + "f", "F", "g", "G", "n", + "o", "s", "x", "X", "%", '']: form = self.format_prfx + form - return format(value, form) + return format(value, form) except ValueError: pass except TypeError: pass - # Finally, try the default again: - if default_val is None: - raise ValueError('Invalid conversion specification') + # Finally, try the default again: + if default_val is None: + raise ValueError('Invalid conversion specification') return self._format_default(default_val)
@@ -223,14 +224,11 @@

Related Topics

@@ -238,11 +236,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/input.html b/docs/_modules/pyts/io/input.html index 9b26a84..fd5d554 100644 --- a/docs/_modules/pyts/io/input.html +++ b/docs/_modules/pyts/io/input.html @@ -1,38 +1,39 @@ + - - - pyts.io.input — PyTurbSim 0.4.7 documentation - + pyts.io.input — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,17 +41,18 @@

Source code for pyts.io.input

-"""
+"""
 This module is for reading/writing PyTurbSim input (.inp) files.
 """
-from os import listdir
+from os import listdir
 import pkg_resources
-from pyts import _version as ver
-from pyts.runInput.base import tsinput
-from copy import deepcopy
-import numpy as np
-from pyts.base import ts_float
-from pyts.io.formatter import SuperFormatter
+from pyts import _version as ver
+from pyts.runInput.base import tsinput
+from copy import deepcopy
+import numpy as np
+from pyts.base import ts_float
+from pyts.io.formatter import SuperFormatter
+from .._base import string_type
 
 
 
[docs]class InputFormatter(SuperFormatter): @@ -60,38 +62,40 @@

Source code for pyts.io.input

     file.
     """
 
-    format_prfx = '<20'
+    format_prfx = '<20'
 
     def _format_qs(self, value):
         """
         The "quote string" format specifier.
         """
-        if not value.startswith('"'):
-            value = '"' + value
-        if not value.endswith('"'):
-            value += '"'
+        if not value.startswith('"'):
+            value = '"' + value
+        if not value.endswith('"'):
+            value += '"'
         return value
 
     def _format_bool(self, value):
-        return format(value.__repr__(),
-                      self.format_prfx + 's')
+        return format(value.__repr__(),
+                      self.format_prfx + 's')
 
     def _format_dec(self, value):
-        if isinstance(value, (float, int, long)):
-            return format(value, self.format_prfx + '.2g')
-        return format('"%0.2f %0.2f"' % value, self.format_prfx + 's')
+        if isinstance(value, (float, int, long)):
+            return format(value, self.format_prfx + '.2g')
+        return format('"%0.2f %0.2f"' % value, self.format_prfx + 's')
-# This is the input-file template object:
+# This is the input-file template object template = InputFormatter( pkg_resources.resource_string(ver.pkg_name, - 'io/templates/inp')) + 'io/templates/inp')) +# This creates the mapping of line-numbers to variables, based on the +# input-file template. It is used in the read function. inputfile_form = dict() -for idx, ln in enumerate(template.template.split('\n')): - if ln.startswith('{'): - nm = ln[1:].split('!')[0].split(':')[0] +for idx, ln in enumerate(template.template.split('\n')): + if ln.startswith('{'): + nm = ln[1:].split('!')[0].split(':')[0] inputfile_form[idx] = nm @@ -102,11 +106,11 @@

Source code for pyts.io.input

 
     outstr = template(**in_dict)
 
-    with open(filename, 'w') as outfl:
+    with open(filename, 'w') as outfl:
         outfl.write(outstr)
-    return outstr
+    return outstr
+ -
[docs]def read(fname): """ Read a TurbSim input (.inp) file. @@ -122,92 +126,92 @@

Source code for pyts.io.input

                 A PyTurbSim input dictionary.
 
     """
-    # TurbSim input files are static:
-    #   Variable are determined by line number.
-    #   Only the first string on the line matters.
-    #   All else is commenting.
-    #   Therefore we simply assign variables by line number.
+    # TurbSim input files are static:
+    #   Variable are determined by line number.
+    #   Only the first string on the line matters.
+    #   All else is commenting.
+    #   Therefore we simply assign variables by line number.
     ril = _readInputLine
     out = tsinput()
     out.filename = fname
-    out['UserProfile'] = False
+    out['UserProfile'] = False
     with open(fname) as fl:
         dat = fl.readlines()
     fl.close()
-    out['header'] = dat[0]
-    # Header line at top of file.
-    # (Sometimes used to indicate the files specific use)
-    # Deal the data from the file:
+    out['header'] = dat[0]
+    # Header line at top of file.
+    # (Sometimes used to indicate the files specific use)
+    # Deal the data from the file:
     for idx, ln in enumerate(dat):
         if idx in inputfile_form:
             out[inputfile_form[idx]] = ril(dat[idx])
-    # Customize the input fields for pyTurbSim...
-    if out['RandSeed2'].__class__ is str and \
-       out['RandSeed2'].upper() == 'RANLUX':
-        out['RandSeed2'] = None
-    for nm in ['IncDec1', 'IncDec2', 'IncDec3']:
-        if out[nm] is not None:
-            if out[nm].__class__ is str:
+    # Customize the input fields for pyTurbSim...
+    if out['RandSeed2'].__class__ is str and \
+       out['RandSeed2'].upper() == 'RANLUX':
+        out['RandSeed2'] = None
+    for nm in ['IncDec1', 'IncDec2', 'IncDec3']:
+        if out[nm] is not None:
+            if out[nm].__class__ is str:
                 try:
                     out[nm] = np.array(out[nm].split(), dtype=ts_float)
                 except ValueError:
-                    # This allows strings that don't convert to pass through.
+                    # This allows strings that don't convert to pass through.
                     pass
             else:
                 out[nm] = np.array([out[nm], 0])
-    if len(dat) >= 70 and dat[64].split()[1] == 'NumUSRz':
-        # This file has a user-defined profile.
-        out['UserProf_H'] = np.empty(out['NumUSRz'], dtype='float32')
-        out['UserProf_U'] = np.empty_like(out['UserProf_H'])
-        out['UserProf_Ang'] = np.empty_like(out['UserProf_H'])
-        out['UserProf_Std'] = np.empty_like(out['UserProf_H'])
-        out['UserProf_L'] = np.empty_like(out['UserProf_H'])
-        for i in range(out['NumUSRz']):
+    if len(dat) >= 70 and dat[64].split()[1] == 'NumUSRz':
+        # This file has a user-defined profile.
+        out['UserProf_H'] = np.empty(out['NumUSRz'], dtype='float32')
+        out['UserProf_U'] = np.empty_like(out['UserProf_H'])
+        out['UserProf_Ang'] = np.empty_like(out['UserProf_H'])
+        out['UserProf_Std'] = np.empty_like(out['UserProf_H'])
+        out['UserProf_L'] = np.empty_like(out['UserProf_H'])
+        for i in range(out['NumUSRz']):
             tmp = dat[72 + i].split()
-            out['UserProf_H'][i] = ts_float(tmp[0])
-            out['UserProf_U'][i] = ts_float(tmp[1])
-            out['UserProf_Ang'][i] = ts_float(tmp[2])
-            out['UserProf_Std'][i] = ts_float(tmp[3])
-            out['UserProf_L'][i] = ts_float(tmp[4])
-        out['UserProfile'] = True
-        fls = listdir(fname.rpartition('/')[0])
-        for fl in [fname.rpartition('/')[2].rpartition('.')[0] + '_Spec.inp',
-                   'UsrSpec.inp', ]:
+            out['UserProf_H'][i] = ts_float(tmp[0])
+            out['UserProf_U'][i] = ts_float(tmp[1])
+            out['UserProf_Ang'][i] = ts_float(tmp[2])
+            out['UserProf_Std'][i] = ts_float(tmp[3])
+            out['UserProf_L'][i] = ts_float(tmp[4])
+        out['UserProfile'] = True
+        fls = listdir(fname.rpartition('/')[0])
+        for fl in [fname.rpartition('/')[2].rpartition('.')[0] + '_Spec.inp',
+                   'UsrSpec.inp', ]:
             if fl in fls:
                 break
-        out['psd'] = readInPSD(fname.rpartition('/')[0] + '/' + fl)
+        out['psd'] = readInPSD(fname.rpartition('/')[0] + '/' + fl)
     for ky, val in out.iteritems():
-        if val == 'default':
-            out[ky] = None
+        if isinstance(val, string_type) and val == 'default':
+            out[ky] = None
     out.__original__ = deepcopy(out)
-    return out
+    return out
+ -
def _readInputLine(line): """ This function parses data from input file lines and returns it as the correct 'type' (e.g. int, float, bool, str). """ types = [np.int32, np.float32, bool, str] - if line[0] == '"': - val = line.split('"')[1] - elif line[0] == "'": - val = line.split("'")[1] + if line[0] == '"': + val = line.split('"')[1] + elif line[0] == "'": + val = line.split("'")[1] else: val = line.split()[0] idx = 0 - if val == 'default': - return None - while True: + if val == 'default': + return None + while True: try: if types[idx] is bool: - tmp = val.lower().replace('"', '').replace("'", "") - if not (tmp == 'false' or tmp == 'true'): + tmp = val.lower().replace('"', '').replace("'", "") + if not (tmp == 'false' or tmp == 'true'): raise ValueError else: - return tmp == 'true' + return tmp == 'true' out = types[idx](val) - if types[idx] is str and out.startswith('"') and out.endswith('"'): + if types[idx] is str and out.startswith('"') and out.endswith('"'): out = out[1:-1] return out except ValueError: @@ -229,7 +233,7 @@

Source code for pyts.io.input

     """
     ril = _readInputLine
     out = {}
-    if fname.__class__ is file:
+    if fname.__class__ is file:
         dat = fname.readlines()
     else:
         with open(fname) as fl:
@@ -238,30 +242,30 @@ 

Source code for pyts.io.input

     SpecScale1 = ril(dat[4])
     SpecScale2 = ril(dat[5])
     SpecScale3 = ril(dat[6])
-    out['freq'] = np.empty(NumUSRf, **ts_float)
-    out['Suu'] = np.empty(NumUSRf, **ts_float)
-    out['Svv'] = np.empty(NumUSRf, **ts_float)
-    out['Sww'] = np.empty(NumUSRf, **ts_float)
+    out['freq'] = np.empty(NumUSRf, **ts_float)
+    out['Suu'] = np.empty(NumUSRf, **ts_float)
+    out['Svv'] = np.empty(NumUSRf, **ts_float)
+    out['Sww'] = np.empty(NumUSRf, **ts_float)
     for ind in range(out.NumUSRf):
         tmp = dat[ind + 11].split()
-        out['freq'][ind] = tmp[0]
-        out['Suu'][ind] = tmp[1]
-        out['Svv'][ind] = tmp[2]
-        out['Sww'][ind] = tmp[3]
-    out['Suu'] *= SpecScale1
-    out['Svv'] *= SpecScale2
-    out['Sww'] *= SpecScale3
-    return out
+        out['freq'][ind] = tmp[0]
+        out['Suu'][ind] = tmp[1]
+        out['Svv'][ind] = tmp[2]
+        out['Sww'][ind] = tmp[3]
+    out['Suu'] *= SpecScale1
+    out['Svv'] *= SpecScale2
+    out['Sww'] *= SpecScale3
+    return out
-
-if __name__ == '__main__': + +if __name__ == '__main__': def dict_diff(d1, d2): out = dict() for ky in d1: if ky in d2.keys(): if not d2[ky] == d1[ky]: - out[ky] = str(d1[ky]) + ' - ' + str(d2[ky]) + out[ky] = str(d1[ky]) + ' - ' + str(d2[ky]) else: out[ky] = d1[ky] for ky in d2: @@ -274,8 +278,8 @@

Source code for pyts.io.input

         URef=19.3,
         RandSeed1=34728904,
         RandSeed2=34728904,
-        WrBHHTP=True,
-        WrADHH=True,
+        WrBHHTP=True,
+        WrADHH=True,
         NumGrid_Z=10,
         NumGrid_Y=10,
         TimeStep=0.01,
@@ -284,17 +288,17 @@ 

Source code for pyts.io.input

         HubHt=80,
         GridHeight=90,
         GridWidth=90,
-        TurbModel='SMOOTH',
+        TurbModel='SMOOTH',
         RefHt=90,
         IncDec1=(10.444, 0.1),
         IncDec2=10
         )
 
-    fl = write('tmp/testfile.inp', dout)
+    fl = write('tmp/testfile.inp', dout)
 
-    ## print dict_diff(inputfile_form, ifile_form_old)
+    ## print dict_diff(inputfile_form, ifile_form_old)
 
-    dnew = read('tmp/testfile.inp')
+    dnew = read('tmp/testfile.inp')
 
@@ -313,14 +317,11 @@

Related Topics

@@ -328,11 +329,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/main.html b/docs/_modules/pyts/io/main.html index 6ff113c..1dca601 100644 --- a/docs/_modules/pyts/io/main.html +++ b/docs/_modules/pyts/io/main.html @@ -1,38 +1,39 @@ + - - - pyts.io.main — PyTurbSim 0.4.7 documentation - + pyts.io.main — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.io.main

-"""
+"""
 This is the main (top-level) io module. It defines the 'readModel'
 function, which is useful for collecting information from available
 TurbSim input/output files.
@@ -48,9 +49,9 @@ 

Source code for pyts.io.main

 
 import read
 
-readers = {'wnd': read.bladed,
-           'bl': read.bladed,
-           'bts': read.turbsim, }
+readers = {'wnd': read.bladed,
+           'bl': read.bladed,
+           'bts': read.turbsim, }
 
 
 
[docs]def readModel(fname, ): @@ -61,10 +62,12 @@

Source code for pyts.io.main

     Parameters
     ----------
     fname : str
-            The filename to load.
-            If the file ends in:
-              .bl or .wnd,  the file is assumed to be a bladed-format file.
-              .bts, the file is assumed to be a TurbSim-format file.
+            The filename to load. If the file ends in:
+
+            - .bl or .wnd,  the file is assumed to be a bladed-format file.
+
+            - .bts, the file is assumed to be a TurbSim-format file.
+
     Returns
     -------
     tsdata : :class:`tsdata <pyts.main.tsdata>`
@@ -75,8 +78,8 @@ 

Source code for pyts.io.main

         if fname.endswith(sfx):
             return rdr(fname)
 
-    # Otherwise try reading it as a .wnd file.
-    read.bladed(fname)  # This will raise an error if it doesn't work.
+ # Otherwise try reading it as a .wnd file. + read.bladed(fname) # This will raise an error if it doesn't work.
@@ -95,14 +98,11 @@

Related Topics

@@ -110,11 +110,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/read.html b/docs/_modules/pyts/io/read.html index 402070b..0d33d10 100644 --- a/docs/_modules/pyts/io/read.html +++ b/docs/_modules/pyts/io/read.html @@ -1,38 +1,39 @@ + - - - pyts.io.read — PyTurbSim 0.4.7 documentation - + pyts.io.read — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,12 +41,12 @@

Source code for pyts.io.read

-from struct import unpack
-from .base import e, checkname, convname
-import numpy as np
-from ..main import tsdata
-from ..base import tsGrid
-from warnings import warn
+from struct import unpack
+from .base import e, checkname, convname
+import numpy as np
+from ..main import tsdata
+from ..base import tsGrid
+from warnings import warn
 
 
 
[docs]def bladed(fname,): @@ -63,49 +64,49 @@

Source code for pyts.io.read

              The TurbSim data contained in the binary data file.
 
     """
-    fname = checkname(fname, ['.wnd', '.bl'])
-    with file(fname, 'rb') as fl:
-        junk, nffc, ncomp, lat, z0, center = unpack(e + '2hl3f', fl.read(20))
+    fname = checkname(fname, ['.wnd', '.bl'])
+    with file(fname, 'rb') as fl:
+        junk, nffc, ncomp, lat, z0, center = unpack(e + '2hl3f', fl.read(20))
         if junk != -99 or nffc != 4:
-            raise IOError("The file %s does not appear to be a valid 'bladed (.bts)' format file."
+            raise IOError("The file %s does not appear to be a valid 'bladed (.bts)' format file."
                           % fname)
-        ti = np.array(unpack(e + '3f', fl.read(12))) / 100
-        dz, dy, dx, n_f, uhub = unpack(e + '3flf', fl.read(20))
+        ti = np.array(unpack(e + '3f', fl.read(12))) / 100
+        dz, dy, dx, n_f, uhub = unpack(e + '3flf', fl.read(20))
         n_t = int(2 * n_f)
-        fl.seek(12, 1)  # Unused bytes
-        clockwise, randseed, n_z, n_y = unpack(e + '4l', fl.read(16))
-        fl.seek(24, 1)  # Unused bytes
+        fl.seek(12, 1)  # Unused bytes
+        clockwise, randseed, n_z, n_y = unpack(e + '4l', fl.read(16))
+        fl.seek(24, 1)  # Unused bytes
         nbt = ncomp * n_y * n_z * n_t
         dat = np.rollaxis(np.fromstring(fl.read(2 * nbt), dtype=np.int16)
                           .astype(np.float32).reshape([ncomp,
                                                        n_y,
                                                        n_z,
-                                                       n_t], order='F'),
+                                                       n_t], order='F'),
                           2, 1)
     dat[0] += 1000.0 / ti[0]
-    dat /= 1000. / (uhub * ti[:, None, None, None])
-    # Create the grid object:
+    dat /= 1000. / (uhub * ti[:, None, None, None])
+    # Create the grid object:
     dt = dx / uhub
-    # Determine the clockwise value.
+    # Determine the clockwise value.
     if clockwise == 0:
         try:
-            d = sum_scan(convname(fname, '.sum'))
-            clockwise = d['clockwise']
+            d = sum_scan(convname(fname, '.sum'))
+            clockwise = d['clockwise']
         except IOError:
-            warn("Value of 'CLOCKWISE' not specified in binary file, "
-                 "and no .sum file found. Assuming CLOCKWISE = True.")
-            clockwise = True
+            warn("Value of 'CLOCKWISE' not specified in binary file, "
+                 "and no .sum file found. Assuming CLOCKWISE = True.")
+            clockwise = True
         except KeyError:
-            warn("Value of 'CLOCKWISE' not specified in binary file, "
-                 "and %s has no line containing 'clockwise'. Assuming "
-                 "CLOCKWISE = True." % convname(fname, '.sum'))
-            clockwise = True
+            warn("Value of 'CLOCKWISE' not specified in binary file, "
+                 "and %s has no line containing 'clockwise'. Assuming "
+                 "CLOCKWISE = True." % convname(fname, '.sum'))
+            clockwise = True
     else:
         clockwise = bool(clockwise - 1)
     if clockwise:
-        # flip the data back
+        # flip the data back
         dat = dat[:, :, ::-1, :]
-    # Create the tsdata object.
+    # Create the tsdata object.
     grid = tsGrid(center=center,
                   ny=n_y, nz=n_z,
                   dy=dy, dz=dz,
@@ -113,10 +114,10 @@ 

Source code for pyts.io.read

                   clockwise=clockwise)
     out = tsdata(grid)
     out.uprof = dat.mean(-1)
-    out.uturb = dat - out.uprof[:, :, :, None]
-    return out
+    out.uturb = dat - out.uprof[:, :, :, None]
+    return out
+ -
[docs]def turbsim(fname): """ Read TurbSim format (.bts) full-field time-series binary @@ -133,10 +134,10 @@

Source code for pyts.io.read

              The TurbSim data contained in the binary data file.
 
     """
-    fname = checkname(fname, ['.bts'])
+    fname = checkname(fname, ['.bts'])
     u_scl = np.zeros(3, np.float32)
     u_off = np.zeros(3, np.float32)
-    fl = file(fname, 'rb')
+    fl = file(fname, 'rb')
     (junk,
      n_z,
      n_y,
@@ -154,26 +155,26 @@ 

Source code for pyts.io.read

      u_off[1],
      u_scl[2],
      u_off[2],
-     strlen) = unpack(e + 'h4l12fl', fl.read(70))
+     strlen) = unpack(e + 'h4l12fl', fl.read(70))
     center = z0 + (n_z - 1) * dz / 2.0
-    #print fname, u_scl, u_off
-    desc_str = fl.read(strlen)  # skip these bytes.
+    #print fname, u_scl, u_off
+    desc_str = fl.read(strlen)  # skip these bytes.
     nbt = 3 * n_y * n_z * n_t
     dat = np.rollaxis(np.fromstring(fl.read(2 * nbt), dtype=np.int16).astype(
-        np.float32).reshape([3, n_y, n_z, n_t], order='F'), 2, 1)
-    dat -= u_off[:, None, None, None]
-    dat /= u_scl[:, None, None, None]
-    # Create the tsdata object.
+        np.float32).reshape([3, n_y, n_z, n_t], order='F'), 2, 1)
+    dat -= u_off[:, None, None, None]
+    dat /= u_scl[:, None, None, None]
+    # Create the tsdata object.
     grid = tsGrid(center=center,
                   ny=n_y, nz=n_z,
                   dy=dy, dz=dz,
                   dt=dt, nt=n_t, )
     out = tsdata(grid)
     out.uprof = dat.mean(-1)
-    out.uturb = dat - out.uprof[:, :, :, None]
-    return out
+    out.uturb = dat - out.uprof[:, :, :, None]
+    return out
+ -
[docs]def sum_scan(filename,): """ Scan a sum file for specific variables. @@ -188,17 +189,17 @@

Source code for pyts.io.read

     out : dict
         A dictionary of values identified.
     """
-    # Currently this routine only searches for 'clockwise'.
+    # Currently this routine only searches for 'clockwise'.
     out = dict()
-    with open(checkname(filename, ['.sum', '.SUM']), 'r') as infl:
+    with open(checkname(filename, ['.sum', '.SUM']), 'r') as infl:
         for ln in infl:
             ln = ln.lower()
-            if 'clockwise' in ln.lower():
+            if 'clockwise' in ln.lower():
                 v = ln.split()[0]
-                if v in ['t', 'y']:
-                    out['clockwise'] = True
+                if v in ['t', 'y']:
+                    out['clockwise'] = True
                 else:
-                    out['clockwise'] = False
+                    out['clockwise'] = False
     return out
@@ -218,14 +219,11 @@

Related Topics

@@ -233,11 +231,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/sum.html b/docs/_modules/pyts/io/sum.html index 27b2475..b0cd712 100644 --- a/docs/_modules/pyts/io/sum.html +++ b/docs/_modules/pyts/io/sum.html @@ -1,38 +1,39 @@ + - - - pyts.io.sum — PyTurbSim 0.4.7 documentation - + pyts.io.sum — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,65 +41,65 @@

Source code for pyts.io.sum

-import numpy as np
-from pyts.io.formatter import SuperFormatter
+import numpy as np
+from pyts.io.formatter import SuperFormatter
 import pkg_resources
-import pyts._version as ver
-from .base import convname
+import pyts._version as ver
+from .base import convname
 
 
 
[docs]class SumFormatter(SuperFormatter): - default_format_prfx = '>10' + default_format_prfx = '>10' def _format_f(self, value): - return format(value, '10.3f') + return format(value, '10.3f') def _format_b(self, value): - return format('FT'[value], '>10s') + return format('FT'[value], '>10s') def _format_ScaleIECtxt(self, value): - return format({0: 'None', - 1: 'HUB', - 2: 'ALL'}[value], '>5s') + return format({0: 'None', + 1: 'HUB', + 2: 'ALL'}[value], '>5s') def _format_TurbModelstr(self, value): - return format(value, '>10s') + return format(value, '>10s') def _format_WindProfilestr(self, value): - return format(value, '>10s') + return format(value, '>10s') def _format_stringlist(self, value): - out = '' + out = '' for v in value: - out += v + '\n' + out += v + '\n' return out def _format_grid(self, value, form): - out = '' + out = '' if isinstance(value, (np.ndarray)) and value.ndim > 1: for v in value: - out += self._format_grid(v, form) + '\n' + out += self._format_grid(v, form) + '\n' return out n = len(value) - form = form.split(',') - # Extrapolate the last value to the last n points: + form = form.split(',') + # Extrapolate the last value to the last n points: form = form + [form[-1]] * (n - len(form)) for v, f in zip(value, form): - out += format(v, f) + out += format(v, f) return out def _format_tup(self, value): - return '( %8.3f, %8.3f )' % tuple(value) + return '( %8.3f, %8.3f )' % tuple(value)
-# This is the input-file template object:
+# This is the input-file template object: template = SumFormatter( pkg_resources.resource_string(ver.pkg_name, - 'io/templates/sum')) + 'io/templates/sum'))
[docs]def write(filename, in_dict): @@ -106,20 +107,20 @@

Source code for pyts.io.sum

     Write a sum file.
     """
 
-    with open(convname(filename, '.sum'), 'w') as outfl:
-        outfl.write(template(**in_dict))
+    with open(convname(filename, '.sum'), 'w') as outfl:
+        outfl.write(template(**in_dict))
-
-if __name__ == '__main__': - from .input import read as readInput - from ..runInput import run +if __name__ == '__main__': + + from .input import read as readInput + from ..runInput import run - inp = readInput('tmp/TurbSim.inp') + inp = readInput('tmp/TurbSim.inp') tsdat = run(inp) - write('tmp/TurbSim.sum', tsdat._sumdict) + write('tmp/TurbSim.sum', tsdat._sumdict) - tsdat.writeSum('tmp/TurbSim_alt.sum') + tsdat.writeSum('tmp/TurbSim_alt.sum')
@@ -138,14 +139,11 @@

Related Topics

@@ -153,11 +151,11 @@

Quick search

diff --git a/docs/_modules/pyts/io/write.html b/docs/_modules/pyts/io/write.html index 9dd59a4..386dd34 100644 --- a/docs/_modules/pyts/io/write.html +++ b/docs/_modules/pyts/io/write.html @@ -1,38 +1,39 @@ + - - - pyts.io.write — PyTurbSim 0.4.7 documentation - + pyts.io.write — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,23 +41,23 @@

Source code for pyts.io.write

-"""
+"""
 This module is for writing PyTurbSim data objects to various formats.
 
 The functions in this module were translated directly from the
 original TSsubs.f90 file.
 """
-from .base import convname
-import numpy as np
-from struct import pack
-from .base import e
-from .. import _version as ver
+from .base import convname
+import numpy as np
+from struct import pack
+from .base import e
+from .. import _version as ver
 import time
-from .sum import write as sum  # Make sum.write available here.
+from .sum import write as sum  # Make sum.write available here.
 try:
     import h5py
 except ImportError:
-    h5py = None
+    h5py = None
 
 
 
[docs]def bladed(fname, tsdat): @@ -75,55 +76,55 @@

Source code for pyts.io.write

     Bladed is a Trademark of GL Garrad-Hassan.
     """
     prms = tsdat.parameters
-    lat = prms.get('Latitude', 0.0)
-    Z0 = prms.get('Z0', 0.0)
+    lat = prms.get('Latitude', 0.0)
+    Z0 = prms.get('Z0', 0.0)
     ts = tsdat.utotal
     ti = np.sqrt(tsdat.tke[:, tsdat.ihub[0], tsdat.ihub[1]]) / tsdat.UHUB
     ti[ti < 1e-5] = 1
-    scale = 1000. / (tsdat.UHUB * ti[:, None, None, None])
-    off = np.array([1000. / (ti[0]), 0, 0])[:, None, None, None]
-    fl = file(convname(fname, '.wnd'), 'wb')
-    # First write some setup data:
-    fl.write(pack(e + '2hl3f',
+    scale = 1000. / (tsdat.UHUB * ti[:, None, None, None])
+    off = np.array([1000. / (ti[0]), 0, 0])[:, None, None, None]
+    fl = file(convname(fname, '.wnd'), 'wb')
+    # First write some setup data:
+    fl.write(pack(e + '2hl3f',
                   -99,
                   4,
                   3,
                   lat,
                   Z0,
                   tsdat.grid.z[0] + tsdat.grid.height / 2.0))
-    # Now write the turbulence intensity, grid spacing, numsteps, and hub mean wind speed
-    # For some reason this takes half the number of timesteps...
-    fl.write(pack(e + '3f', * (100 * ti)))
-    fl.write(pack(e + '3flf',
+    # Now write the turbulence intensity, grid spacing, numsteps, and hub mean wind speed
+    # For some reason this takes half the number of timesteps...
+    fl.write(pack(e + '3f', * (100 * ti)))
+    fl.write(pack(e + '3flf',
                   tsdat.grid.dz,
                   tsdat.grid.dy,
                   tsdat.UHUB * tsdat.dt,
                   tsdat.shape[-1] / 2,
                   tsdat.UHUB))
-    fl.write(pack(e + '3f', *([0] * 3)))  # Unused bytes
-    # Previously this was unused. Now I am using it to store the clockwise flag.
-    # 0 is reserved for TurbSim (no specification), 1 is False, 2 is True.
-    fl.write(pack(e + 'l', (tsdat.grid.clockwise + 1)))
-    fl.write(pack(e + '3l',
-                  tsdat.info['RandSeed'],
+    fl.write(pack(e + '3f', *([0] * 3)))  # Unused bytes
+    # Previously this was unused. Now I am using it to store the clockwise flag.
+    # 0 is reserved for TurbSim (no specification), 1 is False, 2 is True.
+    fl.write(pack(e + 'l', (tsdat.grid.clockwise + 1)))
+    fl.write(pack(e + '3l',
+                  tsdat.info['RandSeed'],
                   tsdat.grid.n_z,
                   tsdat.grid.n_y))
-    fl.write(pack(e + '6l', *([0] * 6)))  # Unused bytes
+    fl.write(pack(e + '6l', *([0] * 6)))  # Unused bytes
     if tsdat.grid.clockwise:
         out = (ts[:, :, ::-1, :] * scale - off).astype(np.int16)
     else:
         out = (ts[:, :, :, :] * scale - off).astype(np.int16)
-    # Swap the y and z indices so that fortran-order writing agrees with the
-    # file format.
+    # Swap the y and z indices so that fortran-order writing agrees with the
+    # file format.
     out = np.rollaxis(out, 2, 1)
-    # Write the data so that the first index varies fastest (F order).
-    # With the swap of y and z indices above, the indexes vary in the following
-    # (decreasing) order:
-    # component (fastest), y-index, z-index, time (slowest).
-    fl.write(out.tostring(order='F'))
-    fl.close()
+    # Write the data so that the first index varies fastest (F order).
+    # With the swap of y and z indices above, the indexes vary in the following
+    # (decreasing) order:
+    # component (fastest), y-index, z-index, time (slowest).
+    fl.write(out.tostring(order='F'))
+    fl.close()
+ -
[docs]def formatted(fname, tsdat): """Write the data to a set of TurbSim 'formatted' (readable) files (.u, .v, .w). @@ -137,52 +138,52 @@

Source code for pyts.io.write

 
     """
 
-    header = ("\nThis full-field turbulence file was generated by {ver.__prog_name__} "
-              "(v{ver.__version__}, {ver.__version_date__}) on {date} at {time}.".format(
+    header = ("\nThis full-field turbulence file was generated by {ver.__prog_name__} "
+              "(v{ver.__version__}, {ver.__version_date__}) on {date} at {time}.".format(
                   ver=ver,
-                  date=time.strftime('%d-%b-%Y', time.localtime()),
-                  time=time.strftime('%H:%M:%S (%Z)', time.localtime())))
-    header += ("\n\n"
-               " | %s-comp |  Y  x  Z  | Grid Resolution (Y x Z) | "
-               "Time-step | Hub Elev | Mean U |\n"
-               "          {n_y: 4d}  {n_z: 4d}  {dy: 9.3f}  {dz: 9.3f}   "
-               "   {dt:9.3f}  {zhub:9.2f} {uhub:9.2f}\n"
-               "\n"
-               " Z Coordinates (m):\n"
-               " {zcoords}\n"
-               "\n"
-               " Y Coordinates (m):\n"
-               " {ycoords}\n".format(n_y=tsdat.grid.n_y,
+                  date=time.strftime('%d-%b-%Y', time.localtime()),
+                  time=time.strftime('%H:%M:%S (%Z)', time.localtime())))
+    header += ("\n\n"
+               " | %s-comp |  Y  x  Z  | Grid Resolution (Y x Z) | "
+               "Time-step | Hub Elev | Mean U |\n"
+               "          {n_y: 4d}  {n_z: 4d}  {dy: 9.3f}  {dz: 9.3f}   "
+               "   {dt:9.3f}  {zhub:9.2f} {uhub:9.2f}\n"
+               "\n"
+               " Z Coordinates (m):\n"
+               " {zcoords}\n"
+               "\n"
+               " Y Coordinates (m):\n"
+               " {ycoords}\n".format(n_y=tsdat.grid.n_y,
                                      n_z=tsdat.grid.n_z,
                                      dy=tsdat.grid.dy,
                                      dz=tsdat.grid.dz,
                                      dt=tsdat.dt,
                                      zhub=tsdat.grid.zhub,
                                      uhub=tsdat.UHUB,
-                                     zcoords=(' {: 7.3f}' * tsdat.grid.n_z).format(*tsdat.z),
-                                     ycoords=(' {: 7.3f}' * tsdat.grid.n_y).format(*tsdat.y), ))
-    outform = ("\n"
-               "  {: 7.3f} {: 7.3f}\n")
-    outform += (' ' + (' {: 7.3f}' * tsdat.grid.n_y) + '\n') * tsdat.grid.n_z
+                                     zcoords=(' {: 7.3f}' * tsdat.grid.n_z).format(*tsdat.z),
+                                     ycoords=(' {: 7.3f}' * tsdat.grid.n_y).format(*tsdat.y), ))
+    outform = ("\n"
+               "  {: 7.3f} {: 7.3f}\n")
+    outform += (' ' + (' {: 7.3f}' * tsdat.grid.n_y) + '\n') * tsdat.grid.n_z
 
-    fname = fname.rstrip('.inp')
+    fname = fname.rstrip('.inp')
 
-    print("Writing formatted files...")
+    print("Writing formatted files...")
     for idc in range(tsdat.n_comp):
         comp = tsdat.comp_name[idc]
-        print("{}-component, timestep:".format(comp))
-        fl = open(fname + '.' + comp, 'w')
+        print("{}-component, timestep:".format(comp))
+        fl = open(fname + '.' + comp, 'w')
         fl.write(header % (comp))
         nt = tsdat.time.shape[0]
         for idt in range(nt):
             if idt % 1000 == 0:
-                print('{}/{}'.format(idt, nt))
+                print('{}/{}'.format(idt, nt))
             fl.write(outform.format(tsdat.time[idt],
                                     tsdat.uhub[idt],
                                     *tsdat.uturb[idc, :, :, idt].flatten()))
-        fl.close()
+        fl.close()
+ -
[docs]def turbsim(fname, tsdat): """Write the data to a TurbSim-format binary file (.bts). @@ -200,11 +201,11 @@

Source code for pyts.io.write

     u_minmax = np.empty((3, 2), dtype=np.float32)
     u_off = np.empty((3), dtype=np.float32)
     u_scl = np.empty((3), dtype=np.float32)
-    desc_str = 'generated by %s v%s, %s.' % (
+    desc_str = 'generated by %s v%s, %s.' % (
         ver.__prog_name__,
         ver.__version__,
-        time.strftime('%b %d, %Y, %H:%M (%Z)', time.localtime()))
-    # Calculate the ranges:
+        time.strftime('%b %d, %Y, %H:%M (%Z)', time.localtime()))
+    # Calculate the ranges:
     out = np.empty(tsdat.shape, dtype=np.int16)
     for ind in range(3):
         u_minmax[ind] = ts[ind].min(), ts[ind].max()
@@ -214,8 +215,8 @@ 

Source code for pyts.io.write

             u_scl[ind] = intrng / np.diff(u_minmax[ind])
         u_off[ind] = intmin - u_scl[ind] * u_minmax[ind, 0]
         out[ind] = (ts[ind] * u_scl[ind] + u_off[ind]).astype(np.int16)
-    fl = file(convname(fname, '.bts'), 'wb')
-    fl.write(pack(e + 'h4l12fl',
+    fl = file(convname(fname, '.bts'), 'wb')
+    fl.write(pack(e + 'h4l12fl',
                   7,
                   tsdat.grid.n_z,
                   tsdat.grid.n_y,
@@ -235,18 +236,18 @@ 

Source code for pyts.io.write

                   u_off[2],
                   len(desc_str)))
     fl.write(desc_str)
-    # Swap the y and z indices so that fortran-order writing agrees with the file format.
-    # Also, we swap the order of z-axis to agree with the file format.
-    # Write the data so that the first index varies fastest (F order).
-    # The indexes vary in the following order:
-    # component (fastest), y-index, z-index, time (slowest).
-    fl.write(np.rollaxis(out, 2, 1).tostring(order='F'))
-    fl.close()
+    # Swap the y and z indices so that fortran-order writing agrees with the file format.
+    # Also, we swap the order of z-axis to agree with the file format.
+    # Write the data so that the first index varies fastest (F order).
+    # The indexes vary in the following order:
+    # component (fastest), y-index, z-index, time (slowest).
+    fl.write(np.rollaxis(out, 2, 1).tostring(order='F'))
+    fl.close()
-
-if h5py is not None: -
[docs] def hdf5(fname, tsdat): +if h5py is not None: + + def hdf5(fname, tsdat): """Write the data to an hdf5 format file. Parameters @@ -259,26 +260,26 @@

Source code for pyts.io.write

                  The 'tsdata' object that contains the data.
 
         """
-        fname = fname.rstrip('.inp')
-        if '.' not in (fname.split('/')[-1]).split('\\')[-1]:
-            fname += '.h5'
-        with h5py.File(fname, mode='w') as fl:
-            # The turbulence velocity:
-            ds_uturb = fl.create_dataset('uturb', data=tsdat.uturb)
-            ds_uturb.attrs.create('units', 'm/s')
-            ds_uturb.attrs.create('dims', ['u,v,w', 'z', 'y', 'time'])
-            # The mean velocity profile:
-            ds_uprof = fl.create_dataset('uprof', data=tsdat.uprof)
-            ds_uprof.attrs.create('units', 'm/s')
-            ds_uprof.attrs.create('dims', ['u,v,w', 'z', 'y'])
-            # The spatial grid:
-            ds_z = fl.create_dataset('z', data=tsdat.z)
-            ds_z.attrs.create('units', 'm')
-            ds_y = fl.create_dataset('y', data=tsdat.y)
-            ds_y.attrs.create('units', 'm')
-            # The time vector:
-            ds_time = fl.create_dataset('time', data=tsdat.time)
-            ds_time.attrs.create('units', 'sec')
+ fname = fname.rstrip('.inp') + if '.' not in (fname.split('/')[-1]).split('\\')[-1]: + fname += '.h5' + with h5py.File(fname, mode='w') as fl: + # The turbulence velocity: + ds_uturb = fl.create_dataset('uturb', data=tsdat.uturb) + ds_uturb.attrs.create('units', 'm/s') + ds_uturb.attrs.create('dims', ['u,v,w', 'z', 'y', 'time']) + # The mean velocity profile: + ds_uprof = fl.create_dataset('uprof', data=tsdat.uprof) + ds_uprof.attrs.create('units', 'm/s') + ds_uprof.attrs.create('dims', ['u,v,w', 'z', 'y']) + # The spatial grid: + ds_z = fl.create_dataset('z', data=tsdat.z) + ds_z.attrs.create('units', 'm') + ds_y = fl.create_dataset('y', data=tsdat.y) + ds_y.attrs.create('units', 'm') + # The time vector: + ds_time = fl.create_dataset('time', data=tsdat.time) + ds_time.attrs.create('units', 'sec')
@@ -297,14 +298,11 @@

Related Topics

@@ -312,11 +310,11 @@

Quick search

diff --git a/docs/_modules/pyts/main.html b/docs/_modules/pyts/main.html index af620d5..3fc00bf 100644 --- a/docs/_modules/pyts/main.html +++ b/docs/_modules/pyts/main.html @@ -1,38 +1,39 @@ + - - - pyts.main — PyTurbSim 0.4.7 documentation - + pyts.main — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.main

-"""
+"""
 This module brings together the main components of the TurbSim program
 and defines the primary high-level objects that users of the Python
 interface will utilize.
@@ -50,51 +51,51 @@ 

Source code for pyts.main

 PyTurbSim interface import the ./api.py package.
 
 """
-from .base import ts_complex, gridProps, dbg, np, statObj
-from .profModels.base import profModelBase, profObj
-from .specModels.base import specModelBase, specObj
-from .cohereModels.base import cohereModelBase, cohereObj, cohereUser
-from .stressModels.base import stressModelBase, stressObj
-from .phaseModels.api import randPhase
-import _version as ver
-from .io import write
-from numpy import random
-from numpy import ulonglong
-from numpy.fft import irfft
+from .base import ts_complex, gridProps, dbg, np, statObj
+from .profModels.base import profModelBase, profObj
+from .specModels.base import specModelBase, specObj
+from .cohereModels.base import cohereModelBase, cohereObj, cohereUser
+from .stressModels.base import stressModelBase, stressObj
+from .phaseModels.api import randPhase
+import _version as ver
+from .io import write
+from numpy import random
+from numpy import ulonglong
+from numpy.fft import irfft
 import time
 
-# !!!VERSION_INCONSISTENCY
-# inconsistency between this and older versions of TurbSim
-# !!!CHECKTHIS
-# means I need to ensure that something is right.
-# !!!FIXTHIS
-# means I know I am doing something wrong.
-# !!!ADDDOC
-# Means add documentation here
-
-# TODO:
-#  - Testing:
-#     . Test 'user-defined' models
-#  - Documentation
-#     . Document plotting tools.
-################
-## These require branches
-#  - Fix Reynold's stress!
-#  - Break Cholesky from coherence models/objects and into 'main', or tslib.
-#     . How do callbacks work fortran->python?
-#     . Can we implement this so that 'models/objects' are separated from tslib?
-#  - Add 'mods':
-#      . Add ability to rotate mean velocity field (for a prof instance and a profModel).
-#      . Add ability to add veer to mean velocity field (prof instance and profModel).
-#  - Write .sum summary files (io package), (so they are fully self-contained).
-#     . Add parameter logging, so that we can write summary files that
-#       track all parameters that were input.
-################
-## Low priority
-#  - Write FF files (tsio.py).
-#  - Write HubHeight files (tsio.py).
-#  - Add KHtest functionality? (rgrep for '#KHTEST')
-#  - Write 'events' (includes adding 'coherent events' to TS)
+# !!!VERSION_INCONSISTENCY
+# inconsistency between this and older versions of TurbSim
+# !!!CHECKTHIS
+# means I need to ensure that something is right.
+# !!!FIXTHIS
+# means I know I am doing something wrong.
+# !!!ADDDOC
+# Means add documentation here
+
+# TODO:
+#  - Testing:
+#     . Test 'user-defined' models
+#  - Documentation
+#     . Document plotting tools.
+################
+## These require branches
+#  - Fix Reynold's stress!
+#  - Break Cholesky from coherence models/objects and into 'main', or tslib.
+#     . How do callbacks work fortran->python?
+#     . Can we implement this so that 'models/objects' are separated from tslib?
+#  - Add 'mods':
+#      . Add ability to rotate mean velocity field (for a prof instance and a profModel).
+#      . Add ability to add veer to mean velocity field (prof instance and profModel).
+#  - Write .sum summary files (io package), (so they are fully self-contained).
+#     . Add parameter logging, so that we can write summary files that
+#       track all parameters that were input.
+################
+## Low priority
+#  - Write FF files (tsio.py).
+#  - Write HubHeight files (tsio.py).
+#  - Add KHtest functionality? (rgrep for '#KHTEST')
+#  - Write 'events' (includes adding 'coherent events' to TS)
 
 
 
[docs]class tsrun(object): @@ -114,27 +115,27 @@

Source code for pyts.main

             Number of cores (processors) to use for the pyTurbSim run
 
     """
-    def __init__(self, RandSeed=None, ncore=1):
+    def __init__(self, RandSeed=None, ncore=1):
         """
         PyTurbSim 'run' objects can be initialized with a specific
         random seed, `RandSeed`, and number of cores, `ncore`.
         """
-        # Initialize the random number generator before doing anything else.
-        if RandSeed is None:
+        # Initialize the random number generator before doing anything else.
+        if RandSeed is None:
             self.RandSeed = random.randint(-2147483647, 2147483647)
         else:
             self.RandSeed = RandSeed
-        # Seeds for numpy must be positive, but original-TurbSim had
-        # negative seeds.  In order to attempt to be consistent, we
-        # use the values in the files but make them positive for the
-        # numpy random generator.
+        # Seeds for numpy must be positive, but original-TurbSim had
+        # negative seeds.  In order to attempt to be consistent, we
+        # use the values in the files but make them positive for the
+        # numpy random generator.
         self.randgen = random.RandomState(
             ulonglong(self.RandSeed + 2147483648))
         self.ncore = ncore
         if dbg:
-            self.timer = dbg.timer('Veers84')
-    # For now this is a place-holder, I may want to make this an
-    # 'input property' eventually.
+            self.timer = dbg.timer('Veers84')
+    # For now this is a place-holder, I may want to make this an
+    # 'input property' eventually.
     phase = randPhase()
 
     @property
@@ -187,26 +188,26 @@ 

Source code for pyts.main

         tsrun.stress
 
         """
-        if hasattr(self, 'profModel') and not hasattr(self, '_prof'):
+        if hasattr(self, 'profModel') and not hasattr(self, '_prof'):
             self._prof = self.profModel(self)
         return self._prof
 
-    @prof.setter
+    @prof.setter
     def prof(self, val):
-        if profModelBase in val.__class__.__mro__:
+        if profModelBase in val.__class__.__mro__:
             self.profModel = val
-        elif np.ndarray in val.__class__.__mro__:
+        elif np.ndarray in val.__class__.__mro__:
             self._prof = profObj(self)
             self._prof.array[:] = val
-        elif profObj in val.__class__.__mro__:
+        elif profObj in val.__class__.__mro__:
             self._prof = val
         else:
-            raise Exception('The input must be a profile model, '
-                            'profile object or numpy array; it is none of these.')
+            raise Exception('The input must be a profile model, '
+                            'profile object or numpy array; it is none of these.')
 
-    @prof.deleter
+    @prof.deleter
     def prof(self,):
-        if hasattr(self, 'profModel'):
+        if hasattr(self, 'profModel'):
             del self._prof
 
     @property
@@ -259,26 +260,26 @@ 

Source code for pyts.main

         tsrun.stress
 
         """
-        if hasattr(self, 'specModel') and not hasattr(self, '_spec'):
+        if hasattr(self, 'specModel') and not hasattr(self, '_spec'):
             self._spec = self.specModel(self)
         return self._spec
 
-    @spec.setter
+    @spec.setter
     def spec(self, val):
-        if specModelBase in val.__class__.__mro__:
+        if specModelBase in val.__class__.__mro__:
             self.specModel = val
-        elif np.ndarray in val.__class__.__mro__:
+        elif np.ndarray in val.__class__.__mro__:
             self._spec = specObj(self)
             self._spec.array[:] = val
-        elif specObj in val.__class__.__mro__:
+        elif specObj in val.__class__.__mro__:
             self._spec = val
         else:
-            raise Exception('The input must be a spectral model, '
-                            'spectra object or numpy array; it is none of these.')
+            raise Exception('The input must be a spectral model, '
+                            'spectra object or numpy array; it is none of these.')
 
-    @spec.deleter
+    @spec.deleter
     def spec(self,):
-        if hasattr(self, 'specModel'):
+        if hasattr(self, 'specModel'):
             del self._spec
 
     @property
@@ -286,7 +287,7 @@ 

Source code for pyts.main

         """
         This is the 'coherence' input property.
 
-        This property always returns a :class:`.cohereObj`.
+        This property always returns a :class:`~.cohereModels.base.cohereObj`.
 
         Because the bulk of PyTurbSim's computational requirements
         (memory and processor time) are consumed by dealing with this
@@ -352,25 +353,25 @@ 

Source code for pyts.main

         tsrun.stress
 
         """
-        if hasattr(self, 'cohereModel') and not hasattr(self, '_cohere'):
+        if hasattr(self, 'cohereModel') and not hasattr(self, '_cohere'):
             self._cohere = self.cohereModel(self)
         return self._cohere
 
-    @cohere.setter
+    @cohere.setter
     def cohere(self, val):
-        if cohereModelBase in val.__class__.__mro__:
+        if cohereModelBase in val.__class__.__mro__:
             self.cohereModel = val
-        elif np.ndarray in val.__class__.__mro__:
+        elif np.ndarray in val.__class__.__mro__:
             self.cohereModel = cohereUser(val)
-        elif cohereObj in val.__class__.__mro__:
+        elif cohereObj in val.__class__.__mro__:
             self.cohere = val
         else:
-            raise Exception('The input must be a coherence model, '
-                            'coherence object or numpy array; it is none of these.')
+            raise Exception('The input must be a coherence model, '
+                            'coherence object or numpy array; it is none of these.')
 
-    @cohere.deleter
+    @cohere.deleter
     def cohere(self,):
-        if hasattr(self, 'cohereModel'):
+        if hasattr(self, 'cohereModel'):
             del self._cohere
 
     @property
@@ -423,29 +424,29 @@ 

Source code for pyts.main

         tsrun.cohere
 
         """
-        if hasattr(self, 'stressModel') and not hasattr(self, '_stress'):
+        if hasattr(self, 'stressModel') and not hasattr(self, '_stress'):
             self._stress = self.stressModel(self)
         return self._stress
 
-    @stress.setter
+    @stress.setter
     def stress(self, val):
-        if stressModelBase in val.__class__.__mro__:
+        if stressModelBase in val.__class__.__mro__:
             self.stressModel = val
-        elif np.ndarray in val.__class__.__mro__:
+        elif np.ndarray in val.__class__.__mro__:
             self._stress = stressObj(self)
             self._stress.array[:] = val
-        elif stressObj in val.__class__.__mro__:
+        elif stressObj in val.__class__.__mro__:
             self._stress = val
         else:
-            raise Exception('The input must be a stress model, '
-                            'stress object or numpy array; it is none of these.')
+            raise Exception('The input must be a stress model, '
+                            'stress object or numpy array; it is none of these.')
 
-    @stress.deleter
+    @stress.deleter
     def stress(self,):
-        if hasattr(self, 'stressModel'):
+        if hasattr(self, 'stressModel'):
             del self._stress
 
-
[docs] def reset(self, seed=None): +
[docs] def reset(self, seed=None): """ Clear the input statistics and reset the Random Number generator to its initial state. @@ -454,23 +455,23 @@

Source code for pyts.main

         del self.spec
         del self.cohere
         del self.stress
-        if seed is None:
+        if seed is None:
             self.randgen.seed(self.RandSeed)
         else:
-            self.randgen.seed(seed)
-
+ self.randgen.seed(seed)
+ @property def info(self,): """ Model names and initialization parameters. """ out = dict() - out['version'] = (ver.__prog_name__, ver.__version__, ver.__version_date__) - out['RandSeed'] = self.RandSeed - out['StartTime'] = self._starttime - if hasattr(self, '_config'): - out['config'] = self._config - for nm in ['profModel', 'specModel', 'cohereModel', 'stressModel']: + out['version'] = (ver.__prog_name__, ver.__version__, ver.__version_date__) + out['RandSeed'] = self.RandSeed + out['StartTime'] = self._starttime + if hasattr(self, '_config'): + out['config'] = self._config + for nm in ['profModel', 'specModel', 'cohereModel', 'stressModel']: if hasattr(self, nm): mdl = getattr(self, nm) out[nm] = dict(name=mdl.model_name, @@ -479,9 +480,9 @@

Source code for pyts.main

                                sumstring=mdl._sumfile_string(self),
                                )
             else:
-                out[nm] = None
-        out['RandSeed'] = self.RandSeed
-        out['RunTime'] = time.time() - time.mktime(self._starttime)
+                out[nm] = None
+        out['RandSeed'] = self.RandSeed
+        out['RunTime'] = time.time() - time.mktime(self._starttime)
         return out
 
 
[docs] def run(self,): @@ -504,9 +505,9 @@

Source code for pyts.main

         self._starttime = time.localtime()
         self.timeseries = self._calcTimeSeries()
         out = self._build_outdata()
-        return out
-
- __call__ = run + return out
+ + __call__ = run def _build_outdata(self,): """ @@ -556,26 +557,26 @@

Source code for pyts.main

                        dtype=ts_complex)
         if dbg:
             self.timer.start()
-        # First calculate the 'base' set of random phases:
+        # First calculate the 'base' set of random phases:
         phases = self.phase(self)
-        # Now correlate the phases at each point to set the Reynold's stress:
+        # Now correlate the phases at each point to set the Reynold's stress:
         phases = self.stress.calc_phases(phases)
-        # Now correlate the phases between points to set the spatial coherence:
+        # Now correlate the phases between points to set the spatial coherence:
         phases = self.cohere.calc_phases(phases)
-        # Now multiply the phases by the spectrum...
+        # Now multiply the phases by the spectrum...
         tmp[..., 1:] = np.sqrt(self.spec.array) * grid.reshape(phases)
-        # and compute the inverse fft to produce the timeseries:
+        # and compute the inverse fft to produce the timeseries:
         ts = irfft(tmp)
         if dbg:
             self.timer.stop()
-        # Select only the time period requested:
-        # Grab a random number of where to cut the timeseries.
+        # Select only the time period requested:
+        # Grab a random number of where to cut the timeseries.
         i0_out = self.randgen.randint(grid.n_t - grid.n_t_out + 1)
         ts = ts[..., i0_out:i0_out + grid.n_t_out] / (grid.dt / grid.n_f) ** 0.5
-        ts -= ts.mean(-1)[..., None]  # Make sure the turbulence has zero mean.
-        return ts
+        ts -= ts.mean(-1)[..., None]  # Make sure the turbulence has zero mean.
+        return ts
+ -
[docs]class tsdata(gridProps): """ TurbSim output data object. In addition to the output of a @@ -592,78 +593,78 @@

Source code for pyts.main

     def _sumdict(self):
         out = dict()
 
-        # Start by pulling values from the config file
-        # if there was one.
-        if 'config' in self.info:
-            out.update(self.info['config'])
-
-        uhub = out['uhub'] = statObj(self.uhub)
-        out['vhub'] = statObj(self.vhub, uhub.mean)
-        out['whub'] = statObj(self.whub, uhub.mean)
-        out['hhub'] = statObj(np.sqrt(self.uhub ** 2 + self.vhub ** 2))
-        out['grid'] = self.grid
-        out['upvp'] = statObj(self.uhub * self.vhub)
-        out['upwp'] = statObj(self.vhub * self.whub)
-        out['vpwp'] = statObj(self.vhub * self.whub)
-        out['upvp'].scale = 1
-        out['upwp'].scale = 1
-        out['vpwp'].scale = 1
-        out['tke'] = statObj((self.uturb ** 2).sum(0))
-        out['tke'] = statObj((self.uturb ** 2).sum(0))
-        out['ctke'] = statObj(0.5 * np.sqrt(
+        # Start by pulling values from the config file
+        # if there was one.
+        if 'config' in self.info:
+            out.update(self.info['config'])
+
+        uhub = out['uhub'] = statObj(self.uhub)
+        out['vhub'] = statObj(self.vhub, uhub.mean)
+        out['whub'] = statObj(self.whub, uhub.mean)
+        out['hhub'] = statObj(np.sqrt(self.uhub ** 2 + self.vhub ** 2))
+        out['grid'] = self.grid
+        out['upvp'] = statObj(self.uhub * self.vhub)
+        out['upwp'] = statObj(self.vhub * self.whub)
+        out['vpwp'] = statObj(self.vhub * self.whub)
+        out['upvp'].scale = 1
+        out['upwp'].scale = 1
+        out['vpwp'].scale = 1
+        out['tke'] = statObj((self.uturb ** 2).sum(0))
+        out['tke'] = statObj((self.uturb ** 2).sum(0))
+        out['ctke'] = statObj(0.5 * np.sqrt(
             (self.uturb[0] * self.uturb[1]) ** 2 +
             (self.uturb[0] * self.uturb[2]) ** 2 +
             (self.uturb[1] * self.uturb[2]) ** 2))
-        out['u_sigma'] = self.uturb[0].flatten().std()
-        out['v_sigma'] = self.uturb[1].flatten().std()
-        out['w_sigma'] = self.uturb[2].flatten().std()
-        out['TurbModel_desc'] = self.info['specModel']['description']
-        out['RandSeed1'] = self.info['RandSeed']
-
-        out['profModel_sumstring'] = self.info['profModel']['sumstring']
-        out['specModel_sumstring'] = self.info['specModel']['sumstring']
-        out['stressModel_sumstring'] = self.info['stressModel']['sumstring']
-        out['cohereModel_sumstring'] = self.info['cohereModel']['sumstring']
-        out['ver'] = ver
-        out['NowDate'] = time.strftime('%a %b %d, %Y', self.info['StartTime'])
-        out['NowTime'] = time.strftime('%H:%M:%S', self.info['StartTime'])
-        out['RunTime'] = self.info['RunTime']
-        out['FreqNyquist'] = self.f[-1]
-        out['GridBase'] = self.grid.z[0]
-        out['HeightOffset'] = 0.0  # Is this correct?
-        out['ydata'] = self.grid.y
-        out['z_ustd'] = np.concatenate((self.grid.z[:, None], self.uturb[0].std(-1)), axis=1)
-        out['z_vstd'] = np.concatenate((self.grid.z[:, None], self.uturb[1].std(-1)), axis=1)
-        out['z_wstd'] = np.concatenate((self.grid.z[:, None], self.uturb[2].std(-1)), axis=1)
-        u, v, w = self.uprof.mean(-1)[:, :, None]
-        out['WINDSPEEDPROFILE'] = np.concatenate((
-            self.grid.z[:, None],
+        out['u_sigma'] = self.uturb[0].flatten().std()
+        out['v_sigma'] = self.uturb[1].flatten().std()
+        out['w_sigma'] = self.uturb[2].flatten().std()
+        out['TurbModel_desc'] = self.info['specModel']['description']
+        out['RandSeed1'] = self.info['RandSeed']
+
+        out['profModel_sumstring'] = self.info['profModel']['sumstring']
+        out['specModel_sumstring'] = self.info['specModel']['sumstring']
+        out['stressModel_sumstring'] = self.info['stressModel']['sumstring']
+        out['cohereModel_sumstring'] = self.info['cohereModel']['sumstring']
+        out['ver'] = ver
+        out['NowDate'] = time.strftime('%a %b %d, %Y', self.info['StartTime'])
+        out['NowTime'] = time.strftime('%H:%M:%S', self.info['StartTime'])
+        out['RunTime'] = self.info['RunTime']
+        out['FreqNyquist'] = self.f[-1]
+        out['GridBase'] = self.grid.z[0]
+        out['HeightOffset'] = 0.0  # Is this correct?
+        out['ydata'] = self.grid.y
+        out['z_ustd'] = np.concatenate((self.grid.z[:, None], self.uturb[0].std(-1)), axis=1)
+        out['z_vstd'] = np.concatenate((self.grid.z[:, None], self.uturb[1].std(-1)), axis=1)
+        out['z_wstd'] = np.concatenate((self.grid.z[:, None], self.uturb[2].std(-1)), axis=1)
+        u, v, w = self.uprof.mean(-1)[:, :, None]
+        out['WINDSPEEDPROFILE'] = np.concatenate((
+            self.grid.z[:, None],
             np.sqrt(u ** 2 + v ** 2),
-            np.angle(u + 1j * v) * 180 / np.pi,
+            np.angle(u + 1j * v) * 180 / np.pi,
             u, v, w, ), axis=1)
-        out['HFlowAng'] = np.angle(self.uprof[0][self.ihub] + 1j * self.uprof[1][self.ihub])
-        out['VFlowAng'] = np.angle(self.uprof[0][self.ihub] + 1j * self.uprof[2][self.ihub])
-        out['TurbModel'] = self.info['specModel']['name']
-        out['gridheader'] = '---------   ' * self.grid.n_y
-        for nm in ['Zref', 'RefHt', 'ZRef', ]:
-            if nm in self.info['profModel']['params']:
-                out['RefHt'] = self.info['profModel']['params'][nm]
-        for nm in ['URef', 'Uref', ]:
-            if nm in self.info['profModel']['params']:
-                out['URef'] = self.info['profModel']['params'][nm]
-        out['PLExp'] = self.info['profModel']['params'].get('PLexp', None)
+        out['HFlowAng'] = np.angle(self.uprof[0][self.ihub] + 1j * self.uprof[1][self.ihub])
+        out['VFlowAng'] = np.angle(self.uprof[0][self.ihub] + 1j * self.uprof[2][self.ihub])
+        out['TurbModel'] = self.info['specModel']['name']
+        out['gridheader'] = '---------   ' * self.grid.n_y
+        for nm in ['Zref', 'RefHt', 'ZRef', ]:
+            if nm in self.info['profModel']['params']:
+                out['RefHt'] = self.info['profModel']['params'][nm]
+        for nm in ['URef', 'Uref', ]:
+            if nm in self.info['profModel']['params']:
+                out['URef'] = self.info['profModel']['params'][nm]
+        out['PLExp'] = self.info['profModel']['params'].get('PLexp', None)
         return out
 
     def __getitem__(self, ind):
-        if not hasattr(ind, '__len__'):
+        if not hasattr(ind, '__len__'):
             ind = [ind]
         else:
             list(ind)
         for idx, val in enumerate(ind):
-            if val.__class__ is not slice:
+            if val.__class__ is not slice:
                 ind[idx] = slice(val, val + 1)
         out = type(self)(self.grid[ind])
-        ind = [slice(None)] + list(ind)
+        ind = [slice(None)] + list(ind)
         out.uturb = self.uturb[ind]
         out.uprof = self.uprof[ind]
         return out
@@ -671,11 +672,11 @@ 

Source code for pyts.main

     @property
     def parameters(self,):
         out = {}
-        if hasattr(self, 'info'):
-            for nm in ['profModel_params',
-                       'specModel_params',
-                       'cohereModel_params',
-                       'stressModel_params']:
+        if hasattr(self, 'info'):
+            for nm in ['profModel_params',
+                       'specModel_params',
+                       'cohereModel_params',
+                       'stressModel_params']:
                 if nm in self.info:
                     out.update(self.info[nm])
         return out
@@ -705,13 +706,13 @@ 

Source code for pyts.main

         """
         The time vector, in seconds, starting at zero.
         """
-        if not hasattr(self, '_time'):
+        if not hasattr(self, '_time'):
             self._time = np.arange(0, self.uturb.shape[-1] * self.dt, self.dt)
         return self._time
 
     def __repr__(self,):
-        return ('<TurbSim data object:\n'
-                '%d %4.2fs-timesteps, %0.2fx%0.2fm (%dx%d) z-y grid (hubheight=%0.2fm).>' %
+        return ('<TurbSim data object:\n'
+                '%d %4.2fs-timesteps, %0.2fx%0.2fm (%dx%d) z-y grid (hubheight=%0.2fm).>' %
                 (self.uturb.shape[-1],
                  self.dt,
                  self.grid.height,
@@ -725,28 +726,28 @@ 

Source code for pyts.main

         """
         The total (mean + turbulent), 3-d velocity array
         """
-        return self.uturb + self.uprof[:, :, :, None]
+        return self.uturb + self.uprof[:, :, :, None]
 
     @property
     def u(self,):
         """
         The total (mean + turbulent), u-component of velocity.
         """
-        return self.uturb[0] + self.uprof[0, :, :, None]
+        return self.uturb[0] + self.uprof[0, :, :, None]
 
     @property
     def v(self,):
         """
         The total (mean + turbulent), v-component of velocity.
         """
-        return self.uturb[1] + self.uprof[1, :, :, None]
+        return self.uturb[1] + self.uprof[1, :, :, None]
 
     @property
     def w(self,):
         """
         The total (mean + turbulent), w-component of velocity.
         """
-        return self.uturb[2] + self.uprof[2, :, :, None]
+        return self.uturb[2] + self.uprof[2, :, :, None]
 
     @property
     def UHUB(self,):
@@ -799,11 +800,11 @@ 

Source code for pyts.main

         """
         The Reynold's stress tensor.
         """
-        if not hasattr(self, '_dat_stress'):
+        if not hasattr(self, '_dat_stress'):
             self._stress_dat = np.concatenate(
-                (np.mean(self.uturb[0] * self.uturb[1], axis=-1)[None],
-                 np.mean(self.uturb[0] * self.uturb[2], axis=-1)[None],
-                 np.mean(self.uturb[1] * self.uturb[2], axis=-1)[None]),
+                (np.mean(self.uturb[0] * self.uturb[1], axis=-1)[None],
+                 np.mean(self.uturb[0] * self.uturb[2], axis=-1)[None],
+                 np.mean(self.uturb[1] * self.uturb[2], axis=-1)[None]),
                 0)
         return self._stress_dat
 
@@ -838,9 +839,9 @@ 

Source code for pyts.main

         stats : dict
                 A dictionary containing various statistics of interest.
         """
-        slc = [slice(None)] + list(self.ihub)
+        slc = [slice(None)] + list(self.ihub)
         stats = {}
-        stats['Ti'] = self.tke[slc] / self.UHUB
+        stats['Ti'] = self.tke[slc] / self.UHUB
         return stats
 
 
[docs] def write_formatted(self, filename): @@ -853,8 +854,8 @@

Source code for pyts.main

         filename : string
                 '.u', '.v', and '.w' will be appended to the end of the filename.
         """
-        write.formatted(filename, self)
-
+ write.formatted(filename, self)
+
[docs] def write_bladed(self, filename): """ Save the data in this tsdata object in 'bladed' format (.wnd). @@ -865,8 +866,8 @@

Source code for pyts.main

                    The filename to which the data should be written.
 
         """
-        write.bladed(filename, self)
-
+ write.bladed(filename, self)
+
[docs] def write_turbsim(self, filename): """Save the data in this tsdata object in 'TurbSim' format. @@ -875,16 +876,16 @@

Source code for pyts.main

         filename : str
                    The filename to which the data should be written.
         """
-        write.turbsim(filename, self)
-
+ write.turbsim(filename, self)
+
[docs] def write_sum(self, filename): """ Currently PyTurbSim does not support writing summary (.sum) files. """ - write.sum(filename, self._sumdict) -
- if write.h5py is not None: -
[docs] def write_hdf5(self, filename): + write.sum(filename, self._sumdict)
+ + if write.h5py is not None: + def write_hdf5(self, filename): """Save the data in this tsdata object as an hdf5 file. Parameters @@ -892,7 +893,7 @@

Source code for pyts.main

             filename : str
                        The filename to which the data should be written.
             """
-            write.hdf5(filename, self)
+ write.hdf5(filename, self)
@@ -911,14 +912,11 @@

Related Topics

@@ -926,11 +924,11 @@

Quick search

diff --git a/docs/_modules/pyts/misc.html b/docs/_modules/pyts/misc.html index 08fdc17..1ece68c 100644 --- a/docs/_modules/pyts/misc.html +++ b/docs/_modules/pyts/misc.html @@ -1,38 +1,39 @@ + - - - pyts.misc — PyTurbSim 0.4.7 documentation - + pyts.misc — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,13 +41,13 @@

Source code for pyts.misc

-"""
+"""
 This module contains a few random helper functions that are used
 throughout the code.
 """
-from . import pyts_numpy as np
+from . import pyts_numpy as np
 
-kappa = 0.41  # Von-Karman's constant
+kappa = 0.41  # Von-Karman's constant
 
 
 
[docs]def Lambda(zhub, IECedition): @@ -60,10 +61,10 @@

Source code for pyts.misc

     """
     if IECedition <= 2:
         return 0.7 * min(30, zhub)
-    return 0.7 * min(60, zhub)
+    return 0.7 * min(60, zhub)
-
-
[docs]def zL(Ri, TurbModel=None): + +
[docs]def zL(Ri, TurbModel=None): """ *zL* is the Monin-Obhukov (M-O) stability parameter z/L, where L is the M-O length. @@ -79,7 +80,7 @@

Source code for pyts.misc

                 In some cases z/L depends on the Turbulence model.
 
     """
-    if TurbModel.__class__ is str and TurbModel.lower() == 'nwtcup':
+    if TurbModel.__class__ is str and TurbModel.lower() == 'nwtcup':
         Ri = max(min(Ri, 0.155), -1.)
         if Ri <= -0.1:
             return -0.254 + 1.047 * Ri
@@ -87,7 +88,7 @@ 

Source code for pyts.misc

             return 10.369 * Ri / (1. - 19.393 * Ri)
         else:
             return 2.535 * Ri / (1. - 6.252 * Ri)
-    elif TurbModel.__class__ is str and TurbModel.lower() == 'gp_llj':
+    elif TurbModel.__class__ is str and TurbModel.lower() == 'gp_llj':
         Ri = max(min(Ri, 0.1367), -1.)
         if Ri <= -0.1:
             return -0.047 + 1.056 * Ri
@@ -96,18 +97,18 @@ 

Source code for pyts.misc

         else:
             return 3.132 * Ri / (1. - 6.762 * Ri)
     else:
-        # This is the relationship between zL and Ri detailed in:
-        # Businger etal 'Flux-Profile Relationships in the Atmospheric Surface
-        # Layer' 1971,
+        # This is the relationship between zL and Ri detailed in:
+        # Businger etal 'Flux-Profile Relationships in the Atmospheric Surface
+        # Layer' 1971,
         if Ri < 0:
             return Ri
         elif Ri < .16666666:
             return Ri / (1 - 5. * Ri)
         else:
-            return 1
+            return 1
-
-
[docs]def psiM(Ri, TurbModel=None): + +
[docs]def psiM(Ri, TurbModel=None): """ The psi_M stability parameter is used for various mean wind-speed profiles and turbulence models. @@ -133,9 +134,9 @@

Source code for pyts.misc

     else:
         tmp = (1. - 15.0 * zl) ** 0.25
         return (-np.log(0.125 * ((1.0 + tmp) ** 2 * (1.0 + tmp ** 2)))
-                + 2.0 * np.arctan(tmp) - 0.5 * np.pi)
+                + 2.0 * np.arctan(tmp) - 0.5 * np.pi)
+ -
[docs]def pfactor(n, pmax=31): """ Calculate the prime factors of the integer *n*. @@ -166,10 +167,10 @@

Source code for pyts.misc

             n /= ip
     if n != 1:
         lst.add(n)
-    return np.sort(list(lst))
+    return np.sort(list(lst))
-
-
[docs]def lowPrimeFact_near(n, pmax=31, nmin=None, evens_only=True): + +
[docs]def lowPrimeFact_near(n, pmax=31, nmin=None, evens_only=True): """ Find the nearest integer to `n` with prime factors all less than `pmax`. @@ -192,14 +193,14 @@

Source code for pyts.misc

     """
     if (np.array(pfactor(n, pmax)) < pmax).all():
         return n
-    if evens_only:  # Only deal with evens.
+    if evens_only:  # Only deal with evens.
         dl = 2
         if np.mod(n, 2) > 0:
             n += 1
     else:
         dl = 1
     ih = n
-    if nmin is not None:
+    if nmin is not None:
         il = n - dl
         while il > nmin:
             if (np.array(pfactor(il, pmax)) < pmax).all():
@@ -210,9 +211,9 @@ 

Source code for pyts.misc

             ih += dl
     while not (np.array(pfactor(ih, pmax)) < pmax).all():
         ih += dl
-    return ih
+    return ih
+ -
[docs]def fix2range(vals, minval, maxval): """ A helper function that sets the value of the array or number `vals` to @@ -235,12 +236,12 @@

Source code for pyts.misc

     fixed_vals : float or array_like (matches `vals`)
                  The fixed values.
     """
-    if not hasattr(vals, '__len__'):
+    if not hasattr(vals, '__len__'):
         return max(min(vals, maxval), minval)
     vals[vals > maxval], vals[vals < minval] = maxval, minval
-    return vals
+    return vals
+ -
[docs]class InvalidConfig(Exception): """ @@ -248,7 +249,7 @@

Source code for pyts.misc

     a model has not defined a necessary attribute.
     """
 
-    def __init__(self, msg='Invalid option specified in config file.'):
+    def __init__(self, msg='Invalid option specified in config file.'):
         self.msg = msg
@@ -268,14 +269,11 @@

Related Topics

@@ -283,11 +281,11 @@

Quick search

diff --git a/docs/_modules/pyts/phaseModels/base.html b/docs/_modules/pyts/phaseModels/base.html index 0683246..c2b9d99 100644 --- a/docs/_modules/pyts/phaseModels/base.html +++ b/docs/_modules/pyts/phaseModels/base.html @@ -1,38 +1,39 @@ + - - - pyts.phaseModels.base — PyTurbSim 0.4.7 documentation - + pyts.phaseModels.base — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.phaseModels.base

-"""
+"""
 This is the base module for phase models.  Phase models produce the
 initial phase information that is then correlated in the stress and
 coherence models.
@@ -48,7 +49,7 @@ 

Source code for pyts.phaseModels.base

 The basic phase model simply returns a 'random' array.
 
 """
-from ..base import modelBase, np, ts_complex
+from ..base import modelBase, np, ts_complex
 
 
 
[docs]class phaseModelBase(modelBase): @@ -71,14 +72,11 @@

Related Topics

@@ -86,11 +84,11 @@

Quick search

diff --git a/docs/_modules/pyts/phaseModels/main.html b/docs/_modules/pyts/phaseModels/main.html index 6015c77..94a0df7 100644 --- a/docs/_modules/pyts/phaseModels/main.html +++ b/docs/_modules/pyts/phaseModels/main.html @@ -1,38 +1,39 @@ + - - - pyts.phaseModels.main — PyTurbSim 0.4.7 documentation - + pyts.phaseModels.main — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,10 +41,10 @@

Source code for pyts.phaseModels.main

-"""
+"""
 The main random phase models.
 """
-from .base import phaseModelBase, np, ts_complex
+from .base import phaseModelBase, np, ts_complex
 
 
 
[docs]class randPhase(phaseModelBase): @@ -72,8 +73,8 @@

Source code for pyts.phaseModels.main

 
         """
         phases = np.empty((tsrun.grid.n_comp, tsrun.grid.n_p, tsrun.grid.n_f),
-                          dtype=ts_complex, order='F')
-        phases[:] = np.exp(1j * 2 * np.pi *
+                          dtype=ts_complex, order='F')
+        phases[:] = np.exp(1j * 2 * np.pi *
                            tsrun.randgen.rand(tsrun.grid.n_comp,
                                               tsrun.grid.n_p,
                                               tsrun.grid.n_f))
@@ -96,14 +97,11 @@ 

Related Topics

@@ -111,11 +109,11 @@

Quick search

diff --git a/docs/_modules/pyts/plot/_basefuncs.html b/docs/_modules/pyts/plot/_basefuncs.html index 6641652..25e0571 100644 --- a/docs/_modules/pyts/plot/_basefuncs.html +++ b/docs/_modules/pyts/plot/_basefuncs.html @@ -1,38 +1,39 @@ + - - - pyts.plot._basefuncs — PyTurbSim 0.4.7 documentation - + pyts.plot._basefuncs — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,10 +41,10 @@

Source code for pyts.plot._basefuncs

-import numpy as np
-import matplotlib as mpl
+import numpy as np
+import matplotlib as mpl
 transforms = mpl.transforms
-from string import lowercase
+from string import lowercase
 
 
 def pair(val):
@@ -71,33 +72,33 @@ 

Source code for pyts.plot._basefuncs

     """
     threshx = np.inf
     threshy = np.inf
-    fixgaps = True
+    fixgaps = True
     argind = 0
     if isinstance(args[0], mpl.axes.Axes):
-        # Data is the second (1) element of args... (see below)
+        # Data is the second (1) element of args... (see below)
         argind += 1
         ax = args[0]
-    elif ('ax' in kwargs.keys()) or \
-            ('axes' in kwargs.keys()) or ('parent' in kwargs.keys()):
-        if 'parent' in kwargs.keys():
-            ax = kwargs.pop('parent')
-        elif 'ax' in kwargs.keys():
-            ax = kwargs.pop('ax')
+    elif ('ax' in kwargs.keys()) or \
+            ('axes' in kwargs.keys()) or ('parent' in kwargs.keys()):
+        if 'parent' in kwargs.keys():
+            ax = kwargs.pop('parent')
+        elif 'ax' in kwargs.keys():
+            ax = kwargs.pop('ax')
         else:
-            ax = kwargs.pop('axes')
+            ax = kwargs.pop('axes')
     else:
         ax = mpl.pylab.gca()
 
-    if 'fixgaps' in kwargs.keys():
-        fixgaps = kwargs.pop('fixgaps')
-    if 'threshx' in kwargs.keys():
-        threshx = kwargs.pop('threshx')
-    if 'threshy' in kwargs.keys():
-        threshy = kwargs.pop('threshy')
-    if 'clim' in kwargs.keys():
-        clm = kwargs.pop('clim')
-        kwargs['vmin'] = clm[0]
-        kwargs['vmax'] = clm[1]
+    if 'fixgaps' in kwargs.keys():
+        fixgaps = kwargs.pop('fixgaps')
+    if 'threshx' in kwargs.keys():
+        threshx = kwargs.pop('threshx')
+    if 'threshy' in kwargs.keys():
+        threshy = kwargs.pop('threshy')
+    if 'clim' in kwargs.keys():
+        clm = kwargs.pop('clim')
+        kwargs['vmin'] = clm[0]
+        kwargs['vmax'] = clm[1]
 
     if len(args) - argind == 1:
         dat = args[0 + argind]
@@ -108,23 +109,23 @@ 

Source code for pyts.plot._basefuncs

         y = args[1 + argind]
         dat = args[2 + argind]
 
-    dfx = np.diff(x, 1, 0).astype('double')
+    dfx = np.diff(x, 1, 0).astype('double')
     dx = dfx
     gd = abs(dx) <= 3 * np.nanmean(abs(dx))
     while not gd.all():
         dx = dx[gd]
         gd = abs(dx) <= 3 * np.nanmean(abs(dx))
 
-    dx = np.nanmean(dx).astype('double')
+    dx = np.nanmean(dx).astype('double')
 
-    dfy = np.diff(y, 1, 0).astype('double')
+    dfy = np.diff(y, 1, 0).astype('double')
     dy = dfy
     gd = abs(dy) <= 3 * np.nanmean(abs(dy))
     while not gd.all():
         dy = dy[gd]
         gd = abs(dy) <= 3 * np.nanmean(abs(dy))
 
-    dy = np.nanmean(dy).astype('double')
+    dy = np.nanmean(dy).astype('double')
 
     N = dat.shape[1] + sum(abs(dfx) > 3 * abs(dx)) * fixgaps
     datn = np.NaN * np.ones([dat.shape[0], N + 1])
@@ -191,22 +192,22 @@ 

Source code for pyts.plot._basefuncs

     mx = np.ma.array(mx, mask=np.isnan(mx))
     my = np.ma.array(my, mask=np.isnan(my))
 
-    # mx=xn
-    # my=yn
+    # mx=xn
+    # my=yn
 
-    hndl = ax.pcolormesh(mx, my, datm, shading='flat', **kwargs)
-    hndl.set_rasterized(True)
+    hndl = ax.pcolormesh(mx, my, datm, shading='flat', **kwargs)
+    hndl.set_rasterized(True)
     mpl.pylab.draw_if_interactive()
     return hndl
 
 
-def labelax(peer, str, place='right', **kwargs):
-    if place == 'right':
+def labelax(peer, str, place='right', **kwargs):
+    if place == 'right':
         place = (1.025, .6)
-    elif place == 'over':
+    elif place == 'over':
         place = (.48, 1.1)
-        if 'horizontalalignment' not in kwargs.keys():
-            kwargs['horizontalalignment'] = 'right'
+        if 'horizontalalignment' not in kwargs.keys():
+            kwargs['horizontalalignment'] = 'right'
 
     hndl = peer.text(
         place[0], place[1], str, transform=peer.transAxes, **kwargs)
@@ -214,19 +215,19 @@ 

Source code for pyts.plot._basefuncs

     return hndl
 
 
-def errorshadex(peer, x, y, xerr, ecolor=None,
-                ealpha=.5, color='b', zorder=0, **kwargs):
+def errorshadex(peer, x, y, xerr, ecolor=None,
+                ealpha=.5, color='b', zorder=0, **kwargs):
     """
     Plot a line with a shaded region for error.
     """
-    if ecolor is None:
+    if ecolor is None:
         ecolor = color
     peer.plot(x, y, color=color, zorder=zorder, **kwargs)
     peer.fill_betweenx(
         y, x - xerr, x + xerr, alpha=ealpha, color=ecolor, zorder=zorder - 1)
 
 
-def vecs2fillvec(y1, y2, meanstd=False, x=None, axis=0):
+def vecs2fillvec(y1, y2, meanstd=False, x=None, axis=0):
     """
     *y1* and *y2* should be the ranges.
     This function will then flip y2 and tack it onto y1.
@@ -239,14 +240,14 @@ 

Source code for pyts.plot._basefuncs

     if meanstd:
         y1, y2 = y1 + y2, y1 - y2
 
-    if x is None:
+    if x is None:
         return np.concatenate((y1, y2[::-1], y1[[0]]), axis)
     else:
         return (np.concatenate((y1, y2[::-1], y1[[0]]), axis),
                 np.concatenate((x, x[::-1], x[[0]]), axis))
 
 
-def calcFigSize(n, ax=np.array([1, 0]), frm=np.array([.5, .5]), norm=False):
+def calcFigSize(n, ax=np.array([1, 0]), frm=np.array([.5, .5]), norm=False):
     """
     sz,vec = calcFigSize(n,ax,frame) calculates the width (or height)
     of a figure with *n* subplots.  Specify the width (height) of each
@@ -259,13 +260,13 @@ 

Source code for pyts.plot._basefuncs

 
     See also: saxes, axes, calcAxesSize
     """
-    if hasattr(n, '__iter__'):
+    if hasattr(n, '__iter__'):
         n = np.sum(n)
     sz = n * ax[0] + (n - 1) * ax[1] + frm[0] + frm[1]
     frm = np.array(frm)
     ax = np.array(ax)
-    if not (norm.__class__ is False.__class__ and not norm):
-        # This checks that it is not the default.
+    if not (norm.__class__ is False.__class__ and not norm):
+        # This checks that it is not the default.
         frm = frm / sz * norm
         ax = ax / sz * norm
         sz = norm
@@ -284,12 +285,12 @@ 

Source code for pyts.plot._basefuncs

 
     See also: saxes, axes, calcFigSize
     """
-    if hasattr(gap, '__len__'):
+    if hasattr(gap, '__len__'):
         gtot = np.sum(gap[:n])
     else:
         gtot = gap * (n - 1)
     axsz = (totsize - frame[0] - frame[1] - gtot) / n
-    sz, v = calcFigSize(n, [axsz, gap], frame, False)
+    sz, v = calcFigSize(n, [axsz, gap], frame, False)
     return axsz, v
 
 
@@ -304,16 +305,16 @@ 

Source code for pyts.plot._basefuncs

 
     See also: saxes, axes, calcFigSize
     """
-    if hasattr(gap, '__len__'):
+    if hasattr(gap, '__len__'):
         gtot = np.sum(gap[:n])
     else:
         gtot = gap * (n - 1)
     axsz = (totsize - frame[0] - frame[1] - gtot) / n
-    sz, v = calcFigSize(n, [axsz, gap], frame, False)
+    sz, v = calcFigSize(n, [axsz, gap], frame, False)
     return axsz, v
 
 
-def axvec2axpos(n, vec, vertflag=False, rel=False):
+def axvec2axpos(n, vec, vertflag=False, rel=False):
     """
     calculates the positions for the `n` axes, based on the axes
     vector `vec`.
@@ -347,8 +348,8 @@ 

Source code for pyts.plot._basefuncs

 
     """
 
-    if rel.__class__ is False.__class__ and not rel:
-        # Default value.
+    if rel.__class__ is False.__class__ and not rel:
+        # Default value.
         rel = np.ones(n)
     wd = (((vec[1] - vec[0]) + vec[2]) / n - vec[2]) * rel / rel.mean()
     if vertflag:
@@ -361,14 +362,14 @@ 

Source code for pyts.plot._basefuncs

 
 
 def get_transform(ax, trans):
-    if trans.__class__ is not str:
+    if trans.__class__ is not str:
         return trans
     if hasattr(ax, trans):
         return getattr(ax, trans)
-    return getattr(ax, 'trans' + trans)
+    return getattr(ax, 'trans' + trans)
 
 
-def offset_text(ax, x, y, s, offset=(0, 0), transform=None, **kwargs):
+def offset_text(ax, x, y, s, offset=(0, 0), transform=None, **kwargs):
     """
     Add text to an axes offset from a location.
 
@@ -382,11 +383,11 @@ 

Source code for pyts.plot._basefuncs

     a different 'transform' to change this.
 
     """
-    if transform is None:
+    if transform is None:
         transform = ax.transData
     else:
         transform = get_transform(ax, transform)
-    if (offset.__class__ is list) or (offset.__class__ is tuple):
+    if (offset.__class__ is list) or (offset.__class__ is tuple):
         osx = offset[0] / 72.
         osy = offset[1] / 72.
     else:
@@ -398,7 +399,7 @@ 

Source code for pyts.plot._basefuncs

     return ax.text(x, y, s, transform=trfrm, **kwargs)
 
 
-def annoteCorner(ax, s, pos='ll', offset=10, **kwargs):
+def annoteCorner(ax, s, pos='ll', offset=10, **kwargs):
     """
     annotate a corner of an axes with a string.
 
@@ -431,29 +432,29 @@ 

Source code for pyts.plot._basefuncs

     prm = {}
     yp = 0.0
     xp = 0.0
-    prm['va'] = 'baseline'
-    prm['ha'] = 'left'
-    # prm['fontsize']='medium'
-    if (offset.__class__ is list) or (offset.__class__ is tuple):
+    prm['va'] = 'baseline'
+    prm['ha'] = 'left'
+    # prm['fontsize']='medium'
+    if (offset.__class__ is list) or (offset.__class__ is tuple):
         osx = offset[0]
         osy = offset[1]
     else:
         osx = offset
         osy = offset
-    if pos.__class__ is str:
-        if pos[0] == 'u':
+    if pos.__class__ is str:
+        if pos[0] == 'u':
             osy = -osy
             yp = 1.
-            prm['va'] = 'top'
-        if pos[1] == 'r':
+            prm['va'] = 'top'
+        if pos[1] == 'r':
             osx = -osx
             xp = 1.
-            prm['ha'] = 'right'
+            prm['ha'] = 'right'
     else:
         xp = pos[0]
         yp = pos[1]
-    prm['offset'] = (osx, osy)
-    prm['transform'] = ax.transAxes
+    prm['offset'] = (osx, osy)
+    prm['transform'] = ax.transAxes
 
     for key in prm:
         if key not in kwargs.keys():
@@ -462,16 +463,16 @@ 

Source code for pyts.plot._basefuncs

     return ax.corner_label
 
 
-def shadex(ax, x, y=[0, 1], transform='DataXAxesY', label='_nolegend_',
-           zorder=-100, color='k', alpha=0.2, edgecolor='none', **kwargs):
+def shadex(ax, x, y=[0, 1], transform='DataXAxesY', label='_nolegend_',
+           zorder=-100, color='k', alpha=0.2, edgecolor='none', **kwargs):
     transform = get_transform(ax, transform)
     ax.fill_between(x, y[0], y[1], label=label, transform=transform,
                     zorder=zorder, color=color, alpha=alpha,
                     edgecolor=edgecolor, **kwargs)
 
 
-def shadey(ax, y, x=[0, 1], transform='AxesXDataY', label='_nolegend_',
-           zorder=-100, color='k', alpha=0.2, edgecolor='none', **kwargs):
+def shadey(ax, y, x=[0, 1], transform='AxesXDataY', label='_nolegend_',
+           zorder=-100, color='k', alpha=0.2, edgecolor='none', **kwargs):
     transform = get_transform(ax, transform)
     ax.fill_betweenx(y, x[0], x[1], label=label, transform=transform,
                      zorder=zorder, color=color, alpha=alpha,
@@ -480,49 +481,49 @@ 

Source code for pyts.plot._basefuncs

 
 def _setaxesframe(ax, str):
     str = np.array(list(str))
-    if any(str == 't') and any(str == 'b'):
-        ax.xaxis.set_ticks_position('both')
-        ax.spines['top'].set_visible(True)
-        ax.spines['bottom'].set_visible(True)
-    elif any(str == 't'):
-        ax.xaxis.set_ticks_position('top')
-        ax.xaxis.set_label_position('top')
-        ax.spines['top'].set_visible(True)
-        ax.spines['bottom'].set_visible(False)
-    elif any(str == 'b'):
-        ax.xaxis.set_ticks_position('bottom')
-        ax.xaxis.set_label_position('bottom')
-        ax.spines['top'].set_visible(False)
-        ax.spines['bottom'].set_visible(True)
+    if any(str == 't') and any(str == 'b'):
+        ax.xaxis.set_ticks_position('both')
+        ax.spines['top'].set_visible(True)
+        ax.spines['bottom'].set_visible(True)
+    elif any(str == 't'):
+        ax.xaxis.set_ticks_position('top')
+        ax.xaxis.set_label_position('top')
+        ax.spines['top'].set_visible(True)
+        ax.spines['bottom'].set_visible(False)
+    elif any(str == 'b'):
+        ax.xaxis.set_ticks_position('bottom')
+        ax.xaxis.set_label_position('bottom')
+        ax.spines['top'].set_visible(False)
+        ax.spines['bottom'].set_visible(True)
     else:
-        ax.xaxis.set_ticks_position('none')
-        ax.spines['top'].set_visible(False)
-        ax.spines['bottom'].set_visible(False)
-        ax.xaxis.set_ticklabels('')
-
-    if any(str == 'l') and any(str == 'r'):
-        ax.yaxis.set_ticks_position('both')
-        ax.spines['left'].set_visible(True)
-        ax.spines['right'].set_visible(True)
-    elif any(str == 'l'):
-        ax.yaxis.set_ticks_position('left')
-        ax.yaxis.set_label_position('left')
-        ax.spines['left'].set_visible(True)
-        ax.spines['right'].set_visible(False)
-    elif any(str == 'r'):
-        ax.yaxis.set_ticks_position('right')
-        ax.yaxis.set_label_position('right')
-        ax.spines['left'].set_visible(False)
-        ax.spines['right'].set_visible(True)
+        ax.xaxis.set_ticks_position('none')
+        ax.spines['top'].set_visible(False)
+        ax.spines['bottom'].set_visible(False)
+        ax.xaxis.set_ticklabels('')
+
+    if any(str == 'l') and any(str == 'r'):
+        ax.yaxis.set_ticks_position('both')
+        ax.spines['left'].set_visible(True)
+        ax.spines['right'].set_visible(True)
+    elif any(str == 'l'):
+        ax.yaxis.set_ticks_position('left')
+        ax.yaxis.set_label_position('left')
+        ax.spines['left'].set_visible(True)
+        ax.spines['right'].set_visible(False)
+    elif any(str == 'r'):
+        ax.yaxis.set_ticks_position('right')
+        ax.yaxis.set_label_position('right')
+        ax.spines['left'].set_visible(False)
+        ax.spines['right'].set_visible(True)
     else:
-        ax.yaxis.set_ticks_position('none')
-        ax.spines['left'].set_visible(False)
-        ax.spines['right'].set_visible(False)
-        ax.yaxis.set_ticklabels('')
-        # for tk in ax.yaxis.get_ticklabels
+        ax.yaxis.set_ticks_position('none')
+        ax.spines['left'].set_visible(False)
+        ax.spines['right'].set_visible(False)
+        ax.yaxis.set_ticklabels('')
+        # for tk in ax.yaxis.get_ticklabels
 
 
-def alphNumAxes(axs, vals=lowercase, prefix='', suffix=')', **kwargs):
+def alphNumAxes(axs, vals=lowercase, prefix='', suffix=')', **kwargs):
     """
     Label the axes with alphanumeric characters.
 
@@ -544,11 +545,11 @@ 

Source code for pyts.plot._basefuncs

 
     :func:`annoteCorner`
     """
-    if suffix is None:
-        suffix = ')'
-    if prefix is None:
-        prefix = ''
-    corner_labels = np.empty(len(axs), 'O')
+    if suffix is None:
+        suffix = ')'
+    if prefix is None:
+        prefix = ''
+    corner_labels = np.empty(len(axs), 'O')
     for idx, ax in enumerate(axs):
         corner_labels[idx] = ax.annoteCorner(
             prefix + vals[idx] + suffix, **kwargs)
@@ -570,14 +571,11 @@ 

Related Topics

@@ -585,11 +583,11 @@

Quick search

diff --git a/docs/_modules/pyts/plot/axform.html b/docs/_modules/pyts/plot/axform.html index 8ad4b0c..b7b0063 100644 --- a/docs/_modules/pyts/plot/axform.html +++ b/docs/_modules/pyts/plot/axform.html @@ -1,38 +1,39 @@ + - - - pyts.plot.axform — PyTurbSim 0.4.7 documentation - + pyts.plot.axform — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,11 +41,11 @@

Source code for pyts.plot.axform

-from ..main import tsdata, tsrun  # used to identify object types
-import superaxes as supax
+from ..main import tsdata, tsrun  # used to identify object types
+import superaxes as supax
 import psd
-from base import indx, mpl
-import numpy as np
+from base import indx, mpl
+import numpy as np
 
 
 
[docs]class axesForm(object): @@ -63,13 +64,13 @@

Source code for pyts.plot.axform

     yscale : ('log' or 'linear')
         specify whether the y-scale should be logarithmic or linear.
     """
-    method_map = {tsdata: '_calc_tsdata', tsrun: '_calc_tsrun'}
-    hide_ylabels = False
+    method_map = {tsdata: '_calc_tsdata', tsrun: '_calc_tsrun'}
+    hide_ylabels = False
     _lin_x_scale = 0
 
     def __init__(self,
-                 xlim=[None, None], ylim=[None, None],
-                 xscale='linear', yscale='linear',):
+                 xlim=[None, None], ylim=[None, None],
+                 xscale='linear', yscale='linear',):
         self.xlim = xlim
         self.ylim = ylim
         self.xscale = xscale
@@ -84,32 +85,32 @@ 

Source code for pyts.plot.axform

         ----------
         axes : A :class:`superaxes.axgroup` instance.
         """
-        axes.hide('xticklabels', ax=axes[-1])
+        axes.hide('xticklabels', ax=axes[-1])
         if self.hide_ylabels:
-            axes.hide('yticklabels')
-        if not self.hide_ylabels and hasattr(self, '_ylabel'):
+            axes.hide('yticklabels')
+        if not self.hide_ylabels and hasattr(self, '_ylabel'):
             for ax in axes:
                 ax.set_ylabel(self._ylabel)
-        if hasattr(self, '_xlabel'):
+        if hasattr(self, '_xlabel'):
             axes[-1].set_xlabel(self._xlabel)
-        if hasattr(self, '_title'):
+        if hasattr(self, '_title'):
             axes[0].set_title(self._title)
-        if hasattr(self, '_grid_x'):
+        if hasattr(self, '_grid_x'):
             for ax in axes:
                 for val in self._grid_x:
-                    ax.axvline(val, linestyle=':', color='k', zorder=-10)
-        if hasattr(self, '_labels'):
+                    ax.axvline(val, linestyle=':', color='k', zorder=-10)
+        if hasattr(self, '_labels'):
             for ax in axes:
-                ax.annoteCorner(self._labels[ax.comp], pos='ul')
-        if hasattr(self, 'xtick_n'):
+                ax.annoteCorner(self._labels[ax.comp], pos='ul')
+        if hasattr(self, 'xtick_n'):
             for ax in axes:
                 ax.xaxis.set_major_locator(
                     mpl.ticker.MaxNLocator(self.xtick_n))
         for ax in axes:
             ax.set_xlim(self.xlim)
         for ax in axes:
-            ax.set_ylim(self.ylim)
-
+ ax.set_ylim(self.ylim)
+ def _calc(self, obj, comp): """ Call the appropriate 'calc' method depending on the object @@ -137,15 +138,15 @@

Source code for pyts.plot.axform

         method should be called for each `obj` object type.
 
         """
-        if comp.__class__ is str:
+        if comp.__class__ is str:
             comp = indx[comp]
-        for cls, meth in self.method_map.iteritems():
-            if isinstance(obj, cls):
+        for cls, meth in self.method_map.iteritems():
+            if isinstance(obj, cls):
                 if not hasattr(self, meth):
                     return np.NaN, np.NaN
                 return getattr(self, meth)(obj, comp)
-        raise Exception('Object type %s not recognized for %s axes-type' %
-                        (obj.__class__, self.__class__))
+        raise Exception('Object type %s not recognized for %s axes-type' %
+                        (obj.__class__, self.__class__))
 
 
[docs] def plot(self, obj, axes, **kwargs): """ @@ -160,27 +161,27 @@

Source code for pyts.plot.axform

         """
         for ax in axes:
             x, y = self._calc(obj, ax.comp)
-            # print x, y, self._lin_x_scale
+            # print x, y, self._lin_x_scale
             ax.plot(x / (10 ** self._lin_x_scale), y, **kwargs)
             ax.set_xscale(self.xscale)
-            ax.set_yscale(self.yscale)
-
+ ax.set_yscale(self.yscale)
+ @property def _xlabel(self,): if self._lin_x_scale == 0: - return '$\mathrm{[m^2s^{-2}]}$' + return '$\mathrm{[m^2s^{-2}]}$' else: - return '$\mathrm{[10^{%d}m^2s^{-2}]}$' % self._lin_x_scale + return '$\mathrm{[10^{%d}m^2s^{-2}]}$' % self._lin_x_scale
+ -
[docs]class prof(axesForm): - "A base axesForm for plotting vertical profiles." - yax = 'z' - _ylabel = '$z\,\mathrm{[m]}$' + "A base axesForm for plotting vertical profiles." + yax = 'z' + _ylabel = '$z\,\mathrm{[m]}$' hrel = 0.6 - xtick_n = 3 + xtick_n = 3
+ -
[docs]class velprof(prof): """A 'mean velocity profile' axesForm format. @@ -189,25 +190,25 @@

Source code for pyts.plot.axform

     :class:`prof`
     :class:`axesForm`
     """
-    xax = 'vel'
-    _title = 'Mean Velocity'
-    _xlabel = '$\mathrm{[m/s]}$'
+    xax = 'vel'
+    _title = 'Mean Velocity'
+    _xlabel = '$\mathrm{[m/s]}$'
 
-    def _calc_tsdata(self, tsdat, comp, igrid=None):
+    def _calc_tsdata(self, tsdat, comp, igrid=None):
         """
         The function that calculates x,y values for plotting
         :class:`.tsdata` objects.
         """
         return tsdat.uprof[comp, :, tsdat.ihub[1]], tsdat.z
 
-    def _calc_tsrun(self, tsr, comp, igrid=None):
+    def _calc_tsrun(self, tsr, comp, igrid=None):
         """
         The function that calculates x,y values for plotting
         :class:`.tsrun` objects.
         """
-        return tsr.prof[comp, :, tsr.grid.ihub[1]], tsr.grid.z
+        return tsr.prof[comp, :, tsr.grid.ihub[1]], tsr.grid.z
+ -
[docs]class tkeprof(prof): """A 'tke profile' axesForm. @@ -216,17 +217,17 @@

Source code for pyts.plot.axform

     :class:`prof`
     :class:`axesForm`
     """
-    xax = 'tke'
-    _title = 'tke'
-    #_lin_x_scale = -2  # Units are 10^-2
+    xax = 'tke'
+    _title = 'tke'
+    #_lin_x_scale = -2  # Units are 10^-2
 
-    def _calc_tsdata(self, tsdat, comp, igrid=None):
+    def _calc_tsdata(self, tsdat, comp, igrid=None):
         return tsdat.tke[comp, :, tsdat.ihub[1]], tsdat.z
 
-    def _calc_tsrun(self, tsr, comp, igrid=None):
-        return tsr.spec.tke[comp, :, tsr.grid.ihub[1]], tsr.grid.z
+    def _calc_tsrun(self, tsr, comp, igrid=None):
+        return tsr.spec.tke[comp, :, tsr.grid.ihub[1]], tsr.grid.z
+ -
[docs]class Tiprof(prof): """A Turbulence intensity axesForm @@ -235,22 +236,22 @@

Source code for pyts.plot.axform

     :class:`prof`
     :class:`axesForm`
     """
-    xax = 'Ti'
-    _title = 'Ti'
+    xax = 'Ti'
+    _title = 'Ti'
     _lin_x_scale = 0
-    _ylabel = '%'
+    _ylabel = '%'
 
-    def _calc_tsdata(self, tsdat, comp, igrid=None):
+    def _calc_tsdata(self, tsdat, comp, igrid=None):
         tmp = (100 * np.std(tsdat.uturb[comp, :, tsdat.ihub[1]], axis=-1)
                / tsdat.uprof[0, :, tsdat.ihub[1]])
         return tmp, tsdat.z
 
-    def _calc_tsrun(self, tsr, comp, igrid=None):
+    def _calc_tsrun(self, tsr, comp, igrid=None):
         return (100 * np.sqrt(tsr.spec.tke[comp, :, tsr.grid.ihub[1]])
                 / tsr.prof.u[:, tsr.grid.ihub[1]],
-                tsr.grid.z)
+                tsr.grid.z)
+ -
[docs]class stressprof(tkeprof): """A 'Reynold's stress profile' axesForm. @@ -259,23 +260,23 @@

Source code for pyts.plot.axform

     :class:`prof`
     :class:`axesForm`
     """
-    xax = 'tke'
-    _title = 'stress'
-    _lin_x_scale = -2  # Units are 10^-2
+    xax = 'tke'
+    _title = 'stress'
+    _lin_x_scale = -2  # Units are 10^-2
     _grid_x = [0]
-    _labels = {'u': r"$\overline{u'v'}$",
-               'v': r"$\overline{u'w'}$",
-               'w': r"$\overline{v'w'}$"}
+    _labels = {'u': r"$\overline{u'v'}$",
+               'v': r"$\overline{u'w'}$",
+               'w': r"$\overline{v'w'}$"}
 
-    def _calc_tsdata(self, tsdat, comp, igrid=None):
+    def _calc_tsdata(self, tsdat, comp, igrid=None):
         igrid = igrid or tsdat.ihub[1]
         return tsdat.stress[comp, :, igrid], tsdat.z
 
-    def _calc_tsrun(self, tsr, comp, igrid=None):
+    def _calc_tsrun(self, tsr, comp, igrid=None):
         igrid = igrid or tsr.grid.ihub[1]
-        return tsr.stress.array[comp, :, igrid], tsr.grid.z
+        return tsr.stress.array[comp, :, igrid], tsr.grid.z
+ -
[docs]class spec(axesForm): """A 'spectral' axesForm. @@ -297,34 +298,34 @@

Source code for pyts.plot.axform

     :class:`axesForm`
     """
     hrel = 1
-    _title = 'spectrum'
-    yax = 'spec'
-    xax = 'freq'
-    _xlabel = '$f\,\mathrm{[Hz]}$'
-    _ylabel = '$\mathrm{[m^2s^{-2}/Hz]}$'
-
-    def __init__(self, window_time_sec=600, igrid=None,
-                 xscale='log', yscale='log',
+    _title = 'spectrum'
+    yax = 'spec'
+    xax = 'freq'
+    _xlabel = '$f\,\mathrm{[Hz]}$'
+    _ylabel = '$\mathrm{[m^2s^{-2}/Hz]}$'
+
+    def __init__(self, window_time_sec=600, igrid=None,
+                 xscale='log', yscale='log',
                  **kwargs):
-        axesForm.__init__(self, xscale=xscale, yscale=yscale, **kwargs)
+        axesForm.__init__(self, xscale=xscale, yscale=yscale, **kwargs)
         self.window_time = window_time_sec
         self.igrid = igrid
 
-    def _calc_tsdata(self, tsdat, comp, igrid=None):
+    def _calc_tsdata(self, tsdat, comp, igrid=None):
         nfft = int(self.window_time / tsdat.dt)
         nfft += np.mod(nfft, 2)
         igrid = igrid or self.igrid or tsdat.ihub
         tmp = psd.psd(tsdat.uturb[comp][igrid],
                       1. / tsdat.dt,
                       nfft)
-        # print tmp
+        # print tmp
         return tmp
 
-    def _calc_tsrun(self, tsr, comp, igrid=None):
+    def _calc_tsrun(self, tsr, comp, igrid=None):
         igrid = igrid or self.igrid or tsr.grid.ihub
-        return tsr.grid.f, tsr.spec[comp][igrid]
+        return tsr.grid.f, tsr.spec[comp][igrid]
+ -
[docs]class cohere(axesForm): """ A 'coherence' plotting format for showing coherence between two @@ -352,20 +353,20 @@

Source code for pyts.plot.axform

     :class:`axesForm`
     """
     hrel = 1
-    _title = 'coherence'
-    xax = 'freq'
-    yax = 'coh'
-    _xlabel = '$f\,\mathrm{[Hz]}$'
+    _title = 'coherence'
+    xax = 'freq'
+    yax = 'coh'
+    _xlabel = '$f\,\mathrm{[Hz]}$'
 
-    def __init__(self, window_time_sec=600, igrid0=None, igrid1=None,
-                 xscale='log', ylim=[0, 1],
+    def __init__(self, window_time_sec=600, igrid0=None, igrid1=None,
+                 xscale='log', ylim=[0, 1],
                  **kwargs):
-        axesForm.__init__(self, xscale=xscale, ylim=ylim, **kwargs)
+        axesForm.__init__(self, xscale=xscale, ylim=ylim, **kwargs)
         self.window_time = 600
         self.igrid0 = igrid0
         self.igrid1 = igrid1
 
-    def _calc_tsdata(self, tsdat, comp, igrid0=None, igrid1=None):
+    def _calc_tsdata(self, tsdat, comp, igrid0=None, igrid1=None):
         nfft = int(self.window_time / tsdat.dt)
         nfft += np.mod(nfft, 2)
         igrid0 = igrid0 or self.igrid0 or tsdat.ihub
@@ -374,15 +375,15 @@ 

Source code for pyts.plot.axform

                        tsdat.uturb[comp][igrid1],
                        1. / tsdat.dt, nfft)
 
-    def _calc_tsrun(self, tsr, comp, igrid0=None, igrid1=None):
+    def _calc_tsrun(self, tsr, comp, igrid0=None, igrid1=None):
         igrid0 = tsr.grid.sub2ind(igrid0 or self.igrid0 or tsr.grid.ihub)
         igrid1 = tsr.grid.sub2ind(igrid1 or self.igrid1 or (0, 0))
         return tsr.grid.f, tsr.cohere.calcCoh(tsr.grid.f,
-                                              comp, igrid0, igrid1) ** 2
+                                              comp, igrid0, igrid1) ** 2
+ -
[docs]class FigAxForm(supax.sfig): - """The 'figure' class that uses and handles :class:`axesForm`s. + """The 'figure' class that uses and handles :class:`axesForm`. Parameters ---------- @@ -421,7 +422,7 @@

Source code for pyts.plot.axform

     def __init__(self,
                  fignum,
                  axforms=[],
-                 comp=['u', 'v', 'w'],
+                 comp=['u', 'v', 'w'],
                  axsize=2,
                  frame=[.6, .3, 1, .3],
                  gap=[.2, 1],
@@ -429,8 +430,8 @@ 

Source code for pyts.plot.axform

                  **kwargs):
 
         if len(axforms) == 0:
-            raise Exception('At least one axes-type \
-            instance must be provided.')
+            raise Exception('At least one axes-type \
+            instance must be provided.')
 
         sharex = np.tile(np.arange(len(axforms), dtype=np.uint8) + 1,
                          (len(comp), 1))
@@ -439,19 +440,19 @@ 

Source code for pyts.plot.axform

 
         hspacer = supax.simpleAxSpacer(len(axforms), axsize, gap[1], frame[2:])
         vspacer = supax.simpleAxSpacer(len(comp), axsize, gap[0], frame[:2],
-                                       vertical=True)
+                                       vertical=True)
 
-        last_yax = None
+        last_yax = None
         for idx, axt in enumerate(axforms):
             if axt.yax == last_yax:
                 sharey[:, idx] = sharey[:, idx - 1]
                 hspacer.gap[idx] = tightgap
-                axt.hide_ylabels = True
+                axt.hide_ylabels = True
             last_yax = axt.yax
-            if hasattr(axt, 'hrel'):
+            if hasattr(axt, 'hrel'):
                 hspacer.axsize[idx] *= axt.hrel
         axp = supax.axPlacer(vspacer, hspacer)
-        supax.sfig.__init__(self, fignum, axp,
+        supax.sfig.__init__(self, fignum, axp,
                             sharex=sharex, sharey=sharey, **kwargs)
         self.comp = comp
         for idx, axt in enumerate(axforms):
@@ -469,8 +470,8 @@ 

Source code for pyts.plot.axform

               A data or turbsim object to plot.
         """
         for idx, axt in enumerate(self.axforms):
-            axt.plot(obj, self.sax[:, idx], **kwargs)
-
+ axt.plot(obj, self.sax[:, idx], **kwargs)
+
[docs] def finalize(self,): """ Finalize the figure according to the plotting formats. @@ -479,10 +480,10 @@

Source code for pyts.plot.axform

             axt.finalize(self.sax[:, idx])
         for c, ax in zip(self.comp, self.ax[:, 0]):
             p = ax.get_position().ymax
-            self.fig.text(0.02, p, '$' + c + '$', va='top', ha='left',
-                          size='x-large', backgroundcolor='w')
+            self.fig.text(0.02, p, '$' + c + '$', va='top', ha='left',
+                          size='x-large', backgroundcolor='w')
+ -
[docs]def summfig(fignum=400, axforms=[velprof(), spec(600)], **kwargs): return FigAxForm(fignum, axforms=axforms, **kwargs)
@@ -503,14 +504,11 @@

Related Topics

@@ -518,11 +516,11 @@

Quick search

diff --git a/docs/_modules/pyts/plot/psd.html b/docs/_modules/pyts/plot/psd.html index 3ddc2ac..3d7d699 100644 --- a/docs/_modules/pyts/plot/psd.html +++ b/docs/_modules/pyts/plot/psd.html @@ -1,38 +1,39 @@ + - - - pyts.plot.psd — PyTurbSim 0.4.7 documentation - + pyts.plot.psd — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,7 +41,7 @@

Source code for pyts.plot.psd

-import matplotlib as mpl
+import matplotlib as mpl
 
 
 
[docs]def psd(u, sr, nfft): @@ -65,9 +66,9 @@

Source code for pyts.plot.psd

     """
     p, f = mpl.mlab.psd(
         u, nfft, sr, detrend=mpl.pylab.detrend_linear, noverlap=nfft / 2)
-    return f[1:], p[1:]
+    return f[1:], p[1:]
+ -
[docs]def coh(u1, u2, sr, nfft): """ Helper function to compute the coherence between two signals. @@ -92,7 +93,7 @@

Source code for pyts.plot.psd

     """
     p, f = mpl.mlab.cohere(u1, u2, nfft, sr,
                            detrend=mpl.pylab.detrend_linear,
-                           noverlap=nfft / 2, scale_by_freq=False)
+                           noverlap=nfft / 2, scale_by_freq=False)
     return f[1:], p[1:]
@@ -112,14 +113,11 @@

Related Topics

@@ -127,11 +125,11 @@

Quick search

diff --git a/docs/_modules/pyts/plot/superaxes.html b/docs/_modules/pyts/plot/superaxes.html index 7c9d903..aead0fc 100644 --- a/docs/_modules/pyts/plot/superaxes.html +++ b/docs/_modules/pyts/plot/superaxes.html @@ -1,38 +1,39 @@ + - - - pyts.plot.superaxes — PyTurbSim 0.4.7 documentation - + pyts.plot.superaxes — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,40 +41,40 @@

Source code for pyts.plot.superaxes

-import matplotlib as mpl
-import numpy as np
+import matplotlib as mpl
+import numpy as np
 import new
-import matplotlib.pylab as pylab
+import matplotlib.pylab as pylab
 transforms = mpl.transforms
 Axes = mpl.axes.Axes
 rcParams = mpl.rcParams
-import _basefuncs as bf
-# try:
-# import pyPdf as pdf
-# except:
-# pdf=None
+import _basefuncs as bf
+# try:
+# import pyPdf as pdf
+# except:
+# pdf=None
 
 
-
[docs]def skip_ticklabels(ax, rep=2, offset=0, axis='x', force=True): +
[docs]def skip_ticklabels(ax, rep=2, offset=0, axis='x', force=True): """ hide the ticklabels on ticks except for every *rep*'th tick. *offset* specifies an offset, of tick to start on. *axis* specifies the x (default) or y axis. when *force* is True (default) this function turns on every *rep*'th tick. """ - if axis == 'x': + if axis == 'x': tks = ax.get_xticklabels() else: tks = ax.get_yticklabels() for idx, tk in enumerate(tks): if np.mod(idx + offset, rep): - tk.set_visible(False) + tk.set_visible(False) elif force: - tk.set_visible(True) + tk.set_visible(True)
+ +# class myAxes(matplotlib.axes.Axes): -# class myAxes(matplotlib.axes.Axes): -
[docs]class myaxes(mpl.axes.Axes): """ @@ -92,29 +93,29 @@

Source code for pyts.plot.superaxes

             self.transData, self.transAxes)
 
 
[docs] def plot(self, *args, **kwargs): - # This just makes sure that my lines get drawn, - # otherwise it just calls the axes' plot instance. + # This just makes sure that my lines get drawn, + # otherwise it just calls the axes' plot instance. super(myaxes, self).plot(*args, **kwargs) - pylab.draw_if_interactive() -
+ pylab.draw_if_interactive()
+ skip_ticklabels = skip_ticklabels labelax = bf.labelax - #cbar = bf.cbar + #cbar = bf.cbar offset_text = bf.offset_text annoteCorner = bf.annoteCorner setaxesframe = bf._setaxesframe errorshadex = bf.errorshadex - def __init__(self, fig=None, rect=None, **kwargs): - if fig is None: + def __init__(self, fig=None, rect=None, **kwargs): + if fig is None: fig = pylab.gcf() - if rect is None: + if rect is None: rect = [.15, .15, .75, .75] - super(myaxes, self).__init__(fig, rect, **kwargs) + super(myaxes, self).__init__(fig, rect, **kwargs) fig.add_axes(self) - pylab.draw_if_interactive() + pylab.draw_if_interactive()
+ -
[docs]def axes(*args, **kwargs): """ Add an axes at position rect specified by: @@ -153,26 +154,26 @@

Source code for pyts.plot.superaxes

     if nargs == 0:
         args = [[.1, .1, .8, .8]]
     if nargs > 1:
-        raise TypeError('Only one non keyword arg to axes allowed')
+        raise TypeError('Only one non keyword arg to axes allowed')
     arg = args[0]
 
     axd = {}
     newd = {}
-    newd['lw'] = rcParams['axes.linewidth']
+    newd['lw'] = rcParams['axes.linewidth']
     try:
-        axd['axisbg'] = kwargs.pop('axisbg')
+        axd['axisbg'] = kwargs.pop('axisbg')
     except:
         pass
-    for nm in ['axisbg', 'frameon', 'sharex', 'sharey', 'polar', ]:
+    for nm in ['axisbg', 'frameon', 'sharex', 'sharey', 'polar', ]:
         if nm in kwargs.keys():
             axd[nm] = kwargs.pop(nm)
-    if 'ticksize' in kwargs.keys():
-        newd['xticksize'] = kwargs.get('ticksize')
-        newd['yticksize'] = kwargs.pop('ticksize')
-    for nm in [('lw', 'linewidth'), 'linewidth', 'xticksize',
-               'yticksize', ('fs', 'fontsize'), 'fontsize',
-               'xlocation', 'ylocation']:
-        if nm.__class__ is tuple:
+    if 'ticksize' in kwargs.keys():
+        newd['xticksize'] = kwargs.get('ticksize')
+        newd['yticksize'] = kwargs.pop('ticksize')
+    for nm in [('lw', 'linewidth'), 'linewidth', 'xticksize',
+               'yticksize', ('fs', 'fontsize'), 'fontsize',
+               'xlocation', 'ylocation']:
+        if nm.__class__ is tuple:
             ky = nm[0]
             nm = nm[1]
         else:
@@ -180,12 +181,12 @@ 

Source code for pyts.plot.superaxes

             nm = nm
         if ky in kwargs:
             newd[nm] = kwargs.pop(ky)
-    if ('fig' not in kwargs.keys()) and ('figure' not in kwargs.keys()):
+    if ('fig' not in kwargs.keys()) and ('figure' not in kwargs.keys()):
         fig = pylab.gcf()
-    elif 'figure' in kwargs.keys():
-        fig = kwargs.pop('figure')
+    elif 'figure' in kwargs.keys():
+        fig = kwargs.pop('figure')
     else:
-        fig = kwargs.pop('fig')
+        fig = kwargs.pop('fig')
 
     if isinstance(arg, mpl.axes.Axes):
         a = fig.sca(arg)
@@ -194,36 +195,36 @@ 

Source code for pyts.plot.superaxes

         a = fig.add_axes(rect, **axd)
         a.set(**kwargs)
 
-        if 'xlocation' in newd.keys():
-            a.xaxis.set_ticks_position(newd['xlocation'])
-            if newd['xlocation'] == 'top':
-                a.spines['bottom'].set_visible(False)
-            elif newd['xlocation'] == 'bottom':
-                a.spines['top'].set_visible(False)
-        if 'ylocation' in newd.keys():
-            a.yaxis.set_ticks_position(newd['ylocation'])
-            if newd['ylocation'] == 'right':
-                a.spines['left'].set_visible(False)
-            elif newd['ylocation'] == 'left':
-                a.spines['right'].set_visible(False)
-        if 'lw' in newd.keys():
+        if 'xlocation' in newd.keys():
+            a.xaxis.set_ticks_position(newd['xlocation'])
+            if newd['xlocation'] == 'top':
+                a.spines['bottom'].set_visible(False)
+            elif newd['xlocation'] == 'bottom':
+                a.spines['top'].set_visible(False)
+        if 'ylocation' in newd.keys():
+            a.yaxis.set_ticks_position(newd['ylocation'])
+            if newd['ylocation'] == 'right':
+                a.spines['left'].set_visible(False)
+            elif newd['ylocation'] == 'left':
+                a.spines['right'].set_visible(False)
+        if 'lw' in newd.keys():
             for sp in a.spines:
-                a.spines[sp].set_linewidth(newd['lw'])
+                a.spines[sp].set_linewidth(newd['lw'])
             for tck in a.xaxis.get_ticklines():
-                tck.set_mew(newd['lw'])
+                tck.set_mew(newd['lw'])
             for tck in a.yaxis.get_ticklines():
-                tck.set_mew(newd['lw'])
-        if 'xticksize' in newd.keys():
+                tck.set_mew(newd['lw'])
+        if 'xticksize' in newd.keys():
             for tck in a.xaxis.get_ticklines():
-                tck.set_ms(newd['xticksize'])
-        if 'yticksize' in newd.keys():
+                tck.set_ms(newd['xticksize'])
+        if 'yticksize' in newd.keys():
             for tck in a.yaxis.get_ticklines():
-                tck.set_ms(newd['yticksize'])
-        if 'fontsize' in newd.keys():
+                tck.set_ms(newd['yticksize'])
+        if 'fontsize' in newd.keys():
             for tklbl in a.xaxis.get_ticklabels():
-                tklbl.set_fontsize(newd['fontsize'])
+                tklbl.set_fontsize(newd['fontsize'])
             for tklbl in a.yaxis.get_ticklabels():
-                tklbl.set_fontsize(newd['fontsize'])
+                tklbl.set_fontsize(newd['fontsize'])
 
     a.transAxesXDataY = transforms.blended_transform_factory(
         a.transAxes, a.transData)
@@ -239,12 +240,12 @@ 

Source code for pyts.plot.superaxes

     a.labelax = new.instancemethod(bf.labelax, a, Axes)
     a.skip_ticklabels = new.instancemethod(skip_ticklabels, a, Axes)
     a.errorshadex = new.instancemethod(bf.errorshadex, a, Axes)
-    # a.plot_specobj=new.instancemethod(plot_specobj,a,Axes)
+    # a.plot_specobj=new.instancemethod(plot_specobj,a,Axes)
 
     pylab.draw_if_interactive()
-    return a
+    return a
+ -
[docs]class axgroup(object): alphNumAxes = bf.alphNumAxes @@ -269,114 +270,114 @@

Source code for pyts.plot.superaxes

 
 
[docs] def annotate(self, *args, **kwargs): for ax in self: - ax.annotate(*args, **kwargs) -
+ ax.annotate(*args, **kwargs)
+ def __getitem__(self, val): - if hasattr(val, '__len__'): + if hasattr(val, '__len__'): for v in val: - if v.__class__ is slice: + if v.__class__ is slice: return axgroup(self.axes[val]) - elif val.__class__ is slice: + elif val.__class__ is slice: return axgroup(self.axes[val]) return self.axes[val] -
[docs] def xgrid(self, b=None, **kwargs): +
[docs] def xgrid(self, b=None, **kwargs): for ax in self: - ax.xaxis.grid(b, **kwargs) -
-
[docs] def ygrid(self, b=None, **kwargs): + ax.xaxis.grid(b, **kwargs)
+ +
[docs] def ygrid(self, b=None, **kwargs): for ax in self: - ax.yaxis.grid(b, **kwargs) -
+ ax.yaxis.grid(b, **kwargs)
+
[docs] def shadex(self, *args, **kwargs): for ax in self: - ax.shadex(*args, **kwargs) -
+ ax.shadex(*args, **kwargs)
+
[docs] def shadey(self, *args, **kwargs): for ax in self: - ax.shadey(*args, **kwargs) -
+ ax.shadey(*args, **kwargs)
+
[docs] def hln(self, y=0, *args, **kwargs): for ax in self: - ax.hln(y, *args, **kwargs) -
+ ax.hln(y, *args, **kwargs)
+
[docs] def vln(self, x=0, *args, **kwargs): for ax in self: - ax.vln(x, *args, **kwargs) -
+ ax.vln(x, *args, **kwargs)
+
[docs] def fill_between(self, *args, **kwargs): """ Iterates a fill_between call over all axes in the group. See fill_between """ for ax in self: - ax.fill_between(*args, **kwargs) -
+ ax.fill_between(*args, **kwargs)
+
[docs] def fill_betweenx(self, *args, **kwargs): """ Iterates a fill_betweenx call over all axes in the group. See fill_betweenx """ for ax in self: - ax.fill_betweenx(*args, **kwargs) -
+ ax.fill_betweenx(*args, **kwargs)
+
[docs] def set_xscale(self, val): for ax in self: - ax.set_xscale(val) -
+ ax.set_xscale(val)
+
[docs] def set_yscale(self, val): for ax in self: - ax.set_yscale(val) -
+ ax.set_yscale(val)
+
[docs] def set_xlim(self, *args, **kwargs): for ax in self: - ax.set_xlim(*args, **kwargs) -
+ ax.set_xlim(*args, **kwargs)
+
[docs] def set_ylim(self, *args, **kwargs): for ax in self: - ax.set_ylim(*args, **kwargs) -
+ ax.set_ylim(*args, **kwargs)
+
[docs] def set_xticks(self, *args, **kwargs): for ax in self: - ax.set_xticks(*args, **kwargs) -
+ ax.set_xticks(*args, **kwargs)
+
[docs] def set_yticks(self, *args, **kwargs): for ax in self: - ax.set_yticks(*args, **kwargs) -
+ ax.set_yticks(*args, **kwargs)
+
[docs] def set_ylabel(self, lbls, *args, **kwargs): - if lbls.__class__ is not list: + if lbls.__class__ is not list: lbls = list(lbls) if len(lbls) == 1: lbls = lbls * len(self) for ax, lbl in zip(self, lbls): - ax.set_ylabel(lbl, *args, **kwargs) -
+ ax.set_ylabel(lbl, *args, **kwargs)
+
[docs] def set_xlabel(self, lbls, *args, **kwargs): - if lbls.__class__ is not list: + if lbls.__class__ is not list: lbls = list(lbls) if len(lbls) == 1: lbls = lbls * len(self) for ax, lbl in zip(self, lbls): - ax.set_xlabel(lbl, *args, **kwargs) -
+ ax.set_xlabel(lbl, *args, **kwargs)
+ def __init__(self, axes): self.axes = axes
[docs] def iterplot(self, iter, *args, **kwargs): for ax, (dat) in zip(self, iter): tmp = list(dat) + list(args) - ax.plot(*tmp, **kwargs) -
+ ax.plot(*tmp, **kwargs)
+
[docs] def plot(self, *args, **kwargs): for ax in self: - ax.plot(*args, **kwargs) -
+ ax.plot(*args, **kwargs)
+
[docs] def offset_text(self, x, y, s, offset=(0, 0), *args, **kwargs): for ax in self: - ax.offset_text(x, y, s, offset=offset, *args, **kwargs) -
-
[docs] def hide(self, objs='xticklabels', ax=None): + ax.offset_text(x, y, s, offset=offset, *args, **kwargs)
+ +
[docs] def hide(self, objs='xticklabels', ax=None): """ Hide `objs` on all axes of this group *except* for those specified in `ax`. @@ -401,68 +402,68 @@

Source code for pyts.plot.superaxes

         antiset
 
         """
-        if objs.__class__ is str:
+        if objs.__class__ is str:
             objs = [objs]
-        types = {'x': ['xticklabels', 'minorxticks'],
-                 'y': ['yticklabels', 'minoryticks']}
+        types = {'x': ['xticklabels', 'minorxticks'],
+                 'y': ['yticklabels', 'minoryticks']}
         for obj in objs:
-            if ax.__class__ is str and ax == 'all':
+            if ax.__class__ is str and ax == 'all':
                 axs = self.ax.flatten()
             else:
-                if ax is None:
-                    if obj in types['x'] and hasattr(self, '_xlabel_ax'):
+                if ax is None:
+                    if obj in types['x'] and hasattr(self, '_xlabel_ax'):
                         ax = self._xlabel_ax
-                    elif obj in types['y'] and hasattr(self, '_ylabel_ax'):
+                    elif obj in types['y'] and hasattr(self, '_ylabel_ax'):
                         ax = self._ylabel_ax
-                    else:  # This gives default behavior?
+                    else:  # This gives default behavior?
                         ax = []
-                if not hasattr(ax, '__len__'):
+                if not hasattr(ax, '__len__'):
                     ax = [ax]
                 axs = list(set(self.ax.flatten()) - set(ax))
             for axn in axs:
-                if obj == 'xticklabels':
-                    pylab.setp(axn.get_xticklabels(), visible=False)
-                elif obj == 'yticklabels':
-                    pylab.setp(axn.get_yticklabels(), visible=False)
-                elif obj == 'minorxticks':
-                    pylab.setp(axn.xaxis.get_minorticklines(), visible=False)
-                elif obj == 'minoryticks':
-                    pylab.setp(axn.yaxis.get_minorticklines(), visible=False)
+                if obj == 'xticklabels':
+                    pylab.setp(axn.get_xticklabels(), visible=False)
+                elif obj == 'yticklabels':
+                    pylab.setp(axn.get_yticklabels(), visible=False)
+                elif obj == 'minorxticks':
+                    pylab.setp(axn.xaxis.get_minorticklines(), visible=False)
+                elif obj == 'minoryticks':
+                    pylab.setp(axn.yaxis.get_minorticklines(), visible=False)
                 else:
-                    error
-
+ error
+
[docs] def set(self, **kwargs): - pylab.setp(self.ax.flatten(), **kwargs) -
+ pylab.setp(self.ax.flatten(), **kwargs)
+
[docs] def antiset(self, ax, **kwargs): - # Some backwards compatability stuff: - if 'xticklabels' in kwargs.keys() and kwargs['xticklabels'] == '': - kwargs.pop('xticklabels') - self.hide('xticklabels', ax) - if 'yticklabels' in kwargs.keys() and kwargs['yticklabels'] == '': - kwargs.pop('yticklabels') - self.hide('yticklabels', ax) - if 'minorxticks' in kwargs.keys() and not kwargs['minorxticks']: - kwargs.pop('minorxticks') - self.hide('minorxticks', ax) - if 'minoryticks' in kwargs.keys() and not kwargs['minoryticks']: - kwargs.pop('minoryticks', ax) - self.hide('minoryticks', ax) + # Some backwards compatability stuff: + if 'xticklabels' in kwargs.keys() and kwargs['xticklabels'] == '': + kwargs.pop('xticklabels') + self.hide('xticklabels', ax) + if 'yticklabels' in kwargs.keys() and kwargs['yticklabels'] == '': + kwargs.pop('yticklabels') + self.hide('yticklabels', ax) + if 'minorxticks' in kwargs.keys() and not kwargs['minorxticks']: + kwargs.pop('minorxticks') + self.hide('minorxticks', ax) + if 'minoryticks' in kwargs.keys() and not kwargs['minoryticks']: + kwargs.pop('minoryticks', ax) + self.hide('minoryticks', ax) if len(kwargs) == 0: return - # The meat: - if not hasattr(ax, '__len__'): + # The meat: + if not hasattr(ax, '__len__'): ax = [ax] - pylab.setp(list(set(self.ax.flatten()) - set(ax)), **kwargs) + pylab.setp(list(set(self.ax.flatten()) - set(ax)), **kwargs)
+ -
[docs]class axSharer(object):
[docs] def map_vals(self,): - return set(self.map.flatten()) -
- def __init__(self, saxes, share_map=False): + return set(self.map.flatten())
+ + def __init__(self, saxes, share_map=False): self.saxes = saxes self.map = np.zeros(saxes.n, dtype=np.uint16) self.map[:] = share_map @@ -490,22 +491,22 @@

Source code for pyts.plot.superaxes

                   has not yet been created that it matches.
         """
         mapVal = self.map[iv, ih]
-        if not mapVal:  # mapVal==0 do not share axes.
+        if not mapVal:  # mapVal==0 do not share axes.
             return
         elif mapVal in self._share_ax:
-            # The mapVal is already in the _share_ax dictionary
+            # The mapVal is already in the _share_ax dictionary
             return self._share_ax[mapVal]
         else:
             axs = self.saxes.axes[self.map == mapVal]
             if np.any(axs):
-                # An axis for this mapVal has been created. Add it to
-                # the _share_ax dict.
+                # An axis for this mapVal has been created. Add it to
+                # the _share_ax dict.
                 self._share_ax[mapVal] = axs[np.nonzero(axs)][0]
                 return self._share_ax[mapVal]
-            else:  # No axis exists yet for this mapVal.
-                return
+            else:  # No axis exists yet for this mapVal.
+                return
+ -
[docs]class axSpacer(object): """ @@ -535,7 +536,7 @@

Source code for pyts.plot.superaxes

         """
         return self.axsize / self.totsize
 
-    @axsize_.setter
+    @axsize_.setter
     def axsize_(self, val):
         self.axsize = val * self.totsize
 
@@ -546,7 +547,7 @@ 

Source code for pyts.plot.superaxes

         """
         return self.gap / self.totsize
 
-    @gap_.setter
+    @gap_.setter
     def gap_(self, val):
         self.gap = val * self.totsize
 
@@ -567,10 +568,10 @@ 

Source code for pyts.plot.superaxes

     def __len__(self,):
         return self.n
 
-    def __init__(self, axsize=[1, 1], gap=[.7, .2, .2], vertical=False):
+    def __init__(self, axsize=[1, 1], gap=[.7, .2, .2], vertical=False):
         self.axsize = axsize
         self.gap = gap
-        # self.units=units # Add support for units other than inches.
+        # self.units=units # Add support for units other than inches.
         self.vertical = vertical
 
     @property
@@ -580,7 +581,7 @@ 

Source code for pyts.plot.superaxes

         """
         return self.__axsize
 
-    @axsize.setter
+    @axsize.setter
     def axsize(self, val):
         self.__axsize = np.array(val)
 
@@ -591,7 +592,7 @@ 

Source code for pyts.plot.superaxes

         """
         return self.__gap
 
-    @gap.setter
+    @gap.setter
     def gap(self, val):
         self.__gap = np.array(val)
 
@@ -610,7 +611,7 @@ 

Source code for pyts.plot.superaxes

     def totsize(self,):
         return self.axsize.sum() + self.gap.sum()
 
-    @totsize.setter
+    @totsize.setter
     def totsize(self, val):
         self.__axsize *= val / self.totsize
         self.__gap *= val / self.totsize
@@ -620,10 +621,10 @@ 

Source code for pyts.plot.superaxes

         """
         The bounding 'frame' around the axes, in inches.
         """
-        return self.gap[[0, -1]]
+        return self.gap[[0, -1]]
-
-
[docs]def axvec2axSpacer(n, vec, vertflag, rel=False): + +
[docs]def axvec2axSpacer(n, vec, vertflag, rel=False): """ Returns an :class:`axSpacer` corresponding to the `n` axes based on the axes vector `vec`. @@ -654,18 +655,18 @@

Source code for pyts.plot.superaxes

     The units of the returned axSpacer match that of the input `vec`.
 
     """
-    if rel.__class__ is False.__class__ and not rel:
-        # Default value.
+    if rel.__class__ is False.__class__ and not rel:
+        # Default value.
         rel = np.ones(n)
     wd = (((vec[1] - vec[0]) + vec[2]) / n - vec[2]) * rel / rel.mean()
     gap = np.empty((len(wd) + 1), dtype=wd.dtype)
     gap[0] = vec[0]
     gap[1:-1] = vec[2]
     gap[-1] = vec[1]
-    return axSpacer(wd, gap, vertflag)
+    return axSpacer(wd, gap, vertflag)
-
-
[docs]def simpleAxSpacer(n, axsize, gap, frm=np.array([.5, .5]), vertical=False): + +
[docs]def simpleAxSpacer(n, axsize, gap, frm=np.array([.5, .5]), vertical=False): """ calculates the width (or height) of a figure with *n* subplots. Specify the width (height) of each subplot with *ax[0]*, the space @@ -677,9 +678,9 @@

Source code for pyts.plot.superaxes

     gap = np.ones(n + 1) * gap
     gap[0] = frm[0]
     gap[-1] = frm[1]
-    return axSpacer(np.ones(n) * axsize, gap, vertical=vertical)
+    return axSpacer(np.ones(n) * axsize, gap, vertical=vertical)
+ -
[docs]class axPlacer(object): """ @@ -702,8 +703,8 @@

Source code for pyts.plot.superaxes

         return (self.hSpacer.pos_[ih],
                 self.vSpacer.pos_[iv],
                 self.hSpacer.axsize_[ih],
-                self.vSpacer.axsize_[iv])
-
+ self.vSpacer.axsize_[iv])
+ @property def figSize(self,): """ @@ -722,15 +723,15 @@

Source code for pyts.plot.superaxes

         Returns a list of location tuples (left, bottom, width,
         height) for axes objects.
         """
-        return list(self.__iter__())
+        return list(self.__iter__())
 
     def __init__(self, vSpacer, hSpacer):
         if not vSpacer.vertical:
-            raise Exception("The vSpacer must have property `vertical`=True")
+            raise Exception("The vSpacer must have property `vertical`=True")
         self.vSpacer = vSpacer
-        self.hSpacer = hSpacer
+        self.hSpacer = hSpacer
+ -
[docs]class saxes_szr(axgroup): @property @@ -738,35 +739,35 @@

Source code for pyts.plot.superaxes

         return self.axPlacer.n
 
     def __init__(self, axPlacer, **kwargs):
-        self.axes = np.empty(axPlacer.n, dtype='object')
-        self.linewidth = kwargs.pop('linewidth', rcParams['axes.linewidth'])
+        self.axes = np.empty(axPlacer.n, dtype='object')
+        self.linewidth = kwargs.pop('linewidth', rcParams['axes.linewidth'])
         self.axPlacer = axPlacer
-        self.sharex = axSharer(self, kwargs.pop('sharex', False))
-        self.sharey = axSharer(self, kwargs.pop('sharey', False))
-        self.drawax = np.ones(axPlacer.n, dtype='bool')
+        self.sharex = axSharer(self, kwargs.pop('sharex', False))
+        self.sharey = axSharer(self, kwargs.pop('sharey', False))
+        self.drawax = np.ones(axPlacer.n, dtype='bool')
         for key in kwargs:
             setattr(self, key, kwargs[key])
 
-
[docs] def set_ylabel_pos(self, pos, axs=None,): - if axs is None: +
[docs] def set_ylabel_pos(self, pos, axs=None,): + if axs is None: axs = self.ax.flatten() for ax in axs: - ax.yaxis.set_label_coords(pos, 0.5) -
+ ax.yaxis.set_label_coords(pos, 0.5)
+
[docs] def xlabel(self, *args, **kwargs): """ This is different than 'set_xlabel' because it sets the xlabel only for the 'self._xlabel_ax'. """ - self._xlabel_ax.set_xlabel(*args, **kwargs) -
+ self._xlabel_ax.set_xlabel(*args, **kwargs)
+
[docs] def ylabel(self, *args, **kwargs): """ This is different than 'set_ylabel' because it sets the ylabel only for the 'self._ylabel_ax'. """ - self._ylabel_ax.set_ylabel(*args, **kwargs) -
+ self._ylabel_ax.set_ylabel(*args, **kwargs)
+ def _iter_axinds(self,): for iv in range(self.n[0]): for ih in range(self.n[1]): @@ -774,18 +775,18 @@

Source code for pyts.plot.superaxes

 
 
[docs] def drawall(self, **kwargs): if not self.n == self.drawax.shape: - self.drawax = np.ones(self.n, dtype='bool') - if 'lw' in kwargs.keys(): - kwargs['linewidth'] = kwargs.pop('lw', self.linewidth) - if 'linewidth' not in kwargs.keys(): - kwargs['linewidth'] = self.linewidth + self.drawax = np.ones(self.n, dtype='bool') + if 'lw' in kwargs.keys(): + kwargs['linewidth'] = kwargs.pop('lw', self.linewidth) + if 'linewidth' not in kwargs.keys(): + kwargs['linewidth'] = self.linewidth else: - self.linewidth = kwargs['linewidth'] + self.linewidth = kwargs['linewidth'] inter = pylab.isinteractive() - pylab.interactive(False) - # wait to draw the axes, until they've all been - # created. + pylab.interactive(False) + # wait to draw the axes, until they've all been + # created. for iv, ih in self._iter_axinds(): if self.drawax[iv, ih]: self.ax[iv, ih] = axes(self.axPlacer(iv, ih), @@ -796,9 +797,9 @@

Source code for pyts.plot.superaxes

         self._ylabel_ax = self._xlabel_ax
         pylab.interactive(inter)
         pylab.draw_if_interactive()
-        return self.ax
+        return self.ax
+ -
[docs]class saxes(saxes_szr): """ @@ -829,36 +830,36 @@

Source code for pyts.plot.superaxes

     sharey=True, chooses whether the axes share a yaxis.
 
     """
-    n = None  # Override the property above.
+    n = None  # Override the property above.
 
-    def __init__(self, n=(1, 1), h=[.1, .9, .05], v=[.1, .9, .05], **kwargs):
-        self.linewidth = rcParams['axes.linewidth']
+    def __init__(self, n=(1, 1), h=[.1, .9, .05], v=[.1, .9, .05], **kwargs):
+        self.linewidth = rcParams['axes.linewidth']
         nax = [1, 1]
-        if hasattr(n[0], '__iter__'):
+        if hasattr(n[0], '__iter__'):
             nax[0] = len(n[0])
-            self.vrel = np.array(n[0], dtype='float32')
+            self.vrel = np.array(n[0], dtype='float32')
         else:
             nax[0] = n[0]
-            self.vrel = np.ones(n[0], dtype='float32')
-        if hasattr(n[1], '__iter__'):
+            self.vrel = np.ones(n[0], dtype='float32')
+        if hasattr(n[1], '__iter__'):
             nax[1] = len(n[1])
-            self.hrel = np.array(n[1], dtype='float32')
+            self.hrel = np.array(n[1], dtype='float32')
         else:
             nax[1] = n[1]
-            self.hrel = np.ones(n[1], dtype='float32')
+            self.hrel = np.ones(n[1], dtype='float32')
         self.n = nax
         self.h = h
         self.v = v
-        self.sharex = np.ones(nax, dtype='int8')
-        self.sharey = np.ones(nax, dtype='int8')
-        self._sharex_ax = np.empty(16, dtype='object')
-        self._sharey_ax = np.empty(16, dtype='object')
-        self.axes = np.empty(self.n, dtype='object')
-        self.drawax = np.ones(nax, dtype='bool')
+        self.sharex = np.ones(nax, dtype='int8')
+        self.sharey = np.ones(nax, dtype='int8')
+        self._sharex_ax = np.empty(16, dtype='object')
+        self._sharey_ax = np.empty(16, dtype='object')
+        self.axes = np.empty(self.n, dtype='object')
+        self.drawax = np.ones(nax, dtype='bool')
         for key in kwargs:
-            if key == 'sharey' and kwargs[key].__class__ is bool:
+            if key == 'sharey' and kwargs[key].__class__ is bool:
                 self.sharey[:] = kwargs[key]
-            elif key == 'sharex' and kwargs[key].__class__ is bool:
+            elif key == 'sharex' and kwargs[key].__class__ is bool:
                 self.sharex[:] = kwargs[key]
             else:
                 setattr(self, key, kwargs[key])
@@ -870,53 +871,53 @@ 

Source code for pyts.plot.superaxes

                                                     rel=self.hrel)
         axg[:, :, 1], axg[:, :, 3] = bf.axvec2axpos(self.n[0],
                                                     self.v,
-                                                    True,
+                                                    True,
                                                     rel=self.vrel)
-        return axg
-
+ return axg
+
[docs] def drawall(self, **kwargs): if not self.n == self.drawax.shape: - self.drawax = np.ones(self.n, dtype='bool') + self.drawax = np.ones(self.n, dtype='bool') if not self.n[1] == self.hrel.shape[0]: - self.hrel = np.ones(self.n[1], dtype='float32') + self.hrel = np.ones(self.n[1], dtype='float32') if not self.n[0] == self.vrel.shape[0]: - self.vrel = np.ones(self.n[0], dtype='float32') - if 'lw' in kwargs.keys(): - kwargs['linewidth'] = kwargs.pop('lw', self.linewidth) - if 'linewidth' not in kwargs.keys(): - kwargs['linewidth'] = self.linewidth + self.vrel = np.ones(self.n[0], dtype='float32') + if 'lw' in kwargs.keys(): + kwargs['linewidth'] = kwargs.pop('lw', self.linewidth) + if 'linewidth' not in kwargs.keys(): + kwargs['linewidth'] = self.linewidth else: - self.linewidth = kwargs['linewidth'] - - forcesharex = False - forcesharey = False - if 'sharex' in kwargs.keys(): - forcesharex = True - if 'sharey' in kwargs.keys(): - forcesharey = True + self.linewidth = kwargs['linewidth'] + + forcesharex = False + forcesharey = False + if 'sharex' in kwargs.keys(): + forcesharex = True + if 'sharey' in kwargs.keys(): + forcesharey = True inter = pylab.isinteractive() - pylab.interactive(False) - # wait to draw the axes, until they've all been - # created. + pylab.interactive(False) + # wait to draw the axes, until they've all been + # created. axg = self.axgrid() for iv in range(self.n[0]): for ih in range(self.n[1]): - if forcesharex: # I should put this functionality into a func. + if forcesharex: # I should put this functionality into a func. pass elif (self.sharex[iv, ih] and self._sharex_ax[self.sharex[iv, ih]]): - kwargs['sharex'] = self._sharex_ax[self.sharex[iv, ih]] - elif 'sharex' in kwargs.keys(): - kwargs.pop('sharex') + kwargs['sharex'] = self._sharex_ax[self.sharex[iv, ih]] + elif 'sharex' in kwargs.keys(): + kwargs.pop('sharex') if forcesharey: pass elif (self.sharey[iv, ih] and self._sharey_ax[self.sharey[iv, ih]]): - kwargs['sharey'] = self._sharey_ax[self.sharey[iv, ih]] - elif 'sharey' in kwargs.keys(): - kwargs.pop('sharey') + kwargs['sharey'] = self._sharey_ax[self.sharey[iv, ih]] + elif 'sharey' in kwargs.keys(): + kwargs.pop('sharey') if self.drawax[iv, ih]: - # self.ax[iv,ih]=myaxes(axg[iv,ih,:],**kwargs) + # self.ax[iv,ih]=myaxes(axg[iv,ih,:],**kwargs) self.ax[iv, ih] = axes(axg[iv, ih, :], **kwargs) if self.sharex[iv, ih] and not\ self._sharex_ax[self.sharex[iv, ih]]: @@ -928,38 +929,38 @@

Source code for pyts.plot.superaxes

         self._ylabel_ax = self._xlabel_ax
         pylab.interactive(inter)
         pylab.draw_if_interactive()
-        return self.ax
+        return self.ax
+ -
[docs]class fig_meta(object): - title = None - author = u'Levi Kilcher' - script = None - producer = u'matplotlib ' + mpl.__version__ + ', http://matplotlib.sf.net' - description = None - keywords = None - _fields = ['title', 'author', 'script', - 'producer', 'description', 'keywords'] + title = None + author = u'Levi Kilcher' + script = None + producer = u'matplotlib ' + mpl.__version__ + ', http://matplotlib.sf.net' + description = None + keywords = None + _fields = ['title', 'author', 'script', + 'producer', 'description', 'keywords'] def __repr__(self,): - ostring = '<ptools.fig_meta object>\n' + ostring = '<ptools.fig_meta object>\n' for fld in self._fields: - ostring += '%16s' % (fld) + ' : ' + str(getattr(self, fld)) + '\n' + ostring += '%16s' % (fld) + ' : ' + str(getattr(self, fld)) + '\n' return ostring
[docs] def write_pdf(self, fname): - pass -
+ pass
+
[docs] def write(self, fname): - if fname.endswith('.pdf'): + if fname.endswith('.pdf'): self.write_pdf(fname) - elif fname.endswith('.svg'): + elif fname.endswith('.svg'): pass - # self.write_svg(fname) + # self.write_svg(fname) else: - pass + pass
+ -
[docs]class figobj(axgroup): """ @@ -1000,50 +1001,50 @@

Source code for pyts.plot.superaxes

 
 
[docs] def savefig(self, *args, **kwargs): self.fig.savefig(*args, **kwargs) - self.meta.write(args[0]) -
+ self.meta.write(args[0])
+
[docs] def sax_params(self, **kwargs): - return kwargs -
-
[docs] def saxes(self, nax=None, **kwargs): - if nax is None: + return kwargs
+ +
[docs] def saxes(self, nax=None, **kwargs): + if nax is None: nax = self.nax self.sax = saxes(nax, **self.sax_params(**kwargs)) self.sax.drawall() - self.axes = self.sax.ax.flatten() -
-
[docs] def initFig(self, fignum, nax=None, **kwargs): + self.axes = self.sax.ax.flatten()
+ +
[docs] def initFig(self, fignum, nax=None, **kwargs): figkws = {} - figkws['figsize'] = kwargs.pop('figsize', None) + figkws['figsize'] = kwargs.pop('figsize', None) self.fig = pylab.figure(fignum, **figkws) - if figkws['figsize'] is not None: - self.fig.set_size_inches(figkws['figsize'], forward=True) + if figkws['figsize'] is not None: + self.fig.set_size_inches(figkws['figsize'], forward=True) self.clf = self.fig.clf self.clf() - if 'title' in kwargs.keys(): + if 'title' in kwargs.keys(): self.fig.canvas.set_window_title( - 'Fg%d: ' % (self.fig.number) + kwargs['title']) -
- def __init__(self, fignum, nax=None, axsize=None, + 'Fg%d: ' % (self.fig.number) + kwargs['title'])
+ + def __init__(self, fignum, nax=None, axsize=None, frame=[.6, .3, 1, .3], gap=.4, **kwargs): saxparams = {} - if nax is None: + if nax is None: nax = [1, 1] - if 'vrel' in kwargs.keys(): - nax[0] = saxparams['vrel'] = kwargs['vrel'] + if 'vrel' in kwargs.keys(): + nax[0] = saxparams['vrel'] = kwargs['vrel'] self.meta = fig_meta() - if axsize is not None: + if axsize is not None: axsize = bf.pair(axsize) gap = bf.pair(gap) - kwargs['figsize'] = np.zeros(2) - kwargs['figsize'][0], saxparams['h'] = bf.calcFigSize( + kwargs['figsize'] = np.zeros(2) + kwargs['figsize'][0], saxparams['h'] = bf.calcFigSize( nax[1], ax=[axsize[1], gap[1]], frm=frame[2:]) - kwargs['figsize'][1], saxparams['v'] = bf.calcFigSize( + kwargs['figsize'][1], saxparams['v'] = bf.calcFigSize( nax[0], ax=[axsize[0], gap[0]], frm=frame[:2]) - saxparams['sharex'] = kwargs.pop('sharex', True) - saxparams['sharey'] = kwargs.pop('sharey', False) - if 'saxparams' in kwargs.keys(): - saxparams.update(**kwargs.pop('saxparams')) + saxparams['sharex'] = kwargs.pop('sharex', True) + saxparams['sharey'] = kwargs.pop('sharey', False) + if 'saxparams' in kwargs.keys(): + saxparams.update(**kwargs.pop('saxparams')) self.initFig(fignum, **kwargs) self.saxes(nax=nax, **saxparams) @@ -1051,14 +1052,14 @@

Source code for pyts.plot.superaxes

         return self
 
     def __exit__(self, type, value, trace):
-        pass
+        pass
+ -
[docs]class sfig(axgroup):
[docs] def clf(self): - self.fig.clf() -
+ self.fig.clf()
+ @property def axes(self,): return self.sax.axes @@ -1070,9 +1071,9 @@

Source code for pyts.plot.superaxes

     def __init__(self, fignum, axPlacer, **kwargs):
         self.meta = fig_meta()
         self.fig = pylab.figure(fignum, figsize=axPlacer.figSize)
-        if 'title' in kwargs.keys():
+        if 'title' in kwargs.keys():
             self.fig.canvas.set_window_title(
-                'Fg%d: ' % (self.fig.number) + kwargs['title'])
+                'Fg%d: ' % (self.fig.number) + kwargs['title'])
         self.clf()
         self.sax = saxes_szr(axPlacer, **kwargs)
         self.sax.drawall()
@@ -1094,14 +1095,11 @@

Related Topics

@@ -1109,11 +1107,11 @@

Quick search

diff --git a/docs/_modules/pyts/profModels/base.html b/docs/_modules/pyts/profModels/base.html index fb820e8..e7d5e1f 100644 --- a/docs/_modules/pyts/profModels/base.html +++ b/docs/_modules/pyts/profModels/base.html @@ -1,38 +1,39 @@ + - - - pyts.profModels.base — PyTurbSim 0.4.7 documentation - + pyts.profModels.base — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,11 +41,11 @@

Source code for pyts.profModels.base

-"""
+"""
 This is the velocity profile package's base module.
 
 """
-from ..base import np, gridProps, calcObj, modelBase, ts_float
+from ..base import np, gridProps, calcObj, modelBase, ts_float
 
 
 
[docs]class profObj(gridProps, calcObj): @@ -70,18 +71,18 @@

Source code for pyts.profModels.base

     def __init__(self, tsrun):
         self.grid = tsrun.grid
         self.array = np.zeros(
-            [3] + list(self.grid.shape), dtype=ts_float, order='F')
+            [3] + list(self.grid.shape), dtype=ts_float, order='F')
 
     @property
     def _dudz(self,):
         """
         This is a property for creating/returning the vertical shear.
         """
-        if not hasattr(self, '_val_dudz'):
+        if not hasattr(self, '_val_dudz'):
             self._val_dudz = np.concatenate(
-                ((self.array[:, 1] - self.array[:, 0])[:, None, :] / self.grid.dz,
+                ((self.array[:, 1] - self.array[:, 0])[:, None, :] / self.grid.dz,
                  (self.array[:, 2:] - self.array[:, :-2]) / (2 * self.grid.dz),
-                 (self.array[:, -1] - self.array[:, -2])[:, None, :] / self.grid.dz),
+                 (self.array[:, -1] - self.array[:, -2])[:, None, :] / self.grid.dz),
                 axis=1)
         return self._val_dudz
 
@@ -135,9 +136,9 @@ 

Source code for pyts.profModels.base

         The vertical derivative of the w-component of the mean velocity field.
         (Centered difference)
         """
-        return self._dudz[2]
+        return self._dudz[2]
+ -
[docs]class profModelBase(modelBase): """ @@ -162,14 +163,11 @@

Related Topics

@@ -177,11 +175,11 @@

Quick search

diff --git a/docs/_modules/pyts/profModels/iec.html b/docs/_modules/pyts/profModels/iec.html index 12be86e..d8593f4 100644 --- a/docs/_modules/pyts/profModels/iec.html +++ b/docs/_modules/pyts/profModels/iec.html @@ -1,38 +1,39 @@ + - - - pyts.profModels.iec — PyTurbSim 0.4.7 documentation - + pyts.profModels.iec — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,18 +41,18 @@

Source code for pyts.profModels.iec

-"""
+"""
 This module contains the power-law mean-velocity profiles:
  main   - The IEC mean wind speed profile.
 
 """
-from .base import profObj
-from .log import nwtc as logmain
-from .power import nwtc as powmain
-from numpy import tile, where
+from .base import profObj
+from .log import nwtc as logmain
+from .power import nwtc as powmain
+from numpy import tile, where
 
-# !!!VERSION_INCONSISTENCY
-# This model needs to account for the EWM50 and EWM1 turbulence models.
+# !!!VERSION_INCONSISTENCY
+# This model needs to account for the EWM50 and EWM1 turbulence models.
 
 
 
[docs]class main(powmain, logmain, ): @@ -93,7 +94,7 @@

Source code for pyts.profModels.iec

 
     """
 
-    def __init__(self, URef, RefHt, Z0, PLexp=0.2, turbmodel=None):
+    def __init__(self, URef, RefHt, Z0, PLexp=0.2, turbmodel=None):
         self.Uref = URef
         self.Zref = RefHt
         self.PLexp = PLexp
@@ -102,14 +103,14 @@ 

Source code for pyts.profModels.iec

         self.TurbModel = turbmodel
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.4g} [m/s]
-        Reference height (RefHt)                         =  {dat.Zref:0.4g} [m]
-        Power-low exponent (PLexp)                       =  {dat.PLexp:0.4g}
-        Surface roughness length (Z0)                    =  {dat.Z0:0.4g} [m]
-        Turbulence Model                                 =  {dat.TurbModel}
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.4g} [m/s]
+        Reference height (RefHt)                         =  {dat.Zref:0.4g} [m]
+        Power-low exponent (PLexp)                       =  {dat.PLexp:0.4g}
+        Surface roughness length (Z0)                    =  {dat.Z0:0.4g} [m]
+        Turbulence Model                                 =  {dat.TurbModel}
+        """
         return sumstring_format.format(dat=self)
 
 
[docs] def __call__(self, tsrun): @@ -129,14 +130,14 @@

Source code for pyts.profModels.iec

 
         """
         out = profObj(tsrun)
-        g = tsrun.grid  # A temporary, internal shortcut.
+        g = tsrun.grid  # A temporary, internal shortcut.
         zinds = (((-g.rotor_diam / 2 <= g.z - g.zhub)
-                 & (g.z - g.zhub <= g.rotor_diam / 2))[:, None])
+                 & (g.z - g.zhub <= g.rotor_diam / 2))[:, None])
         yinds = ((-g.rotor_diam / 2 <= g.y)
-                 & (g.y <= g.rotor_diam / 2))[None, :]
+                 & (g.y <= g.rotor_diam / 2))[None, :]
         out.array[0] = where(zinds & yinds,
-                             tile(powmain.model(self, g.z)[:, None], len(yinds[0])),
-                             tile(logmain.model(self, g.z)[:, None], len(yinds[0])), )
+                             tile(powmain.model(self, g.z)[:, None], len(yinds[0])),
+                             tile(logmain.model(self, g.z)[:, None], len(yinds[0])), )
         return out
@@ -156,14 +157,11 @@

Related Topics

@@ -171,11 +169,11 @@

Quick search

diff --git a/docs/_modules/pyts/profModels/jet.html b/docs/_modules/pyts/profModels/jet.html index 8c35411..d7dbb63 100644 --- a/docs/_modules/pyts/profModels/jet.html +++ b/docs/_modules/pyts/profModels/jet.html @@ -1,38 +1,39 @@ + - - - pyts.profModels.jet — PyTurbSim 0.4.7 documentation - + pyts.profModels.jet — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,8 +41,8 @@

Source code for pyts.profModels.jet

-from .base import profModelBase, np, profObj
-from numpy.polynomial.chebyshev import chebval
+from .base import profModelBase, np, profObj
+from numpy.polynomial.chebyshev import chebval
 
 
 
[docs]class main(profModelBase): @@ -63,7 +64,7 @@

Source code for pyts.profModels.jet

         the zjet_max property provides a default.
     """
 
-    def __init__(self, URef, ZRef, UStar, Ri, zjet_max=None):
+    def __init__(self, URef, ZRef, UStar, Ri, zjet_max=None):
         self.URef = URef
         self.ZRef = ZRef
         self.UStar = UStar
@@ -71,13 +72,13 @@ 

Source code for pyts.profModels.jet

         self.zjet_max = zjet_max
 
     def _sumfile_string(self,):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.2f}
-        Reference height (ZRef)                          =  {dat.ZRef:0.2f}
-        Richardson Number (RICH_NO)                      =  {dat.Ri:0.2f}
-        Jet Height (ZJet_Max)                            =  {dat.zjet_max:0.2f}
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.2f}
+        Reference height (ZRef)                          =  {dat.ZRef:0.2f}
+        Richardson Number (RICH_NO)                      =  {dat.Ri:0.2f}
+        Jet Height (ZJet_Max)                            =  {dat.zjet_max:0.2f}
+        """
         return sumstring_format.format(dat=self,)
 
 
[docs] def __call__(self, tsrun): @@ -98,9 +99,9 @@

Source code for pyts.profModels.jet

         """
         out = profObj(tsrun)
         u, v = self._model(out)
-        out[0], out[1] = u[:, None], v[:, None]
-        return out
-
+ out[0], out[1] = u[:, None], v[:, None] + return out
+ def _model(self, out): z = out.grid.z HtIndx = min(max(int(self.zjet_max - 50) / 20 - 1, 0), 20) @@ -111,16 +112,16 @@

Source code for pyts.profModels.jet

             prms[0] = self.URef
         else:
             utmp1 = chebval(
-                self.ZRef, np.dot(scoef[:, 1:], prms[1:][:, None]))
+                self.ZRef, np.dot(scoef[:, 1:], prms[1:][:, None]))
             utmp2 = chebval(self.ZRef, scoef[:, 0])
             prms[0] = (self.URef - utmp1) / utmp2
-        scoef = np.dot(scoef, prms[:, None])  # These are now vectors
-        dcoef = np.dot(dcoef, prms[:, None])  # These are now vectors
+        scoef = np.dot(scoef, prms[:, None])  # These are now vectors
+        dcoef = np.dot(dcoef, prms[:, None])  # These are now vectors
         ang = chebval(z, dcoef[:, 0])
-        ang -= ang[out.grid.ihub[0]]  # The hub-height angle should be zero.
+        ang -= ang[out.grid.ihub[0]]  # The hub-height angle should be zero.
         ang[ang < -45.], ang[ang > 45.] = - \
-            45., 45.  # No angle should be more than 45 degrees.
-        tmpdat = chebval(z, scoef) * np.exp(1j * np.pi / 180. * ang)[:, None]
+            45., 45.  # No angle should be more than 45 degrees.
+        tmpdat = chebval(z, scoef) * np.exp(1j * np.pi / 180. * ang)[:, None]
         return tmpdat.real, tmpdat.imag
 
     @property
@@ -130,34 +131,34 @@ 

Source code for pyts.profModels.jet

 
         This property calculates a default value if one is not specified.
         """
-        if self._val_zjet_max is not None:
+        if self._val_zjet_max is not None:
             return self._val_zjet_max
         val = 1.9326 * \
             (-14.820 * self.Ri + 56.488123 * self.zL +
              166.499069 * self.UStar + 188.253377) - 252.7267
         rnd = min(
             max(self.grid.randgen.standard_cauchy(1) * 10 - 20, -160), 120)
-                  # !!!VERSION_INCONSISTENCY: I've used the standard
-                  # !!!Cuachy distribution, rather than 'PearsonIV'
-                  # !!!from indecipherable code.
+                  # !!!VERSION_INCONSISTENCY: I've used the standard
+                  # !!!Cuachy distribution, rather than 'PearsonIV'
+                  # !!!from indecipherable code.
         val += rnd
         self._val_zjet_max = val
         return val
 
-    @zjet_max.setter
+    @zjet_max.setter
     def zjet_max(self, val):
-        self._val_zjet_max = val
+        self._val_zjet_max = val
-### These are the 'Chebyshef' coefficients, copied from the Modules.f90 file of TurbSim v1.x. -### The coefficients are: - ## Column Definition - ## 1 Jet maximum wind speed coefficient - ## 2 Turbine Richardson number coefficient - ## 3 uStar over the rotor coefficient - ## 4 constant - ## The rows are each of the 0-10th Chebyshev basis functions.
+### These are the 'Chebyshef' coefficients, copied from the Modules.f90 file of TurbSim v1.x. +### The coefficients are: + ## Column Definition + ## 1 Jet maximum wind speed coefficient + ## 2 Turbine Richardson number coefficient + ## 3 uStar over the rotor coefficient + ## 4 constant + ## The rows are each of the 0-10th Chebyshev basis functions. spd_coefs = np.array([ - [ # CASE ( 1 ) ! 70-90 m + [ # CASE ( 1 ) ! 70-90 m [0.856851, 7.51E-02, 1.39276, 0.894127], [-4.88E-02, 0.576344, 1.23582, 1.72687], [1.39E-02, 9.67E-02, 1.36737, -0.723851], @@ -169,7 +170,7 @@

Source code for pyts.profModels.jet

         [-2.01E-02, -5.61E-02, 0.220825, 0.179622],
         [8.11E-03, 3.96E-02, 0.109793, -3.81E-02],
         [4.99E-03, 5.00E-02, -0.124887, -0.11035], ],
-    [  # CASE ( 2 )     ! 90-110 m
+    [  # CASE ( 2 )     ! 90-110 m
         [0.741241, -0.122521, 0.875062, 1.43294],
         [-0.264131, 0.28827, 0.717571, 3.30541],
         [-5.92E-02, 3.86E-02, 1.09453, -0.377399],
@@ -181,7 +182,7 @@ 

Source code for pyts.profModels.jet

         [-1.60E-02, 8.88E-03, 0.132523, 9.58E-02],
         [-5.29E-03, 2.98E-02, 0.205812, 9.27E-02],
         [7.00E-03, -1.47E-02, -2.11E-02, -0.123083], ],
-    [  # CASE ( 3 )     ! 110-130 m
+    [  # CASE ( 3 )     ! 110-130 m
         [0.809492, -1.41752, -0.817619, 1.64159],
         [-0.121866, -1.09012, -2.60044, 3.63875],
         [-0.105142, -0.263657, -5.60E-02, 0.374811],
@@ -193,7 +194,7 @@ 

Source code for pyts.profModels.jet

         [-1.18E-02, -0.100754, 0.170602, 3.42E-02],
         [2.09E-02, 3.36E-02, -0.104123, -8.49E-02],
         [-2.91E-03, -3.52E-02, -0.258115, 4.81E-02], ],
-    [  # CASE ( 4 )     ! 130-150 m
+    [  # CASE ( 4 )     ! 130-150 m
         [0.694325, -0.463252, 2.11406, 1.28643],
         [-0.269118, -1.31381, 2.13374, 3.46187],
         [-8.40E-02, -5.97E-02, 2.09803, -0.592335],
@@ -205,7 +206,7 @@ 

Source code for pyts.profModels.jet

         [-3.26E-02, -0.239615, -0.133893, 0.29135],
         [1.52E-02, 7.15E-02, 0.25228, -0.113016],
         [7.19E-03, 9.79E-02, 0.252125, -0.173201], ],
-    [  # CASE ( 5 )     ! 150-170 m
+    [  # CASE ( 5 )     ! 150-170 m
         [0.909534, 0.581254, -2.90539, -0.581377],
         [0.155834, -0.836954, -6.77075, 0.627044],
         [-8.99E-02, -5.28E-02, -2.0719, 2.44E-02],
@@ -217,7 +218,7 @@ 

Source code for pyts.profModels.jet

         [-2.59E-02, 0.174282, 0.193868, -5.81E-03],
         [2.54E-03, -8.22E-02, 1.84E-02, 6.77E-02],
         [5.77E-04, -5.43E-02, -7.69E-02, 2.96E-02], ],
-    [  # CASE ( 6 )     ! 170-190 m
+    [  # CASE ( 6 )     ! 170-190 m
         [0.885753, -1.15015, 0.155218, -0.707043],
         [-2.53E-02, -2.65126, 0.850151, 1.85279],
         [-7.23E-02, -0.399161, 0.142486, -0.917176],
@@ -229,7 +230,7 @@ 

Source code for pyts.profModels.jet

         [-3.95E-02, 0.127418, 0.158511, 0.20932],
         [-2.53E-02, -5.32E-02, 0.36536, 0.214466],
         [4.03E-03, 1.02E-02, -7.01E-03, -4.32E-02], ],
-    [  # CASE ( 7 )     ! 190-210 m
+    [  # CASE ( 7 )     ! 190-210 m
         [0.735269, -1.48574, 0.983734, 0.887351],
         [0.233065, -0.850536, -1.17754, -0.880493],
         [-0.172346, -0.862128, 1.20075, 3.48E-02],
@@ -241,7 +242,7 @@ 

Source code for pyts.profModels.jet

         [-1.98E-02, -7.23E-02, 6.66E-02, 0.133182],
         [-5.57E-03, -5.31E-02, 2.44E-02, 5.60E-02],
         [3.71E-03, -1.63E-02, -5.44E-02, -1.40E-02], ],
-    [  # CASE ( 8 )     ! 210-230 m
+    [  # CASE ( 8 )     ! 210-230 m
         [0.723721, -0.691359, -0.147971, 1.16041],
         [0.18799, 0.370199, 0.354538, -0.494962],
         [-0.204727, -0.166723, 0.682431, 0.367566],
@@ -253,7 +254,7 @@ 

Source code for pyts.profModels.jet

         [-2.25E-02, 2.20E-02, 0.263227, 0.123311],
         [-1.43E-02, -2.01E-02, -5.14E-02, 0.159391],
         [2.64E-03, 3.46E-02, -0.12318, -2.22E-02], ],
-    [  # CASE ( 9 )     ! 230-250 m
+    [  # CASE ( 9 )     ! 230-250 m
         [0.717665, -0.294178, -0.521541, 0.876418],
         [0.183182, -0.52658, -1.34668, 0.414396],
         [-0.196162, 9.84E-02, -3.83E-02, 0.156018],
@@ -265,7 +266,7 @@ 

Source code for pyts.profModels.jet

         [7.03E-03, 2.49E-02, 3.13E-02, -9.70E-02],
         [-3.06E-03, -4.82E-02, -9.70E-02, 5.82E-02],
         [-9.57E-03, -3.93E-02, -0.125623, 0.112639], ],
-    [  # CASE ( 10 )    ! 250-270 m
+    [  # CASE ( 10 )    ! 250-270 m
         [0.786229, -0.164848, 0.244948, -0.126263],
         [0.15218, -0.153233, -0.558524, 0.84425],
         [-0.130716, -0.217411, 0.13439, -0.536893],
@@ -277,7 +278,7 @@ 

Source code for pyts.profModels.jet

         [4.51E-03, -4.37E-02, -0.111911, -9.20E-03],
         [4.05E-03, -6.90E-03, 0.14697, -7.03E-02],
         [-6.68E-03, 1.53E-02, -2.55E-02, 4.97E-02], ],
-    [  # CASE ( 11 )    ! 270-290 m
+    [  # CASE ( 11 )    ! 270-290 m
         [0.715734, -0.772062, -0.556396, 1.02929],
         [0.322509, -0.465616, -0.671711, -1.2413],
         [-0.166728, -0.281268, 0.924893, -0.282907],
@@ -289,7 +290,7 @@ 

Source code for pyts.profModels.jet

         [4.34E-03, 8.12E-02, 0.25764, -0.148492],
         [1.03E-02, 3.24E-02, 0.141971, -0.105207],
         [-4.84E-03, -1.99E-02, 7.33E-02, 2.84E-02], ],
-    [  # CASE ( 12 )    ! 290-310 m
+    [  # CASE ( 12 )    ! 290-310 m
         [0.723348, -0.289581, -1.10618, 0.970713],
         [0.283383, 1.12986, -0.152861, -0.653269],
         [-0.16513, 0.295047, 0.245326, -7.06E-02],
@@ -301,7 +302,7 @@ 

Source code for pyts.profModels.jet

         [-6.35E-03, -6.19E-02, 0.139396, 2.77E-02],
         [1.14E-02, -2.67E-02, 0.24201, -0.127337],
         [1.71E-04, -6.37E-04, 4.39E-02, -5.61E-03], ],
-    [  # CASE ( 13 )    ! 310-330 m
+    [  # CASE ( 13 )    ! 310-330 m
         [0.736987, -0.103727, 9.95E-02, 0.343208],
         [0.28285, 0.370583, 1.17749, -0.490259],
         [-0.130451, -0.557928, -0.272771, -0.230816],
@@ -313,7 +314,7 @@ 

Source code for pyts.profModels.jet

         [-1.23E-02, 4.75E-02, 0.182118, 1.78E-02],
         [4.63E-03, -0.1309, -0.130584, 2.35E-02],
         [9.03E-04, -6.18E-02, -7.85E-03, 1.17E-02], ],
-    [  # CASE ( 14 )    ! 330-350 m
+    [  # CASE ( 14 )    ! 330-350 m
         [0.706488, -1.21766, 1.08617, 0.674247],
         [0.341777, 2.27476, 3.81434, -2.32363],
         [-0.112822, 7.53E-02, 0.221349, -0.700428],
@@ -325,7 +326,7 @@ 

Source code for pyts.profModels.jet

         [-2.30E-02, -5.63E-02, 0.168561, 0.159537],
         [-6.41E-03, -8.48E-02, 0.135087, 8.81E-02],
         [1.13E-03, 2.07E-02, 9.18E-02, -3.77E-02], ],
-    [  # CASE ( 15 )    ! 350-370 m
+    [  # CASE ( 15 )    ! 350-370 m
         [0.721629, -0.941544, 0.923908, 0.543678],
         [0.346956, -0.281582, -2.32358, -0.244435],
         [-0.109484, 0.275053, 0.86928, -0.771081],
@@ -337,7 +338,7 @@ 

Source code for pyts.profModels.jet

         [-1.10E-02, -0.116864, -6.06E-02, 6.09E-02],
         [-2.93E-03, 2.72E-02, 5.08E-02, 7.50E-03],
         [-2.04E-03, -2.07E-02, -3.07E-02, 3.58E-02], ],
-    [  # CASE ( 16 )    ! 370-390 m
+    [  # CASE ( 16 )    ! 370-390 m
         [0.732127, -2.66819, -7.94E-02, 0.676096],
         [0.285167, 3.89442, -0.917426, 0.104248],
         [-8.38E-02, 0.235268, -2.19E-03, -0.914663],
@@ -349,7 +350,7 @@ 

Source code for pyts.profModels.jet

         [-1.05E-02, 9.92E-02, 0.11293, 2.26E-02],
         [-2.99E-03, -0.106831, 0.122628, 1.83E-02],
         [-7.32E-03, 3.52E-02, -3.36E-02, 8.59E-02], ],
-    [  # CASE ( 17 )    ! 390-410 m
+    [  # CASE ( 17 )    ! 390-410 m
         [0.707698, 0.119876, 0.427545, 0.2468],
         [0.307273, 0.428003, -3.09224, 1.01117],
         [-7.33E-02, 0.51572, -0.229086, -0.792402],
@@ -361,7 +362,7 @@ 

Source code for pyts.profModels.jet

         [-7.84E-04, -2.50E-02, 0.137171, -5.77E-02],
         [-2.91E-03, -4.84E-02, 0.168698, 8.22E-03],
         [-4.67E-03, 1.75E-03, 1.80E-02, 4.41E-02], ],
-    [  # CASE ( 18 )    ! 410-430 m
+    [  # CASE ( 18 )    ! 410-430 m
         [0.688761, -0.7286, -1.55711, 1.27145],
         [0.300421, 0.633115, 0.881706, -8.38E-03],
         [-6.81E-02, 0.210301, 0.610772, -0.714435],
@@ -373,7 +374,7 @@ 

Source code for pyts.profModels.jet

         [6.30E-03, -1.50E-02, -7.57E-02, -7.10E-02],
         [2.19E-03, -2.59E-02, 8.53E-02, -2.29E-02],
         [-2.76E-03, 1.68E-02, -8.77E-02, 3.27E-02], ],
-    [  # CASE ( 19 )    ! 430-450 m
+    [  # CASE ( 19 )    ! 430-450 m
         [0.659495, -0.22327, -1.75403, 1.65777],
         [0.384097, 1.06351, 2.53779, -1.63428],
         [-2.42E-02, 0.113735, -1.42805, -0.690773],
@@ -385,7 +386,7 @@ 

Source code for pyts.profModels.jet

         [2.11E-03, -1.45E-02, -8.94E-02, -2.00E-02],
         [3.06E-03, 1.60E-02, 7.45E-02, -3.77E-02],
         [-1.84E-04, -1.56E-02, -6.25E-02, 1.57E-02], ],
-    [  # CASE ( 20 )    ! 450-470 m
+    [  # CASE ( 20 )    ! 450-470 m
         [0.64099, -2.02496, 0.427597, 1.52166],
         [0.391609, 2.03441, -0.122486, -1.03579],
         [8.28E-03, 0.5942, -0.42469, -1.35655],
@@ -397,7 +398,7 @@ 

Source code for pyts.profModels.jet

         [1.54E-03, 5.82E-02, -5.72E-02, -6.37E-02],
         [5.11E-03, -6.11E-02, -7.04E-03, -3.64E-02],
         [1.97E-03, -1.09E-02, -8.18E-02, -6.03E-03], ],
-    [  # CASE ( 21 )    ! 470-490 m
+    [  # CASE ( 21 )    ! 470-490 m
         [0.547127, -0.327778, 2.00666, 2.67869],
         [0.427112, 8.56E-02, -1.61197, -1.17989],
         [6.23E-02, 0.760714, -0.659927, -2.30882],
@@ -413,7 +414,7 @@ 

Source code for pyts.profModels.jet

 
 
 dir_coefs = np.array([
-    [  # CASE ( 1 )     ! 70-90 m
+    [  # CASE ( 1 )     ! 70-90 m
         [5.07735, 96.4785, 18.8465, 110.986],
         [0.75209, -16.5103, -25.9592, 9.05636],
         [-1.50806, 1.69319, -7.7859, 13.3041],
@@ -425,7 +426,7 @@ 

Source code for pyts.profModels.jet

         [-1.26E-02, 0.19732, -2.70454, 0.179412],
         [9.13E-04, 9.65E-02, 0.304467, 4.79E-02],
         [-7.71E-02, -0.11096, 0.51028, 0.585717], ],
-    [  # CASE ( 2 )     ! 90-110 m
+    [  # CASE ( 2 )     ! 90-110 m
         [2.98622, 87.1045, 41.7453, 124.301],
         [0.241282, -10.9238, -31.5696, 11.0764],
         [-0.380786, -1.71395, -8.35561, 3.68007],
@@ -437,7 +438,7 @@ 

Source code for pyts.profModels.jet

         [-0.113556, -1.02575, -5.54619, 2.51668],
         [3.87E-02, 1.0794, 0.98668, -0.942351],
         [7.37E-02, -0.284347, 1.12315, -1.04163], ],
-    [  # CASE ( 3 )     ! 110-130 m
+    [  # CASE ( 3 )     ! 110-130 m
         [-10.8064, 63.1523, 18.7751, 255.252],
         [1.89875, -15.7662, -27.2545, -5.90699],
         [-1.81141, -7.58E-03, 4.49E-02, 19.4007],
@@ -449,7 +450,7 @@ 

Source code for pyts.profModels.jet

         [-0.142081, 0.690143, 1.74256, 0.963168],
         [-0.225792, -0.215169, 0.660299, 1.89319],
         [1.91E-02, -0.23, -1.69222, 0.190668], ],
-    [  # CASE ( 4 )     ! 130-150 m
+    [  # CASE ( 4 )     ! 130-150 m
         [0.270461, 107.786, 140.705, 143.549],
         [2.46519, 25.9261, 54.6629, -43.2182],
         [-1.11746, -4.09287, -5.71316, 16.4144],
@@ -461,7 +462,7 @@ 

Source code for pyts.profModels.jet

         [0.398742, -3.5049, -3.97854, -1.68531],
         [-7.72E-02, 2.14124, 3.42657, -0.982025],
         [0.120525, -1.80518, -3.44124, 0.391772], ],
-    [  # CASE ( 5 )     ! 150-170 m
+    [  # CASE ( 5 )     ! 150-170 m
         [10.3894, 203.711, 87.9736, 0.818669],
         [4.15105, 37.734, 56.1061, -72.0928],
         [-1.60031, -6.42686, 2.99983, 21.7355],
@@ -473,7 +474,7 @@ 

Source code for pyts.profModels.jet

         [-0.294613, -6.61282, -13.756, 9.48747],
         [0.180824, 6.67558, 8.1748, -6.39538],
         [-0.168678, -3.5973, -2.92266, 3.62255], ],
-    [  # CASE ( 6 )     ! 170-190 m
+    [  # CASE ( 6 )     ! 170-190 m
         [-3.05838, 92.242, -6.17694, 218.678],
         [-1.19176, 10.9436, 5.33317, 23.6574],
         [0.396791, 5.36609, 14.86, -12.1807],
@@ -485,7 +486,7 @@ 

Source code for pyts.profModels.jet

         [0.111959, 0.768005, 1.09164, -1.84864],
         [-5.32E-02, -0.753046, 0.517477, 0.77376],
         [2.36E-02, -0.255733, -0.765475, -0.183366], ],
-    [  # CASE ( 7 )     ! 190-210 m
+    [  # CASE ( 7 )     ! 190-210 m
         [2.63747, 48.8574, -148.839, 198.635],
         [0.276349, 8.15568, 11.5466, 4.89475],
         [-0.161153, -3.92434, 15.2465, -2.75263],
@@ -497,7 +498,7 @@ 

Source code for pyts.profModels.jet

         [6.88E-03, 0.618011, 0.600728, -0.312735],
         [-2.96E-02, -0.102388, -0.423526, 0.526055],
         [3.77E-03, -0.79762, -1.48591, 0.487559], ],
-    [  # CASE ( 8 )     ! 210-230 m
+    [  # CASE ( 8 )     ! 210-230 m
         [1.25931, 81.7121, -72.2497, 192.288],
         [-0.421425, 0.812039, 26.4136, 12.7087],
         [-0.477334, -0.804493, 10.2938, 2.63738],
@@ -509,7 +510,7 @@ 

Source code for pyts.profModels.jet

         [-5.13E-02, -0.157795, -0.596316, 0.747777],
         [5.03E-02, 6.23E-02, -0.821348, -0.411198],
         [-2.45E-02, 3.66E-03, 0.61934, 0.147334], ],
-    [  # CASE ( 9 )     ! 230-250 m
+    [  # CASE ( 9 )     ! 230-250 m
         [4.99773, 45.439, -22.9981, 142.166],
         [1.34923, -0.690733, 1.11037, -7.00256],
         [-4.58E-02, -1.48399, 3.15438, -1.20619],
@@ -521,7 +522,7 @@ 

Source code for pyts.profModels.jet

         [-6.54E-04, 0.514329, 0.38488, -0.221416],
         [2.40E-03, -0.307029, -0.455799, 0.167602],
         [5.79E-03, -0.3575, -6.82E-02, -1.79E-02], ],
-    [  # CASE ( 10 )    ! 250-270 m
+    [  # CASE ( 10 )    ! 250-270 m
         [2.87491, 81.7603, -14.221, 143.973],
         [0.176626, 0.711168, 14.3778, 3.41781],
         [-0.112353, -4.44334, 5.01439, -0.539061],
@@ -533,7 +534,7 @@ 

Source code for pyts.profModels.jet

         [6.84E-04, 0.398542, -0.227958, -0.195655],
         [-1.33E-02, -0.148014, 0.112677, 0.28039],
         [4.56E-02, -0.4372, -1.05259, -0.39506], ],
-    [  # CASE ( 11 )    ! 270-290 m
+    [  # CASE ( 11 )    ! 270-290 m
         [-3.74E-02, 5.72313, -25.8459, 204.708],
         [0.387587, 5.70337, 37.0722, -5.10619],
         [0.130067, 8.86213, 7.6219, -6.77984],
@@ -545,7 +546,7 @@ 

Source code for pyts.profModels.jet

         [-2.75E-02, 0.875895, 8.29E-02, 1.47E-02],
         [-4.90E-03, -0.26505, 0.684299, -0.101304],
         [-2.46E-03, -9.03E-02, -0.25124, 0.130552], ],
-    [  # CASE ( 12 )    ! 290-310 m
+    [  # CASE ( 12 )    ! 290-310 m
         [4.48806, 101.681, -24.2152, 108.849],
         [1.12228, -11.8153, -5.83094, -3.59506],
         [0.152934, 0.610899, 10.1148, -6.59595],
@@ -557,7 +558,7 @@ 

Source code for pyts.profModels.jet

         [-5.96E-03, -0.645, 1.0105, -0.256849],
         [-1.79E-02, 0.137457, -7.45E-03, 0.232805],
         [-5.07E-04, -1.20E-03, -0.280138, 9.13E-02], ],
-    [  # CASE ( 13 )    ! 310-330 m
+    [  # CASE ( 13 )    ! 310-330 m
         [0.253568, 43.3822, 42.3741, 166.917],
         [-0.210713, 14.3161, 12.187, 9.66539],
         [0.176871, -3.28688, -2.78059, -1.64384],
@@ -569,7 +570,7 @@ 

Source code for pyts.profModels.jet

         [-2.17E-02, 0.198171, 0.911532, 2.31E-02],
         [-5.64E-03, 0.278658, 0.250055, -9.16E-02],
         [7.21E-03, 2.24E-02, 6.76E-02, -0.1011], ],
-    [  # CASE ( 14 )    ! 330-350 m
+    [  # CASE ( 14 )    ! 330-350 m
         [1.4365, 104.113, 86.7884, 138.082],
         [1.01951, -22.4231, 8.14651, -3.0374],
         [-0.14238, 5.5217, -8.37098, 1.9052],
@@ -581,7 +582,7 @@ 

Source code for pyts.profModels.jet

         [0.127996, -2.88696, -2.49795, -1.24336],
         [-6.71E-02, 1.70388, 0.935254, 0.748082],
         [8.19E-03, -4.50E-02, -0.263839, -5.18E-02], ],
-    [  # CASE ( 15 )    ! 350-370 m
+    [  # CASE ( 15 )    ! 350-370 m
         [-0.675054, 121.016, 0.173435, 199.751],
         [-0.52795, 26.7663, 36.6465, 8.14164],
         [0.686068, -2.58652, 1.37125, -12.8021],
@@ -593,7 +594,7 @@ 

Source code for pyts.profModels.jet

         [3.15E-02, -6.48E-02, -0.882842, -0.404645],
         [-9.69E-03, -0.486174, -0.284323, 0.336898],
         [1.04E-03, -0.144399, -6.10E-02, 6.62E-02], ],
-    [  # CASE ( 16 )    ! 370-390 m
+    [  # CASE ( 16 )    ! 370-390 m
         [0.610558, -90.3161, -86.1311, 221.346],
         [-0.878196, 0.234356, -1.96802, 30.3835],
         [0.536954, 2.31986, 0.611791, -11.624],
@@ -605,7 +606,7 @@ 

Source code for pyts.profModels.jet

         [0.105906, 2.60251, -0.805126, -2.35033],
         [-3.95E-02, -0.866726, 0.244709, 0.996069],
         [5.34E-02, 0.423689, -0.910358, -0.888237], ],
-    [  # CASE ( 17 )    ! 390-410 m
+    [  # CASE ( 17 )    ! 390-410 m
         [-0.256694, -53.0924, -28.899, 212.286],
         [0.368178, 0.200188, -15.1321, 9.40209],
         [-0.102825, -4.83546, 9.24228, -0.64019],
@@ -617,7 +618,7 @@ 

Source code for pyts.profModels.jet

         [-2.97E-02, -0.626331, 1.32958, 0.161941],
         [-4.73E-03, -0.639604, -0.50062, 0.398523],
         [7.78E-04, 0.203885, 0.111938, -9.66E-02], ],
-    [  # CASE ( 18 )    ! 410-430 m
+    [  # CASE ( 18 )    ! 410-430 m
         [-1.05454, 19.3432, 14.3866, 209.914],
         [-5.37E-02, -6.69143, -5.48868, 13.8188],
         [0.130461, 1.84379, 10.2975, -6.85151],
@@ -629,7 +630,7 @@ 

Source code for pyts.profModels.jet

         [-3.19E-02, 0.159054, 1.11463, 9.91E-02],
         [-9.31E-03, -0.514427, -0.486658, 0.472324],
         [5.84E-03, -6.98E-02, -6.53E-02, -7.68E-02], ],
-    [  # CASE ( 19 )    ! 430-450 m
+    [  # CASE ( 19 )    ! 430-450 m
         [0.624689, 63.9533, -115.139, 203.718],
         [-0.249911, 8.56489, 12.0426, 11.2274],
         [0.208499, -2.38494, 8.76157, -7.17681],
@@ -641,7 +642,7 @@ 

Source code for pyts.profModels.jet

         [1.45E-02, -1.29998, -0.491218, -6.91E-02],
         [-6.95E-04, 0.830442, 1.25591, -0.451134],
         [-6.90E-04, 1.30E-02, -0.16423, 7.65E-02], ],
-    [  # CASE ( 20 )    ! 450-470 m
+    [  # CASE ( 20 )    ! 450-470 m
         [4.30205, 83.823, -77.8869, 120.115],
         [0.11147, -2.13123, -13.0305, 11.4506],
         [5.36E-02, -9.82942, 3.21203, -2.14437],
@@ -653,7 +654,7 @@ 

Source code for pyts.profModels.jet

         [-3.25E-02, 0.187007, 0.351131, 0.374602],
         [-1.79E-02, -0.651232, -0.437205, 0.653204],
         [5.74E-03, 0.210108, -0.185616, -8.91E-02], ],
-    [  # CASE ( 21 )    ! 470-490 m
+    [  # CASE ( 21 )    ! 470-490 m
         [0.685959, 76.5757, -26.8137, 187.31],
         [-0.229648, 3.36903, -12.3466, 19.5787],
         [5.56E-02, -6.33886, 2.64958, -2.35925],
@@ -684,14 +685,11 @@ 

Related Topics

@@ -699,11 +697,11 @@

Quick search

diff --git a/docs/_modules/pyts/profModels/log.html b/docs/_modules/pyts/profModels/log.html index 98784ef..a93ca46 100644 --- a/docs/_modules/pyts/profModels/log.html +++ b/docs/_modules/pyts/profModels/log.html @@ -1,38 +1,39 @@ + - - - pyts.profModels.log — PyTurbSim 0.4.7 documentation - + pyts.profModels.log — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,19 +41,19 @@

Source code for pyts.profModels.log

-"""
+"""
 This module contains the log-law mean-velocity profiles:
  nwtc   - The NWTC logarithmic mean wind speed profile.
  H2O    - The hydro-logarithmic mean velocity profile.
 
 """
-from .base import profModelBase, np, profObj
-from ..misc import kappa, psiM
+from .base import profModelBase, np, profObj
+from ..misc import kappa, psiM
 
 
 
[docs]class nwtc(profModelBase,): - r"""NWTC logarithmic wind-speed profile model. + r"""NWTC logarithmic wind-speed profile model. Parameters ---------- @@ -80,7 +81,7 @@

Source code for pyts.profModels.log

 
     """
 
-    def __init__(self, URef, ZRef, Z0, Ri=0, turbmodel=None):
+    def __init__(self, URef, ZRef, Z0, Ri=0, turbmodel=None):
         self.Uref = URef
         self.Zref = ZRef
         self.Z0 = Z0
@@ -88,14 +89,14 @@ 

Source code for pyts.profModels.log

         self.TurbModel = turbmodel
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.4g} [m/s]
-        Reference height (ZRef)                          =  {dat.Zref:0.4g} [m]
-        Surface roughness length (Z0)                    =  {dat.Z0:0.4g} [m]
-        Richardson Number (RICH_NO)                      =  {dat.Ri:0.4g}
-        Turbulence Model                                 =  {dat.TurbModel}
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.4g} [m/s]
+        Reference height (ZRef)                          =  {dat.Zref:0.4g} [m]
+        Surface roughness length (Z0)                    =  {dat.Z0:0.4g} [m]
+        Richardson Number (RICH_NO)                      =  {dat.Ri:0.4g}
+        Turbulence Model                                 =  {dat.TurbModel}
+        """
         return sumstring_format.format(dat=self)
 
 
[docs] def __call__(self, tsrun): @@ -115,9 +116,9 @@

Source code for pyts.profModels.log

 
         """
         out = profObj(tsrun)
-        out[0] = self.model(out.grid.z)[:, None]
-        return out
-
+ out[0] = self.model(out.grid.z)[:, None] + return out
+
[docs] def model(self, z): """ Calculate the log profile for heights `z`. @@ -133,11 +134,11 @@

Source code for pyts.profModels.log

                 The mean velocity array [m/s].
 
         """
-        # Note: this function is separated from the __call__ routine so that it
-        # can be utilized by other modules
+        # Note: this function is separated from the __call__ routine so that it
+        # can be utilized by other modules
         return (self.Uref * (np.log(z / self.Z0) + self.psiM) /
-                (np.log(self.Zref / self.Z0) + self.psiM))
-
+ (np.log(self.Zref / self.Z0) + self.psiM))
+ @property def psiM(self,): """ @@ -145,9 +146,9 @@

Source code for pyts.profModels.log

 
         See the :func:`pyts.misc.psiM` function for details.
         """
-        return psiM(self.Ri, self.TurbModel)
+        return psiM(self.Ri, self.TurbModel)
+ -
[docs]class H2O(profModelBase,): """Logarithmic water velocity profile model. @@ -178,11 +179,11 @@

Source code for pyts.profModels.log

         self.Ustar = ustar
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.4g} [m/s]
-        Reference height (ZRef)                          =  {dat.Zref:0.4g} [m]
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.4g} [m/s]
+        Reference height (ZRef)                          =  {dat.Zref:0.4g} [m]
+        """
         return sumstring_format.format(dat=self)
 
 
[docs] def __call__(self, tsrun): @@ -202,7 +203,7 @@

Source code for pyts.profModels.log

                 spatial grid in tsrun.
         """
         out = profObj(tsrun)
-        out[0] = (self.Ustar / kappa * np.log(out.grid.z / self.Zref) + self.Uref)[:, None]
+        out[0] = (self.Ustar / kappa * np.log(out.grid.z / self.Zref) + self.Uref)[:, None]
         return out
@@ -222,14 +223,11 @@

Related Topics

@@ -237,11 +235,11 @@

Quick search

diff --git a/docs/_modules/pyts/profModels/power.html b/docs/_modules/pyts/profModels/power.html index 2f4114b..fb90f2a 100644 --- a/docs/_modules/pyts/profModels/power.html +++ b/docs/_modules/pyts/profModels/power.html @@ -1,38 +1,39 @@ + - - - pyts.profModels.power — PyTurbSim 0.4.7 documentation - + pyts.profModels.power — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,15 +41,15 @@

Source code for pyts.profModels.power

-"""
+"""
 The NWTC power-law profile model.
 """
-from .base import profModelBase, profObj
+from .base import profModelBase, profObj
 
 
 
[docs]class nwtc(profModelBase): - r"""Power-law wind profile model. + r"""Power-law wind profile model. .. math:: @@ -72,22 +73,22 @@

Source code for pyts.profModels.power

         self.PLexp = PLexp
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.2f} [m/s]
-        Reference Height (Zref)                          =  {dat.Zref:0.2f} [m]
-        Power-low exponent (PLexp)                       =  {dat.PLexp:0.2f}
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.2f} [m/s]
+        Reference Height (Zref)                          =  {dat.Zref:0.2f} [m]
+        Power-low exponent (PLexp)                       =  {dat.PLexp:0.2f}
+        """
         return sumstring_format.format(dat=self)
 
 
[docs] def model(self, z): """ The function for calculating the mean velocity profile. """ - # Note: this function is separated from the __init__ routine so that it - # can be utilized by other modules - return self.Uref * (z / self.Zref) ** self.PLexp -
+ # Note: this function is separated from the __init__ routine so that it + # can be utilized by other modules + return self.Uref * (z / self.Zref) ** self.PLexp
+
[docs] def __call__(self, tsrun): """ Create and calculate the mean-profile object for a `tsrun` @@ -105,7 +106,7 @@

Source code for pyts.profModels.power

 
         """
         out = profObj(tsrun)
-        out[0] = self.model(out.grid.z)[:, None]
+        out[0] = self.model(out.grid.z)[:, None]
         return out
@@ -125,14 +126,11 @@

Related Topics

@@ -140,11 +138,11 @@

Quick search

diff --git a/docs/_modules/pyts/profModels/simple.html b/docs/_modules/pyts/profModels/simple.html index 99905a6..ec96346 100644 --- a/docs/_modules/pyts/profModels/simple.html +++ b/docs/_modules/pyts/profModels/simple.html @@ -1,38 +1,39 @@ + - - - pyts.profModels.simple — PyTurbSim 0.4.7 documentation - + pyts.profModels.simple — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,18 +41,18 @@

Source code for pyts.profModels.simple

-"""
+"""
 This module contains the log-law mean-velocity profiles:
  linear   - A linear wind speed profile
  uniform  - A uniform mean wind speed.
 
 """
-from .base import profModelBase, profObj
+from .base import profModelBase, profObj
 
 
 
[docs]class uniform(profModelBase,): - r"""Uniform wind-speed 'profile' model. + r"""Uniform wind-speed 'profile' model. Parameters ---------- @@ -70,10 +71,10 @@

Source code for pyts.profModels.simple

         self.Uref = URef
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.2f} [m/s]
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.2f} [m/s]
+        """
         return sumstring_format.format(dat=self, )
 
 
[docs] def __call__(self, tsrun): @@ -93,13 +94,13 @@

Source code for pyts.profModels.simple

 
         """
         out = profObj(tsrun)
-        out[0][:] = self.Uref  # Set the velocity.
-        return out
+        out[0][:] = self.Uref  # Set the velocity.
+        return out
+ -
[docs]class linear(profModelBase,): - r""" + r""" A 'linear' mean wind-speed 'profile'. Parameters @@ -128,13 +129,13 @@

Source code for pyts.profModels.simple

         self.Zref2 = ZRef2
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Profile model used                               =  {dat.model_desc}
-        Reference velocity (URef)                        =  {dat.Uref:0.2f} [m/s]
-        Reference height (ZRef)                          =  {dat.Zref:0.2f} [m]
-        Reference velocity 2 (URef)                      =  {dat.Uref2:0.2f} [m/s]
-        Reference height 2 (ZRef)                        =  {dat.Zref2:0.2f} [m]
-        """
+        sumstring_format = """
+        Profile model used                               =  {dat.model_desc}
+        Reference velocity (URef)                        =  {dat.Uref:0.2f} [m/s]
+        Reference height (ZRef)                          =  {dat.Zref:0.2f} [m]
+        Reference velocity 2 (URef)                      =  {dat.Uref2:0.2f} [m/s]
+        Reference height 2 (ZRef)                        =  {dat.Zref2:0.2f} [m]
+        """
         return sumstring_format.format(dat=self,)
 
 
[docs] def __call__(self, tsrun): @@ -175,14 +176,11 @@

Related Topics

@@ -190,11 +188,11 @@

Quick search

diff --git a/docs/_modules/pyts/runInput/base.html b/docs/_modules/pyts/runInput/base.html index e169835..3b0c0f9 100644 --- a/docs/_modules/pyts/runInput/base.html +++ b/docs/_modules/pyts/runInput/base.html @@ -1,38 +1,39 @@ + - - - pyts.runInput.base — PyTurbSim 0.4.7 documentation - + pyts.runInput.base — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.runInput.base

-"""
+"""
 The base module for the runInput package. This module defines the
 TurbSim input class (tsinput). The tsinput class is a dictionary for
 storing data from a TurbSim input file. The class contains several
@@ -49,9 +50,9 @@ 

Source code for pyts.runInput.base

 https://wind.nrel.gov/designcodes/preprocessors/turbsim/TurbSim.pdf
 
 """
-from ..base import np
-from numpy import uint32
-from ..misc import kappa, InvalidConfig, zL, psiM
+from ..base import np
+from numpy import uint32
+from ..misc import kappa, InvalidConfig, zL, psiM
 
 
 
[docs]class tsinput(dict): @@ -84,91 +85,91 @@

Source code for pyts.runInput.base

 
         Otherwise return *None*.
         """
-        if key == 'RandSeed':
+        if key == 'RandSeed':
             return self.randseed
-        if key in ['IECstandard', 'IECedition'] and \
-           dict.__getitem__(self, 'IECstandard').__class__ is str:
-            self['IECstandard'], self['IECedition'] = self.parse_IEC_standard(dict.__getitem__(self, 'IECstandard'))  # noqa
-        if key not in self or dict.__getitem__(self, key) is None:
-            if hasattr(self, '_dflt_' + key):
-                self[key] = self.__getattribute__('_dflt_' + key)
+        if key in ['IECstandard', 'IECedition'] and \
+           dict.__getitem__(self, 'IECstandard').__class__ is str:
+            self['IECstandard'], self['IECedition'] = self.parse_IEC_standard(dict.__getitem__(self, 'IECstandard'))  # noqa
+        if key not in self or dict.__getitem__(self, key) is None:
+            if hasattr(self, '_dflt_' + key):
+                self[key] = self.__getattribute__('_dflt_' + key)
                 self._dict_isdefault[key] = 2
                 return self[key]
             else:
-                return None
-        return dict.__getitem__(self, key)
+                return None
+        return dict.__getitem__(self, key)
 
     def __setitem__(self, key, val):
-        if key == 'RandSeed':
+        if key == 'RandSeed':
             self.randseed = val
         else:
-            dict.__setitem__(self, key, val)
+            dict.__setitem__(self, key, val)
 
     @property
     def incdec_a(self,):
         """
         The 'a' coherence decrement.
         """
-        out = [None, None, None]
-        if self['IncDec1'] is not None:
-            if hasattr(self['IncDec1'], '__len__'):
-                out[0] = self['IncDec1'][0]
+        out = [None, None, None]
+        if self['IncDec1'] is not None:
+            if hasattr(self['IncDec1'], '__len__'):
+                out[0] = self['IncDec1'][0]
             else:
-                out[0] = self['IncDec1']
-        if self['IncDec2'] is not None:
-            if hasattr(self['IncDec2'], '__len__'):
-                out[1] = self['IncDec2'][0]
+                out[0] = self['IncDec1']
+        if self['IncDec2'] is not None:
+            if hasattr(self['IncDec2'], '__len__'):
+                out[1] = self['IncDec2'][0]
             else:
-                out[1] = self['IncDec2']
-        if self['IncDec3'] is not None:
-            if hasattr(self['IncDec3'], '__len__'):
-                out[2] = self['IncDec3'][0]
+                out[1] = self['IncDec2']
+        if self['IncDec3'] is not None:
+            if hasattr(self['IncDec3'], '__len__'):
+                out[2] = self['IncDec3'][0]
             else:
-                out[2] = self['IncDec3']
+                out[2] = self['IncDec3']
         return out
 
     @property
     def incdec_b(self,):
         out = [0., 0., 0.]
-        if self['IncDec1'] is not None and hasattr(self['IncDec1'], '__len__'):
-            out[0] = self['IncDec1'][1]
-        if self['IncDec2'] is not None and hasattr(self['IncDec2'], '__len__'):
-            out[1] = self['IncDec2'][1]
-        if self['IncDec3'] is not None and hasattr(self['IncDec3'], '__len__'):
-            out[2] = self['IncDec3'][1]
+        if self['IncDec1'] is not None and hasattr(self['IncDec1'], '__len__'):
+            out[0] = self['IncDec1'][1]
+        if self['IncDec2'] is not None and hasattr(self['IncDec2'], '__len__'):
+            out[1] = self['IncDec2'][1]
+        if self['IncDec3'] is not None and hasattr(self['IncDec3'], '__len__'):
+            out[2] = self['IncDec3'][1]
         return out
 
 
[docs] def parse_IEC_standard(self, iecstd): - if iecstd.__class__ is str: + if iecstd.__class__ is str: iecstd = iecstd.lower() tmp = int(iecstd[0]) if len(iecstd) > 1 and tmp == 1: iecedt = int(iecstd[-1]) else: - iecedt = None - # There are no editions to the -2 and -3 standards. + iecedt = None + # There are no editions to the -2 and -3 standards. iecstd = tmp - elif iecstd == 1 or iecstd is None: + elif iecstd == 1 or iecstd is None: iecstd = 1 - if self.turbmodel == 'ieckai': + if self.turbmodel == 'ieckai': iecedt = 3 else: iecedt = 2 else: - iecedt = None # There are no editions to the -2 and -3 standards. - if iecedt == 3 and self.turbmodel == 'iecvkm': - raise InvalidConfig("The von-Karman spectral model (IECVKM) \ - is not valid for IEC standard 61400-1's 3rd edition. Either \ - change TurbModel to IECKAI, or change the IECstandard to '1-ed2' \ - or simply '1'.") - elif iecedt > 1 and self['IEC_WindType'].lower() != 'ntm': - raise InvalidConfig("If the IECstandard is 1-ed2 or 1-ed3, \ - than the WindType must be 'NTM'.") - return (iecstd, iecedt) -
+ iecedt = None # There are no editions to the -2 and -3 standards. + if iecedt == 3 and self.turbmodel == 'iecvkm': + raise InvalidConfig("The von-Karman spectral model (IECVKM) \ + is not valid for IEC standard 61400-1's 3rd edition. Either \ + change TurbModel to IECKAI, or change the IECstandard to '1-ed2' \ + or simply '1'.") + elif iecedt > 1 and self['IEC_WindType'].lower() != 'ntm': + raise InvalidConfig("If the IECstandard is 1-ed2 or 1-ed3, \ + than the WindType must be 'NTM'.") + return (iecstd, iecedt)
+ def __init__(self, *args, **kwargs): self._dict_isdefault = {} - dict.__init__(self, *args, **kwargs) + dict.__init__(self, *args, **kwargs)
[docs] def isdefault(self, key): """ @@ -179,90 +180,90 @@

Source code for pyts.runInput.base

         False: The value is specified explicitly in the configuration.
 
         """
-        if self[key] is None:
-            return True
+        if self[key] is None:
+            return True
         if key in self._dict_isdefault:
             return self._dict_isdefault[key]
         else:
-            return False
-
+ return False
+ @property def randseed(self,): tmpval = 0 - if 'RandSeed1' in self and self['RandSeed1'] is not None: - tmpval += uint32(self['RandSeed1']) - if 'RandSeed2' in self and self['RandSeed2'] is not None: - tmpval += uint32(self['RandSeed2']) << 32 + if 'RandSeed1' in self and self['RandSeed1'] is not None: + tmpval += uint32(self['RandSeed1']) + if 'RandSeed2' in self and self['RandSeed2'] is not None: + tmpval += uint32(self['RandSeed2']) << 32 if tmpval == 0: - return None + return None return tmpval - @randseed.setter + @randseed.setter def randseed(self, val): - if val is None: - self['RandSeed1'] = None - self['RandSeed2'] = None + if val is None: + self['RandSeed1'] = None + self['RandSeed2'] = None else: - self['RandSeed1'] = np.int32(val & 2 ** 32 - 1) + self['RandSeed1'] = np.int32(val & 2 ** 32 - 1) val2 = np.int32(val >> 32) if val2 > 0: - self['RandSeed2'] = val2 + self['RandSeed2'] = val2 else: - self['RandSeed2'] = None + self['RandSeed2'] = None @property def _dflt_WindProfileType(self,): - if self.turbmodel == 'gp_llj': - return 'JET' - elif self.turbmodel in ['river', 'tidal']: - return 'H2L' + if self.turbmodel == 'gp_llj': + return 'JET' + elif self.turbmodel in ['river', 'tidal']: + return 'H2L' else: - return 'IEC' + return 'IEC' @property def turbmodel(self,): - return self['TurbModel'].lower() + return self['TurbModel'].lower() - # These are only called if the key is not in the dictionary: + # These are only called if the key is not in the dictionary: @property def _dflt_Z0(self,): - return {'ieckai': 0.03, - 'iecvkm': 0.03, - 'smooth': 0.01, - 'gp_llj': 0.005, - 'nwtcup': 0.021, - 'wf_upw': 0.018, - 'wf_07d': 0.064, - 'wf_14d': 0.233, - 'tidal': 0.1, - 'river': 0.1 + return {'ieckai': 0.03, + 'iecvkm': 0.03, + 'smooth': 0.01, + 'gp_llj': 0.005, + 'nwtcup': 0.021, + 'wf_upw': 0.018, + 'wf_07d': 0.064, + 'wf_14d': 0.233, + 'tidal': 0.1, + 'river': 0.1 }[self.turbmodel] @property def _dflt_UStar(self,): - if ('URef' not in self or self['URef'] is None) and \ - ('UStar' not in self or self['UStar'] is None): - raise InvalidConfig('Either URef or UStar must be defined in the input file.') + if ('URef' not in self or self['URef'] is None) and \ + ('UStar' not in self or self['UStar'] is None): + raise InvalidConfig('Either URef or UStar must be defined in the input file.') mdl = self.turbmodel ustar0 = self.ustar0 - if mdl == 'smooth': + if mdl == 'smooth': ustar = ustar0 - elif mdl == 'nwtcup': + elif mdl == 'nwtcup': ustar = 0.2716 + 0.7573 * ustar0 ** 1.2599 - elif mdl == 'gp_llj': + elif mdl == 'gp_llj': ustar = 0.17454 + 0.72045 * ustar0 ** 1.36242 - elif mdl == 'wf_upw': + elif mdl == 'wf_upw': if self.zL < 0: ustar = 1.162 * ustar0 ** 0.66666 else: ustar = 0.911 * ustar0 ** 0.66666 - elif mdl in ['wf_07d', 'wf_14d']: + elif mdl in ['wf_07d', 'wf_14d']: if self.zL < 0: ustar = 1.484 * ustar0 ** 0.66666 else: ustar = 1.370 * ustar0 ** 0.66666 - elif mdl in ['tidal', 'river']: - ustar = self['URef'] * 0.05 + elif mdl in ['tidal', 'river']: + ustar = self['URef'] * 0.05 return ustar @property @@ -271,10 +272,10 @@

Source code for pyts.runInput.base

 
     @property
     def _dflt_ZI(self,):
-        if self['UStar'] < self.ustar0:
-            return 400 * self['URef'] / np.log(self['RefHt'] / self['Z0'])
+        if self['UStar'] < self.ustar0:
+            return 400 * self['URef'] / np.log(self['RefHt'] / self['Z0'])
         else:
-            return self['UStar'] / (12 * 7.292116e-5 * np.sin(np.pi / 180 * np.abs(self['Latitude'])))  # noqa
+            return self['UStar'] / (12 * 7.292116e-5 * np.sin(np.pi / 180 * np.abs(self['Latitude'])))  # noqa
 
     @property
     def _dflt_PC_UV(self,):
@@ -294,48 +295,48 @@ 

Source code for pyts.runInput.base

         The default Wind Profile power law exponent.
         """
         tm = self.turbmodel
-        Ri = self['RICH_NO']
-        if tm in ['ieckai', 'iecvkm']:
-            if self['IECstandard'] == 1 and \
-               self['IEC_WindType'].lower() == 'ewm':
+        Ri = self['RICH_NO']
+        if tm in ['ieckai', 'iecvkm']:
+            if self['IECstandard'] == 1 and \
+               self['IEC_WindType'].lower() == 'ewm':
                 plexp = 0.11
-            elif self['IECstandard'] == 3:
+            elif self['IECstandard'] == 3:
                 plexp = 0.14
-            plexp = {'ewm': 0.11, 'ntm': 0.14}.get(
-                self['WindProfileType'], 0.2)
-        elif tm in ['wf_upw', 'nwtcup']:
-            if self['IECturbc'].lower() == 'khtest' and \
-               self.turbmodel == 'nwtcup':
+            plexp = {'ewm': 0.11, 'ntm': 0.14}.get(
+                self['WindProfileType'], 0.2)
+        elif tm in ['wf_upw', 'nwtcup']:
+            if self['IECturbc'].lower() == 'khtest' and \
+               self.turbmodel == 'nwtcup':
                 plexp = 0.3
             if Ri > 0:
                 plexp = 0.14733
             else:
                 plexp = 0.087688 + 0.059641 * np.exp(Ri / 0.04717783)
-        elif tm in ['wf_07d', 'wf_14d']:
+        elif tm in ['wf_07d', 'wf_14d']:
             if Ri > 0.04:
                 plexp = 0.17903
             else:
                 plexp = 0.1277 + 0.031229 * np.exp(Ri / 0.0805173)
-        else:  # ['smooth','gp_llj','tidal','river']:
+        else:  # ['smooth','gp_llj','tidal','river']:
             plexp = 0.143
         return plexp
 
-    ### These are helper functions, not 'default input parameters':
+    ### These are helper functions, not 'default input parameters':
     @property
     def ustar0(self,):
-        return (kappa * self['URef'] /
-                (np.log(self['RefHt'] / self['Z0']) - self.psiM))
+        return (kappa * self['URef'] /
+                (np.log(self['RefHt'] / self['Z0']) - self.psiM))
 
     @property
     def zL(self,):
-        if not hasattr(self, '_val_zL'):
-            self._val_zL = zL(self['RICH_NO'], self['TurbModel'])
+        if not hasattr(self, '_val_zL'):
+            self._val_zL = zL(self['RICH_NO'], self['TurbModel'])
         return self._val_zL
 
     @property
     def psiM(self,):
-        if not hasattr(self, '_val_psiM'):
-            self._val_psiM = psiM(self['RICH_NO'], self['TurbModel'])
+        if not hasattr(self, '_val_psiM'):
+            self._val_psiM = psiM(self['RICH_NO'], self['TurbModel'])
         return self._val_psiM
@@ -355,14 +356,11 @@

Related Topics

@@ -370,11 +368,11 @@

Quick search

diff --git a/docs/_modules/pyts/runInput/main.html b/docs/_modules/pyts/runInput/main.html index a9bb426..31992ec 100644 --- a/docs/_modules/pyts/runInput/main.html +++ b/docs/_modules/pyts/runInput/main.html @@ -1,38 +1,39 @@ + - - - pyts.runInput.main — PyTurbSim 0.4.7 documentation - + pyts.runInput.main — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.runInput.main

-"""
+"""
 The 'main' module for the PyTurbSim runInput package defines the
 'run' and 'write' routines for performing a TurbSim run and
 writing-out data.
@@ -66,11 +67,11 @@ 

Source code for pyts.runInput.main

 >>> runInput.write(tsdata,tsinput)
 
 """
-from ..base import tsGrid
-from ..main import tsrun
-from ..io.input import read as readInput
-from turbModels import getModel as tm_getModel
-from profModels import getModel as pm_getModel
+from ..base import tsGrid
+from ..main import tsrun
+from ..io.input import read as readInput
+from turbModels import getModel as tm_getModel
+from profModels import getModel as pm_getModel
 
 
 
[docs]def run_fname(fname): @@ -88,9 +89,9 @@

Source code for pyts.runInput.main

                 A PyTurbSim data object.
     """
     inp = readInput(fname)
-    return run(inp)
+    return run(inp)
+ -
[docs]def run(tsinput): """Perform a PyTurbSim run based on the input object `tsinput`. @@ -106,10 +107,10 @@

Source code for pyts.runInput.main

     """
     tsr = cfg2tsrun(tsinput)
 
-    return tsr()
+    return tsr()
-
-
[docs]def write(tsdat, tsinput, fname=None): + +
[docs]def write(tsdat, tsinput, fname=None): """ Write TurbSim-output to a file. @@ -125,17 +126,17 @@

Source code for pyts.runInput.main

     This function determines which file-types to writeout (bladed or
     TurbSim) from the `tsinput` object
     """
-    if fname is None:
+    if fname is None:
         fname = tsinput.fname
-    if tsinput['WrBLFF']:
+    if tsinput['WrBLFF']:
         tsdat.write_bladed(fname)
-    if tsinput['WrADFF']:
+    if tsinput['WrADFF']:
         tsdat.write_turbsim(fname)
-    if tsinput['WrFMTFF']:
+    if tsinput['WrFMTFF']:
         tsdat.write_formatted(fname)
-    tsdat.write_sum(fname)
+    tsdat.write_sum(fname)
+ -
[docs]def cfg2grid(tsinput): """ cfg2grid produces a TurbSim-grid object that matches the @@ -152,16 +153,16 @@

Source code for pyts.runInput.main

                 A PyTurbSim grid object.
 
     """
-    return tsGrid(tsinput['HubHt'],
-                  ny=tsinput['NumGrid_Y'], nz=tsinput['NumGrid_Z'],
-                  dt=tsinput['TimeStep'],
-                  width=tsinput['GridWidth'], height=tsinput['GridHeight'],
-                  time_sec=tsinput['AnalysisTime'],
-                  time_sec_out=(tsinput['UsableTime'] + tsinput['GridWidth']
-                                / tsinput['URef']),
-                  clockwise=tsinput['Clockwise'])
+    return tsGrid(tsinput['HubHt'],
+                  ny=tsinput['NumGrid_Y'], nz=tsinput['NumGrid_Z'],
+                  dt=tsinput['TimeStep'],
+                  width=tsinput['GridWidth'], height=tsinput['GridHeight'],
+                  time_sec=tsinput['AnalysisTime'],
+                  time_sec_out=(tsinput['UsableTime'] + tsinput['GridWidth']
+                                / tsinput['URef']),
+                  clockwise=tsinput['Clockwise'])
+ -
[docs]def cfg2tsrun(tsinput): """ Produce a `tsrun` object that matches the configuration options in @@ -181,7 +182,7 @@

Source code for pyts.runInput.main

 
     """
 
-    tsr = tsrun(tsinput['RandSeed'])
+    tsr = tsrun(tsinput['RandSeed'])
 
     tsr.grid = cfg2grid(tsinput)
 
@@ -189,7 +190,7 @@ 

Source code for pyts.runInput.main

 
     tsr.specModel, tsr.cohereModel, tsr.stressModel = tm_getModel(tsinput)
 
-    # Store this for use when writing sum files.
+    # Store this for use when writing sum files.
     tsr._config = tsinput
 
     return tsr
@@ -211,14 +212,11 @@

Related Topics

@@ -226,11 +224,11 @@

Quick search

diff --git a/docs/_modules/pyts/runInput/profModels.html b/docs/_modules/pyts/runInput/profModels.html index 43833e6..91c261f 100644 --- a/docs/_modules/pyts/runInput/profModels.html +++ b/docs/_modules/pyts/runInput/profModels.html @@ -1,38 +1,39 @@ + - - - pyts.runInput.profModels — PyTurbSim 0.4.7 documentation - + pyts.runInput.profModels — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,7 +41,7 @@

Source code for pyts.runInput.profModels

-"""
+"""
 This module contains functions for producing the appropriate profile
 model for a specific TurbSim input object (derived from an input
 file).
@@ -49,7 +50,7 @@ 

Source code for pyts.runInput.profModels

 wrapper function here in order to be accessible using input files.
 
 """
-from ..profModels import api as pm
+from ..profModels import api as pm
 
 
 
[docs]def getModel(tsinput): @@ -69,11 +70,11 @@

Source code for pyts.runInput.profModels

                 specified in `tsinput`.
 
     """
-    # This executes the sub-wrapper function (defined below) specified
-    # in the tsinput-object (input file WINDPROFILETYPE line)
-    return eval('_' + tsinput['WindProfileType'].lower() + '(tsinput)')
+    # This executes the sub-wrapper function (defined below) specified
+    # in the tsinput-object (input file WINDPROFILETYPE line)
+    return eval('_' + tsinput['WindProfileType'].lower() + '(tsinput)')
+ -
def _h2l(tsinput): """ This function parses the correct variables from the tsinput @@ -90,9 +91,9 @@

Source code for pyts.runInput.profModels

                 H2O-log mean profile model instance.
 
     """
-    return pm.h2l(tsinput['URef'],
-                  tsinput['RefHt'],
-                  tsinput['UStar'])
+    return pm.h2l(tsinput['URef'],
+                  tsinput['RefHt'],
+                  tsinput['UStar'])
 
 
 def _log(tsinput):
@@ -111,11 +112,11 @@ 

Source code for pyts.runInput.profModels

                 wind log mean profile model instance.
 
     """
-    return pm.log(tsinput['URef'],
-                  tsinput['RefHt'],
-                  tsinput['Z0'],
-                  tsinput['RICH_NO'],
-                  tsinput['TurbModel'])
+    return pm.log(tsinput['URef'],
+                  tsinput['RefHt'],
+                  tsinput['Z0'],
+                  tsinput['RICH_NO'],
+                  tsinput['TurbModel'])
 
 
 def _pl(tsinput):
@@ -134,9 +135,9 @@ 

Source code for pyts.runInput.profModels

                 power-law mean profile model instance.
 
     """
-    return pm.pl(tsinput['URef'],
-                 tsinput['RefHt'],
-                 tsinput['PLExp'])
+    return pm.pl(tsinput['URef'],
+                 tsinput['RefHt'],
+                 tsinput['PLExp'])
 
 
 def _iec(tsinput):
@@ -155,11 +156,11 @@ 

Source code for pyts.runInput.profModels

                 IEC mean profile model instance.
 
     """
-    return pm.iec(tsinput['URef'],
-                  tsinput['RefHt'],
-                  tsinput['Z0'],
-                  tsinput['PLExp'],
-                  tsinput['TurbModel'],)
+    return pm.iec(tsinput['URef'],
+                  tsinput['RefHt'],
+                  tsinput['Z0'],
+                  tsinput['PLExp'],
+                  tsinput['TurbModel'],)
 
@@ -178,14 +179,11 @@

Related Topics

@@ -193,11 +191,11 @@

Quick search

diff --git a/docs/_modules/pyts/runInput/turbModels.html b/docs/_modules/pyts/runInput/turbModels.html index 7e7c47a..f40ace8 100644 --- a/docs/_modules/pyts/runInput/turbModels.html +++ b/docs/_modules/pyts/runInput/turbModels.html @@ -1,38 +1,39 @@ + - - - pyts.runInput.turbModels — PyTurbSim 0.4.7 documentation - + pyts.runInput.turbModels — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,7 +41,7 @@

Source code for pyts.runInput.turbModels

-"""
+"""
 This module contains functions for producing the appropriate turbulence
 model for a specific TurbSim input object (derived from an input
 file).
@@ -58,9 +59,9 @@ 

Source code for pyts.runInput.turbModels

 input files add a wrapper function for it here.
 
 """
-from ..specModels import api as sm
-from ..cohereModels import api as cm
-from ..stressModels import api as rm
+from ..specModels import api as sm
+from ..cohereModels import api as cm
+from ..stressModels import api as rm
 
 
 
[docs]def getModel(tsinput): @@ -86,37 +87,37 @@

Source code for pyts.runInput.turbModels

                         specified in `tsinput`.
 
     """
-    # This executes the sub-wrapper function (defined below) specified
-    # in the tsinput-object (input file TurbModel line)
-    return eval('_' + tsinput['TurbModel'].lower() + '(tsinput)')
+    # This executes the sub-wrapper function (defined below) specified
+    # in the tsinput-object (input file TurbModel line)
+    return eval('_' + tsinput['TurbModel'].lower() + '(tsinput)')
+ -
def _tidal(tsinput): - smodel = sm.tidal(tsinput['UStar'], tsinput['RefHt']) - cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, tsinput['CohExp']) - rmodel = rm.tidal(tsinput['UStar'], tsinput['RefHt']) + smodel = sm.tidal(tsinput['UStar'], tsinput['RefHt']) + cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, tsinput['CohExp']) + rmodel = rm.tidal(tsinput['UStar'], tsinput['RefHt']) return smodel, cmodel, rmodel def _river(tsinput): - smodel = sm.river(tsinput['UStar'], - tsinput['RefHt']) + smodel = sm.river(tsinput['UStar'], + tsinput['RefHt']) cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, - tsinput['CohExp']) - rmodel = rm.tidal(tsinput['UStar'], - tsinput['RefHt']) + tsinput['CohExp']) + rmodel = rm.tidal(tsinput['UStar'], + tsinput['RefHt']) return smodel, cmodel, rmodel def _ieckai(tsinput): - smodel = sm.ieckai(tsinput['IEC_WindType'], - tsinput['IECstandard'], - tsinput['IECedition'], - tsinput['IECturbc'], - tsinput['ETMc']) - cmodel = cm.iec(tsinput['IECedition']) - # The IEC models do not look at Reynold's Stress. + smodel = sm.ieckai(tsinput['IEC_WindType'], + tsinput['IECstandard'], + tsinput['IECedition'], + tsinput['IECturbc'], + tsinput['ETMc']) + cmodel = cm.iec(tsinput['IECedition']) + # The IEC models do not look at Reynold's Stress. rmodel = rm.uniform(upvp_=0.0, upwp_=0.0, vpwp_=0.0) @@ -124,13 +125,13 @@

Source code for pyts.runInput.turbModels

 
 
 def _iecvkm(tsinput):
-    smodel = sm.iecvkm(tsinput['IEC_WindType'],
-                       tsinput['IECstandard'],
-                       tsinput['IECedition'],
-                       tsinput['IECturbc'],
-                       tsinput['ETMc'])
-    cmodel = cm.iec(tsinput['IECedition'])
-    # The IEC models do not look at Reynold's Stress.
+    smodel = sm.iecvkm(tsinput['IEC_WindType'],
+                       tsinput['IECstandard'],
+                       tsinput['IECedition'],
+                       tsinput['IECturbc'],
+                       tsinput['ETMc'])
+    cmodel = cm.iec(tsinput['IECedition'])
+    # The IEC models do not look at Reynold's Stress.
     rmodel = rm.uniform(upvp_=0.0,
                         upwp_=0.0,
                         vpwp_=0.0)
@@ -138,21 +139,21 @@ 

Source code for pyts.runInput.turbModels

 
 
 def _nwtcup(tsinput):
-    smodel = sm.nwtcup(tsinput['UStar'], tsinput['RICH_NO'], tsinput['ZI'])
-    cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, tsinput['CohExp'])
-    rmodel = rm.uniform(upvp_=tsinput['PC_UV'],
-                        upwp_=tsinput['PC_UW'],
-                        vpwp_=tsinput['PC_VW'])
+    smodel = sm.nwtcup(tsinput['UStar'], tsinput['RICH_NO'], tsinput['ZI'])
+    cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, tsinput['CohExp'])
+    rmodel = rm.uniform(upvp_=tsinput['PC_UV'],
+                        upwp_=tsinput['PC_UW'],
+                        vpwp_=tsinput['PC_VW'])
     return smodel, cmodel, rmodel
 
 
 def _smooth(tsinput):
     smodel = sm.nwtc.smooth(
-        tsinput['UStar'], tsinput['RICH_NO'], tsinput['ZI'])
-    cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, tsinput['CohExp'])
-    rmodel = rm.uniform(upvp_=tsinput['PC_UV'],
-                        upwp_=tsinput['PC_UW'],
-                        vpwp_=tsinput['PC_VW'])
+        tsinput['UStar'], tsinput['RICH_NO'], tsinput['ZI'])
+    cmodel = cm.nwtc(tsinput.incdec_a, tsinput.incdec_b, tsinput['CohExp'])
+    rmodel = rm.uniform(upvp_=tsinput['PC_UV'],
+                        upwp_=tsinput['PC_UW'],
+                        vpwp_=tsinput['PC_VW'])
     return smodel, cmodel, rmodel
 
@@ -172,14 +173,11 @@

Related Topics

@@ -187,11 +185,11 @@

Quick search

diff --git a/docs/_modules/pyts/specModels/base.html b/docs/_modules/pyts/specModels/base.html index 9ad92ba..1faa86b 100644 --- a/docs/_modules/pyts/specModels/base.html +++ b/docs/_modules/pyts/specModels/base.html @@ -1,38 +1,39 @@ + - - - pyts.specModels.base — PyTurbSim 0.4.7 documentation - + pyts.specModels.base — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,12 +41,12 @@

Source code for pyts.specModels.base

-"""
+"""
 This is the turbulence spectrum package's base module.
 
 """
-from ..base import modelBase, ts_float, np, gridProps, calcObj
-from numpy import trapz
+from ..base import modelBase, ts_float, np, gridProps, calcObj
+from numpy import trapz
 
 
 
[docs]class specObj(gridProps, calcObj): @@ -68,7 +69,7 @@

Source code for pyts.specModels.base

                                tsrun.grid.n_z,
                                tsrun.grid.n_y,
                                tsrun.grid.n_f),
-                              dtype=ts_float, order='F')
+                              dtype=ts_float, order='F')
 
     @property
     def Suu(self,):
@@ -116,9 +117,9 @@ 

Source code for pyts.specModels.base

         coherence.
 
         """
-        return self.grid.flatten(self.array)
+        return self.grid.flatten(self.array)
+ -
[docs]class specModelBase(modelBase): """ @@ -144,14 +145,11 @@

Related Topics

@@ -159,11 +157,11 @@

Quick search

diff --git a/docs/_modules/pyts/specModels/hydro.html b/docs/_modules/pyts/specModels/hydro.html index 994ce54..f9fb48b 100644 --- a/docs/_modules/pyts/specModels/hydro.html +++ b/docs/_modules/pyts/specModels/hydro.html @@ -1,38 +1,39 @@ + - - - pyts.specModels.hydro — PyTurbSim 0.4.7 documentation - + pyts.specModels.hydro — PyTurbSim 0.4.8 documentation - - + - - + + + - + + - + +
@@ -40,16 +41,16 @@

Source code for pyts.specModels.hydro

-"""
+"""
 This module contains the turbulence models for the aquatic environment.
 
 """
-from .base import specModelBase, np, specObj, ts_float
+from .base import specModelBase, np, specObj, ts_float
 
 
 
[docs]class tidal(specModelBase): - r"""Tidal Channel spectral model. + r"""Tidal Channel spectral model. The tidal spectral model is based on measurements from Admiralty Inlet, in Puget Sound, WA. @@ -88,18 +89,20 @@

Source code for pyts.specModels.hydro

     :attr:`coef` : The 'fit coefficients'
 
     """
-    coef = np.array([[1.21, 4.3], [0.33, 0.50], [0.23, 0.26]], dtype=ts_float)
+    coef = np.array([[1.21, 4.3],
+                     [0.33, 0.50],
+                     [0.23, 0.26]], dtype=ts_float)
 
     def __init__(self, Ustar, Zref):
         self.Ustar = Ustar
         self.Zref = Zref
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Turbulence model used                            =  {dat.model_desc}
-        Turbulence velocity (UStar)                      =  {dat.Ustar:0.4g} [m/s]
-        Log roughness scale (Zref)                       =  {dat.Zref:0.4g} [m]
-        """
+        sumstring_format = """
+        Turbulence model used                            =  {dat.model_desc}
+        Turbulence velocity (UStar)                      =  {dat.Ustar:0.4g} [m/s]
+        Log roughness scale (Zref)                       =  {dat.Zref:0.4g} [m]
+        """
         return sumstring_format.format(dat=self)
 
 
[docs] def __call__(self, tsrun): @@ -117,16 +120,16 @@

Source code for pyts.specModels.hydro

 
         """
         out = specObj(tsrun)
-        dudz = np.abs(tsrun.prof.dudz[None, :, :, None])
-        out.sigma2 = self.Ustar ** 2 * np.array([4.5, 2.25, 0.9])[:, None] \
-            * np.exp(-2 * tsrun.grid.z[None, :] / self.Zref)
-        out[:] = (out.sigma2[:, :, None, None]
-                  * self.coef[:, 0][:, None, None, None] / dudz
-                  ) / (1 + self.coef[:, 1][:, None, None, None]
-                       * (tsrun.grid.f[None, None, None, :] / dudz) ** self.pow5_3)
-        return out
-
-
+ dudz = np.abs(tsrun.prof.dudz[None, :, :, None]) + out.sigma2 = self.Ustar ** 2 * np.array([4.5, 2.25, 0.9])[:, None] \ + * np.exp(-2 * tsrun.grid.z[None, :] / self.Zref) + out[:] = (out.sigma2[:, :, None, None] + * self.coef[:, 0][:, None, None, None] / dudz + ) / (1 + self.coef[:, 1][:, None, None, None] + * (tsrun.grid.f[None, None, None, :] / dudz) ** self.pow5_3) + return out
+ +
[docs]class river(tidal): """River turbulence spectral model. @@ -136,14 +139,14 @@

Source code for pyts.specModels.hydro

     different values for :attr:`coef`.
     """
 
-    # These fit positive velocity data in eastriver:
+    # These fit positive velocity data in eastriver:
     coef = np.array([[1.057, 3.432],
                      [0.351, 0.546],
-                     [0.265, 0.341]], dtype=ts_float)
-    ## # These fit negative velocity data in eastriver:
-    ## coef = np.array([[0.784, 2.085],
-    ##                  [0.272, 0.357],
-    ##                  [0.240, 0.290]], dtype=ts_float)
+ [0.265, 0.341]], dtype=ts_float)
+ ## # These fit negative velocity data in eastriver: + ## coef = np.array([[0.784, 2.085], + ## [0.272, 0.357], + ## [0.240, 0.290]], dtype=ts_float)
@@ -162,14 +165,11 @@

Related Topics

@@ -177,11 +177,11 @@

Quick search

diff --git a/docs/_modules/pyts/specModels/iec.html b/docs/_modules/pyts/specModels/iec.html index a9f7000..8259fb7 100644 --- a/docs/_modules/pyts/specModels/iec.html +++ b/docs/_modules/pyts/specModels/iec.html @@ -1,38 +1,39 @@ + - - - pyts.specModels.iec — PyTurbSim 0.4.7 documentation - + pyts.specModels.iec — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.specModels.iec

-"""
+"""
 This module contains the IEC turbulence models.
 
 See the
@@ -49,14 +50,14 @@ 

Source code for pyts.specModels.iec

 for more info on IEC spectral models.
 
 """
-from .base import specModelBase, np, ts_float, specObj
-from ..misc import InvalidConfig, Lambda
+from .base import specModelBase, np, ts_float, specObj
+from ..misc import InvalidConfig, Lambda
 import warnings
 
 
 
[docs]class iecbase(specModelBase): - r""" + r""" This is a base class for the IEC spectral models (IECKAI and IECVKM). Parameters @@ -91,7 +92,7 @@

Source code for pyts.specModels.iec

     """
 
     def __init__(self, IECwindtype, IECstandard,
-                 IECedition, IECturbc, ETMc=None):
+                 IECedition, IECturbc, ETMc=None):
         self.IECwindtype = IECwindtype
         self.IECstandard = IECstandard
         self.IECedition = IECedition
@@ -99,37 +100,37 @@ 

Source code for pyts.specModels.iec

         self.ETMc = ETMc
 
     def _sumfile_string(self, tsrun):
-        windtype_desc = {'NTM': 'Normal Turbulence Model',
-                         'ETM': 'Extreme Turbulence Model',
-                         '1EWM1': 'Extreme 1-Year Wind Speed Model (Class 1)',
-                         '2EWM1': 'Extreme 1-Year Wind Speed Model (Class 2)',
-                         '3EWM1': 'Extreme 1-Year Wind Speed Model (Class 3)',
-                         '1EWM50': 'Extreme 50-Year Wind Speed Model (Class 1)',
-                         '2EWM50': 'Extreme 50-Year Wind Speed Model (Class 2)',
-                         '3EWM50': 'Extreme 50-Year Wind Speed Model (Class 3)',
+        windtype_desc = {'NTM': 'Normal Turbulence Model',
+                         'ETM': 'Extreme Turbulence Model',
+                         '1EWM1': 'Extreme 1-Year Wind Speed Model (Class 1)',
+                         '2EWM1': 'Extreme 1-Year Wind Speed Model (Class 2)',
+                         '3EWM1': 'Extreme 1-Year Wind Speed Model (Class 3)',
+                         '1EWM50': 'Extreme 50-Year Wind Speed Model (Class 1)',
+                         '2EWM50': 'Extreme 50-Year Wind Speed Model (Class 2)',
+                         '3EWM50': 'Extreme 50-Year Wind Speed Model (Class 3)',
                          }
-        edition_desc = {(1, 1): 'IEC 61400-1 Ed. 1: 1993',
-                        (1, 2): 'IEC 61400-1 Ed. 2: 1999',
-                        (1, 3): 'IEC 61400-1 Ed. 3: 2005',
-                        (2, 2): 'IEC 61400-2 Ed. 2: 2005',
-                        (3, 1): 'IEC 61400-3 Ed. 1: 2006',
+        edition_desc = {(1, 1): 'IEC 61400-1 Ed. 1: 1993',
+                        (1, 2): 'IEC 61400-1 Ed. 2: 1999',
+                        (1, 3): 'IEC 61400-1 Ed. 3: 2005',
+                        (2, 2): 'IEC 61400-2 Ed. 2: 2005',
+                        (3, 1): 'IEC 61400-3 Ed. 1: 2006',
                         }
-        sumstring_format = """
-        Turbulence model used                            =  {TurbModel_desc}
-        Turbulence characteristic                        =  {IECturbc}
-        IEC turbulence type                              =  {IECwindtype_desc}
-        IEC standard                                     =  {IECstandard_desc}
-        IEC Length scale (Lambda)                        =  {Lambda:0.4g} [m]
-        IEC Sigma                                        =  {Sigma:0.4g} [m/s]
-        ETM 'c' value                                    =  {etmc}
-        """
+        sumstring_format = """
+        Turbulence model used                            =  {TurbModel_desc}
+        Turbulence characteristic                        =  {IECturbc}
+        IEC turbulence type                              =  {IECwindtype_desc}
+        IEC standard                                     =  {IECstandard_desc}
+        IEC Length scale (Lambda)                        =  {Lambda:0.4g} [m]
+        IEC Sigma                                        =  {Sigma:0.4g} [m/s]
+        ETM 'c' value                                    =  {etmc}
+        """
         data = dict(
             TurbModel_desc=self.model_desc,
-            IECturbc=(self.IECturbc if isinstance(self.IECturbc, basestring)
-                      else '0.4g [%]'.format(self.IECturbc)),
+            IECturbc=(self.IECturbc if isinstance(self.IECturbc, basestring)
+                      else '0.4g [%]'.format(self.IECturbc)),
             IECwindtype_desc=windtype_desc[self.IECwindtype],
             IECstandard_desc=edition_desc[(self.IECstandard, self.IECedition)],
-            etmc='N/A' if self.ETMc is None else '{0:0.4g} [m/s]'.format(self.ETMc),
+            etmc='N/A' if self.ETMc is None else '{0:0.4g} [m/s]'.format(self.ETMc),
             Lambda=self.Lambda(tsrun.grid.zhub),
             Sigma=self.IEC_Sigma(tsrun.prof.uhub),
         )
@@ -143,21 +144,21 @@ 

Source code for pyts.specModels.iec

         --------
         :func:`pyts.misc.Lambda`
         """
-        return Lambda(zhub, self.IECedition)
-
+ return Lambda(zhub, self.IECedition)
+ def _check_ewm(self, grid): - if (self.IECturbc.__class__ is str and + if (self.IECturbc.__class__ is str and self.IECstandard == 1 and self.IECedition == 3 and - self.IECwindtype.upper()[1:4] == 'EWM' and + self.IECwindtype.upper()[1:4] == 'EWM' and self.grid.time_sec_out != 600.): - warnings.warn("The extreme wind model is only valid \ - for 10min(600s) runs. Setting \ - 'UsableTime' to 600s.") + warnings.warn("The extreme wind model is only valid \ + for 10min(600s) runs. Setting \ + 'UsableTime' to 600s.") grid.time_sec_out = 600.
[docs] def IEC_Sigma(self, uhub): - r""" + r""" Calculate the default value of the standard deviation of u-component wind speed, :math:`\sigma` or :math:`\sigma_u`. @@ -211,64 +212,64 @@

Source code for pyts.specModels.iec

                  \sigma = 0.11 V_{ref}
         """
         iecver = self.IECstandard
-        if self.IECturbc.__class__ is str:
-            # !!!VERSION_INCONSISTENCY: add 'khtest' functionality.
+        if self.IECturbc.__class__ is str:
+            # !!!VERSION_INCONSISTENCY: add 'khtest' functionality.
             val = self.IECturbc.lower()
             wndtp = self.IECwindtype.lower()
             edi = self.IECedition
-            if iecver is None:
-                return None
-            if iecver == 1:  # Onshore-big wind.
-                if edi == 2:  # 2nd edition
-                    if (wndtp != 'ntm'):
-                        raise InvalidConfig("For IEC Turbulence models \
-                        other than NTM, the iec edition must be 3.")
-                    if val == 'a':
+            if iecver is None:
+                return None
+            if iecver == 1:  # Onshore-big wind.
+                if edi == 2:  # 2nd edition
+                    if (wndtp != 'ntm'):
+                        raise InvalidConfig("For IEC Turbulence models \
+                        other than NTM, the iec edition must be 3.")
+                    if val == 'a':
                         TurbInt15 = 0.18
                         SigmaSlope = 2.0
-                    elif val == 'b':
+                    elif val == 'b':
                         TurbInt15 = 0.16
                         SigmaSlope = 3.0
                     else:
                         raise InvalidConfig(
-                            "For the 61400-1 2nd edition, IECturbc must be \
-                            set to 'a', 'b', or a number (Turbulence \
-                            intensity)."
+                            "For the 61400-1 2nd edition, IECturbc must be \
+                            set to 'a', 'b', or a number (Turbulence \
+                            intensity)."
                         )
 
                     IEC_Sigma = TurbInt15 * \
                         ((15.0 + SigmaSlope * uhub) / (SigmaSlope + 1))
                     return IEC_Sigma
 
-                elif edi == 3:  # 3rd edition
-                    if val == 'a':
+                elif edi == 3:  # 3rd edition
+                    if val == 'a':
                         TurbInt15 = 0.16
-                    elif val == 'b':
+                    elif val == 'b':
                         TurbInt15 = 0.14
-                    elif val == 'c':
+                    elif val == 'c':
                         TurbInt15 = 0.12
                     else:
                         raise InvalidConfig(
-                            "For the 61400-1 3rd edition, IECturbc must be \
-                            set to 'a', 'b', 'c', or a number (Turbulence \
-                            intensity)."
+                            "For the 61400-1 3rd edition, IECturbc must be \
+                            set to 'a', 'b', 'c', or a number (Turbulence \
+                            intensity)."
                         )
 
-                    if wndtp == 'ntm':
-                        IEC_Sigma = TurbInt15 * (0.75 * uhub + 5.6)  # /uhub
+                    if wndtp == 'ntm':
+                        IEC_Sigma = TurbInt15 * (0.75 * uhub + 5.6)  # /uhub
                         return IEC_Sigma
-                    elif wndtp[0] not in ['1', '2', '3']:
+                    elif wndtp[0] not in ['1', '2', '3']:
                         raise InvalidConfig(
-                            "A wind turbine class (1, 2 or 3) must be \
-                            specified with the extreme turbulence and \
-                            extreme wind types (e.g. '1ETM' or '2EWM')."
+                            "A wind turbine class (1, 2 or 3) must be \
+                            specified with the extreme turbulence and \
+                            extreme wind types (e.g. '1ETM' or '2EWM')."
                         )
 
-                    elif wndtp[1:4] in ['etm', 'ewm']:
-                        Vref = {'1': 50, '2': 42.5, '3': 37.5}[wndtp[0]]
+                    elif wndtp[1:4] in ['etm', 'ewm']:
+                        Vref = {'1': 50, '2': 42.5, '3': 37.5}[wndtp[0]]
                         wndtp = wndtp[1:]
-                        if wndtp == 'etm':
-                            if self.ETMc is None:
+                        if wndtp == 'etm':
+                            if self.ETMc is None:
                                 self.ETMc = 2.0
                             IEC_Sigma = self.ETMc * TurbInt15 * \
                                 (0.072 * (0.2 * Vref / self.ETMc + 3.) * (
@@ -277,22 +278,22 @@ 

Source code for pyts.specModels.iec

                         else:
                             return 0.11 * Vref
                     else:
-                        raise InvalidConfig("Invalid 'IEC_WindType' specified in the input file.")
-            elif iecver == 2:  # Small wind.
-                raise InvalidConfig("The 'small wind' spectral model (IEC version 2) is not "
-                                    "implemented in PyTurbSim")
-            elif iecver == 3:  # Offshore wind.
-                raise InvalidConfig("The offshore wind IEC spectral model (IEC version 3) is "
-                                    "not implemented in PyTurbSim")
-        else:  # The IECturbc is numeric.
-            if wndtp != 'ntm':
-                raise InvalidConfig("If the 'IECturbc' input option is a number (specifying "
-                                    "turbulence intensity), the IEC_WindType must be 'NTM'.")
-
-
+ raise InvalidConfig("Invalid 'IEC_WindType' specified in the input file.") + elif iecver == 2: # Small wind. + raise InvalidConfig("The 'small wind' spectral model (IEC version 2) is not " + "implemented in PyTurbSim") + elif iecver == 3: # Offshore wind. + raise InvalidConfig("The offshore wind IEC spectral model (IEC version 3) is " + "not implemented in PyTurbSim") + else: # The IECturbc is numeric. + if wndtp != 'ntm': + raise InvalidConfig("If the 'IECturbc' input option is a number (specifying " + "turbulence intensity), the IEC_WindType must be 'NTM'.")
+ +
[docs]class IECKai(iecbase): - r"""IEC Kaimal spectral model. + r"""IEC Kaimal spectral model. Notes ----- @@ -340,13 +341,13 @@

Source code for pyts.specModels.iec

             np.array([8.10, 2.70, 0.66], dtype=ts_float)
         for comp in self.comp:
             out[comp] = (sig2 * fctr[comp] * L_u[comp] / (
-                1 + 6 * out.f * L_u[comp]) ** self.pow5_3)[None, None, :]
-        return out
+                1 + 6 * out.f * L_u[comp]) ** self.pow5_3)[None, None, :]
+        return out
+ -
[docs]class IECVKm(iecbase): - r"""IEC Von-Karman spectral model + r"""IEC Von-Karman spectral model Notes ----- @@ -391,9 +392,9 @@

Source code for pyts.specModels.iec

         sig2 = 4 * self.IEC_Sigma(tsrun.prof.uhub) ** 2
         L_u = 3.5 * self.Lambda(tsrun.grid.zhub) / tsrun.prof.uhub
         dnm = 1 + 71 * (out.f * L_u) ** 2
-        out[0] = (sig2 * L_u / (dnm) ** 0.8333333)[None, None, :]
+        out[0] = (sig2 * L_u / (dnm) ** 0.8333333)[None, None, :]
         out[2] = out[1] = (sig2 / 2 * L_u / (dnm) ** 1.8333333 *
-                           (1 + 189 * (out.f * L_u) ** 2))[None, None, :]
+                           (1 + 189 * (out.f * L_u) ** 2))[None, None, :]
         return out
@@ -413,14 +414,11 @@

Related Topics

@@ -428,11 +426,11 @@

Quick search

diff --git a/docs/_modules/pyts/specModels/kelley_coefs.html b/docs/_modules/pyts/specModels/kelley_coefs.html index a631956..0bca30e 100644 --- a/docs/_modules/pyts/specModels/kelley_coefs.html +++ b/docs/_modules/pyts/specModels/kelley_coefs.html @@ -1,38 +1,39 @@ + - - - pyts.specModels.kelley_coefs — PyTurbSim 0.4.7 documentation - + pyts.specModels.kelley_coefs — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,99 +41,99 @@

Source code for pyts.specModels.kelley_coefs

-from ..base import ts_float,np
+from ..base import ts_float,np
 
 p_coefs_unstable=[
-    # u-coefs
+    # u-coefs
     [0.5,105.],
-    # v-coefs
+    # v-coefs
     [0.95,17.],
-    # w-coefs
+    # w-coefs
     [0.95,2.],]
 f_coefs_unstable=[
-    # u-coefs
+    # u-coefs
     [ts_float(2.2**(3./5.)),33],
-    # v-coefs
+    # v-coefs
     [2,9.5],
-    # w-coefs
+    # w-coefs
     [2,5.3],]
 
-# These coefficients are copied from TSsubs.f90.
-# They were calculated by Neil Kelley based on data from the NWTC.
-nwtcup_coefs={'stable':{},'unstable':{}}
-nwtcup_coefs['stable']['terms']={'fr_il':np.array([[0.0964,-0.316,0,-0.386,0],
+# These coefficients are copied from TSsubs.f90.
+# They were calculated by Neil Kelley based on data from the NWTC.
+nwtcup_coefs={'stable':{},'unstable':{}}
+nwtcup_coefs['stable']['terms']={'fr_il':np.array([[0.0964,-0.316,0,-0.386,0],
                                              [0.0323,-0.388,0,-0.389,0],
                                              [0.0972,-0.0964,0,-0.616,0]],dtype=ts_float),
-                           'fr_ih':np.array([[1.69,-.340,0,-.133,0],
+                           'fr_ih':np.array([[1.69,-.340,0,-.133,0],
                                              [0.473,-0.441,0,0.291,0],
                                              [0.470,-0.218,0,-0.158,0],],dtype=ts_float),
-                           'Pr_il':np.array([[1.21,0.0523,0,0.189,0],
+                           'Pr_il':np.array([[1.21,0.0523,0,0.189,0],
                                              [1.29,0.00664,0,0.354,0],
                                              [0.368,0.0938,0,0.109,0],],dtype=ts_float),
-                           'Pr_ih':np.array([[0.224,0.170,0,0.223,0],
+                           'Pr_ih':np.array([[0.224,0.170,0,0.223,0],
                                              [0.991,0.344,0,-0.605,0],
                                              [0.639,0.0354,0,-0.0319,0],],dtype=ts_float)
                            }
-nwtcup_coefs['stable']['min']={'fr_il':(0.015,0.003,0.006),
-                         'fr_ih':(0.35,0.25,0.2),
-                         'Pr_il':(0.8,0.95,0.2),
-                         'Pr_ih':(0.05,0.2,0.25),
+nwtcup_coefs['stable']['min']={'fr_il':(0.015,0.003,0.006),
+                         'fr_ih':(0.35,0.25,0.2),
+                         'Pr_il':(0.8,0.95,0.2),
+                         'Pr_ih':(0.05,0.2,0.25),
                          }
-nwtcup_coefs['stable']['max']={'fr_il':(0.4,0.23,0.175),
-                         'fr_ih':(10.,3.,1.25),
-                         'Pr_il':(2.25,2.25,0.75),
-                         'Pr_ih':(0.8,1.0,1.0),
+nwtcup_coefs['stable']['max']={'fr_il':(0.4,0.23,0.175),
+                         'fr_ih':(10.,3.,1.25),
+                         'Pr_il':(2.25,2.25,0.75),
+                         'Pr_ih':(0.8,1.0,1.0),
                          }
-nwtcup_coefs['unstable']['terms']={
-    'fr_il':np.array([
+nwtcup_coefs['unstable']['terms']={
+    'fr_il':np.array([
         [  0.08825035, -0.08806865, -0.26295052,  1.74135233, 1.86785832 ],
         [  0.58374913, -0.53220033,  1.49509302,  3.61867635, -0.98540722 ],
         [  0.81092087, -0.03483105,  0.58332966, -0.10731274, -0.16463702 ],],dtype=ts_float),
-    'fr_ih':np.array([
+    'fr_ih':np.array([
         [  1.34307411, -0.55126969, -0.07034031,  0.40185202, -0.55083463 ],
         [  4.30596626,  0.31302745, -0.26457011, -1.41513284, 0.91503248 ],
         [  1.05515450, -0.25002535,  0.14528047,  1.00641958, -0.67569359 ],],dtype=ts_float),
-    'Pr_il':np.array([
+    'Pr_il':np.array([
         [ 57.51578485, -1.89080610,  4.03260796,  6.09158000, -7.47414385 ],
         [ 32.06436225, -1.43676866,  3.57797045,  5.31617813, -5.76800891 ],
         [  6.60003543, -0.45005503,  1.35937877,  2.45632937, -1.98267575 ],],dtype=ts_float),
-    'Pr_ih':np.array([
+    'Pr_ih':np.array([
         [  4.52702491,  0.72447070, -0.10602646, -3.73265876, -0.49429015 ],
         [  3.93109762,  0.57974534, -0.20510478, -4.85367443, -0.61610914 ],
         [ 16.56290180,  0.40464339,  0.82276250, -3.92300971, -1.82957067 ],],dtype=ts_float),
     }
-nwtcup_coefs['unstable']['min']={'fr_il':(0.2,0.12,0.2),
-                           'fr_ih':(0.1,1.8,.95),
-                           'Pr_il':(1.0,0.2,1.0),
-                           'Pr_ih':(0.1,0.2,0.3),
+nwtcup_coefs['unstable']['min']={'fr_il':(0.2,0.12,0.2),
+                           'fr_ih':(0.1,1.8,.95),
+                           'Pr_il':(1.0,0.2,1.0),
+                           'Pr_ih':(0.1,0.2,0.3),
                            }
-nwtcup_coefs['unstable']['max']={'fr_il':(1.5,2.3,1.4),
-                           'fr_ih':(8.0,7.5,1.75),
-                           'Pr_il':(8.,8.,7.),
-                           'Pr_ih':(1.2,0.9,1.0),
+nwtcup_coefs['unstable']['max']={'fr_il':(1.5,2.3,1.4),
+                           'fr_ih':(8.0,7.5,1.75),
+                           'Pr_il':(8.,8.,7.),
+                           'Pr_ih':(1.2,0.9,1.0),
                            }
 
 
[docs]def calc_nwtcup_coefs(zL): p_coefs=np.empty((3,2),dtype=ts_float) f_coefs=np.empty((3,2),dtype=ts_float) if zL>0: - dat=nwtcup_coefs['stable'] + dat=nwtcup_coefs['stable'] loc_zL=fix2range(zL,0.005,3.5) ustar_tmp=0. else: - dat=nwtcup_coefs['unstable'] + dat=nwtcup_coefs['unstable'] loc_zL=np.abs(fix2range(zL,-0.5,-0.025)) ustar_tmp=fix2range(self.UStar,0.2,1.4) - for i0,sfx in enumerate(['il','ih']): - nm='Pr_'+sfx - arr=dat['terms'][nm] - p_coefs[:,i0]=fix2range(arr[:,0]*(loc_zL**arr[:,1])*ustar_tmp**arr[:,2]*np.exp(arr[:,3]*loc_zL+arr[:,4]*ustar_tmp),dat['min'][nm],dat['max'][nm]) - nm='fr_'+sfx - arr=dat['terms'][nm] - f_coefs[:,i0]=fix2range(arr[:,0]*(loc_zL**arr[:,1])*ustar_tmp**arr[:,2]*np.exp(arr[:,3]*loc_zL+arr[:,4]*ustar_tmp),dat['min'][nm],dat['max'][nm]) - f_coefs**=-1 # Invert the second (fr) coefficient. - p_coefs*=f_coefs # All of the first coefficients are the product of the first and the second (inverse included). - # The factors in unstable_coefs are included in the fits that N. Kelley did. + for i0,sfx in enumerate(['il','ih']): + nm='Pr_'+sfx + arr=dat['terms'][nm] + p_coefs[:,i0]=fix2range(arr[:,0]*(loc_zL**arr[:,1])*ustar_tmp**arr[:,2]*np.exp(arr[:,3]*loc_zL+arr[:,4]*ustar_tmp),dat['min'][nm],dat['max'][nm]) + nm='fr_'+sfx + arr=dat['terms'][nm] + f_coefs[:,i0]=fix2range(arr[:,0]*(loc_zL**arr[:,1])*ustar_tmp**arr[:,2]*np.exp(arr[:,3]*loc_zL+arr[:,4]*ustar_tmp),dat['min'][nm],dat['max'][nm]) + f_coefs**=-1 # Invert the second (fr) coefficient. + p_coefs*=f_coefs # All of the first coefficients are the product of the first and the second (inverse included). + # The factors in unstable_coefs are included in the fits that N. Kelley did. p_coefs*=np.array(p_coefs_unstable,dtype=ts_float) f_coefs*=np.array(f_coefs_unstable,dtype=ts_float)
@@ -153,14 +154,11 @@

Related Topics

@@ -168,11 +166,11 @@

Quick search

diff --git a/docs/_modules/pyts/specModels/nwtc.html b/docs/_modules/pyts/specModels/nwtc.html index c828a13..4d3c2ed 100644 --- a/docs/_modules/pyts/specModels/nwtc.html +++ b/docs/_modules/pyts/specModels/nwtc.html @@ -1,38 +1,39 @@ + - - - pyts.specModels.nwtc — PyTurbSim 0.4.7 documentation - + pyts.specModels.nwtc — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,12 +41,12 @@

Source code for pyts.specModels.nwtc

-"""
+"""
 This module contains the nwtc spectral models.
 """
-from .base import np, ts_float, specObj, specModelBase
-from ..misc import zL
-from .kelley_coefs import calc_nwtcup_coefs, p_coefs_unstable, f_coefs_unstable
+from .base import np, ts_float, specObj, specModelBase
+from ..misc import zL
+from .kelley_coefs import calc_nwtcup_coefs, p_coefs_unstable, f_coefs_unstable
 
 
 
[docs]class genNWTC(specModelBase): @@ -72,23 +73,23 @@

Source code for pyts.specModels.nwtc

 
         """
         out = specObj(tsrun)
-        # !!!FIXTHIS: The following lines bind calculation to the
-        # !!!MODEL. This goes against the PyTurbSim philosophy of
-        # !!!keeping calculations separated from models.
+        # !!!FIXTHIS: The following lines bind calculation to the
+        # !!!MODEL. This goes against the PyTurbSim philosophy of
+        # !!!keeping calculations separated from models.
         self.f = out.f
         self._work = np.zeros(out.n_f, dtype=ts_float)
         self.zhub = tsrun.grid.zhub
-        # Fixing this will require something like changing:
-        #   out[comp][iz, iy] = model(z, u, comp)
-        # to:
-        #   self.model(out, u, icomp, iz, iy)
-        # Note here that u must be supplied explicitly because it is
-        # not known to 'out'.
-        # This would also require:
-        # 1) deleting the self._work variable
-        # 2) changing ``def L(self,)`` from a property to ``def
-        #    L(self, tsrun)`` and using tsrun.grid.zhub their.
-        # 3) changing all calls to ``self.L`` accordingly.
+        # Fixing this will require something like changing:
+        #   out[comp][iz, iy] = model(z, u, comp)
+        # to:
+        #   self.model(out, u, icomp, iz, iy)
+        # Note here that u must be supplied explicitly because it is
+        # not known to 'out'.
+        # This would also require:
+        # 1) deleting the self._work variable
+        # 2) changing ``def L(self,)`` from a property to ``def
+        #    L(self, tsrun)`` and using tsrun.grid.zhub their.
+        # 3) changing all calls to ``self.L`` accordingly.
         for iz in range(out.n_z):
             for iy in range(out.n_y):
                 z = out.grid.z[iz]
@@ -96,12 +97,12 @@ 

Source code for pyts.specModels.nwtc

                 for comp in out.grid.comp:
                     self._work[:] = 0.0
                     out[comp][iz, iy] = self.model(z, u, comp)
-        return out
+        return out
+ -
[docs]class NWTC_stable(genNWTC): - r"""The NWTC 'stable' spectral model. + r"""The NWTC 'stable' spectral model. Parameters ---------- @@ -148,24 +149,24 @@

Source code for pyts.specModels.nwtc

     """
     s_coef = np.array([[79., 263.], [13., 32.], [3.5, 8.6]])
 
-    def __init__(self, Ustar, zL, coef=None):
+    def __init__(self, Ustar, zL, coef=None):
         self.Ustar = Ustar
         self.Ustar2 = self.Ustar ** 2
         self.zL = zL
-        if coef is None:
+        if coef is None:
             self.coefs = np.ones((3, 2), dtype=ts_float)
         else:
             self.coefs = coef
 
     def _sumfile_string(self, tsrun):
-        sumstring_format = """
-        Turbulence model used                            =  {dat.model_desc}
-        Turbulence velocity (UStar)                      =  {dat.Ustar:0.2f} [m/s]
-        Stability parameter (z/L)                        =  {dat.zL:0.2f}
-        coefs  u                           =  [{p[0][0]:0.2f}, {p[0][1]:0.2f}]
-               v                           =  [{p[1][0]:0.2f}, {p[1][1]:0.2f}]
-               w                           =  [{p[2][0]:0.2f}, {p[2][1]:0.2f}]
-        """
+        sumstring_format = """
+        Turbulence model used                            =  {dat.model_desc}
+        Turbulence velocity (UStar)                      =  {dat.Ustar:0.2f} [m/s]
+        Stability parameter (z/L)                        =  {dat.zL:0.2f}
+        coefs  u                           =  [{p[0][0]:0.2f}, {p[0][1]:0.2f}]
+               v                           =  [{p[1][0]:0.2f}, {p[1][1]:0.2f}]
+               w                           =  [{p[2][0]:0.2f}, {p[2][1]:0.2f}]
+        """
         return sumstring_format.format(dat=self,
                                        p=self.coefs,)
 
@@ -192,12 +193,12 @@ 

Source code for pyts.specModels.nwtc

                 self._work += self.model(z, u, comp)
             return self._work
         return (coef[0] * self.s_coef[comp, 0] * numer * z_u /
-                (1. + self.s_coef[comp, 1] * (coef[1] * z_u * denom) ** self.pow5_3))
+                (1. + self.s_coef[comp, 1] * (coef[1] * z_u * denom) ** self.pow5_3))
+ -
[docs]class NWTC_unstable(genNWTC): - r"""The NWTC 'unstable' spectral model. + r"""The NWTC 'unstable' spectral model. .. math:: S_k(f) = U_\mathrm{star}^2 G_k(f,\bar{u},z,ZI) \qquad k = u, v, w @@ -222,30 +223,30 @@

Source code for pyts.specModels.nwtc

 
     """
 
-    def __init__(self, Ustar, zL, ZI, p_coefs=None, f_coefs=None):
+    def __init__(self, Ustar, zL, ZI, p_coefs=None, f_coefs=None):
         self.Ustar = Ustar
         self.Ustar2 = self.Ustar ** 2
         self.zL = zL
         self.ZI = ZI
-        if p_coefs is None:
+        if p_coefs is None:
             self.p_coefs = p_coefs_unstable
-        if f_coefs is None:
+        if f_coefs is None:
             self.f_coefs = f_coefs_unstable
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Turbulence model used                            =  {dat.model_desc}
-        Turbulence velocity (UStar)                      =  {dat.Ustar:0.4g} [m/s]
-        Mixing layer depth (ZI)                          =  {dat.ZI:0.4g} [m]
-        Stability parameter (z/L)                        =  {dat.zL:0.4g}
-        Monin-Obhukov Length scale                       =  {Lmo:0.4g} [m]
-        p_coefs   u                =  [{p[0][0]:0.4g}, {p[0][1]:0.4g}]
-                  v                =  [{p[1][0]:0.4g}, {p[1][1]:0.4g}]
-                  w                =  [{p[2][0]:0.4g}, {p[2][1]:0.4g}]
-        f_coefs   u                =  [{f[0][0]:0.4g}, {f[0][1]:0.4g}]
-                  v                =  [{f[1][0]:0.4g}, {f[1][1]:0.4g}]
-                  w                =  [{f[2][0]:0.4g}, {f[2][1]:0.4g}]
-        """
+        sumstring_format = """
+        Turbulence model used                            =  {dat.model_desc}
+        Turbulence velocity (UStar)                      =  {dat.Ustar:0.4g} [m/s]
+        Mixing layer depth (ZI)                          =  {dat.ZI:0.4g} [m]
+        Stability parameter (z/L)                        =  {dat.zL:0.4g}
+        Monin-Obhukov Length scale                       =  {Lmo:0.4g} [m]
+        p_coefs   u                =  [{p[0][0]:0.4g}, {p[0][1]:0.4g}]
+                  v                =  [{p[1][0]:0.4g}, {p[1][1]:0.4g}]
+                  w                =  [{p[2][0]:0.4g}, {p[2][1]:0.4g}]
+        f_coefs   u                =  [{f[0][0]:0.4g}, {f[0][1]:0.4g}]
+                  v                =  [{f[1][0]:0.4g}, {f[1][1]:0.4g}]
+                  w                =  [{f[2][0]:0.4g}, {f[2][1]:0.4g}]
+        """
         return sumstring_format.format(dat=self,
                                        Lmo=self.L,
                                        p=self.p_coefs,
@@ -253,13 +254,13 @@ 

Source code for pyts.specModels.nwtc

 
     @property
     def L(self, ):
-        if not hasattr(self, 'zhub'):
-            raise Exception("The Monin-Obhukov is unknown until this "
-                            "model has been '__call__'d.")
+        if not hasattr(self, 'zhub'):
+            raise Exception("The Monin-Obhukov is unknown until this "
+                            "model has been '__call__'d.")
         return self.zhub / self.zL
 
 
[docs] def model(self, z, u, comp): - r""" + r""" Computes the spectrum for this 'unstable' spectral model. Parameters @@ -333,17 +334,17 @@

Source code for pyts.specModels.nwtc

             tmp0 = 1 + 2.8 * z_ZI
             self._work = (p_coef[0] * num0 / (1 + f_coef[0] * fZI_u) ** pow5_3
                           + p_coef[1] * num1 / (tmp0 + f_coef[1] * fz_u) ** pow5_3)
-            ## # Handle extra (e.g. wake, for outf_turb) coefficients:
-            ## if coef.shape[0]>2 and not np.isnan(coef[2,0]+coef[2,1]):
-            # self._work+=coef[2,0]*17*num1/(tmp0+coef[2,1]*9.5*fz_u)**pow5_3
+            ## # Handle extra (e.g. wake, for outf_turb) coefficients:
+            ## if coef.shape[0]>2 and not np.isnan(coef[2,0]+coef[2,1]):
+            # self._work+=coef[2,0]*17*num1/(tmp0+coef[2,1]*9.5*fz_u)**pow5_3
         else:
             self._work = (p_coef[0] * num0 / (1 + f_coef[0] * fZI_u) ** pow5_3
                           * np.sqrt((fz_u ** 2 + (0.3 * z_ZI) ** 2) / (fz_u ** 2 + 0.0225))
                           + p_coef[1] * num1 / (1 + f_coef[1] * fz_u ** pow5_3))
-        return self._work
+        return self._work
+ -
-
[docs]def smooth(Ustar, Ri, ZI=None): +
[docs]def smooth(Ustar, Ri, ZI=None): """ Compute the 'smooth' spectral model. @@ -363,15 +364,15 @@

Source code for pyts.specModels.nwtc

     specModel : :class:`NWTC_stable` (Ri>0), or :class:`NWTC_unstable` (Ri<0)
 
     """
-    zl_ = zL(Ri, 'smooth')
+    zl_ = zL(Ri, 'smooth')
     if zl_ >= 0:
         out = NWTC_stable(Ustar, zl_)
     else:
         out = NWTC_unstable(Ustar, zl_, ZI)
-    return out
+    return out
-
-
[docs]def nwtcup(Ustar, Ri, ZI=None): + +
[docs]def nwtcup(Ustar, Ri, ZI=None): """ Compute the 'nwtcup' spectral model. @@ -391,7 +392,7 @@

Source code for pyts.specModels.nwtc

     specModel : :class:`NWTC_stable` (Ri>0), or :class:`NWTC_unstable` (Ri<0)
 
     """
-    zl_ = zL(Ri, 'nwtcup')
+    zl_ = zL(Ri, 'nwtcup')
     coefs = calc_nwtcup_coefs(zl_)
     if zl_ >= 0:
         out = NWTC_stable(Ustar, zl_, coefs)
@@ -416,14 +417,11 @@ 

Related Topics

@@ -431,11 +429,11 @@

Quick search

diff --git a/docs/_modules/pyts/stressModels/base.html b/docs/_modules/pyts/stressModels/base.html index 6193d48..b488e1d 100644 --- a/docs/_modules/pyts/stressModels/base.html +++ b/docs/_modules/pyts/stressModels/base.html @@ -1,38 +1,39 @@ + - - - pyts.stressModels.base — PyTurbSim 0.4.7 documentation - + pyts.stressModels.base — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.stressModels.base

-"""
+"""
 This is the stress package's base module.
 
 produce estimates of Reynold's
@@ -48,27 +49,27 @@ 

Source code for pyts.stressModels.base

 
 """
 
-from .. import base
+from .. import base
 np = base.np
 
 
 
[docs]class stressModelBase(base.modelBase): - pass + pass
+ -
[docs]class stressObj(base.calcObj, base.gridProps): def __init__(self, tsrun): self.grid = tsrun.grid self.randgen = tsrun.randgen self.array = np.zeros( - [3] + self.grid.shape, dtype=base.ts_float, order='F') + [3] + self.grid.shape, dtype=base.ts_float, order='F') self.spec = tsrun.spec std_u = np.sqrt(self.spec.tke) self.stress_max = np.empty_like(self.array) - self.stress_max[0] = std_u[0] * std_u[1] # u'v' - self.stress_max[1] = std_u[0] * std_u[2] # u'w' - self.stress_max[2] = std_u[1] * std_u[2] # v'w' + self.stress_max[0] = std_u[0] * std_u[1] # u'v' + self.stress_max[1] = std_u[0] * std_u[2] # u'w' + self.stress_max[2] = std_u[1] * std_u[2] # v'w' @property def upvp_max(self,): @@ -101,7 +102,7 @@

Source code for pyts.stressModels.base

         """
         return self.array[0]
 
-    @upvp_.setter
+    @upvp_.setter
     def upvp_(self, val):
         self.array[0] = val
 
@@ -112,7 +113,7 @@ 

Source code for pyts.stressModels.base

         """
         return self.array[1]
 
-    @upwp_.setter
+    @upwp_.setter
     def upwp_(self, val):
         self.array[1] = val
 
@@ -123,7 +124,7 @@ 

Source code for pyts.stressModels.base

         """
         return self.array[2]
 
-    @vpwp_.setter
+    @vpwp_.setter
     def vpwp_(self, val):
         self.array[2] = val
 
@@ -159,45 +160,45 @@ 

Source code for pyts.stressModels.base

         srt = np.sort(np.abs(self.corr))
         valid = np.empty(srt.shape, dtype=bool)
 
-        # All individual stresses must be less than stress_max
-        # (i.e. the correlation between components can not be
-        # larger than the product of their standard devations).
+        # All individual stresses must be less than stress_max
+        # (i.e. the correlation between components can not be
+        # larger than the product of their standard devations).
         valid[0] = (srt < 1).all(0)
 
-        # This is the 'overlap' criterion.
+        # This is the 'overlap' criterion.
         valid[1] = (1 + srt[0] - srt[1] - srt[2] > 0)
 
-        # This is the 'sign' criterion: if there is only one negative
-        # stress, their can be no overlap (sum(srt) must be <1).
+        # This is the 'sign' criterion: if there is only one negative
+        # stress, their can be no overlap (sum(srt) must be <1).
         valid[2] = ((self.array < 0).sum(0) != 1) | (srt.sum(0) <= 1)
-        ############################
-        # Now compute the 'overlap' (so that we don't have to redo or
-        # store the sort for calc_phases).  average the product of the
-        # smallest value with the two larger ones. Then take the
-        # minimum value of that with the smallest value. This is the
-        # 'overlap', i.e. the fraction of points that will have the
-        # same phase for all three components.
-        #
-        # Note, this is specific choice of how the three components are
-        # correlated.
+        ############################
+        # Now compute the 'overlap' (so that we don't have to redo or
+        # store the sort for calc_phases).  average the product of the
+        # smallest value with the two larger ones. Then take the
+        # minimum value of that with the smallest value. This is the
+        # 'overlap', i.e. the fraction of points that will have the
+        # same phase for all three components.
+        #
+        # Note, this is specific choice of how the three components are
+        # correlated.
         self._overlap = np.minimum((srt[0] * srt[1] + srt[0] * srt[2]) / 2, srt[0])
-        # If there is only 1 negative stress than the overlap must be zero (if they are valid):
+        # If there is only 1 negative stress than the overlap must be zero (if they are valid):
         self._overlap[(self.array < 0).sum(0) == 1] = 0
-        #pdb.set_trace()
+        #pdb.set_trace()
         return valid
 
 
[docs] def check_validity(self,): """ Check that the Reynold's stress magnitudes are valid. """ - # Currently, this raises an error if any of the points have invalid - # stresses. In the future it may make sense to adjust/modify the - # stresses to make them valid? + # Currently, this raises an error if any of the points have invalid + # stresses. In the future it may make sense to adjust/modify the + # stresses to make them valid? if ~(self.validity.all()): - print self.validity.shape - print self.validity - raise Exception('The input reynolds stresses are inconsistent.') -
+ print self.validity.shape + print self.validity + raise Exception('The input reynolds stresses are inconsistent.')
+
[docs] def calc_phases(self, phases): """ Here we control the Reynold's stress by setting the phases @@ -207,35 +208,35 @@

Source code for pyts.stressModels.base

         self.check_validity()
         rgen = self.randgen.rand
         if (self.array == 0).all():
-            return phases  # No stress, so the phases are independently-random.
-        # fudge_factor=0.93 #!!!FIXTHIS: The 0.93 is a fudge factor to account
-        # for ... ???
+            return phases  # No stress, so the phases are independently-random.
+        # fudge_factor=0.93 #!!!FIXTHIS: The 0.93 is a fudge factor to account
+        # for ... ???
         fudge_factor = 1
-        rstrmat = self.grid.flatten(self.corr)[..., None]
+        rstrmat = self.grid.flatten(self.corr)[..., None]
         shp = (self.grid.n_p, self.grid.n_f)
 
-        ####
-        # First we set the 'overlap' stress. i.e. the phases that are the same
-        # (or opposite) for all three components.
-        # This is computed during check_validity:
-        ovr = self.grid.flatten(self._overlap)[:, None]
+        ####
+        # First we set the 'overlap' stress. i.e. the phases that are the same
+        # (or opposite) for all three components.
+        # This is computed during check_validity:
+        ovr = self.grid.flatten(self._overlap)[:, None]
         inds_used = (rgen(*shp) * fudge_factor) < ovr
         phases[2][inds_used] = (np.sign(rstrmat[1]) * phases[0])[inds_used]
         phases[1][inds_used] = (np.sign(rstrmat[0]) * phases[0])[inds_used]
-        ####
-        # Now set the u'v' non-overlap piece.
+        ####
+        # Now set the u'v' non-overlap piece.
         inds = ((rgen(*shp) * fudge_factor) <
                 np.abs(rstrmat[0]) - ovr) & (~inds_used)
         phases[1][inds] = (np.sign(rstrmat[0]) * phases[0])[inds]
         inds_used |= inds
-        ####
-        # Now set the u'w' non-overlap piece.
+        ####
+        # Now set the u'w' non-overlap piece.
         inds = ((rgen(*shp) * fudge_factor) <
                 np.abs(rstrmat[1]) - ovr) & (~inds_used)
         phases[2][inds] = (np.sign(rstrmat[1]) * phases[0])[inds]
         inds_used |= inds
-        ####
-        # Now set the v'w' non-overlap piece.
+        ####
+        # Now set the v'w' non-overlap piece.
         inds = ((rgen(*shp) * fudge_factor) <
                 np.abs(rstrmat[2]) - ovr) & (~inds_used)
         phases[2][inds] = (np.sign(rstrmat[2]) * phases[1])[inds]
@@ -259,14 +260,11 @@ 

Related Topics

@@ -274,11 +272,11 @@

Quick search

diff --git a/docs/_modules/pyts/stressModels/hydro.html b/docs/_modules/pyts/stressModels/hydro.html index ee2d796..6ee1f01 100644 --- a/docs/_modules/pyts/stressModels/hydro.html +++ b/docs/_modules/pyts/stressModels/hydro.html @@ -1,38 +1,39 @@ + - - - pyts.stressModels.hydro — PyTurbSim 0.4.7 documentation - + pyts.stressModels.hydro — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.stressModels.hydro

-from .base import stressModelBase, stressObj
+from .base import stressModelBase, stressObj
 
 
 
[docs]class tidal(stressModelBase): @@ -72,11 +73,11 @@

Source code for pyts.stressModels.hydro

         self.Ustar = Ustar
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Stress model used                                =  {dat.model_desc}
-        Friction velocity (UStar)                        =  {dat.Ustar:0.4g} [m/s]
-        Reference height (ZRef)                          =  {dat.Zref:0.4g} [m]
-        """
+        sumstring_format = """
+        Stress model used                                =  {dat.model_desc}
+        Friction velocity (UStar)                        =  {dat.Ustar:0.4g} [m/s]
+        Reference height (ZRef)                          =  {dat.Zref:0.4g} [m]
+        """
         return sumstring_format.format(dat=self, )
 
 
[docs] def __call__(self, tsrun): @@ -97,9 +98,9 @@

Source code for pyts.stressModels.hydro

         """
         out = stressObj(tsrun)
         out.upwp_[out.z < self.Zref] = -self.Ustar ** 2 * \
-            (1 - out.z[out.z < self.Zref][:, None] / self.Zref)
-             #*out.upwp_max[-1:]
-        # The other components default to zero.
+            (1 - out.z[out.z < self.Zref][:, None] / self.Zref)
+             #*out.upwp_max[-1:]
+        # The other components default to zero.
         return out
@@ -119,14 +120,11 @@

Related Topics

@@ -134,11 +132,11 @@

Quick search

diff --git a/docs/_modules/pyts/stressModels/main.html b/docs/_modules/pyts/stressModels/main.html index b0f6e76..a20cccc 100644 --- a/docs/_modules/pyts/stressModels/main.html +++ b/docs/_modules/pyts/stressModels/main.html @@ -1,38 +1,39 @@ + - - - pyts.stressModels.main — PyTurbSim 0.4.7 documentation - + pyts.stressModels.main — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,7 +41,7 @@

Source code for pyts.stressModels.main

-from .base import stressModelBase, stressObj
+from .base import stressModelBase, stressObj
 
 
 
[docs]class uniform(stressModelBase): @@ -68,12 +69,12 @@

Source code for pyts.stressModels.main

         self.vals = [upvp_, upwp_, vpwp_]
 
     def _sumfile_string(self, tsrun, ):
-        sumstring_format = """
-        Stress model used                                =  {dat.model_desc}
-        u'v'                                             =  {dat.vals[0]:0.4g} [m^2/s^2]
-        u'w'                                             =  {dat.vals[1]:0.4g} [m^2/s^2]
-        v'w'                                             =  {dat.vals[2]:0.4g} [m^2/s^2]
-        """
+        sumstring_format = """
+        Stress model used                                =  {dat.model_desc}
+        u'v'                                             =  {dat.vals[0]:0.4g} [m^2/s^2]
+        u'w'                                             =  {dat.vals[1]:0.4g} [m^2/s^2]
+        v'w'                                             =  {dat.vals[2]:0.4g} [m^2/s^2]
+        """
         return sumstring_format.format(dat=self, )
 
 
[docs] def __call__(self, tsrun): @@ -115,14 +116,11 @@

Related Topics

@@ -130,11 +128,11 @@

Quick search

diff --git a/docs/_modules/pyts/stressModels/stress_freq.html b/docs/_modules/pyts/stressModels/stress_freq.html index e61368f..2defe28 100644 --- a/docs/_modules/pyts/stressModels/stress_freq.html +++ b/docs/_modules/pyts/stressModels/stress_freq.html @@ -1,38 +1,39 @@ + - - - pyts.stressModels.stress_freq — PyTurbSim 0.4.7 documentation - + pyts.stressModels.stress_freq — PyTurbSim 0.4.8 documentation - - + - - + + + + - + - + +
@@ -40,8 +41,8 @@

Source code for pyts.stressModels.stress_freq

-from .base import stressModelBase, np
-from ..base import ts_float
+from .base import stressModelBase, np
+from ..base import ts_float
 
 
 
[docs]class stressModelBase_f(stressModelBase): @@ -52,24 +53,24 @@

Source code for pyts.stressModels.stress_freq

components. """ - def __new__(cls, turbModel, *args, **kwargs): - self = super(stressModelBase_f, cls).__new__( - cls, turbModel, *args, **kwargs) + def __new__(cls, turbModel, *args, **kwargs): + self = super(stressModelBase_f, cls).__new__( + cls, turbModel, *args, **kwargs) self._rstrCoh = np.zeros([self.n_comp] + list(self.grid.shape) + [self.n_f], dtype=ts_float) - # In the future I need to overwrite the _setPhases routine to - # allow for more control of the _rstrCoh array. For example: - # It may be worthwhile to base the cross-coherence - # function _rstrCoh, on observed cross-component - # coherences (and phases). Perhaps this is a gaussion - # distribution (with some width) of phase shifts - # vs. frequency. For now we simply set a fraction of the - # phase shifts to be the same between the components to - # control the Reynold's stress. - # For now, I have simply copied the code that was here before I simplified - # the stressModelBase class. + # In the future I need to overwrite the _setPhases routine to + # allow for more control of the _rstrCoh array. For example: + # It may be worthwhile to base the cross-coherence + # function _rstrCoh, on observed cross-component + # coherences (and phases). Perhaps this is a gaussion + # distribution (with some width) of phase shifts + # vs. frequency. For now we simply set a fraction of the + # phase shifts to be the same between the components to + # control the Reynold's stress. + # For now, I have simply copied the code that was here before I simplified + # the stressModelBase class. def _setPhases(self,): """ Here we control the Reynold's stress by setting the 'random' @@ -78,53 +79,53 @@

Source code for pyts.stressModels.stress_freq

""" - # fudge_factor=0.93 #!!!FIXTHIS: The 0.93 is a fudge factor to account - # for ... ??? + # fudge_factor=0.93 #!!!FIXTHIS: The 0.93 is a fudge factor to account + # for ... ??? fudge_factor = 1 - self._rstrCoh = self.stress[..., None] / self.stress_max[..., None] + self._rstrCoh = self.stress[..., None] / self.stress_max[..., None] rstrmat = self.grid.flatten( - self._rstrCoh) # This doesn't currently work + self._rstrCoh) # This doesn't currently work srt = np.sort(np.abs(rstrmat), axis=0) - #rem=1+srt[0]-srt[1]-srt[2] + #rem=1+srt[0]-srt[1]-srt[2] if ((1 + srt[0] - srt[1] - srt[2] < 0).any() or (((rstrmat < 0).sum(0) == 1) & (srt.sum(0) > 1)).any()): - # We can't have rem<0, or only one negative correlation if the - # total correlation is greater than 1. - raise Exception('The input reynolds stresses are inconsistent.') + # We can't have rem<0, or only one negative correlation if the + # total correlation is greater than 1. + raise Exception('The input reynolds stresses are inconsistent.') ovr = np.minimum((srt[0] * srt[1] + srt[0] * srt[2]) / 2, srt[0]) - # average the product of the smallest value with the - # two larger ones. Then take the minimum value of that - # with the smallest value. This is the 'overlap', i.e. - # the fraction of points that will have the same phase - # for all three components. + # average the product of the smallest value with the + # two larger ones. Then take the minimum value of that + # with the smallest value. This is the 'overlap', i.e. + # the fraction of points that will have the same phase + # for all three components. ovr[(rstrmat < 0).sum(0) - == 1] = 0 # If there is only 1 negative stress than the overlap must be zero. + == 1] = 0 # If there is only 1 negative stress than the overlap must be zero. rgen = self.grid.randgen.rand shp = (self.grid.n_p, self.grid.n_f) - #### - # First we set the 'overlap' stress. i.e. the phases that are the same - # (or opposite) for all three components. + #### + # First we set the 'overlap' stress. i.e. the phases that are the same + # (or opposite) for all three components. inds_used = (rgen(*shp) * fudge_factor) < ovr self.rand[2][inds_used] = np.sign( rstrmat[1][inds_used]) * self.rand[0][inds_used] self.rand[1][inds_used] = np.sign( rstrmat[0][inds_used]) * self.rand[0][inds_used] - #### - # Now set the u'v' non-overlap piece. + #### + # Now set the u'v' non-overlap piece. inds = ((rgen(*shp) * fudge_factor) < np.abs(rstrmat[0]) - ovr) & (~inds_used) self.rand[1][inds] = np.sign(rstrmat[0][inds]) * self.rand[0][inds] inds_used |= inds - #### - # Now set the u'w' non-overlap piece. + #### + # Now set the u'w' non-overlap piece. inds = ((rgen(*shp) * fudge_factor) < np.abs(rstrmat[1]) - ovr) & (~inds_used) self.rand[2][inds] = np.sign(rstrmat[1][inds]) * self.rand[0][inds] inds_used |= inds - #### - # Now set the v'w' non-overlap piece. + #### + # Now set the v'w' non-overlap piece. inds = ((rgen(*shp) * fudge_factor) < np.abs(rstrmat[2]) - ovr) & (~inds_used) self.rand[2][inds] = np.sign(rstrmat[2][inds]) * self.rand[1][inds] @@ -147,14 +148,11 @@

Related Topics

@@ -162,11 +160,11 @@

Quick search

diff --git a/docs/_sources/about.txt b/docs/_sources/about.rst.txt similarity index 100% rename from docs/_sources/about.txt rename to docs/_sources/about.rst.txt diff --git a/docs/_sources/api/pyts.cohereModels.txt b/docs/_sources/api/pyts.cohereModels.rst.txt similarity index 64% rename from docs/_sources/api/pyts.cohereModels.txt rename to docs/_sources/api/pyts.cohereModels.rst.txt index 9ede53d..8e6068c 100644 --- a/docs/_sources/api/pyts.cohereModels.txt +++ b/docs/_sources/api/pyts.cohereModels.rst.txt @@ -1,27 +1,27 @@ -pyts.cohereModels package -========================= +pyts\.cohereModels package +========================== Submodules ---------- -pyts.cohereModels.api module ----------------------------- +pyts\.cohereModels\.api module +------------------------------ .. automodule:: pyts.cohereModels.api :members: :undoc-members: :show-inheritance: -pyts.cohereModels.base module ------------------------------ +pyts\.cohereModels\.base module +------------------------------- .. automodule:: pyts.cohereModels.base :members: :undoc-members: :show-inheritance: -pyts.cohereModels.main module ------------------------------ +pyts\.cohereModels\.main module +------------------------------- .. automodule:: pyts.cohereModels.main :members: diff --git a/docs/_sources/api/pyts.gui.txt b/docs/_sources/api/pyts.gui.txt deleted file mode 100644 index 19615fd..0000000 --- a/docs/_sources/api/pyts.gui.txt +++ /dev/null @@ -1,62 +0,0 @@ -pyts.gui package -================ - -Submodules ----------- - -pyts.gui.base module --------------------- - -.. automodule:: pyts.gui.base - :members: - :undoc-members: - :show-inheritance: - -pyts.gui.base4wdr module ------------------------- - -.. automodule:: pyts.gui.base4wdr - :members: - :undoc-members: - :show-inheritance: - -pyts.gui.gTurbSim_wdr module ----------------------------- - -.. automodule:: pyts.gui.gTurbSim_wdr - :members: - :undoc-members: - :show-inheritance: - -pyts.gui.grid module --------------------- - -.. automodule:: pyts.gui.grid - :members: - :undoc-members: - :show-inheritance: - -pyts.gui.prof module --------------------- - -.. automodule:: pyts.gui.prof - :members: - :undoc-members: - :show-inheritance: - -pyts.gui.turb module --------------------- - -.. automodule:: pyts.gui.turb - :members: - :undoc-members: - :show-inheritance: - - -Module contents ---------------- - -.. automodule:: pyts.gui - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/_sources/api/pyts.io.txt b/docs/_sources/api/pyts.io.rst.txt similarity index 70% rename from docs/_sources/api/pyts.io.txt rename to docs/_sources/api/pyts.io.rst.txt index 1f22fe3..bdb5ed7 100644 --- a/docs/_sources/api/pyts.io.txt +++ b/docs/_sources/api/pyts.io.rst.txt @@ -1,59 +1,59 @@ -pyts.io package -=============== +pyts\.io package +================ Submodules ---------- -pyts.io.base module -------------------- +pyts\.io\.base module +--------------------- .. automodule:: pyts.io.base :members: :undoc-members: :show-inheritance: -pyts.io.formatter module ------------------------- +pyts\.io\.formatter module +-------------------------- .. automodule:: pyts.io.formatter :members: :undoc-members: :show-inheritance: -pyts.io.input module --------------------- +pyts\.io\.input module +---------------------- .. automodule:: pyts.io.input :members: :undoc-members: :show-inheritance: -pyts.io.main module -------------------- +pyts\.io\.main module +--------------------- .. automodule:: pyts.io.main :members: :undoc-members: :show-inheritance: -pyts.io.read module -------------------- +pyts\.io\.read module +--------------------- .. automodule:: pyts.io.read :members: :undoc-members: :show-inheritance: -pyts.io.sum module ------------------- +pyts\.io\.sum module +-------------------- .. automodule:: pyts.io.sum :members: :undoc-members: :show-inheritance: -pyts.io.write module --------------------- +pyts\.io\.write module +---------------------- .. automodule:: pyts.io.write :members: diff --git a/docs/_sources/api/pyts.phaseModels.txt b/docs/_sources/api/pyts.phaseModels.rst.txt similarity index 64% rename from docs/_sources/api/pyts.phaseModels.txt rename to docs/_sources/api/pyts.phaseModels.rst.txt index 7f41e7a..56f9f95 100644 --- a/docs/_sources/api/pyts.phaseModels.txt +++ b/docs/_sources/api/pyts.phaseModels.rst.txt @@ -1,27 +1,27 @@ -pyts.phaseModels package -======================== +pyts\.phaseModels package +========================= Submodules ---------- -pyts.phaseModels.api module ---------------------------- +pyts\.phaseModels\.api module +----------------------------- .. automodule:: pyts.phaseModels.api :members: :undoc-members: :show-inheritance: -pyts.phaseModels.base module ----------------------------- +pyts\.phaseModels\.base module +------------------------------ .. automodule:: pyts.phaseModels.base :members: :undoc-members: :show-inheritance: -pyts.phaseModels.main module ----------------------------- +pyts\.phaseModels\.main module +------------------------------ .. automodule:: pyts.phaseModels.main :members: diff --git a/docs/_sources/api/pyts.plot.txt b/docs/_sources/api/pyts.plot.rst.txt similarity index 70% rename from docs/_sources/api/pyts.plot.txt rename to docs/_sources/api/pyts.plot.rst.txt index a3b3e11..a90940a 100644 --- a/docs/_sources/api/pyts.plot.txt +++ b/docs/_sources/api/pyts.plot.rst.txt @@ -1,43 +1,43 @@ -pyts.plot package -================= +pyts\.plot package +================== Submodules ---------- -pyts.plot.api module --------------------- +pyts\.plot\.api module +---------------------- .. automodule:: pyts.plot.api :members: :undoc-members: :show-inheritance: -pyts.plot.axform module ------------------------ +pyts\.plot\.axform module +------------------------- .. automodule:: pyts.plot.axform :members: :undoc-members: :show-inheritance: -pyts.plot.base module ---------------------- +pyts\.plot\.base module +----------------------- .. automodule:: pyts.plot.base :members: :undoc-members: :show-inheritance: -pyts.plot.psd module --------------------- +pyts\.plot\.psd module +---------------------- .. automodule:: pyts.plot.psd :members: :undoc-members: :show-inheritance: -pyts.plot.superaxes module --------------------------- +pyts\.plot\.superaxes module +---------------------------- .. automodule:: pyts.plot.superaxes :members: diff --git a/docs/_sources/api/pyts.profModels.txt b/docs/_sources/api/pyts.profModels.rst.txt similarity index 68% rename from docs/_sources/api/pyts.profModels.txt rename to docs/_sources/api/pyts.profModels.rst.txt index d7f9fac..1535d27 100644 --- a/docs/_sources/api/pyts.profModels.txt +++ b/docs/_sources/api/pyts.profModels.rst.txt @@ -1,59 +1,59 @@ -pyts.profModels package -======================= +pyts\.profModels package +======================== Submodules ---------- -pyts.profModels.api module --------------------------- +pyts\.profModels\.api module +---------------------------- .. automodule:: pyts.profModels.api :members: :undoc-members: :show-inheritance: -pyts.profModels.base module ---------------------------- +pyts\.profModels\.base module +----------------------------- .. automodule:: pyts.profModels.base :members: :undoc-members: :show-inheritance: -pyts.profModels.iec module --------------------------- +pyts\.profModels\.iec module +---------------------------- .. automodule:: pyts.profModels.iec :members: :undoc-members: :show-inheritance: -pyts.profModels.jet module --------------------------- +pyts\.profModels\.jet module +---------------------------- .. automodule:: pyts.profModels.jet :members: :undoc-members: :show-inheritance: -pyts.profModels.log module --------------------------- +pyts\.profModels\.log module +---------------------------- .. automodule:: pyts.profModels.log :members: :undoc-members: :show-inheritance: -pyts.profModels.power module ----------------------------- +pyts\.profModels\.power module +------------------------------ .. automodule:: pyts.profModels.power :members: :undoc-members: :show-inheritance: -pyts.profModels.simple module ------------------------------ +pyts\.profModels\.simple module +------------------------------- .. automodule:: pyts.profModels.simple :members: diff --git a/docs/_sources/api/pyts.txt b/docs/_sources/api/pyts.rst.txt similarity index 82% rename from docs/_sources/api/pyts.txt rename to docs/_sources/api/pyts.rst.txt index 8de51b5..3920dca 100644 --- a/docs/_sources/api/pyts.txt +++ b/docs/_sources/api/pyts.rst.txt @@ -7,7 +7,6 @@ Subpackages .. toctree:: pyts.cohereModels - pyts.gui pyts.io pyts.phaseModels pyts.plot @@ -19,48 +18,48 @@ Subpackages Submodules ---------- -pyts.api module ---------------- +pyts\.api module +---------------- .. automodule:: pyts.api :members: :undoc-members: :show-inheritance: -pyts.base module ----------------- +pyts\.base module +----------------- .. automodule:: pyts.base :members: :undoc-members: :show-inheritance: -pyts.dbg module ---------------- +pyts\.dbg module +---------------- .. automodule:: pyts.dbg :members: :undoc-members: :show-inheritance: -pyts.main module ----------------- +pyts\.main module +----------------- .. automodule:: pyts.main :members: :undoc-members: :show-inheritance: -pyts.misc module ----------------- +pyts\.misc module +----------------- .. automodule:: pyts.misc :members: :undoc-members: :show-inheritance: -pyts.pyts_numpy module ----------------------- +pyts\.pyts\_numpy module +------------------------ .. automodule:: pyts.pyts_numpy :members: diff --git a/docs/_sources/api/pyts.runInput.txt b/docs/_sources/api/pyts.runInput.rst.txt similarity index 64% rename from docs/_sources/api/pyts.runInput.txt rename to docs/_sources/api/pyts.runInput.rst.txt index e5a968f..1f5557c 100644 --- a/docs/_sources/api/pyts.runInput.txt +++ b/docs/_sources/api/pyts.runInput.rst.txt @@ -1,35 +1,35 @@ -pyts.runInput package -===================== +pyts\.runInput package +====================== Submodules ---------- -pyts.runInput.base module -------------------------- +pyts\.runInput\.base module +--------------------------- .. automodule:: pyts.runInput.base :members: :undoc-members: :show-inheritance: -pyts.runInput.main module -------------------------- +pyts\.runInput\.main module +--------------------------- .. automodule:: pyts.runInput.main :members: :undoc-members: :show-inheritance: -pyts.runInput.profModels module -------------------------------- +pyts\.runInput\.profModels module +--------------------------------- .. automodule:: pyts.runInput.profModels :members: :undoc-members: :show-inheritance: -pyts.runInput.turbModels module -------------------------------- +pyts\.runInput\.turbModels module +--------------------------------- .. automodule:: pyts.runInput.turbModels :members: diff --git a/docs/_sources/api/pyts.specModels.txt b/docs/_sources/api/pyts.specModels.rst.txt similarity index 65% rename from docs/_sources/api/pyts.specModels.txt rename to docs/_sources/api/pyts.specModels.rst.txt index 8a7f5bb..2a19d27 100644 --- a/docs/_sources/api/pyts.specModels.txt +++ b/docs/_sources/api/pyts.specModels.rst.txt @@ -1,51 +1,51 @@ -pyts.specModels package -======================= +pyts\.specModels package +======================== Submodules ---------- -pyts.specModels.api module --------------------------- +pyts\.specModels\.api module +---------------------------- .. automodule:: pyts.specModels.api :members: :undoc-members: :show-inheritance: -pyts.specModels.base module ---------------------------- +pyts\.specModels\.base module +----------------------------- .. automodule:: pyts.specModels.base :members: :undoc-members: :show-inheritance: -pyts.specModels.hydro module ----------------------------- +pyts\.specModels\.hydro module +------------------------------ .. automodule:: pyts.specModels.hydro :members: :undoc-members: :show-inheritance: -pyts.specModels.iec module --------------------------- +pyts\.specModels\.iec module +---------------------------- .. automodule:: pyts.specModels.iec :members: :undoc-members: :show-inheritance: -pyts.specModels.kelley_coefs module ------------------------------------ +pyts\.specModels\.kelley\_coefs module +-------------------------------------- .. automodule:: pyts.specModels.kelley_coefs :members: :undoc-members: :show-inheritance: -pyts.specModels.nwtc module ---------------------------- +pyts\.specModels\.nwtc module +----------------------------- .. automodule:: pyts.specModels.nwtc :members: diff --git a/docs/_sources/api/pyts.stressModels.txt b/docs/_sources/api/pyts.stressModels.rst.txt similarity index 65% rename from docs/_sources/api/pyts.stressModels.txt rename to docs/_sources/api/pyts.stressModels.rst.txt index ce7dd63..32b09eb 100644 --- a/docs/_sources/api/pyts.stressModels.txt +++ b/docs/_sources/api/pyts.stressModels.rst.txt @@ -1,43 +1,43 @@ -pyts.stressModels package -========================= +pyts\.stressModels package +========================== Submodules ---------- -pyts.stressModels.api module ----------------------------- +pyts\.stressModels\.api module +------------------------------ .. automodule:: pyts.stressModels.api :members: :undoc-members: :show-inheritance: -pyts.stressModels.base module ------------------------------ +pyts\.stressModels\.base module +------------------------------- .. automodule:: pyts.stressModels.base :members: :undoc-members: :show-inheritance: -pyts.stressModels.hydro module ------------------------------- +pyts\.stressModels\.hydro module +-------------------------------- .. automodule:: pyts.stressModels.hydro :members: :undoc-members: :show-inheritance: -pyts.stressModels.main module ------------------------------ +pyts\.stressModels\.main module +------------------------------- .. automodule:: pyts.stressModels.main :members: :undoc-members: :show-inheritance: -pyts.stressModels.stress_freq module ------------------------------------- +pyts\.stressModels\.stress\_freq module +--------------------------------------- .. automodule:: pyts.stressModels.stress_freq :members: diff --git a/docs/_sources/code-framework.txt b/docs/_sources/code-framework.rst.txt similarity index 98% rename from docs/_sources/code-framework.txt rename to docs/_sources/code-framework.rst.txt index e383f1c..f37d807 100644 --- a/docs/_sources/code-framework.txt +++ b/docs/_sources/code-framework.rst.txt @@ -30,7 +30,8 @@ code and its use. The primary components of this framework are: stress profile models. d) :mod:`pyts.cohereModels`, contains the spatial coherence models. - More details on model packages can be found in the :ref:`model-info` section. + + More details on model packages can be found in the :ref:`model-info` section. 3) The :mod:`pyts.io` package supports reading and writing of TurbSim input (.inp) and output files (e.g. .bl, .wnd, etc.). diff --git a/docs/_sources/glossary.txt b/docs/_sources/glossary.rst.txt similarity index 100% rename from docs/_sources/glossary.txt rename to docs/_sources/glossary.rst.txt diff --git a/docs/_sources/index.txt b/docs/_sources/index.rst.txt similarity index 100% rename from docs/_sources/index.txt rename to docs/_sources/index.rst.txt diff --git a/docs/_sources/install.txt b/docs/_sources/install.rst.txt similarity index 100% rename from docs/_sources/install.txt rename to docs/_sources/install.rst.txt diff --git a/docs/_sources/plotting-tools.txt b/docs/_sources/plotting-tools.rst.txt similarity index 100% rename from docs/_sources/plotting-tools.txt rename to docs/_sources/plotting-tools.rst.txt diff --git a/docs/_sources/usage.txt b/docs/_sources/usage.rst.txt similarity index 82% rename from docs/_sources/usage.txt rename to docs/_sources/usage.rst.txt index 9877b80..1300283 100644 --- a/docs/_sources/usage.txt +++ b/docs/_sources/usage.rst.txt @@ -30,8 +30,8 @@ command line do:: Alternatively, this mode can be used from an interactive python shell by doing:: - >>> from pyts.runInput.main import readConfig, run, write - >>> config = readConfig('TurbSim.inp') + >>> from pyts.runInput.main import readInput, run, write + >>> config = readInput('TurbSim.inp') >>> tsdat = run(config) >>> write(tsdat, config, 'TurbSim') @@ -51,6 +51,7 @@ the statistics of |pyts| output explicitly. This api is the core interface of |pyts| (the other two are wrappers). As a starting point for using this interface checkout the :doc:`API documentation `. Or start navigating the api interactively by importing it:: + import pyts.api as pyts More specifically, the :file:`examples/api.py` file includes an @@ -58,20 +59,6 @@ overview of how to begin using |pyts|. The contents of that file is: .. literalinclude:: ../../examples/api.py -3) Graphical user interface (GUI) ---------------------------------- - -The GUI was developed for reading and writing TurbSim input files. -The gui was designed to help new users of TurbSim in understanding -and writing input files. The gui can be used to run |pyts| or -|ots| (if an |ots| executable can be found in path). -'gTurbSim' can be run from a command line in the |pyts| -directory:: - - $ python gTurbSim.py TurbSim.inp - -The source code for this mode is contained in the :mod:`.pyts.gui` package. - Reading output files -------------------- diff --git a/docs/_static/alabaster.css b/docs/_static/alabaster.css index 07a9e2a..be65b13 100644 --- a/docs/_static/alabaster.css +++ b/docs/_static/alabaster.css @@ -15,6 +15,41 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + @import url("basic.css"); /* -- page layout ----------------------------------------------------------- */ @@ -22,12 +57,13 @@ body { font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif; font-size: 17px; - background-color: white; + background-color: #fff; color: #000; margin: 0; padding: 0; } + div.document { width: 940px; margin: 30px auto 0 auto; @@ -44,6 +80,8 @@ div.bodywrapper { div.sphinxsidebar { width: 220px; + font-size: 14px; + line-height: 1.5; } hr { @@ -51,11 +89,15 @@ hr { } div.body { - background-color: #ffffff; + background-color: #fff; color: #3E4349; padding: 0 30px 0 30px; } +div.body > .section { + text-align: left; +} + div.footer { width: 940px; margin: 20px auto 30px auto; @@ -68,6 +110,11 @@ div.footer a { color: #888; } +p.caption { + font-family: inherit; + font-size: inherit; +} + div.relations { display: none; @@ -84,11 +131,6 @@ div.sphinxsidebar a:hover { border-bottom: 1px solid #999; } -div.sphinxsidebar { - font-size: 14px; - line-height: 1.5; -} - div.sphinxsidebarwrapper { padding: 18px 10px; } @@ -168,8 +210,8 @@ div.sphinxsidebar input { div.sphinxsidebar hr { border: none; height: 1px; - color: #999; - background: #999; + color: #AAA; + background: #AAA; text-align: left; margin-left: 0; @@ -225,19 +267,15 @@ div.body p, div.body dd, div.body li { div.admonition { margin: 20px 0px; padding: 10px 30px; - background-color: #FCC; - border: 1px solid #FAA; + background-color: #EEE; + border: 1px solid #CCC; } -div.admonition tt.xref, div.admonition a tt { +div.admonition tt.xref, div.admonition code.xref, div.admonition a tt { + background-color: #FBFBFB; border-bottom: 1px solid #fafafa; } -dd div.admonition { - margin-left: -60px; - padding-left: 60px; -} - div.admonition p.admonition-title { font-family: 'Garamond', 'Georgia', serif; font-weight: normal; @@ -252,25 +290,71 @@ div.admonition p.last { } div.highlight { - background-color: white; + background-color: #fff; } dt:target, .highlight { background: #FAF3E8; } +div.warning { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.danger { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.error { + background-color: #FCC; + border: 1px solid #FAA; + -moz-box-shadow: 2px 2px 4px #D52C2C; + -webkit-box-shadow: 2px 2px 4px #D52C2C; + box-shadow: 2px 2px 4px #D52C2C; +} + +div.caution { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.attention { + background-color: #FCC; + border: 1px solid #FAA; +} + +div.important { + background-color: #EEE; + border: 1px solid #CCC; +} + div.note { background-color: #EEE; border: 1px solid #CCC; } +div.tip { + background-color: #EEE; + border: 1px solid #CCC; +} + +div.hint { + background-color: #EEE; + border: 1px solid #CCC; +} + div.seealso { background-color: #EEE; border: 1px solid #CCC; } div.topic { - background-color: #eee; + background-color: #EEE; } p.admonition-title { @@ -305,16 +389,16 @@ tt.descname, code.descname { } img.screenshot { - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; } table.docutils { border: 1px solid #888; - -moz-box-shadow: 2px 2px 4px #eee; - -webkit-box-shadow: 2px 2px 4px #eee; - box-shadow: 2px 2px 4px #eee; + -moz-box-shadow: 2px 2px 4px #EEE; + -webkit-box-shadow: 2px 2px 4px #EEE; + box-shadow: 2px 2px 4px #EEE; } table.docutils td, table.docutils th { @@ -350,8 +434,22 @@ table.field-list td { padding: 0; } +table.field-list p { + margin-bottom: 0.8em; +} + +/* Cloned from + * https://github.com/sphinx-doc/sphinx/commit/ef60dbfce09286b20b7385333d63a60321784e68 + */ +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} + table.footnote td.label { - width: 0px; + width: .1px; padding: 0.3em 0 0.3em 0.5em; } @@ -374,6 +472,7 @@ blockquote { } ul, ol { + /* Matches the 30px from the narrow-screen "li > ul" selector below */ margin: 10px 0 10px 30px; padding: 0; } @@ -385,16 +484,15 @@ pre { line-height: 1.3em; } +div.viewcode-block:target { + background: #ffd; +} + dl pre, blockquote pre, li pre { margin-left: 0; padding-left: 30px; } -dl dl pre { - margin-left: -90px; - padding-left: 90px; -} - tt, code { background-color: #ecf0f3; color: #222; @@ -403,7 +501,7 @@ tt, code { tt.xref, code.xref, a tt { background-color: #FBFBFB; - border-bottom: 1px solid white; + border-bottom: 1px solid #fff; } a.reference { @@ -411,6 +509,11 @@ a.reference { border-bottom: 1px dotted #004B6B; } +/* Don't put an underline on images */ +a.image-reference, a.image-reference:hover { + border-bottom: none; +} + a.reference:hover { border-bottom: 1px solid #6D4100; } @@ -460,6 +563,11 @@ a:hover tt, a:hover code { margin-left: 0; } + li > ul { + /* Matches the 30px from the "ul, ol" selector above */ + margin-left: 30px; + } + .document { width: auto; } @@ -495,7 +603,7 @@ a:hover tt, a:hover code { div.documentwrapper { float: none; - background: white; + background: #fff; } div.sphinxsidebar { @@ -510,7 +618,7 @@ a:hover tt, a:hover code { div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p, div.sphinxsidebar h3 a { - color: white; + color: #fff; } div.sphinxsidebar a { diff --git a/docs/_static/basic.css b/docs/_static/basic.css index 9fa77d8..6f40830 100644 --- a/docs/_static/basic.css +++ b/docs/_static/basic.css @@ -4,7 +4,7 @@ * * Sphinx stylesheet -- basic theme. * - * :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS. + * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @@ -52,6 +52,8 @@ div.sphinxsidebar { width: 230px; margin-left: -100%; font-size: 90%; + word-wrap: break-word; + overflow-wrap : break-word; } div.sphinxsidebar ul { @@ -83,10 +85,6 @@ div.sphinxsidebar #searchbox input[type="text"] { width: 170px; } -div.sphinxsidebar #searchbox input[type="submit"] { - width: 30px; -} - img { border: 0; max-width: 100%; @@ -124,6 +122,8 @@ ul.keywordmatches li.goodmatch a { table.contentstable { width: 90%; + margin-left: auto; + margin-right: auto; } table.contentstable p.biglink { @@ -151,9 +151,14 @@ table.indextable td { vertical-align: top; } -table.indextable dl, table.indextable dd { +table.indextable ul { margin-top: 0; margin-bottom: 0; + list-style-type: none; +} + +table.indextable > tbody > tr > td > ul { + padding-left: 0em; } table.indextable tr.pcap { @@ -185,8 +190,22 @@ div.genindex-jumpbox { padding: 0.4em; } +/* -- domain module index --------------------------------------------------- */ + +table.modindextable td { + padding: 2px; + border-collapse: collapse; +} + /* -- general body styles --------------------------------------------------- */ +div.body p, div.body dd, div.body li, div.body blockquote { + -moz-hyphens: auto; + -ms-hyphens: auto; + -webkit-hyphens: auto; + hyphens: auto; +} + a.headerlink { visibility: hidden; } @@ -212,10 +231,6 @@ div.body td { text-align: left; } -.field-list ul { - padding-left: 1em; -} - .first { margin-top: 0 !important; } @@ -332,10 +347,6 @@ table.docutils td, table.docutils th { border-bottom: 1px solid #aaa; } -table.field-list td, table.field-list th { - border: 0 !important; -} - table.footnote td, table.footnote th { border: 0 !important; } @@ -372,6 +383,27 @@ div.figure p.caption span.caption-number { div.figure p.caption span.caption-text { } +/* -- field list styles ----------------------------------------------------- */ + +table.field-list td, table.field-list th { + border: 0 !important; +} + +.field-list ul { + margin: 0; + padding-left: 1em; +} + +.field-list p { + margin: 0; +} + +.field-name { + -moz-hyphens: manual; + -ms-hyphens: manual; + -webkit-hyphens: manual; + hyphens: manual; +} /* -- other body styles ----------------------------------------------------- */ @@ -413,24 +445,19 @@ dd { margin-left: 30px; } -dt:target, .highlighted { +dt:target, span.highlighted { background-color: #fbe54e; } +rect.highlighted { + fill: #fbe54e; +} + dl.glossary dt { font-weight: bold; font-size: 1.1em; } -.field-list ul { - margin: 0; - padding-left: 1em; -} - -.field-list p { - margin: 0; -} - .optional { font-size: 1.3em; } @@ -489,6 +516,13 @@ pre { overflow-y: hidden; /* fixes display issues on Chrome browsers */ } +span.pre { + -moz-hyphens: none; + -ms-hyphens: none; + -webkit-hyphens: none; + hyphens: none; +} + td.linenos pre { padding: 5px 0px; border: 0; @@ -580,6 +614,16 @@ span.eqno { float: right; } +span.eqno a.headerlink { + position: relative; + left: 0px; + z-index: 1; +} + +div.math:hover a.headerlink { + visibility: visible; +} + /* -- printout stylesheet --------------------------------------------------- */ @media print { diff --git a/docs/_static/comment-bright.png b/docs/_static/comment-bright.png index 551517b..15e27ed 100644 Binary files a/docs/_static/comment-bright.png and b/docs/_static/comment-bright.png differ diff --git a/docs/_static/comment-close.png b/docs/_static/comment-close.png index 09b54be..4d91bcf 100644 Binary files a/docs/_static/comment-close.png and b/docs/_static/comment-close.png differ diff --git a/docs/_static/comment.png b/docs/_static/comment.png index 92feb52..dfbc0cb 100644 Binary files a/docs/_static/comment.png and b/docs/_static/comment.png differ diff --git a/docs/_static/custom.css b/docs/_static/custom.css new file mode 100644 index 0000000..2a924f1 --- /dev/null +++ b/docs/_static/custom.css @@ -0,0 +1 @@ +/* This file intentionally left blank. */ diff --git a/docs/_static/doctools.js b/docs/_static/doctools.js index c7bfe76..0c15c00 100644 --- a/docs/_static/doctools.js +++ b/docs/_static/doctools.js @@ -4,7 +4,7 @@ * * Sphinx JavaScript utilities for all documentation. * - * :copyright: Copyright 2007-2015 by the Sphinx team, see AUTHORS. + * :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. * :license: BSD, see LICENSE for details. * */ @@ -45,7 +45,7 @@ jQuery.urlencode = encodeURIComponent; * it will always return arrays of strings for the value parts. */ jQuery.getQueryParameters = function(s) { - if (typeof s == 'undefined') + if (typeof s === 'undefined') s = document.location.search; var parts = s.substr(s.indexOf('?') + 1).split('&'); var result = {}; @@ -66,29 +66,53 @@ jQuery.getQueryParameters = function(s) { * span elements with the given class name. */ jQuery.fn.highlightText = function(text, className) { - function highlight(node) { - if (node.nodeType == 3) { + function highlight(node, addItems) { + if (node.nodeType === 3) { var val = node.nodeValue; var pos = val.toLowerCase().indexOf(text); if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) { - var span = document.createElement("span"); - span.className = className; + var span; + var isInSVG = jQuery(node).closest("body, svg, foreignObject").is("svg"); + if (isInSVG) { + span = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); + } else { + span = document.createElement("span"); + span.className = className; + } span.appendChild(document.createTextNode(val.substr(pos, text.length))); node.parentNode.insertBefore(span, node.parentNode.insertBefore( document.createTextNode(val.substr(pos + text.length)), node.nextSibling)); node.nodeValue = val.substr(0, pos); + if (isInSVG) { + var bbox = span.getBBox(); + var rect = document.createElementNS("http://www.w3.org/2000/svg", "rect"); + rect.x.baseVal.value = bbox.x; + rect.y.baseVal.value = bbox.y; + rect.width.baseVal.value = bbox.width; + rect.height.baseVal.value = bbox.height; + rect.setAttribute('class', className); + var parentOfText = node.parentNode.parentNode; + addItems.push({ + "parent": node.parentNode, + "target": rect}); + } } } else if (!jQuery(node).is("button, select, textarea")) { jQuery.each(node.childNodes, function() { - highlight(this); + highlight(this, addItems); }); } } - return this.each(function() { - highlight(this); + var addItems = []; + var result = this.each(function() { + highlight(this, addItems); }); + for (var i = 0; i < addItems.length; ++i) { + jQuery(addItems[i].parent).before(addItems[i].target); + } + return result; }; /* @@ -124,27 +148,28 @@ var Documentation = { this.fixFirefoxAnchorBug(); this.highlightSearchWords(); this.initIndexTable(); + }, /** * i18n support */ TRANSLATIONS : {}, - PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; }, + PLURAL_EXPR : function(n) { return n === 1 ? 0 : 1; }, LOCALE : 'unknown', // gettext and ngettext don't access this so that the functions // can safely bound to a different name (_ = Documentation.gettext) gettext : function(string) { var translated = Documentation.TRANSLATIONS[string]; - if (typeof translated == 'undefined') + if (typeof translated === 'undefined') return string; - return (typeof translated == 'string') ? translated : translated[0]; + return (typeof translated === 'string') ? translated : translated[0]; }, ngettext : function(singular, plural, n) { var translated = Documentation.TRANSLATIONS[singular]; - if (typeof translated == 'undefined') + if (typeof translated === 'undefined') return (n == 1) ? singular : plural; return translated[Documentation.PLURALEXPR(n)]; }, @@ -179,7 +204,7 @@ var Documentation = { * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075 */ fixFirefoxAnchorBug : function() { - if (document.location.hash) + if (document.location.hash && $.browser.mozilla) window.setTimeout(function() { document.location.href += ''; }, 10); @@ -215,7 +240,7 @@ var Documentation = { var src = $(this).attr('src'); var idnum = $(this).attr('id').substr(7); $('tr.cg-' + idnum).toggle(); - if (src.substr(-9) == 'minus.png') + if (src.substr(-9) === 'minus.png') $(this).attr('src', src.substr(0, src.length-9) + 'plus.png'); else $(this).attr('src', src.substr(0, src.length-8) + 'minus.png'); @@ -247,11 +272,34 @@ var Documentation = { var path = document.location.pathname; var parts = path.split(/\//); $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() { - if (this == '..') + if (this === '..') parts.pop(); }); var url = parts.join('/'); return path.substring(url.lastIndexOf('/') + 1, path.length - 1); + }, + + initOnKeyListeners: function() { + $(document).keyup(function(event) { + var activeElementType = document.activeElement.tagName; + // don't navigate when in search box or textarea + if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') { + switch (event.keyCode) { + case 37: // left + var prevHref = $('link[rel="prev"]').prop('href'); + if (prevHref) { + window.location.href = prevHref; + return false; + } + case 39: // right + var nextHref = $('link[rel="next"]').prop('href'); + if (nextHref) { + window.location.href = nextHref; + return false; + } + } + } + }); } }; @@ -260,4 +308,4 @@ _ = Documentation.gettext; $(document).ready(function() { Documentation.init(); -}); +}); \ No newline at end of file diff --git a/docs/_static/down-pressed.png b/docs/_static/down-pressed.png index 7c30d00..5756c8c 100644 Binary files a/docs/_static/down-pressed.png and b/docs/_static/down-pressed.png differ diff --git a/docs/_static/down.png b/docs/_static/down.png index f48098a..1b3bdad 100644 Binary files a/docs/_static/down.png and b/docs/_static/down.png differ diff --git a/docs/_static/file.png b/docs/_static/file.png index 254c60b..a858a41 100644 Binary files a/docs/_static/file.png and b/docs/_static/file.png differ diff --git a/docs/_static/jquery-1.11.1.js b/docs/_static/jquery-3.1.0.js similarity index 53% rename from docs/_static/jquery-1.11.1.js rename to docs/_static/jquery-3.1.0.js index d4b67f7..f2fc274 100644 --- a/docs/_static/jquery-1.11.1.js +++ b/docs/_static/jquery-3.1.0.js @@ -1,27 +1,30 @@ +/*eslint-disable no-unused-vars*/ /*! - * jQuery JavaScript Library v1.11.1 - * http://jquery.com/ + * jQuery JavaScript Library v3.1.0 + * https://jquery.com/ * * Includes Sizzle.js - * http://sizzlejs.com/ + * https://sizzlejs.com/ * - * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors + * Copyright jQuery Foundation and other contributors * Released under the MIT license - * http://jquery.org/license + * https://jquery.org/license * - * Date: 2014-05-01T17:42Z + * Date: 2016-07-07T21:44Z */ +( function( global, factory ) { -(function( global, factory ) { + "use strict"; if ( typeof module === "object" && typeof module.exports === "object" ) { - // For CommonJS and CommonJS-like environments where a proper window is present, - // execute the factory and get jQuery - // For environments that do not inherently posses a window with a document - // (such as Node.js), expose a jQuery-making factory as module.exports - // This accentuates the need for the creation of a real window + + // For CommonJS and CommonJS-like environments where a proper `window` + // is present, execute the factory and get jQuery. + // For environments that do not have a `window` with a `document` + // (such as Node.js), expose a factory as module.exports. + // This accentuates the need for the creation of a real `window`. // e.g. var jQuery = require("jquery")(window); - // See ticket #14549 for more info + // See ticket #14549 for more info. module.exports = global.document ? factory( global, true ) : function( w ) { @@ -35,23 +38,27 @@ } // Pass this if window is not defined yet -}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) { +} )( typeof window !== "undefined" ? window : this, function( window, noGlobal ) { -// Can't do this because several apps including ASP.NET trace -// the stack via arguments.caller.callee and Firefox dies if -// you try to trace through "use strict" call chains. (#13335) -// Support: Firefox 18+ -// +// Edge <= 12 - 13+, Firefox <=18 - 45+, IE 10 - 11, Safari 5.1 - 9+, iOS 6 - 9.1 +// throw exceptions when non-strict code (e.g., ASP.NET 4.5) accesses strict mode +// arguments.callee.caller (trac-13335). But as of jQuery 3.0 (2016), strict mode should be common +// enough that all such attempts are guarded in a try block. +"use strict"; + +var arr = []; -var deletedIds = []; +var document = window.document; -var slice = deletedIds.slice; +var getProto = Object.getPrototypeOf; -var concat = deletedIds.concat; +var slice = arr.slice; -var push = deletedIds.push; +var concat = arr.concat; -var indexOf = deletedIds.indexOf; +var push = arr.push; + +var indexOf = arr.indexOf; var class2type = {}; @@ -59,27 +66,46 @@ var toString = class2type.toString; var hasOwn = class2type.hasOwnProperty; +var fnToString = hasOwn.toString; + +var ObjectFunctionString = fnToString.call( Object ); + var support = {}; + function DOMEval( code, doc ) { + doc = doc || document; + + var script = doc.createElement( "script" ); + + script.text = code; + doc.head.appendChild( script ).parentNode.removeChild( script ); + } +/* global Symbol */ +// Defining this global in .eslintrc would create a danger of using the global +// unguarded in another place, it seems safer to define global only for this module + + + var - version = "1.11.1", + version = "3.1.0", // Define a local copy of jQuery jQuery = function( selector, context ) { + // The jQuery object is actually just the init constructor 'enhanced' // Need init if jQuery is called (just allow error to be thrown if not included) return new jQuery.fn.init( selector, context ); }, - // Support: Android<4.1, IE<9 + // Support: Android <=4.0 only // Make sure we trim BOM and NBSP rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, - rdashAlpha = /-([\da-z])/gi, + rdashAlpha = /-([a-z])/g, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { @@ -87,14 +113,12 @@ var }; jQuery.fn = jQuery.prototype = { + // The current version of jQuery being used jquery: version, constructor: jQuery, - // Start with an empty selector - selector: "", - // The default length of a jQuery object is 0 length: 0, @@ -123,23 +147,20 @@ jQuery.fn = jQuery.prototype = { // Add the old object onto the stack (as a reference) ret.prevObject = this; - ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. - // (You can seed the arguments with an array of args, but this is - // only used internally.) - each: function( callback, args ) { - return jQuery.each( this, callback, args ); + each: function( callback ) { + return jQuery.each( this, callback ); }, map: function( callback ) { - return this.pushStack( jQuery.map(this, function( elem, i ) { + return this.pushStack( jQuery.map( this, function( elem, i ) { return callback.call( elem, i, elem ); - })); + } ) ); }, slice: function() { @@ -157,23 +178,23 @@ jQuery.fn = jQuery.prototype = { eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); - return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); + return this.pushStack( j >= 0 && j < len ? [ this[ j ] ] : [] ); }, end: function() { - return this.prevObject || this.constructor(null); + return this.prevObject || this.constructor(); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: push, - sort: deletedIds.sort, - splice: deletedIds.splice + sort: arr.sort, + splice: arr.splice }; jQuery.extend = jQuery.fn.extend = function() { - var src, copyIsArray, copy, name, options, clone, - target = arguments[0] || {}, + var options, name, src, copy, copyIsArray, clone, + target = arguments[ 0 ] || {}, i = 1, length = arguments.length, deep = false; @@ -182,25 +203,27 @@ jQuery.extend = jQuery.fn.extend = function() { if ( typeof target === "boolean" ) { deep = target; - // skip the boolean and the target + // Skip the boolean and the target target = arguments[ i ] || {}; i++; } // Handle case when target is a string or something (possible in deep copy) - if ( typeof target !== "object" && !jQuery.isFunction(target) ) { + if ( typeof target !== "object" && !jQuery.isFunction( target ) ) { target = {}; } - // extend jQuery itself if only one argument is passed + // Extend jQuery itself if only one argument is passed if ( i === length ) { target = this; i--; } for ( ; i < length; i++ ) { + // Only deal with non-null/undefined values - if ( (options = arguments[ i ]) != null ) { + if ( ( options = arguments[ i ] ) != null ) { + // Extend the base object for ( name in options ) { src = target[ name ]; @@ -212,13 +235,15 @@ jQuery.extend = jQuery.fn.extend = function() { } // Recurse if we're merging plain objects or arrays - if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { + if ( deep && copy && ( jQuery.isPlainObject( copy ) || + ( copyIsArray = jQuery.isArray( copy ) ) ) ) { + if ( copyIsArray ) { copyIsArray = false; - clone = src && jQuery.isArray(src) ? src : []; + clone = src && jQuery.isArray( src ) ? src : []; } else { - clone = src && jQuery.isPlainObject(src) ? src : {}; + clone = src && jQuery.isPlainObject( src ) ? src : {}; } // Never move original objects, clone them @@ -236,7 +261,8 @@ jQuery.extend = jQuery.fn.extend = function() { return target; }; -jQuery.extend({ +jQuery.extend( { + // Unique for each copy of jQuery on the page expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ), @@ -249,98 +275,81 @@ jQuery.extend({ noop: function() {}, - // See test/unit/core.js for details concerning isFunction. - // Since version 1.3, DOM methods and functions like alert - // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { - return jQuery.type(obj) === "function"; + return jQuery.type( obj ) === "function"; }, - isArray: Array.isArray || function( obj ) { - return jQuery.type(obj) === "array"; - }, + isArray: Array.isArray, isWindow: function( obj ) { - /* jshint eqeqeq: false */ - return obj != null && obj == obj.window; + return obj != null && obj === obj.window; }, isNumeric: function( obj ) { - // parseFloat NaNs numeric-cast false positives (null|true|false|"") - // ...but misinterprets leading-number strings, particularly hex literals ("0x...") - // subtraction forces infinities to NaN - return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0; - }, - isEmptyObject: function( obj ) { - var name; - for ( name in obj ) { - return false; - } - return true; + // As of jQuery 3.0, isNumeric is limited to + // strings and numbers (primitives or objects) + // that can be coerced to finite numbers (gh-2662) + var type = jQuery.type( obj ); + return ( type === "number" || type === "string" ) && + + // parseFloat NaNs numeric-cast false positives ("") + // ...but misinterprets leading-number strings, particularly hex literals ("0x...") + // subtraction forces infinities to NaN + !isNaN( obj - parseFloat( obj ) ); }, isPlainObject: function( obj ) { - var key; + var proto, Ctor; - // Must be an Object. - // Because of IE, we also have to check the presence of the constructor property. - // Make sure that DOM nodes and window objects don't pass through, as well - if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { + // Detect obvious negatives + // Use toString instead of jQuery.type to catch host objects + if ( !obj || toString.call( obj ) !== "[object Object]" ) { return false; } - try { - // Not own constructor property must be Object - if ( obj.constructor && - !hasOwn.call(obj, "constructor") && - !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { - return false; - } - } catch ( e ) { - // IE8,9 Will throw exceptions on certain host objects #9897 - return false; - } + proto = getProto( obj ); - // Support: IE<9 - // Handle iteration over inherited properties before own properties. - if ( support.ownLast ) { - for ( key in obj ) { - return hasOwn.call( obj, key ); - } + // Objects with no prototype (e.g., `Object.create( null )`) are plain + if ( !proto ) { + return true; } - // Own properties are enumerated firstly, so to speed up, - // if last one is own, then all properties are own. - for ( key in obj ) {} + // Objects with prototype are plain iff they were constructed by a global Object function + Ctor = hasOwn.call( proto, "constructor" ) && proto.constructor; + return typeof Ctor === "function" && fnToString.call( Ctor ) === ObjectFunctionString; + }, + + isEmptyObject: function( obj ) { + + /* eslint-disable no-unused-vars */ + // See https://github.com/eslint/eslint/issues/6125 + var name; - return key === undefined || hasOwn.call( obj, key ); + for ( name in obj ) { + return false; + } + return true; }, type: function( obj ) { if ( obj == null ) { return obj + ""; } + + // Support: Android <=2.3 only (functionish RegExp) return typeof obj === "object" || typeof obj === "function" ? - class2type[ toString.call(obj) ] || "object" : + class2type[ toString.call( obj ) ] || "object" : typeof obj; }, // Evaluates a script in a global context - // Workarounds based on findings by Jim Driscoll - // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context - globalEval: function( data ) { - if ( data && jQuery.trim( data ) ) { - // We use execScript on Internet Explorer - // We use an anonymous function so that context is window - // rather than jQuery in Firefox - ( window.execScript || function( data ) { - window[ "eval" ].call( window, data ); - } )( data ); - } + globalEval: function( code ) { + DOMEval( code ); }, // Convert dashed to camelCase; used by the css and data modules + // Support: IE <=9 - 11, Edge 12 - 13 // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); @@ -350,49 +359,20 @@ jQuery.extend({ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, - // args is for internal usage only - each: function( obj, callback, args ) { - var value, - i = 0, - length = obj.length, - isArray = isArraylike( obj ); - - if ( args ) { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.apply( obj[ i ], args ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.apply( obj[ i ], args ); + each: function( obj, callback ) { + var length, i = 0; - if ( value === false ) { - break; - } + if ( isArrayLike( obj ) ) { + length = obj.length; + for ( ; i < length; i++ ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; } } - - // A special, fast, case for the most common use of each } else { - if ( isArray ) { - for ( ; i < length; i++ ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } - } - } else { - for ( i in obj ) { - value = callback.call( obj[ i ], i, obj[ i ] ); - - if ( value === false ) { - break; - } + for ( i in obj ) { + if ( callback.call( obj[ i ], i, obj[ i ] ) === false ) { + break; } } } @@ -400,7 +380,7 @@ jQuery.extend({ return obj; }, - // Support: Android<4.1, IE<9 + // Support: Android <=4.0 only trim: function( text ) { return text == null ? "" : @@ -412,7 +392,7 @@ jQuery.extend({ var ret = results || []; if ( arr != null ) { - if ( isArraylike( Object(arr) ) ) { + if ( isArrayLike( Object( arr ) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr @@ -426,42 +406,18 @@ jQuery.extend({ }, inArray: function( elem, arr, i ) { - var len; - - if ( arr ) { - if ( indexOf ) { - return indexOf.call( arr, elem, i ); - } - - len = arr.length; - i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; - - for ( ; i < len; i++ ) { - // Skip accessing in sparse arrays - if ( i in arr && arr[ i ] === elem ) { - return i; - } - } - } - - return -1; + return arr == null ? -1 : indexOf.call( arr, elem, i ); }, + // Support: Android <=4.0 only, PhantomJS 1 only + // push.apply(_, arraylike) throws on ancient WebKit merge: function( first, second ) { var len = +second.length, j = 0, i = first.length; - while ( j < len ) { - first[ i++ ] = second[ j++ ]; - } - - // Support: IE<9 - // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists) - if ( len !== len ) { - while ( second[j] !== undefined ) { - first[ i++ ] = second[ j++ ]; - } + for ( ; j < len; j++ ) { + first[ i++ ] = second[ j ]; } first.length = i; @@ -490,14 +446,13 @@ jQuery.extend({ // arg is for internal usage only map: function( elems, callback, arg ) { - var value, + var length, value, i = 0, - length = elems.length, - isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their new values - if ( isArray ) { + if ( isArrayLike( elems ) ) { + length = elems.length; for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); @@ -527,7 +482,7 @@ jQuery.extend({ // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { - var args, proxy, tmp; + var tmp, args, proxy; if ( typeof context === "string" ) { tmp = fn[ context ]; @@ -553,45 +508,49 @@ jQuery.extend({ return proxy; }, - now: function() { - return +( new Date() ); - }, + now: Date.now, // jQuery.support is not used in Core but other projects attach their // properties to it so it needs to exist. support: support -}); +} ); + +if ( typeof Symbol === "function" ) { + jQuery.fn[ Symbol.iterator ] = arr[ Symbol.iterator ]; +} // Populate the class2type map -jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { +jQuery.each( "Boolean Number String Function Array Date RegExp Object Error Symbol".split( " " ), +function( i, name ) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); -}); +} ); + +function isArrayLike( obj ) { -function isArraylike( obj ) { - var length = obj.length, + // Support: real iOS 8.2 only (not reproducible in simulator) + // `in` check used to prevent JIT error (gh-2145) + // hasOwn isn't used here due to false negatives + // regarding Nodelist length in IE + var length = !!obj && "length" in obj && obj.length, type = jQuery.type( obj ); if ( type === "function" || jQuery.isWindow( obj ) ) { return false; } - if ( obj.nodeType === 1 && length ) { - return true; - } - return type === "array" || length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj; } var Sizzle = /*! - * Sizzle CSS Selector Engine v1.10.19 - * http://sizzlejs.com/ + * Sizzle CSS Selector Engine v2.3.0 + * https://sizzlejs.com/ * - * Copyright 2013 jQuery Foundation, Inc. and other contributors + * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * - * Date: 2014-04-18 + * Date: 2016-01-04 */ (function( window ) { @@ -618,7 +577,7 @@ var i, contains, // Instance-specific data - expando = "sizzle" + -(new Date()), + expando = "sizzle" + 1 * new Date(), preferredDoc = window.document, dirruns = 0, done = 0, @@ -632,10 +591,6 @@ var i, return 0; }, - // General-purpose constants - strundefined = typeof undefined, - MAX_NEGATIVE = 1 << 31, - // Instance methods hasOwn = ({}).hasOwnProperty, arr = [], @@ -643,12 +598,13 @@ var i, push_native = arr.push, push = arr.push, slice = arr.slice, - // Use a stripped-down indexOf if we can't use a native one - indexOf = arr.indexOf || function( elem ) { + // Use a stripped-down indexOf as it's faster than native + // https://jsperf.com/thor-indexof-vs-for/5 + indexOf = function( list, elem ) { var i = 0, - len = this.length; + len = list.length; for ( ; i < len; i++ ) { - if ( this[i] === elem ) { + if ( list[i] === elem ) { return i; } } @@ -659,25 +615,21 @@ var i, // Regular expressions - // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace + // http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", - // http://www.w3.org/TR/css3-syntax/#characters - characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", - // Loosely modeled on CSS identifier characters - // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors - // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier - identifier = characterEncoding.replace( "w", "w#" ), + // http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier + identifier = "(?:\\\\.|[\\w-]|[^\0-\\xa0])+", // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors - attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace + + attributes = "\\[" + whitespace + "*(" + identifier + ")(?:" + whitespace + // Operator (capture 2) "*([*^$|!~]?=)" + whitespace + // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]" "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace + "*\\]", - pseudos = ":(" + characterEncoding + ")(?:\\((" + + pseudos = ":(" + identifier + ")(?:\\((" + // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments: // 1. quoted (capture 3; capture 4 or capture 5) "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" + @@ -688,6 +640,7 @@ var i, ")\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter + rwhitespace = new RegExp( whitespace + "+", "g" ), rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), @@ -699,9 +652,9 @@ var i, ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { - "ID": new RegExp( "^#(" + characterEncoding + ")" ), - "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), - "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), + "ID": new RegExp( "^#(" + identifier + ")" ), + "CLASS": new RegExp( "^\\.(" + identifier + ")" ), + "TAG": new RegExp( "^(" + identifier + "|[*])" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + @@ -723,9 +676,9 @@ var i, rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rsibling = /[+~]/, - rescape = /'|\\/g, - // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters + // CSS escapes + // http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ), funescape = function( _, escaped, escapedWhitespace ) { var high = "0x" + escaped - 0x10000; @@ -739,7 +692,41 @@ var i, String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); - }; + }, + + // CSS string/identifier serialization + // https://drafts.csswg.org/cssom/#common-serializing-idioms + rcssescape = /([\0-\x1f\x7f]|^-?\d)|^-$|[^\x80-\uFFFF\w-]/g, + fcssescape = function( ch, asCodePoint ) { + if ( asCodePoint ) { + + // U+0000 NULL becomes U+FFFD REPLACEMENT CHARACTER + if ( ch === "\0" ) { + return "\uFFFD"; + } + + // Control characters and (dependent upon position) numbers get escaped as code points + return ch.slice( 0, -1 ) + "\\" + ch.charCodeAt( ch.length - 1 ).toString( 16 ) + " "; + } + + // Other potentially-special ASCII characters get backslash-escaped + return "\\" + ch; + }, + + // Used for iframes + // See setDocument() + // Removing the function wrapper causes a "Permission Denied" + // error in IE + unloadHandler = function() { + setDocument(); + }, + + disabledAncestor = addCombinator( + function( elem ) { + return elem.disabled === true; + }, + { dir: "parentNode", next: "legend" } + ); // Optimize for push.apply( _, NodeList ) try { @@ -771,104 +758,128 @@ try { } function Sizzle( selector, context, results, seed ) { - var match, elem, m, nodeType, - // QSA vars - i, groups, old, nid, newContext, newSelector; + var m, i, elem, nid, match, groups, newSelector, + newContext = context && context.ownerDocument, - if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { - setDocument( context ); - } + // nodeType defaults to 9, since context defaults to document + nodeType = context ? context.nodeType : 9; - context = context || document; results = results || []; - if ( !selector || typeof selector !== "string" ) { + // Return early from calls with invalid selector or context + if ( typeof selector !== "string" || !selector || + nodeType !== 1 && nodeType !== 9 && nodeType !== 11 ) { + return results; } - if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { - return []; - } + // Try to shortcut find operations (as opposed to filters) in HTML documents + if ( !seed ) { - if ( documentIsHTML && !seed ) { - - // Shortcuts - if ( (match = rquickExpr.exec( selector )) ) { - // Speed-up: Sizzle("#ID") - if ( (m = match[1]) ) { - if ( nodeType === 9 ) { - elem = context.getElementById( m ); - // Check parentNode to catch when Blackberry 4.6 returns - // nodes that are no longer in the document (jQuery #6963) - if ( elem && elem.parentNode ) { - // Handle the case where IE, Opera, and Webkit return items - // by name instead of ID - if ( elem.id === m ) { - results.push( elem ); + if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { + setDocument( context ); + } + context = context || document; + + if ( documentIsHTML ) { + + // If the selector is sufficiently simple, try using a "get*By*" DOM method + // (excepting DocumentFragment context, where the methods don't exist) + if ( nodeType !== 11 && (match = rquickExpr.exec( selector )) ) { + + // ID selector + if ( (m = match[1]) ) { + + // Document context + if ( nodeType === 9 ) { + if ( (elem = context.getElementById( m )) ) { + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( elem.id === m ) { + results.push( elem ); + return results; + } + } else { return results; } + + // Element context } else { - return results; - } - } else { - // Context is not a document - if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && - contains( context, elem ) && elem.id === m ) { - results.push( elem ); - return results; + + // Support: IE, Opera, Webkit + // TODO: identify versions + // getElementById can match elements by name instead of ID + if ( newContext && (elem = newContext.getElementById( m )) && + contains( context, elem ) && + elem.id === m ) { + + results.push( elem ); + return results; + } } - } - // Speed-up: Sizzle("TAG") - } else if ( match[2] ) { - push.apply( results, context.getElementsByTagName( selector ) ); - return results; + // Type selector + } else if ( match[2] ) { + push.apply( results, context.getElementsByTagName( selector ) ); + return results; - // Speed-up: Sizzle(".CLASS") - } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) { - push.apply( results, context.getElementsByClassName( m ) ); - return results; + // Class selector + } else if ( (m = match[3]) && support.getElementsByClassName && + context.getElementsByClassName ) { + + push.apply( results, context.getElementsByClassName( m ) ); + return results; + } } - } - // QSA path - if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - nid = old = expando; - newContext = context; - newSelector = nodeType === 9 && selector; + // Take advantage of querySelectorAll + if ( support.qsa && + !compilerCache[ selector + " " ] && + (!rbuggyQSA || !rbuggyQSA.test( selector )) ) { - // qSA works strangely on Element-rooted queries - // We can work around this by specifying an extra ID on the root - // and working up from there (Thanks to Andrew Dupont for the technique) - // IE 8 doesn't work on object elements - if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { - groups = tokenize( selector ); + if ( nodeType !== 1 ) { + newContext = context; + newSelector = selector; - if ( (old = context.getAttribute("id")) ) { - nid = old.replace( rescape, "\\$&" ); - } else { - context.setAttribute( "id", nid ); - } - nid = "[id='" + nid + "'] "; + // qSA looks outside Element context, which is not what we want + // Thanks to Andrew Dupont for this workaround technique + // Support: IE <=8 + // Exclude object elements + } else if ( context.nodeName.toLowerCase() !== "object" ) { - i = groups.length; - while ( i-- ) { - groups[i] = nid + toSelector( groups[i] ); + // Capture the context ID, setting it first if necessary + if ( (nid = context.getAttribute( "id" )) ) { + nid = nid.replace( rcssescape, fcssescape ); + } else { + context.setAttribute( "id", (nid = expando) ); + } + + // Prefix every selector in the list + groups = tokenize( selector ); + i = groups.length; + while ( i-- ) { + groups[i] = "#" + nid + " " + toSelector( groups[i] ); + } + newSelector = groups.join( "," ); + + // Expand context for sibling selectors + newContext = rsibling.test( selector ) && testContext( context.parentNode ) || + context; } - newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context; - newSelector = groups.join(","); - } - if ( newSelector ) { - try { - push.apply( results, - newContext.querySelectorAll( newSelector ) - ); - return results; - } catch(qsaError) { - } finally { - if ( !old ) { - context.removeAttribute("id"); + if ( newSelector ) { + try { + push.apply( results, + newContext.querySelectorAll( newSelector ) + ); + return results; + } catch ( qsaError ) { + } finally { + if ( nid === expando ) { + context.removeAttribute( "id" ); + } } } } @@ -881,7 +892,7 @@ function Sizzle( selector, context, results, seed ) { /** * Create key-value caches of limited size - * @returns {Function(string, Object)} Returns the Object data after storing it on itself with + * @returns {function(string, object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ @@ -910,22 +921,22 @@ function markFunction( fn ) { /** * Support testing using an element - * @param {Function} fn Passed the created div and expects a boolean result + * @param {Function} fn Passed the created element and returns a boolean result */ function assert( fn ) { - var div = document.createElement("div"); + var el = document.createElement("fieldset"); try { - return !!fn( div ); + return !!fn( el ); } catch (e) { return false; } finally { // Remove from its parent by default - if ( div.parentNode ) { - div.parentNode.removeChild( div ); + if ( el.parentNode ) { + el.parentNode.removeChild( el ); } // release memory in IE - div = null; + el = null; } } @@ -936,7 +947,7 @@ function assert( fn ) { */ function addHandle( attrs, handler ) { var arr = attrs.split("|"), - i = attrs.length; + i = arr.length; while ( i-- ) { Expr.attrHandle[ arr[i] ] = handler; @@ -952,8 +963,7 @@ function addHandle( attrs, handler ) { function siblingCheck( a, b ) { var cur = b && a, diff = cur && a.nodeType === 1 && b.nodeType === 1 && - ( ~b.sourceIndex || MAX_NEGATIVE ) - - ( ~a.sourceIndex || MAX_NEGATIVE ); + a.sourceIndex - b.sourceIndex; // Use IE sourceIndex if available on both nodes if ( diff ) { @@ -994,6 +1004,34 @@ function createButtonPseudo( type ) { }; } +/** + * Returns a function to use in pseudos for :enabled/:disabled + * @param {Boolean} disabled true for :disabled; false for :enabled + */ +function createDisabledPseudo( disabled ) { + // Known :disabled false positives: + // IE: *[disabled]:not(button, input, select, textarea, optgroup, option, menuitem, fieldset) + // not IE: fieldset[disabled] > legend:nth-of-type(n+2) :can-disable + return function( elem ) { + + // Check form elements and option elements for explicit disabling + return "label" in elem && elem.disabled === disabled || + "form" in elem && elem.disabled === disabled || + + // Check non-disabled form elements for fieldset[disabled] ancestors + "form" in elem && elem.disabled === false && ( + // Support: IE6-11+ + // Ancestry is covered for us + elem.isDisabled === disabled || + + // Otherwise, assume any non-