diff --git a/README.md b/README.md index 23ebcd736..6552c4e66 100644 --- a/README.md +++ b/README.md @@ -36,35 +36,35 @@ Here are some examples of what **tofu** can do #### Built-in one-liners for interactive camera geometry visualization

-Built-in one-liners for interactive camera geometry visualization +Built-in one-liners for interactive camera geometry visualization

#### ...both for 1D and 2D cameras, including the basics for multiple reflections handling

-...both for 1D and 2D cameras, including the basics for multiple reflections handling +...both for 1D and 2D cameras, including the basics for multiple reflections handling

#### Built-in plotting of sinograms

-Built-in plotting of sinograms +Built-in plotting of sinograms

#### Basic magnetic field line tracing

-Basic magnetic field line tracing +Basic magnetic field line tracing

#### Multiple 1d profiles interactive plotting

-Multiple 1d profiles interactive plotting +Multiple 1d profiles interactive plotting

#### Built-in basic data treatment and interactive plotting: svd and spectrograms

-Built-in basic data treatment and interactive plotting: svd and spectrograms +Built-in basic data treatment and interactive plotting: svd and spectrograms

diff --git a/doc/build/doctrees/Auto_tofu.geom.doctree b/doc/build/doctrees/Auto_tofu.geom.doctree index aa5539e79..0441db5da 100644 Binary files a/doc/build/doctrees/Auto_tofu.geom.doctree and b/doc/build/doctrees/Auto_tofu.geom.doctree differ diff --git a/doc/build/doctrees/Auto_tofu.pathfile.doctree b/doc/build/doctrees/Auto_tofu.pathfile.doctree index cca6ef76c..057979fd9 100644 Binary files a/doc/build/doctrees/Auto_tofu.pathfile.doctree and b/doc/build/doctrees/Auto_tofu.pathfile.doctree differ diff --git a/doc/build/doctrees/Auto_tofu.plugins.AUG.doctree b/doc/build/doctrees/Auto_tofu.plugins.AUG.doctree index 91f793ee6..38cf83eb9 100644 Binary files a/doc/build/doctrees/Auto_tofu.plugins.AUG.doctree and b/doc/build/doctrees/Auto_tofu.plugins.AUG.doctree differ diff --git a/doc/build/doctrees/Auto_tofu.plugins.ITER.doctree b/doc/build/doctrees/Auto_tofu.plugins.ITER.doctree index d2ac2ce44..98b6b8517 100644 Binary files a/doc/build/doctrees/Auto_tofu.plugins.ITER.doctree and b/doc/build/doctrees/Auto_tofu.plugins.ITER.doctree differ diff --git a/doc/build/doctrees/Auto_tofu.plugins.doctree b/doc/build/doctrees/Auto_tofu.plugins.doctree index ea041eb32..9ab3679fb 100644 Binary files a/doc/build/doctrees/Auto_tofu.plugins.doctree and b/doc/build/doctrees/Auto_tofu.plugins.doctree differ diff --git a/doc/build/doctrees/Auto_tofu.treat.doctree b/doc/build/doctrees/Auto_tofu.treat.doctree index 528bc7034..7eb13e652 100644 Binary files a/doc/build/doctrees/Auto_tofu.treat.doctree and b/doc/build/doctrees/Auto_tofu.treat.doctree differ diff --git a/doc/build/doctrees/Citation.doctree b/doc/build/doctrees/Citation.doctree index bb6e3631f..db8644f7a 100644 Binary files a/doc/build/doctrees/Citation.doctree and b/doc/build/doctrees/Citation.doctree differ diff --git a/doc/build/doctrees/Dependencies.doctree b/doc/build/doctrees/Dependencies.doctree index 3e27b5a0e..88bb8c4f7 100644 Binary files a/doc/build/doctrees/Dependencies.doctree and b/doc/build/doctrees/Dependencies.doctree differ diff --git a/doc/build/doctrees/Todos.doctree b/doc/build/doctrees/Todos.doctree index f13fd4218..449648150 100644 Binary files a/doc/build/doctrees/Todos.doctree and b/doc/build/doctrees/Todos.doctree differ diff --git a/doc/build/doctrees/Tutorial_AUG.doctree b/doc/build/doctrees/Tutorial_AUG.doctree index 02dc53b68..eea3efb08 100644 Binary files a/doc/build/doctrees/Tutorial_AUG.doctree and b/doc/build/doctrees/Tutorial_AUG.doctree differ diff --git a/doc/build/doctrees/Tutorial_Geom_Advanced.doctree b/doc/build/doctrees/Tutorial_Geom_Advanced.doctree index 4c9d52a18..032d42a79 100644 Binary files a/doc/build/doctrees/Tutorial_Geom_Advanced.doctree and b/doc/build/doctrees/Tutorial_Geom_Advanced.doctree differ diff --git a/doc/build/doctrees/Tutorial_Geom_HowToCreateGeometry.doctree b/doc/build/doctrees/Tutorial_Geom_HowToCreateGeometry.doctree index 7232743ba..7e2609b3d 100644 Binary files a/doc/build/doctrees/Tutorial_Geom_HowToCreateGeometry.doctree and b/doc/build/doctrees/Tutorial_Geom_HowToCreateGeometry.doctree differ diff --git a/doc/build/doctrees/Tutorial_Geom_SynthDiag_Basic.doctree b/doc/build/doctrees/Tutorial_Geom_SynthDiag_Basic.doctree index f40561388..46383adf9 100644 Binary files a/doc/build/doctrees/Tutorial_Geom_SynthDiag_Basic.doctree and b/doc/build/doctrees/Tutorial_Geom_SynthDiag_Basic.doctree differ diff --git a/doc/build/doctrees/Tutorial_ITER.doctree b/doc/build/doctrees/Tutorial_ITER.doctree index 8bbac8225..d55dbc5c5 100644 Binary files a/doc/build/doctrees/Tutorial_ITER.doctree and b/doc/build/doctrees/Tutorial_ITER.doctree differ diff --git a/doc/build/doctrees/Versions.doctree b/doc/build/doctrees/Versions.doctree index ac5da06dd..0faa826c3 100644 Binary files a/doc/build/doctrees/Versions.doctree and b/doc/build/doctrees/Versions.doctree differ diff --git a/doc/build/doctrees/environment.pickle b/doc/build/doctrees/environment.pickle index c9d12b6bd..280387a98 100644 Binary files a/doc/build/doctrees/environment.pickle and b/doc/build/doctrees/environment.pickle differ diff --git a/doc/build/doctrees/index.doctree b/doc/build/doctrees/index.doctree index 48a13497d..c33e16490 100644 Binary files a/doc/build/doctrees/index.doctree and b/doc/build/doctrees/index.doctree differ diff --git a/doc/build/doctrees/overview.doctree b/doc/build/doctrees/overview.doctree index 7d67588d5..040161ec1 100644 Binary files a/doc/build/doctrees/overview.doctree and b/doc/build/doctrees/overview.doctree differ diff --git a/doc/build/html/.buildinfo b/doc/build/html/.buildinfo index e1601ba93..12bc105f3 100644 --- a/doc/build/html/.buildinfo +++ b/doc/build/html/.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: 396f35bc9ac97e5f2534e73d7a02feec +config: 87fdf96d8d844dcd1e999145186e8b50 tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/doc/build/html/Auto_tofu.geom.html b/doc/build/html/Auto_tofu.geom.html index 45f56c2ed..4408d980f 100644 --- a/doc/build/html/Auto_tofu.geom.html +++ b/doc/build/html/Auto_tofu.geom.html @@ -1,34 +1,24 @@ - + - - - 1. tofu.geom — tofu v1.1 - + + 1. tofu.geom — tofu v1.1 - + - - + + + + - - + @@ -55,2109 +45,18 @@

Navigation

1. tofu.geom

-

Load all core packages and modules which are all machine-independent, diagnostic-independent and code-independent

-
-
-class tofu.geom.Ves(Id, Poly, Type='Tor', DLong=None, Sino_RefPt=None, Sino_NP=50, Clock=False, arrayorder='C', Exp=None, shot=None, dtime=None, dtimeIn=False, SavePath=None)[source]
-

A class defining a Linear or Toroidal vaccum vessel (i.e. a 2D polygon representing a cross-section and assumed to be linearly or toroidally invariant)

-

A Ves object is mostly defined by a close 2D polygon, which can be understood as a poloidal cross-section in (R,Z) cylindrical coordinates if Type=’Tor’ (toroidal shape) or as a straight cross-section through a cylinder in (Y,Z) cartesian coordinates if Type=’Lin’ (linear shape). -Attributes such as the surface, the angular volume (if Type=’Tor’) or the center of mass are automatically computed. -The instance is identified thanks to an attribute Id (which is itself a tofu.ID class object) which contains informations on the specific instance (name, Type...).

- --- - - - - - -
Parameters:
    -
  • Id (str / tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • Poly (np.ndarray) – An array (2,N) or (N,2) defining the contour of the vacuum vessel in a cross-section, if not closed, will be closed automatically
  • -
  • Type (str) – Flag indicating whether the vessel will be a torus (‘Tor’) or a linear device (‘Lin’)
  • -
  • DLong (list / np.ndarray) – Array or list of len=2 indicating the limits of the linear device volume on the x axis
  • -
  • Sino_RefPt (None / np.ndarray) – Array specifying a reference point for computing the sinogram (i.e. impact parameter), if None automatically set to the (surfacic) center of mass of the cross-section
  • -
  • Sino_NP (int) – Number of points in [0,2*pi] to be used to plot the vessel sinogram envelop
  • -
  • Clock (bool) – Flag indicating whether the input polygon should be made clockwise (True) or counter-clockwise (False)
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’)
  • -
  • Exp (None / str) – Flag indicating which experiment the object corresponds to, allowed values are in [None,’AUG’,’MISTRAL’,’JET’,’ITER’,’TCV’,’TS’,’Misc’]
  • -
  • shot (None / int) – Shot number from which this Ves is usable (in case of change of geometry)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • dtime (None / dtm.datetime) – A time reference to be used to identify this particular instance (used for debugging mostly)
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly)
  • -
-
Returns:

Ves (Ves object) – The created Ves object, with all necessary computed attributes and methods

-
-
-
-BaryS
-

Return the (surfacic) center of mass of the polygon defining the vessel cross-section

-
- -
-
-BaryV
-

Return the (volumic) center of mass of the polygon defining the vessel cross-section

-
- -
-
-Id
-

Return the tfpf.ID object of the vessel

-
- -
-
-Poly
-

Return the polygon defining the vessel cross-section

-
- -
-
-Sino_NP
-

Return the number of points used used for plotting the Ves polygon in projection space

-
- -
-
-Sino_RefPt
-

Return the 2D coordinates of the points used as a reference for computing the Ves polygon in projection space (where sinograms are plotted)

-
- -
-
-Surf
-

Return the area of the polygon defining the vessel cross-section

-
- -
-
-Type
-

Return the type of vessel

-
- -
-
-Vect
-

Return the polygon elementary vectors

-
- -
-
-Vin
-

Return the normalized vectors pointing inwards for each segment of the polygon

-
- -
-
-VolLin
-

Return the angular volume of the polygon defining the vessel cross-section of Tor type

-
- -
-
-arrayorder
-

Return the flag indicating which order is used for multi-dimensional array attributes

-
- -
-
-get_InsideConvexPoly(RelOff=0.05, ZLim='Def', Spline=True, Splprms=[100.0, 2.0, 3], NP=100, Plot=False, Test=True)[source]
-

Return a polygon that is a smaller and smoothed approximation of Ves.Poly, useful for excluding the divertor region in a Tokamak

-

For some uses, it can be practical to approximate the polygon defining the Ves object (which can be non-convex, like with a divertor), by a simpler, sligthly smaller and convex polygon. -This method provides a fast solution for computing such a proxy.

- --- - - - - - -
Parameters:
    -
  • RelOff (float) – Fraction by which an homothetic polygon should be reduced (1.-RelOff)*(Poly-BaryS)
  • -
  • ZLim (None / str / tuple) – Flag indicating what limits shall be put to the height of the polygon (used for excluding divertor)
  • -
  • Spline (bool) – Flag indiating whether the reduced and truncated polygon shall be smoothed by 2D b-spline curves
  • -
  • Splprms (list) – List of 3 parameters to be used for the smoothing [weights,smoothness,b-spline order], fed to scipy.interpolate.splprep()
  • -
  • NP (int) – Number of points to be used to define the smoothed polygon
  • -
  • Plot (bool) – Flag indicating whether the result shall be plotted for visual inspection
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Poly (np.ndarray) – (2,N) polygon resulting from homothetic transform, truncating and optional smoothing

-
-
- -
-
-get_MeshCrossSection(CrossMesh=[0.01, 0.01], CrossMeshMode='abs', Test=True)[source]
-

Return a (2,N) array of 2D points coordinates meshing the Ves cross-section using the spacing specified by CrossMesh for each direction (taken as absolute distance or relative to the total size)

-

Method used for fast automatic meshing of the cross-section using a rectangular mesh uniform in each direction. -Returns the flattened points coordinates array, as well as the two increasing vectors and number of points.

- --- - - - - - -
Parameters:
    -
  • CrossMesh (iterable) – Iterable of len()==2 specifying the distance to be used between points in each direction (R or Y and Z), in absolute value or relative to the total size of the Ves in each direction
  • -
  • CrossMeshMode (str) – Flag specifying whether the distances provided in CrossMesh are absolute (‘abs’) or relative (‘rel’)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

    -
  • Pts (np.ndarray) – Array of shape (2,N), comtaining the 2D coordinates of the N points consituting the mesh, only points lying inside the cross-section are returned
  • -
  • X1 (np.ndarray) – Flat array of the unique first coordinates of the mesh points (R or Y)
  • -
  • X2 (np.ndarray) – Flat array of the unique second coordinates of the mesh points (Z)
  • -
  • NumX1 (int) – Number of unique values in X1 (=X1.size)
  • -
  • NumX2 (int) – Number of unique values in X2 (=X2.size)
  • -
-

-
-
- -
-
-isInside(Pts, In='(X, Y, Z)')[source]
-

Return an array of booleans indicating whether each point lies inside the Ves volume

-

Tests for each point whether it lies inside the Ves object. -The points coordinates can be provided in 2D or 3D, just specify which coordinate system is provided using the ‘In’ parameter. -An array of boolean flags is returned.

- --- - - - - - -
Parameters:
    -
  • Pts (np.ndarray) – (2,N) or (3,N) array with the coordinates of the points to be tested
  • -
  • In (str) – Flag indicating the coordinate system in which the points are provided, in [‘(X,Y,Z)’,’(R,Z)’,’‘]
  • -
-
Returns:

ind (np.ndarray) – Array of booleans of shape (N,), True if a point is inside the Ves volume

-
-
- -
-
-plot(Lax=None, Proj='All', Elt='PIBsBvV', Pdict=None, Idict={'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, Bsdict={'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, Bvdict={'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, Vdict={'color': 'r', 'scale': 10}, IdictHor={'c': 'k', 'ls': 'dashed'}, BsdictHor={'c': 'b', 'ls': 'dashed'}, BvdictHor={'c': 'g', 'ls': 'dashed'}, Lim=[1.5707963267948966, 6.283185307179586], Nstep=50, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the polygon defining the vessel, with a cross-section view, a longitudinal view or both, and optionally its reference point for plotting it in projection space

-

Generic method for plotting the Ves object, the projections to be plotted, the elements to plot, and the dictionaries or properties to be used for plotting each elements can all be specified using keyword arguments. -If an ax is not provided a default one is created.

- --- - - - - - -
Parameters:
    -
  • Lax (list or plt.Axes) – The axes to be used for plotting (provide a list of 2 axes if Proj=’All’), if None a new figure with axes is created
  • -
  • Proj (str) – Flag specifying the kind of projection used for the plot (‘Cross’ for a cross-section, ‘Hor’ for a horizontal plane, or ‘All’ for the two plots)
  • -
  • Elt (str) –
    -
    Flag specifying which elements to plot, each capital letter corresponds to an element
    -
      -
    • ‘P’: polygon
    • -
    • ‘I’: point used as a reference for computing impact parameters
    • -
    • ‘Bs’: (surfacic) center of mass
    • -
    • ‘Bv’: (volumic) center of mass for Tor type
    • -
    • ‘V’: vector pointing inward perpendicular to each segment defining the polygon
    • -
    -
    -
    -
  • -
  • Pdict (dict or None) – Dictionary of properties used for plotting the polygon, fed to plt.Axes.plot() or plt.plot_surface() if Proj=‘3d’, set to ToFu_Defauts.py if None
  • -
  • Idict (dict) – Dictionary of properties used for plotting point ‘I’ in Cross-section projection, fed to plt.Axes.plot()
  • -
  • IdictHor (dict) – Dictionary of properties used for plotting point ‘I’ in horizontal projection, fed to plt.Axes.plot()
  • -
  • Bsdict (dict) – Dictionary of properties used for plotting point ‘Bs’ in Cross-section projection, fed to plt.Axes.plot()
  • -
  • BsdictHor (dict) – Dictionry of properties used for plotting point ‘Bs’ in horizontal projection, fed to plt.Axes.plot()
  • -
  • Bvdict (dict) – Dictionary of properties used for plotting point ‘Bv’ in Cross-section projection, fed to plt.Axes.plot()
  • -
  • BvdictHor (dict) – Dictionary of properties used for plotting point ‘Bv’ in horizontal projection, fed to plt.Axes.plot()
  • -
  • Vdict (dict) – Dictionary of properties used for plotting point ‘V’ in cross-section projection, fed to plt.Axes.quiver()
  • -
  • LegDict (dict or None) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • Lim (list or tuple) – Array of a lower and upper limit of angle (rad.) or length for plotting the ‘3d’ Proj
  • -
  • Nstep (int) – Number of points for sampling in ignorable coordinate (toroidal angle or length)
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • a4 (bool) – Flag indicating whether the figure should be plotted in a4 dimensions for printing
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

La list or plt.Axes Handles of the axes used for plotting (list if several axes where used)

-
-
- -
-
-plot_Sinogram(Proj='Cross', ax=None, Ang='theta', AngUnit='rad', Sketch=True, Pdict=None, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can also plot a 3D version of it

-

The envelop of the polygon is computed using self.Sino_RefPt as a reference point in projection space, and plotted using the provided dictionary of properties. -Optionaly a smal sketch can be included illustrating how the angle and the impact parameters are defined (if the axes is not provided).

- --- - - - - - -
Parameters:
    -
  • Proj (str) – Flag indicating whether to plot a classic sinogram (‘Cross’) from the vessel cross-section (assuming 2D), or an extended 3D version ‘3d’ of it with additional angle
  • -
  • ax (None or plt.Axes) – The axes on which the plot should be done, if None a new figure and axes is created
  • -
  • Ang (str) – Flag indicating which angle to use for the impact parameter, the angle of the line itself (xi) or of its impact parameter (theta)
  • -
  • AngUnit (str) – Flag for the angle units to be displayed, ‘rad’ for radians or ‘deg’ for degrees
  • -
  • Sketch (bool) – Flag indicating whether a small skecth showing the definitions of angles ‘theta’ and ‘xi’ should be included or not
  • -
  • Pdict (dict) – Dictionary of properties used for plotting the polygon envelopp, fed to plt.plot() if Proj=’Cross’ and to plt.plot_surface() if Proj=‘3d’
  • -
  • LegDict (None or dict) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • a4 (bool) – Flag indicating whether the figure should be plotted in a4 dimensions for printing
  • -
  • Test (bool) – Flag indicating whether the inputs shall be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used to plot

-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
- -
-
-class tofu.geom.Struct(Id, Poly, Type='Tor', DLong=None, Ves=None, Clock=False, arrayorder='C', Exp=None, shot=None, dtime=None, dtimeIn=False, SavePath=None)[source]
-

A class defining a Linear or Toroidal structural element (i.e. a 2D polygon representing a cross-section and assumed to be linearly or toroidally invariant), like a Ves but with less properties.

-

A Struct object is mostly defined by a close 2D polygon, which can be understood as a poloidal cross-section in (R,Z) cylindrical coordinates if Type=’Tor’ (toroidal shape) or as a straight cross-section through a cylinder in (Y,Z) cartesian coordinates if Type=’Lin’ (linear shape). -Attributes such as the surface, the angular volume (if Type=’Tor’) or the center of mass are automatically computed. -The instance is identified thanks to an attribute Id (which is itself a tofu.ID class object) which contains informations on the specific instance (name, Type...).

- --- - - - - - -
Parameters:
    -
  • Id (str / tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • Poly (np.ndarray) – An array (2,N) or (N,2) defining the contour of the vacuum vessel in a cross-section, if not closed, will be closed automatically
  • -
  • Type (str) – Flag indicating whether the vessel will be a torus (‘Tor’) or a linear device (‘Lin’)
  • -
  • DLong (list / np.ndarray) – Array or list of len=2 indicating the limits of the linear device volume on the x axis
  • -
  • Ves (None or Ves) – An optional associated vessel
  • -
  • Clock (bool) – Flag indicating whether the input polygon should be made clockwise (True) or counter-clockwise (False)
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’)
  • -
  • Exp (None / str) – Flag indicating which experiment the object corresponds to, allowed values are in [None,’AUG’,’MISTRAL’,’JET’,’ITER’,’TCV’,’TS’,’Misc’]
  • -
  • shot (None / int) – Shot number from which this Ves is usable (in case of change of geometry)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • dtime (None / dtm.datetime) – A time reference to be used to identify this particular instance (used for debugging mostly)
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly)
  • -
-
Returns:

struct (Struct object) – The created Struct object, with all necessary computed attributes and methods

-
-
-
-BaryS
-

Return the (surfacic) center of mass of the polygon defining the vessel cross-section

-
- -
-
-BaryV
-

Return the (volumic) center of mass of the polygon defining the vessel cross-section

-
- -
-
-DLong
-

Return the length spanned by the object in the ignorable coordinate

-
- -
-
-Id
-

Return the tfpf.ID object of the structure

-
- -
-
-Poly
-

Return the polygon defining the vessel cross-section

-
- -
-
-Surf
-

Return the area of the polygon defining the vessel cross-section

-
- -
-
-Type
-

Return the type of structure

-
- -
-
-Vect
-

Return the polygon elementary vectors

-
- -
-
-Ves
-

Return the associated Ves object, if any

-
- -
-
-Vin
-

Return the normalized vectors pointing inwards for each segment of the polygon

-
- -
-
-VolLin
-

Return the angular volume of the polygon defining the vessel cross-section of Tor type

-
- -
-
-arrayorder
-

Return the flag indicating which order is used for multi-dimensional array attributes

-
- -
-
-isInside(Pts, In='(X, Y, Z)')[source]
-

Return an array of booleans indicating whether each point lies inside the Ves volume

-

Tests for each point whether it lies inside the Ves object. -The points coordinates can be provided in 2D or 3D, just specify which coordinate system is provided using the ‘In’ parameter. -An array of boolean flags is returned.

- --- - - - - - -
Parameters:
    -
  • Pts (np.ndarray) – (2,N) or (3,N) array with the coordinates of the points to be tested
  • -
  • In (str) – Flag indicating the coordinate system in which the points are provided, in [‘(X,Y,Z)’,’(R,Z)’,’‘]
  • -
-
Returns:

ind (np.ndarray) – Array of booleans of shape (N,), True if a point is inside the Ves volume

-
-
- -
-
-plot(Lax=None, Proj='All', Elt='P', Pdict=None, Bsdict={'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, Bvdict={'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, Vdict={'color': 'r', 'scale': 10}, BsdictHor={'c': 'b', 'ls': 'dashed'}, BvdictHor={'c': 'g', 'ls': 'dashed'}, Lim=[1.5707963267948966, 6.283185307179586], Nstep=50, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the polygon defining the vessel, with a cross-section view, a longitudinal view or both, and optionally its reference point for plotting it in projection space

-

Generic method for plotting the Ves object, the projections to be plotted, the elements to plot, and the dictionaries or properties to be used for plotting each elements can all be specified using keyword arguments. -If an ax is not provided a default one is created.

- --- - - - - - -
Parameters:
    -
  • Lax (list or plt.Axes) – The axes to be used for plotting (provide a list of 2 axes if Proj=’All’), if None a new figure with axes is created
  • -
  • Proj (str) – Flag specifying the kind of projection used for the plot (‘Cross’ for a cross-section, ‘Hor’ for a horizontal plane, or ‘All’ for the two plots)
  • -
  • Elt (str) –
    -
    Flag specifying which elements to plot, each capital letter corresponds to an element
    -
      -
    • ‘P’: polygon
    • -
    • ‘Bs’: (surfacic) center of mass
    • -
    • ‘Bv’: (volumic) center of mass for Tor type
    • -
    • ‘V’: vector pointing inward perpendicular to each segment defining the polygon
    • -
    -
    -
    -
  • -
  • Pdict (dict or None) – Dictionary of properties used for plotting the polygon, fed to plt.Axes.plot() or plt.plot_surface() if Proj=‘3d’, set to ToFu_Defauts.py if None
  • -
  • Bsdict (dict) – Dictionary of properties used for plotting point ‘Bs’ in Cross-section projection, fed to plt.Axes.plot()
  • -
  • BsdictHor (dict) – Dictionry of properties used for plotting point ‘Bs’ in horizontal projection, fed to plt.Axes.plot()
  • -
  • Bvdict (dict) – Dictionary of properties used for plotting point ‘Bv’ in Cross-section projection, fed to plt.Axes.plot()
  • -
  • BvdictHor (dict) – Dictionary of properties used for plotting point ‘Bv’ in horizontal projection, fed to plt.Axes.plot()
  • -
  • Vdict (dict) – Dictionary of properties used for plotting point ‘V’ in cross-section projection, fed to plt.Axes.quiver()
  • -
  • LegDict (dict or None) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • Lim (list or tuple) – Array of a lower and upper limit of angle (rad.) or length for plotting the ‘3d’ Proj
  • -
  • Nstep (int) – Number of points for sampling in ignorable coordinate (toroidal angle or length)
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • a4 (bool) – Flag indicating whether the figure should be plotted in a4 dimensions for printing
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

La list or plt.Axes Handles of the axes used for plotting (list if several axes where used)

-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
- -
-
-class tofu.geom.LOS(Id, Du, Ves=None, Sino_RefPt=None, arrayorder='C', Clock=False, Type=None, Exp=None, Diag=None, shot=None, dtime=None, dtimeIn=False, SavePath=None)[source]
-

A Line-Of-Sight object (semi-line with signed direction) with all useful geometrical parameters, associated Ves object and built-in methods for plotting, defined in (X,Y,Z) cartesian coordinates

-

A Line of Sight (LOS) is a semi-line. It is a useful approximate representation of a (more accurate) Volume of Sight (VOS) when the latter is narrow and elongated. -It is usually associated to a detector placed behind apertures. -When associated to a Ves object, special points are automatically computed (entry point, exit point, closest point to the center of the Ves object...) as well as a projection in a cross-section. -While tofu provides the possibility of creating LOS objects for academic and simplification pueposes, it is generally not recommended to use them for doing physics, consider using a Detect object instead (which will provide you with a proper and automatically-computed VOS as well as with a LOS if you want).

- --- - - - -
Parameters:
    -
  • Id (str / tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • Du (list / tuple) – List of 2 arrays of len=3, the (X,Y,Z) coordinates of respectively the starting point D of the LOS and its directing vector u (will be automatically normalized)
  • -
  • Ves (Ves) – A Ves instance to be associated to the created LOS
  • -
  • Sino_RefPt (None or np.ndarray) – If provided, array of size=2 containing the (R,Z) (for ‘Tor’ Type) or (Y,Z) (for ‘Lin’ Type) coordinates of the reference point for the sinogram
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’)
  • -
  • Type (None) – (not used in the current version)
  • -
  • Exp (None / str) – Experiment to which the Lens belongs, should be identical to Ves.Id.Exp if Ves is provided, if None and Ves is provided, Ves.Id.Exp is used
  • -
  • Diag (None / str) – Diagnostic to which the Lens belongs
  • -
  • shot (None / int) – Shot number from which this Lens is usable (in case its position was changed from a previous configuration)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • dtime (None / dtm.datetime) – A time reference to be used to identify this particular instance (used for debugging mostly)
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly)
  • -
-
-
-
-plot(Lax=None, Proj='All', Lplot='Tot', Elt='LDIORP', EltVes='', Leg='', Ldict={'lw': 2, 'c': 'k'}, MdictD={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictI={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictO={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictR={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictP={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, draw=True, a4=False, Test=True)[source]
-

Plot the LOS, in a cross-section projection, a horizontal projection or both, and optionally the Ves object associated to it.

-

Plot the desired projections of the LOS object. -The plot can include the special points, the directing vector, and the properties of the plotted objects are specified by dictionaries.

- --- - - - - - -
Parameters:
    -
  • Lax (list / plt.Axes) – The axes to be used for plotting (provide a list of 2 axes if Proj=’All’), if None a new figure with axes is created
  • -
  • Proj (str) – Flag specifying the kind of projection used for the plot (‘Cross’ for a cross-section, ‘Hor’ for a horizontal plane, ‘All’ both and ‘3d’ for 3d)
  • -
  • Elt (str) –
    -
    Flag specifying which elements to plot, each capital letter corresponds to an element
    -
      -
    • ‘L’: LOS
    • -
    • ‘D’: Starting point of the LOS
    • -
    • ‘I’: Input point (i.e.: where the LOS enters the Vessel)
    • -
    • ‘O’: Output point (i.e.: where the LOS exits the Vessel)
    • -
    • ‘R’: Point of minimal major radius R (only for Vessel of Type=’Tor’)
    • -
    • ‘P’: Point of used for impact parameter (i.e.: minimal distance to reference point Sino_RefPt)
    • -
    -
    -
    -
  • -
  • Lplot (str) – Flag specifying whether to plot the full LOS (‘Tot’: from starting point output point) or only the fraction inside the vessel (‘In’: from input to output point)
  • -
  • EltVes (str) – Flag specifying the elements of the Vessel to be plotted, fed to plot()
  • -
  • Leg (str) – Legend to be used to identify this LOS, if Leg=’’ the LOS name is used
  • -
  • Ldict (dict / None) – Dictionary of properties used for plotting the polygon, fed to plt.Axes.plot() or plt.plot_surface() if Proj=‘3d’, set to ToFu_Defauts.py if None
  • -
  • MdictD (dict) – Dictionary of properties used for plotting point ‘D’, fed to plt.Axes.plot()
  • -
  • MdictI (dict) – Dictionary of properties used for plotting point ‘I’, fed to plt.Axes.plot()
  • -
  • MdictO (dict) – Dictionary of properties used for plotting point ‘O’, fed to plt.Axes.plot()
  • -
  • MdictR (dict) – Dictionary of properties used for plotting point ‘R’, fed to plt.Axes.plot()
  • -
  • MdictP (dict) – Dictionary of properties used for plotting point ‘P’, fed to plt.Axes.plot()
  • -
  • LegDict (dict or None) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • Vesdict (dict) – Dictionary of kwdargs to fed to plot(), and ‘EltVes’ is used instead of ‘Elt’
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • a4 (bool) – Flag indicating whether the figure should be plotted in a4 dimensions for printing
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

La (list / plt.Axes) – Handles of the axes used for plotting (list if several axes where used)

-
-
- -
-
-plot_Sinogram(Proj='Cross', ax=None, Elt='LV', Sketch=True, Ang='theta', AngUnit='rad', Ldict={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, Vdict={'edgecolor': (0.8, 0.8, 0.8, 1.0), 'linewidth': 1, 'linestyle': 'solid', 'facecolor': (0.8, 0.8, 0.8, 1.0)}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can also plot a 3D version of it

-

Plot the LOS in projection space (where sinograms are plotted) as a point. -You can plot the conventional projection-space (in 2D in a cross-section), or a 3D extrapolation of it, where the third coordinate is provided by the angle that the LOS makes with the cross-section plane (useful in case of multiple LOS with a partially tangential view).

- --- - - - - - -
Parameters:
    -
  • Proj (str) – Flag indicating whether to plot a classic sinogram (‘Cross’) from the vessel cross-section (assuming 2D), or an extended 3D version (‘3d’) of it with additional angle
  • -
  • ax (None or plt.Axes) – The axes on which the plot should be done, if None a new figure and axes is created
  • -
  • Elt (str) –
    -
    Flag indicating which elements to plot, each capital letter stands for one element
    -
      -
    • ‘L’: LOS
    • -
    • ‘V’: Vessel
    • -
    -
    -
    -
  • -
  • Ang (str) – Flag indicating which angle to use for the impact parameter, the angle of the line itself (xi) or of its impact parameter (theta)
  • -
  • AngUnit (str) – Flag for the angle units to be displayed, ‘rad’ for radians or ‘deg’ for degrees
  • -
  • Sketch (bool) – Flag indicating whether a small skecth showing the definitions of angles ‘theta’ and ‘xi’ should be included or not
  • -
  • Ldict (dict) – Dictionary of properties used for plotting the LOS point, fed to plt.plot() if Proj=’Cross’ and to plt.plot_surface() if Proj=‘3d’
  • -
  • Vdict (dict) – Dictionary of properties used for plotting the polygon envelopp, fed to plt.plot() if Proj=’Cross’ and to plt.plot_surface() if Proj=‘3d’
  • -
  • LegDict (None or dict) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the figure should be plotted in a4 dimensions for printing
  • -
  • Test (bool) – Flag indicating whether the inputs shall be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used to plot

-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
- -
-
-class tofu.geom.GLOS(Id, LLOS, Ves=None, Sino_RefPt=None, Type=None, Exp=None, Diag=None, shot=None, arrayorder='C', Clock=False, dtime=None, dtimeIn=False, SavePath=None)[source]
-

An object regrouping a group of LOS objects with some common features (e.g.: all belong to the same camera) and the same Ves object, provides methods for common computing and plotting

-

Usually LOS correspond to detectors which are naturally grouped in ‘cameras’ (sets of detectors located in the same place or sharing an aperture or a data acquisition system). -The GLOS object provided by tofu provides the object-oriented equivalent. -The GLOS objects provides the same methods as the LOS objects, plus extra methods for fast handling or selecting of the whole set. -Note that you must first create each LOS independently and then provide them as a list argument to a GLOS object.

- --- - - - -
Parameters:
    -
  • Id (str / tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • LLOS (list / :class:'LOS') – List of LOS instances with the same Ves instance
  • -
  • Type (None) – (not used in the current version)
  • -
  • Exp (None / str) – Experiment to which the Lens belongs, should be identical to Ves.Id.Exp if Ves is provided, if None and Ves is provided, Ves.Id.Exp is used
  • -
  • Diag (None / str) – Diagnostic to which the Lens belongs
  • -
  • shot (None / int) – Shot number from which this Lens is usable (in case its position was changed from a previous configuration)
  • -
  • Sino_RefPt (None / iterable) – If provided, array of size=2 containing the (R,Z) (for ‘Tor’ Type) or (Y,Z) (for ‘Lin’ Type) coordinates of the reference point for the sinogram
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • None / dtm.datetime (dtime) – A time reference to be used to identify this particular instance (used for debugging mostly)
  • -
  • bool (dtimeIn) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly)
  • -
-
-
-
-plot(Lax=None, Proj='All', Lplot='Tot', Elt='LDIORP', EltVes='', Leg='', Ldict={'lw': 2, 'c': 'k'}, MdictD={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictI={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictO={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictR={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, MdictP={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, draw=True, a4=False, Test=True)[source]
-

Plot the GLOS, with a cross-section view, a horizontal view or both, and optionally the Ves object associated to it.

-

Plot all the LOS of the GLOS, or only a selection of them (using the same parameters as self.select()).

- --- - - - - - -
Parameters:
    -
  • Lax (list or plt.Axes) – The axes to be used for plotting (provide a list of 2 axes if Proj=’All’), if None a new figure with axes is created
  • -
  • Proj (str) – Flag specifying the kind of projection used for the plot (‘Cross’ for a cross-section, ‘Hor’ for a horizontal plane, ‘All’ both and ‘3d’ for 3d)
  • -
  • Elt (str) –
    -
    Flag specifying which elements to plot, each capital letter corresponds to an element
    -
      -
    • ‘L’: LOS
    • -
    • ‘D’: Starting point of the LOS
    • -
    • ‘I’: Input point (i.e.: where the LOS enters the Vessel)
    • -
    • ‘O’: Output point (i.e.: where the LOS exits the Vessel)
    • -
    • ‘R’: Point of minimal major radius R (only for Vessel of Type=’Tor’)
    • -
    • ‘P’: Point of used for impact parameter (i.e.: minimal distance to reference point ImpRZ)
    • -
    -
    -
    -
  • -
  • Lplot (str) – Flag specifying whether to plot the full LOS (‘Tot’: from starting point output point) or only the fraction inside the vessel (‘In’: from input to output point)
  • -
  • EltVes (str) – Flag specifying the elements of the Vessel to be plotted, fed to plot()
  • -
  • Leg (str) – Legend to be used to identify this LOS, if Leg=’’ the LOS name is used
  • -
  • Ldict (dict or None) – Dictionary of properties used for plotting the polygon, fed to plt.Axes.plot() or plt.plot_surface() if Proj=‘3d’, set to ToFu_Defauts.py if None
  • -
  • MdictD (dict) – Dictionary of properties used for plotting point ‘D’, fed to plt.Axes.plot()
  • -
  • MdictI (dict) – Dictionary of properties used for plotting point ‘I’, fed to plt.Axes.plot()
  • -
  • MdictO (dict) – Dictionary of properties used for plotting point ‘O’, fed to plt.Axes.plot()
  • -
  • MdictR (dict) – Dictionary of properties used for plotting point ‘R’, fed to plt.Axes.plot()
  • -
  • MdictP (dict) – Dictionary of properties used for plotting point ‘P’, fed to plt.Axes.plot()
  • -
  • LegDict (dict or None) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • Vesdict (dict) – Dictionary of kwdargs to fed to plot(), and ‘EltVes’ is used instead of ‘Elt’
  • -
  • Lim (list or tuple) – Array of a lower and upper limit of angle (rad.) or length for plotting the ‘3d’ Proj
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
  • None or np.ndarray (ind) – Array of indices (int or bool) of the LOS to be plotted if only some of them are to be plotted
  • -
  • kwdargs – kwdargs to be fed to GLOS.select() if ind=None and only a fraction of the LOS are to be plotted
  • -
-
Returns:

La (list or plt.Axes) – Handles of the axes used for plotting (list if several axes where used)

-
-
- -
-
-plot_Sinogram(Proj='Cross', ax=None, Elt='LV', Sketch=True, Ang='theta', AngUnit='rad', Ldict={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, Vdict={'edgecolor': (0.8, 0.8, 0.8, 1.0), 'linewidth': 1, 'linestyle': 'solid', 'facecolor': (0.8, 0.8, 0.8, 1.0)}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot the sinogram of the vessel polygon, by computing its envelopp in a cross-section, can also plot a 3D version of it

-

Plot all the LOS of the GLOS, or only a selection of them in projection space

- --- - - - - - -
Parameters:
    -
  • Proj (str) – Flag indicating whether to plot a classic sinogram (‘Cross’) from the vessel cross-section (assuming 2D), or an extended 3D version ‘3d’ of it with additional angle, default: ‘Cross’
  • -
  • ax (None or plt.Axes) – The axes on which the plot should be done, if None a new figure and axes is created, default: None
  • -
  • Elt (str) –
    -
    Flag indicating which elements to plot, each capital letter stands for one element, default: ‘LV’
    -
      -
    • ‘L’: LOS
    • -
    • ‘V’: Vessel
    • -
    -
    -
    -
  • -
  • Ang (str) – Flag indicating which angle to use for the impact parameter, the angle of the line itself (xi) or of its impact parameter (theta), default: ‘theta’
  • -
  • AngUnit (str) – Flag for the angle units to be displayed, ‘rad’ for radians or ‘deg’ for degrees, default: ‘rad’
  • -
  • Sketch (bool) – Flag indicating whether a small skecth showing the definitions of angles ‘theta’ and ‘xi’ should be included or not
  • -
  • Ldict (dict) – Dictionary of properties used for plotting the LOS point, fed to plt.plot() if Proj=’Cross’ and to plt.plot_surface() if Proj=‘3d’, default: see ToFu_Defaults.py
  • -
  • Vdict (dict) – Dictionary of properties used for plotting the polygon envelopp, fed to plt.plot() if Proj=’Cross’ and to plt.plot_surface() if Proj=‘3d’, default: see ToFu_Defaults.py
  • -
  • LegDict (None or dict) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None, default: see ToFu_Defaults.py
  • -
  • draw (bool) – Flag indicating whether to draw the figure, default: True
  • -
  • Test (bool) – Flag indicating whether the inputs shall be tested for conformity, default: True
  • -
-
Returns:

ax (plt.Axes) – The axes used to plot

-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
-
-select(Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=<type 'bool'>)[source]
-

Return the indices or instances of all instances matching the specified criterion.

-

The selection can be done according to 2 different mechanism (1) and (2).

-

For mechanism (1): the user provides the value (Val) that the specified criterion (Crit) should take for a LOS to be selected. -The criteria are typically attributes of the self.Id attribute (i.e.: name of the instance, or user-defined attributes like the camera head...)

-

For mechanism (2), used if Val=None: the user provides a str expression (or a list of such) to be fed to eval(), used to check on quantitative criteria, placed before the criterion value (e.g.: ‘not ‘ or ‘<=’). -Another str or list of str expressions can be provided that will be placed after the criterion value.

-

Other parameters are used to specify logical operators for the selection (match any or all the criterion...) and the type of output.

- --- - - - - - -
Parameters:
    -
  • Crit (str) – Flag indicating which criterion to use for discrimination -Can be set to any attribute of the tofu.pathfile.ID class (e.g.: ‘Name’,’SaveName’,’SavePath’...) or any key of ID.USRdict (e.g.: ‘Exp’...)
  • -
  • Val (list, str or None) – The value to match for the chosen criterion, can be a list of different values -Used for selection mechanism (1)
  • -
  • PreExp (list, str or None) – A str of list of str expressions to be fed to eval(), used to check on quantitative criteria, placed before the criterion value (e.g.: ‘not ‘) -Used for selection mechanism (2)
  • -
  • PostExp (list, str or None) – A str of list of str expressions to be fed to eval(), used to check on quantitative criteria, placed after the criterion value (e.g.: ‘>=5.’) -Used for selection mechanism (2)
  • -
  • Log (str) – Flag indicating whether the criterion shall match all provided values or one of them (‘any’ or ‘all’)
  • -
  • InOut (str) – Flag indicating whether the returned indices are the ones matching the criterion (‘In’) or the ones not matching it (‘Out’)
  • -
  • Out (type / str) – Flag indicating in which form shall the result be returned, as an array of integer indices (int), an array of booleans (bool), a list of names (‘Names’) or a list of instances (‘LOS’)
  • -
-
Returns:

ind (list / np.ndarray) – The computed output (array of index, list of names or instances depending on parameter ‘Out’)

-
-

Examples

-
>>> import tofu.geom as tfg
->>> ves = tfg.Ves('ves', [[0.,1.,1.,0.],[0.,0.,1.,1.]], DLong=[-1.,1.], Type='Lin', Exp='Misc', shot=0)
->>> los1 = tfg.LOS('los1', ([0.,-0.1,-0.1],[0.,1.,1.]), Ves=ves, Exp='Misc', Diag='D', shot=0)
->>> los2 = tfg.LOS('los2', ([0.,-0.1,-0.1],[0.,0.5,1.]), Ves=ves, Exp='Misc', Diag='D', shot=1)
->>> los3 = tfg.LOS('los3', ([0.,-0.1,-0.1],[0.,1.,0.5]), Ves=ves, Exp='Misc', Diag='D', shot=1)
->>> glos = tfg.GLOS('glos', [los1,los2,los3])
->>> ind = glos.select(Val=['los1','los3'], Log='any', Out='LOS')
->>> print [ii.Id.Name for ii in ind]
-['los1', 'los3']
->>> ind = glos.select(Val=['los1','los3'], Log='any', InOut='Out', Out=int)
-array([1])
-
-
-
- -
- -
-
-class tofu.geom.Lens(Id, O, nIn, Rad, F1, F2=inf, R1=None, R2=None, dd=None, Ves=None, Type='Sph', Exp=None, Diag=None, shot=None, arrayorder='C', Clock=False, SavePath=None, dtime=None, dtimeIn=False)[source]
-

A Lens class with all geometrical data and built-in methods, defined as a planar polygon in 3D cartesian coordinates, with optional Ves object

-

A Lens object is useful for implementing one of the two possible optical arrangements available in tofu. -A Lens (implicitly convergent) is used for focusing incoming light on a detector of reduced size (i.e.g: like the end of an optic fiber cable). -In this case, anmd in its current version, tofu only handles spherical lenses and assumes that the detector has a circular active surface, centered on the same axis as the lens and located in its focal plane.

- --- - - - -
Parameters:
    -
  • Id (str or tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • O (iterable) – Array of 3D cartesian coordinates of the center of the Lens
  • -
  • nIn (iterable) – Array of 3D cartesian coordiantes of the vector defining the axis of the Lens
  • -
  • Rad (float) – Radius of the Lens
  • -
  • F1 (float) – Focal length of the Lens, on the detector side
  • -
  • F2 (float) – Focal length of the Lens, on the plasma side (only np.inf supported so far)
  • -
  • Type (str) – Flag indicating the type of Lens (only ‘Sph’ - for spherical lens - supported so far)
  • -
  • R1 (None or float) – Radius of the first face of the Lens, for full description only
  • -
  • R2 (None or float) – Radius of the second face of the Lens, for full description only
  • -
  • dd (None or float) – Width of the Lens along its axis, for full description only
  • -
  • Ves (Ves) – Ves object to which the aperture is assigned
  • -
  • Exp (None or str) – Experiment to which the Lens belongs, should be identical to Ves.Id.Exp if Ves is provided, if None and Ves is provided, Ves.Id.Exp is used
  • -
  • Diag (None or str) – Diagnostic to which the Lens belongs
  • -
  • shot (None or int) – Shot number from which this Lens is usable (in case its position was changed from a previous configuration)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • Clock (bool) – Flag indicating whether the input polygon should be made clockwise (True) or counter-clockwise (False), default: False
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’), default: ‘C’
  • -
  • dtime (None or dtm.datetime) – A time reference to be used to identify this particular instance (used for debugging mostly), default: None
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly), default: False
  • -
-
-
-
-Poly
-

Return a simple representation of the Lens as a 3D circle (if Lens.Type=’Sph’)

-
- -
-
-plot(Lax=None, Proj='All', Elt='PV', EltVes='', Leg=None, LVIn=0.1, Pdict={'lw': 2, 'c': 'k', 'ls': 'solid'}, Vdict={'color': 'r', 'lw': 2, 'ls': 'solid'}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the Lens object, optionally with the associated Ves object

-

Plot the chosen projections of the Lens polygon.

- --- - - - - - -
Parameters:
    -
  • Lax (list or plt.Axes) – The axes to be used for plotting (provide a list of 2 axes if Proj=’All’), if None a new figure with axes is created
  • -
  • Proj (str) – Flag specifying the kind of projection used for the plot (‘Cross’ for a cross-section, ‘Hor’ for a horizontal plane, ‘All’ both and ‘3d’ for 3d)
  • -
  • Elt (str) –
    -
    Flag specifying which elements to plot, each capital letter corresponds to an element
    -
      -
    • ‘P’: polygon
    • -
    • ‘V’: vector perpendicular to the polygon, oriented towards the interior of the Vessel
    • -
    -
    -
    -
  • -
  • EltVes (str) – Flag specifying the elements of the Vessel to be plotted, fed to plot()
  • -
  • Leg (str) – Legend to be used to identify this LOS, if Leg=’’ the LOS name is used
  • -
  • LVIn (float) – Length (in data coordinates, meters) of the vector ‘V’
  • -
  • Pdict (dict) – Dictionary of properties used for plotting the polygon, fed to plt.Axes.plot() or plt.plot_surface() if Proj=‘3d’, set to ToFu_Defauts.py if None (default: None)
  • -
  • Vdict (dict) – Dictionary of properties used for plotting vector ‘V’, fed to plt.Axes.plot()
  • -
  • Vesdict (dict) – Dictionary of kwdargs to fed to plot(), and ‘EltVes’ is used instead of ‘Elt’
  • -
  • LegDict (dict or None) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • a4 (bool) – Flag indicating whether the figure should be a4 size (for printing or saving as pdf for example)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Lax (list or plt.Axes) – Handles of the axes used for plotting (list if several axes where used)

-
-
- -
-
-plot_alone(ax=None, V='red', nin=1.5, nout=1.0, Lmax='F', V_NP=50, src=None, draw=True, a4=False, Test=True)[source]
-

Plot a 2D representation of the Lens object, optionally with 2D viewing cone and rays of several sources in the plane, either with reduced of full representation

-

Plot a sketch of the Lens, optionally with ray-traced incoming light beams. -This plotting routine does not consider any syurrounding and plots everything assuming the origine of the coordinate system is on the Lens

- --- - - - - - -
Parameters:
    -
  • ax (None or plt.Axes) – Axes to be used for plotting, if None a new figure with axes is created (default: None)
  • -
  • V (str) – Flag indicating whether the Lens should be considered in its reduced geometry model (‘red’) or its full version (‘full’), default: ‘red’
  • -
  • nin (float) – Value of the optical index to be used inside the Lens (useful when V=’full’ only)
  • -
  • nout (float) – Value of the optical index to be used outside the Lens (useful when V=’full’ only)
  • -
  • Lmax (float) – Maximum length on which the source beams should be plotted after going through the Lens, if ‘F’ all beams are plotted up to the focal plane
  • -
  • V_NP (int) – Number of points to be used to plot each circle fraction of the full version of the Lens geometry (useful when V=’full’ only)
  • -
  • src (None or dict) –
    -
    Dictionary of parameters for the source of ray beams:
    -
      -
    • ‘Pt’: iterable of len()=2 with the 2D cartesian coordinates of the point where the source should be located with reference to the Lens center (0,0) and axis (1,0)
    • -
    • ‘Type’: Flag indicating whether the source should a point (‘Pt’) or an array of parallel beams perpendicular to a plane passing through Pt
    • -
    • ‘nn’: iterable of len()=2 with the 2D cartesian coordinates of a vector directing the array of parallel beams
    • -
    • ‘NP’: int, number of beams to be plotted from the source
    • -
    -
    -
    -
  • -
  • draw (bool) – Flag indicating whether the fig.canvas.draw() shall be called automatically, default: True
  • -
  • a4 (bool) – Flag indicating whether the figure should be a4 size (for printing or saving as pdf for example)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity, default: True
  • -
-
Returns:

ax (plt.Axes) – Handle of the axes used for plotting

-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
- -
-
-class tofu.geom.Apert(Id, Poly, Type=None, Ves=None, Exp=None, Diag=None, shot=None, arrayorder='C', Clock=False, SavePath=None, dtime=None, dtimeIn=False)[source]
-

An Aperture class with all geometrical data and built-in methods, defined as a planar polygon in 3D cartesian coordinates, with optional Ves object

-

An Apert object is useful for implementing one of the two possible optical arrangements available in tofu. -An aperture is modelled as a planar polygon (of any non self-intersecting shape) through which light can pass (fully transparent) and around which light cannot pass (fully non-transparent). -One of the added-values of tofu is that it allows to create several non-coplanar aperture and assign them to a single detector. It then computes automatically the volume of sight by assuming that a detectable photon should go through all apertures.

- --- - - - -
Parameters:
    -
  • Id (str or tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • Poly (np.ndarray) – An array (2,N) or (N,2) defining the contour of the aperture in 3D (X,Y,Z) cartesian coordinates, if not closed, will be closed automatically
  • -
  • Ves (Ves) – Ves object to which the aperture is assigned
  • -
  • Type (None or str) – Flag specifying the type of Apert
  • -
  • Exp (None or str) – Experiment to which the Lens belongs, should be identical to Ves.Id.Exp if Ves is provided, if None and Ves is provided, Ves.Id.Exp is used
  • -
  • Diag (None or str) – Diagnostic to which the Lens belongs
  • -
  • shot (None or int) – Shot number from which this Lens is usable (in case its position was changed from a previous configuration)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • Clock (bool) – Flag indicating whether the input polygon should be made clockwise (True) or counter-clockwise (False)
  • -
  • dtime (None or dtm.datetime) – A time reference to be used to identify this particular instance (mostly used for debugging)
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (mostly used for debugging)
  • -
-
-
-
-BaryS
-

Return the (surfacic) center of mass of the polygon (in 3D cartesian coordinates)

-
- -
-
-Id
-

Return the associated tfpf.ID object

-
- -
-
-NP
-

Return the number of points defining the polygon

-
- -
-
-Poly
-

Return the planar polygon defining the aperture (in 3D cartesian coordinates)

-
- -
-
-Surf
-

Return the area of the polygon

-
- -
-
-Ves
-

Return the associated Ves object

-
- -
-
-nIn
-

Return the normalized vector perpendicular to the polygon surface and oriented towards the interior of the associated vessel (in 3D cartesian coordinates)

-
- -
-
-plot(Lax=None, Proj='All', Elt='PV', EltVes='', Leg=None, LVIn=0.1, Pdict={'lw': 2, 'c': 'k', 'ls': 'solid'}, Vdict={'color': 'r', 'lw': 2, 'ls': 'solid'}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the Apert, with a cross-section view, a horizontal view or both, or a 3d view, and optionally the Ves object associated to it.

-

Plot the desired projections of the polygon defining the aperture.

- --- - - - - - -
Parameters:
    -
  • list or plt.Axes (Lax) – The axes to be used for plotting (provide a list of 2 axes if Proj=’All’), if None a new figure with axes is created
  • -
  • str (Leg) – Flag specifying the kind of projection used for the plot (‘Cross’ for a cross-section, ‘Hor’ for a horizontal plane, ‘All’ both and ‘3d’ for 3d)
  • -
  • str
    -
    Flag specifying which elements to plot, each capital letter corresponds to an element
    -
      -
    • ‘P’: polygon
    • -
    • ‘V’: vector perpendicular to the polygon, oriented towards the interior of the Vessel
    • -
    -
    -
    -
  • -
  • str – Flag specifying the elements of the Vessel to be plotted, fed to plot()
  • -
  • str – Legend to be used to identify this LOS, if Leg=’’ the LOS name is used
  • -
  • float (LVIn) – Length (in data coordinates, meters) of the vector ‘V’
  • -
  • dict (Vesdict) – Dictionary of properties used for plotting the polygon, fed to plt.Axes.plot() or plt.plot_surface() if Proj=‘3d’, set to ToFu_Defauts.py if None
  • -
  • dict – Dictionary of properties used for plotting vector ‘V’, fed to plt.Axes.plot()
  • -
  • dict – Dictionary of kwdargs to fed to plot(), and ‘EltVes’ is used instead of ‘Elt’
  • -
  • dict or None (LegDict) – Dictionary of properties used for plotting the legend, fed to plt.legend(), the legend is not plotted if None
  • -
  • bool (Test) – Flag indicating whether the fig.canvas.draw() shall be called automatically
  • -
  • bool – Flag indicating whether the figure should be a4 size (for printing or saving as pdf for example)
  • -
  • bool – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

La list or plt.Axes – Handles of the axes used for plotting (list if several axes where used)

-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
- -
-
-class tofu.geom.Detect(Id, Poly, Optics=None, Ves=None, Sino_RefPt=None, CalcEtend=True, CalcSpanImp=True, CalcCone=True, CalcPreComp=True, Calc=True, Verb=True, Etend_Method='quad', Etend_RelErr=0.001, Etend_dX12=[0.01, 0.01], Etend_dX12Mode='rel', Etend_Ratio=0.02, Colis=True, LOSRef='Cart', Cone_DRY=0.0025, Cone_DXTheta=None, Cone_DZ=0.0025, Cone_NPsi=20, Cone_Nk=60, arrayorder='C', Clock=False, Type=None, Exp=None, Diag=None, shot=None, dtime=None, dtimeIn=False, SavePath=None)[source]
-

A Detector class with all geometrical data and built-in methods, defined as a planar polygon in 3D cartesian coordinates, with optional aperture objects

-

A Detect object is at the core of tofu’s added value and is mostly defined by a 3D planar polygon of any non self-intersecting shape representing the active surface of a detector. -It can then be associated to optics (a Lens or a list of Apert objects) and to a Ves to automatically compute a natural :class:’LOS’ (with its etendue) and, most importantly, a proper VOS (that can be discretized for 3D numerical integration). -It can be 2 different types: either ‘Circ’ if it is associated to a Lens (in which case it is simply defined by radius and is assumed to be circular and placed at the focal plane of the Lens object), or None in the more general case in which it is associated to a set of apertures. -Most of the commonly used quantities are automatically calculated (etendue of the LOS, VOS...) and it comes with built-in methods for plotting and computing synthetic data.

-

To compute the VOS, tofu tests all points inside a 3D grid to see if each point is visible from the detector through the apertures or not. -The meshed space is determined by the volume spanned by a LOS sampling of the VOS. -Then, a contour function is used to find the polygons limiting the cross-section and horizontal projections of the VOS. -Once computed, the viewing cones are assigned to attributes of the Detect instance.

-

In the particular case (1) when the LOS of the detector lies entirely inside one cross-section (e.g.: tomography diagnostics), tofu also computes the integral in the direction of the ignorable coordinate of the solid angle on a regular mesh (for faster computation of the geometry assuming toroidaly invariant basis functions). -This regular mesh is defined in 2D, by the distance between a mesh point and the detector (k) and by the poloidal angle between the LOS and the line going from the detector to the mesh point (psi)

- --- - - - -
Parameters:
    -
  • Id (str or tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to tfpf.ID()
  • -
  • Poly (dict or np.ndarray) –
    -
    Contains the information regarding the geometry of the Detect object
    -
      -
    • np.ndarray: (2,N) or (N,2) defining the contour of the detector active surface in 3D (X,Y,Z) cartesian coordinates, if not closed, will be closed automatically, if Type=None
    • -
    • dict: dictionary of properties for a circular detector placed in the focal plane of a Lens on its axis, contains field ‘Rad’=float (radius), if Optics is Lens and Type=’Circ’
    • -
    -
    -
    -
  • -
  • Optics (list or Lens) – The optics to be associated to the detector, either a spherical Lens or a list of apertures Apert
  • -
  • Ves (Ves or None) – Ves object to which the detector is assigned
  • -
  • Sino_RefPt (np.ndarray or None) – Array of size=2 containing the (R,Z) (for ‘Tor’ Type) or (Y,Z) (for ‘Lin’ Type) coordinates of the reference point for the sinogram
  • -
  • CalcEtend (bool) – Flag indicating whether to compute the etendue
  • -
  • CalcSpanImp (bool) – Flag indicating whether to compute the maximal span of the viewing volume
  • -
  • CalcCone (bool) – Flag indicating whether to compute the viewing volume or viewing cone and its two projections
  • -
  • CalcPreComp (bool) – Flag indicating whether to pre-compute a set of pre-defined points inside the viewing volume for faster computation of signal from 3D emissivity
  • -
  • Calc (bool) – Flag indicating whether to compute all the above
  • -
  • Verb (bool) – Flag indicating whether the creation of the object should be verbose (comments for each step)
  • -
  • Etend_Method (str) – Flag indicating which numerical integration to use for the computation of the etendue (picked from scipy.integrate : ‘quad’, ‘simps’, ‘trapz’)
  • -
  • Etend_RelErr (float) – If Etend_Method=’quad’, specifies the maximum relative error to be tolerated on the value of the integral (i.e.: etendue)
  • -
  • Etend_dX12 (list) – If Etend_Method in [‘simps’,’trapz’], which implies a discretization of the plane perpendicular to the LOS, specifies the resolution of the discretization
  • -
  • Etend_dX12Mode (str) – If Etend_Method in [‘simps’,’trapz’], specifies whether Etend_dX12 should be iunderstood as an absolute distance (‘abs’) or a fraction of the maximum width (‘rel’)
  • -
  • Etend_Ratio (float) – The numerical integration is performed on an automatically-deterimned interval, this ratio (fraction of unity) is a safety margin to increase a bit the interval and make sure all non-zero values are included
  • -
  • Colis (bool) – Flag indicating whether the collision detection mechanism should be considered when computing the VOS
  • -
  • LOSRef (str) – Key indicating which of the LOS in the LOS dictionary should be considered as the reference LOS
  • -
  • Cone_DRY (float) – Resolution of the grid in the R (for ‘Tor’ vessel types) or Y (for ‘Lin’ vessel types) direction, in meters
  • -
  • Cone_DXTheta (float) – Resolution of the grid in the toroidal (for ‘Tor’ vessel types, in radians) or X (for ‘Lin’ vessel types, in meters) direction
  • -
  • Cone_DZ (float) – Resolution of the grid in the Z direction, in meters
  • -
  • Cone_NPsi (int) – Number of points of the regular mesh in psi direction (angle), in case (1)
  • -
  • Cone_Nk (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
  • Type (None / str) – If the detector is associated to a Lens, it should be of type ‘Circ’ (only circular shaped detectors are handled by tofu behind spherical lenses)
  • -
  • Exp (None or str) – Experiment to which the Lens belongs, should be identical to Ves.Id.Exp if Ves is provided, if None and Ves is provided, Ves.Id.Exp is used
  • -
  • Diag (None or str) – Diagnostic to which the Lens belongs
  • -
  • shot (None or int) – Shot number from which this Lens is usable (in case its position was changed from a previous configuration)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • Clock (bool) – Flag indicating whether the input polygon should be made clockwise (True) or counter-clockwise (False), default: False
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’), default: ‘C’
  • -
  • dtime (None or dtm.datetime) – A time reference to be used to identify this particular instance (used for debugging mostly)
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly)
  • -
-
-
-
-BaryS
-

Return the (surfacic) center of mass of the polygon (in 3D cartesian coordinates)

-
- -
-
-Cone_PolyCross
-

Return the polygon that is the projection in a cross-section of the viewing cone

-
- -
-
-Cone_PolyHor
-

Return the polygon that is the projection in a horizontal plane of the viewing cone

-
- -
-
-Id
-

Return the associated tfpf.ID object

-
- -
-
-LOS
-

Return the dictionary of associated LOS objects

-
- -
-
-NP
-

Return the number of points defining the polygon

-
- -
-
-Optics
-

Return the list of associated Optics objects (Lens or list of Apert)

-
- -
-
-OpticsNb
-

Return the number of associated Optics

-
- -
-
-OpticsType
-

Return the type of associated Optics objects

-
- -
-
-Poly
-

Return the planar polygon defining the aperture (in 3D cartesian coordinates)

-
- -
-
-Rad
-

Return the radius of the polygon (if Type=’Circ’, else None)

-
- -
-
-SAngCross_Int
-

Return the integral of the solid angle at pre-computed points of the VOS in a cross-section projection

-
- -
-
-SAngCross_Points
-

Return the pre-computed points of the VOS in a cross-section projection

-
- -
-
-SAngHor_Int
-

Return the integral of the solid angle at pre-computed points of the VOS in a horizontal projection

-
- -
-
-SAngHor_Points
-

Return the pre-computed points of the VOS in a horizontal projection

-
- -
-
-Sino_RefPt
-

Return the coordinates (R,Z) or (Y,Z) for Ves of Type ‘Tor’ or (Y,Z) for Ves of Type ‘Lin’ of the reference point used to compute the sinogram

-
- -
-
-Surf
-

Return the area of the polygon

-
- -
-
-Ves
-

Return the associated Ves object

-
- -
-
-calc_Etendue_AlongLOS(Length='', NP=20, Modes=['trapz', 'quad'], RelErr=0.001, dX12=[0.005, 0.005], dX12Mode='abs', Ratio=0.02, Colis=True, LOSRef=None, Test=True)[source]
-

Return the etendue computed at different points along the LOS, with various numerical methods, with or without collision detection

-

Computing the etendue along the LOS of a Detect object can be useful for checking whether the etendue is constant (as it should be if the LOS approximation is to be used). -Cases with non-constant etendue include in particular partially obstructed VOS in the divertor region of Tokamaks. -Also useful for debugging: if the etendue is not constant but the VOS is not obstructed, something might be wrong with the computation of the etendue or with the model (e.g.: for Lens optics). -Indeed, the model implemented for a Lens is ideal, but a close look at the etendue shows that the model is not perfect (but sufficiently accurate for most uses though).

- --- - - - - - -
Parameters:
    -
  • Length (str) – Flag indicating whether to use the full length of the VOS (including partially obstructed parts: ‘’), or just the length of the LOS unil its exit point (‘LOS’).
  • -
  • NP (int) – Number of points (uniformly distributed along the LOS) where the etendue should be computed
  • -
  • Modes (list or str) – Flag or list of flags indicating which numerical integration methods shoud be used in [‘quad’,’simps’,’trapz’]
  • -
  • RelErr (float) – For ‘quad’, a positive float defining the relative tolerance allowed
  • -
  • dX12 (list) – For ‘simps’ or ‘trapz’, a list of 2 floats defining the resolution of the sampling in X1 and X2
  • -
  • dX12Mode (str) – For ‘simps’ or’trapz’, ‘rel’ or ‘abs’, if ‘rel’ the resolution dX12 is in dimensionless units in [0;1] (hence a value of 0.1 means 10 discretisation points between the extremes), if ‘abs’ dX12 is in meters
  • -
  • Ratio (float) – A float specifying the relative margin to be taken for integration boundaries
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
  • LOSRef (None or str) – Flag indicating which LOS should be used
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

    -
  • Etend (np.ndarray) – Computed etendues
  • -
  • Pts (np.ndarray) – (3,NP) array specifying the 3D (X,Y,Z) coordinates of the points along the LOS where the etendue was computed
  • -
  • kPts (np.ndarray) – (NP,) array of the distance-coordinate k along the LOS
  • -
  • LOSRef (str) – The LOS that was used
  • -
-

-
-
- -
-
-calc_SAngNb(Pts=None, Proj='Cross', Slice='Int', DRY=None, DXTheta=None, DZ=None, Colis=True)[source]
-

Compute the solid angle subtended by the Detect+Optics system as seen for desired points, in a slice or integrated manner

-

Mostly useful in the GDetect object when there are several detectors. -Computes, for each point in the desired projection, the total solid angle subtended by all the detectors (or its integral) and the number of detectors that ‘see’ each point.

- --- - - - - - -
Parameters:
    -
  • Pts (None / np.ndarray) – (3,N) array of cartesian (X,Y,Z) coordinates of the provided N points, if None a default set of points is computed according to DRY, DXTheta and DZ
  • -
  • Proj (str) – Flag indicating to which projection of the VOS the method should be applied
  • -
  • Slice (str) – Flag indicating whether to compute the solid angle (‘Slice’), the maximum solid angle along the ignorable coordinate (‘Max’), or the integral over the ignorable coordinate (‘Int’)
  • -
  • DRY (None / float) – Resolution (in horizontal direction of the cross-section) of the mesh to be constructed if the points are not provided
  • -
  • DXTheta (None / float) – Resolution (in ignorable coordinate direction) of the mesh to be constructed if the points are not provided
  • -
  • DZ (None / float) – Resolution (in vertical direction) of the mesh to be constructed if the points are not provided
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
-
Returns:

    -
  • SA (np.ndarray) – Array of (ND,NP) solid angle values, where ND is the number of detectors and NP the number of points
  • -
  • Nb (np.ndarray) – Array of (ND,NP) booleans, True if a point is seen by a detector
  • -
  • Pts (np.ndarray) – The computed points (in case they were not provided)
  • -
-

-
-
- -
-
-calc_SAngVect(Pts, In='(X, Y, Z)', Colis=True, Test=True)[source]
-

Return the Solid Angle of the Detect-Apert system as seen from the specified points, including collisions detection or not

-

Compute the solid angle and the directing vector subtended by the Detect-Optics system as seen from the desired points (provided in the specified coordinates). -This can be useful for visualizing the solid angle distribution or for computing synthetic signal from simulated emissivity in a 3D numerical integration manner. -The automtic detection of collisions with the edges of the Ves object can be switched off (not recommended).

- --- - - - - - -
Parameters:
    -
  • Pts (np.ndarray) – (2,N) or (3,N) array of coordinates of the provided N points
  • -
  • In (str) – Flag indicating in which coordinate system the Pts are provided, must be in [‘(R,Z)’,’(X,Y,Z)’,’(R,phi,Z)’]
  • -
  • Colis (bool) – Flag indicating whether collision detection should be activated
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

SAng (np.ndarray) – (N,) array of floats, the computed solid angles

-
-
- -
-
-calc_Sig(ff, extargs={}, Method='Vol', Mode='simps', PreComp=True, epsrel=0.0001, dX12=[0.005, 0.005], dX12Mode='abs', ds=0.005, dsMode='abs', MarginS=0.001, Colis=True, Test=True)[source]
-

Return the signal computed from an input emissivity function, using a 3D or LOS method

-

The synthetic signal resulting from a simulated emissivity can be computed automatically in several ways. -The user can choose between a VOS and a LOS approach (volume integration or line integration with etendue). -In each case the user can choose between the numerical integration method (from scipy.integrate + np.sum()). -It is possible to specify that, for a VOS approach, you want to use the pre-conputed mesh for faster computation (see set_SigPrecomp()). -For a VOS approach, the user can specify how fine the discretization should be. -The collision detection with the edges of the Ves object can be switched off (not recommended).

- --- - - - - - -
Parameters:
    -
  • ff (function) –
    -
    Input emissiviy function, should take one input as follows:
    -
      -
    • ff(Pts), where Points is a np.ndarray of shape=(3,N), with the (X,Y,Z) coordinates of any N number of points
    • -
    -
    -
    -
  • -
  • Method (str) – Flag indicating whether the spatial integration should be done with a volume (‘Vol’) or a LOS (‘LOS’) approach
  • -
  • Mode (str) – Flag indicating the numerical integration method in [‘quad’,’simps’,’trapz’,’nptrapz’,’sum’]
  • -
  • PreComp (bool) – Flag indicating whether the pre-computed grid should be used
  • -
  • epsrel (float) – Float specifying the tolerated relative error on the numerical integration, used for ‘quad’
  • -
  • dX12 (list) – Array of the 2 resolutions to be used to define the grid in a plane perpendicular to the LOS
  • -
  • dX12Mode (str) – Flag specifying whether the values in dX12 are absolute distances or relative values (i.e. fraction of the total width [0;1])
  • -
  • ds (float) – Float indicating the resolution in the longitudinal direction
  • -
  • dsMode (str) – Flag specifying whether ds is an absolute distance or relative (i.e. fraction of the total length [0;1])
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Sig (float) – The computed signal

-
-
- -
-
-isInside(Points, In='(X, Y, Z)', Test=True)[source]
-

Return an array of indices indicating whether each point lies both in the cross-section and horizontal porojections of the viewing cone

-

Like for the Ves object, points can be provided in 2D or 3D coordinates (specified by ‘In’), and an array of booleans is returned.

- --- - - - - - -
Parameters:
    -
  • Points (np.ndarray) – (2,N) or (3,N) array of coordinates of the N points to be tested
  • -
  • In (str) –
    -
    Flag indicating in which coordinate system the Points are provided, must be in [‘(R,Z)’,’(Y,Z)’,’(X,Y)’,’(X,Y,Z)’,’(R,phi,Z)’]
    -
      -
    • ‘(R,Z)’: All points are assumed to lie in the horizontal projection, for ‘Tor’ vessel type only
    • -
    • ‘(Y,Z)’: All points are assumed to lie in the horizontal projection, for ‘Lin’ vessel type only
    • -
    • ‘(X,Y)’: All points are assumed to lie in the cross-section projection
    • -
    -
    -
    -
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ind (np.ndarray) – (N,) array of booleans with True if a point lies inside both projections of the viewing cone

-
-
- -
-
-nIn
-

Return the normalized vector perpendicular to the polygon surface and oriented towards the interior of the associated vessel (in 3D cartesian coordinates)

-
- -
-
-plot(Lax=None, Proj='All', Elt='PVC', EltLOS='LDIORP', EltOptics='P', EltVes='', Leg=None, LOSRef=None, Pdict={'lw': 2, 'c': 'k', 'ls': 'solid'}, Vdict={'color': 'r', 'lw': 2, 'ls': 'solid'}, Cdict={'edgecolors': 'k', 'antialiaseds': False, 'linestyles': '-', 'linewidths': 0.0, 'alpha': 0.2, 'facecolors': (0.8, 0.8, 0.8, 0.2)}, LVIn=0.1, LOSdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'EltVes': '', 'Proj': 'All', 'Test': True, 'Elt': 'LDIORP', 'MdictP': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictR': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Leg': '', 'Lplot': 'Tot', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'MdictI': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Ldict': {'lw': 2, 'c': 'k'}, 'MdictO': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictD': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}}, Opticsdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'Pdict': {'lw': 2, 'c': 'k', 'ls': 'solid'}, 'Vdict': {'color': 'r', 'lw': 2, 'ls': 'solid'}, 'EltVes': '', 'Leg': '', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'LVIn': 0.1, 'Test': True, 'Elt': 'PV', 'Proj': 'All'}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True)[source]
-

Plot the Detect instance in a projection or in 3D, its polygon, perpendicular vector, projected viewing cones and optionally its LOS, Apert, and Ves objects

-

The Detect instance can be plotted in a cross-section or horizontal projection, or in 3D. -Several of its attributes can be plotted too using the usual ‘Elt’ keyword argument. -Dedicated ‘Elt’ keyword arguments are also usable to specify the elements to be plotted for sub-classes like LOS, Apert, and Ves. -Dedicated dictionary help specify how each element sshould be plotted.

- --- - - - - - -
Parameters:
    -
  • Lax (None, plt.Axes or list) – Axes or list of axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • Proj (str) – Flag indicating whether to plot the cross-section (‘Cross’), the horizontal projection (‘Hor’), both (‘All’) or a 3D representation (‘3D’)
  • -
  • Elt (str) –
    -
    Flag indicating which elements of the Detect instance to plot, each capital letter stands for an element
    -
      -
    • ‘P’: polygon
    • -
    • ‘V’: perpendicular vector
    • -
    • ‘C’: viewing cone
    • -
    -
    -
    -
  • -
  • EltLOS (None or str) – Flag indicating which elements of the LOS to plot, will be fed to LOS.plot(), if None uses the ‘Elt’ arg of LOSdict instead
  • -
  • EltOptics (None or str) – Flag indicating which elements of the Aperts to plot, will be fed to Apert.plot(), if None uses the ‘Elt’ arg of Apertdict instead
  • -
  • EltVes (None or str) – Flag indicating which elements of the Ves to plot, will be fed to plot(), if None uses the ‘Elt’ arg of Vesdict instead
  • -
  • Leg (str) – Legend to be used for the detector, if ‘’ the Detect.iD.Name is used
  • -
  • LOSRef (None or str) – Flag indicating which LOS should be represented, if None Detect._LOSRef is used
  • -
  • Pdict (dict) – Dictionary of properties for the Polygon
  • -
  • Vdict (dict) – Dictionary of properties for the Vector
  • -
  • Cdict (dict) – Dictionary of properties for the Cone
  • -
  • LVIn (float) – Length of the Vector
  • -
  • LOSdict (dict) – Dictionary of properties for the LOS if EltLOS is not ‘’, fed to LOS.plot()
  • -
  • Apertdict (dict) – Dictionary of properties for the Apert if EltOptics is not ‘’, fed to Apert.plot()
  • -
  • Vesdict (dict) – Dictionary of properties for the Ves if EltVes is not ‘’, fed to plot()
  • -
  • LegDict (dict) – Dictionary of properties for the legend, fed to plt.legend()
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the default figure should be of size a4 paper
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Lax plt.Axes or list – Axes or list of axes used for plotting

-
-
- -
-
-plot_Etend_AlongLOS(ax=None, NP=20, kMode='rel', Modes=['trapz'], Length='', RelErr=0.001, dX12=[0.005, 0.005], dX12Mode='abs', Ratio=0.02, LOSRef=None, LOSPts=True, Ldict={'lw': 2, 'c': 'k', 'ls': 'solid'}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, Colis=True, draw=True, a4=True, Test=True)[source]
-

Plot the etendue of the selected LOS along it, with or without collision detection

-

The number of points along the LOS where the etendue is computed can be specified via arguments, as well as the numerical integration method. -Arguments Length, NP, Modes, RelErr, dX12, dX12Mode, Ratio, Colis, LOSRef are fed to calc_Etendue_AlongLOS()

- --- - - - - - -
Parameters:
    -
  • ax (None or plt.Axes) – Axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • kMode (str) – Flag indicating whether the distance on the line should be plotted as abolute distance (‘abs’) or relative to the total length (‘rel’)
  • -
  • Ldict (dict) – Dictionary of properties for plotting the result
  • -
  • LegDict (None / dict) – If None, no legend is plotted, else LegDict is fed to :meth:’~matplotlib.pyplot.Axes.legend’
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the created figure should have a4 dimensions (useful for printing)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used for plotting

-
-
- -
-
-plot_SAngNb(Lax=None, Proj='Cross', Slice='Int', Pts=None, plotfunc='scatter', DRY=None, DXTheta=None, DZ=None, Elt='P', EltVes='P', EltLOS='', EltOptics='P', Pdict={'lw': 2, 'c': 'k', 'ls': 'solid'}, Vdict={'color': 'r', 'lw': 2, 'ls': 'solid'}, Cdict={'edgecolors': 'k', 'antialiaseds': False, 'linestyles': '-', 'linewidths': 0.0, 'alpha': 0.2, 'facecolors': (0.8, 0.8, 0.8, 0.2)}, LVIn=0.1, LOSdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'EltVes': '', 'Proj': 'All', 'Test': True, 'Elt': 'LDIORP', 'MdictP': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictR': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Leg': '', 'Lplot': 'Tot', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'MdictI': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Ldict': {'lw': 2, 'c': 'k'}, 'MdictO': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictD': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}}, Opticsdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'Pdict': {'lw': 2, 'c': 'k', 'ls': 'solid'}, 'Vdict': {'color': 'r', 'lw': 2, 'ls': 'solid'}, 'EltVes': '', 'Leg': '', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'LVIn': 0.1, 'Test': True, 'Elt': 'PV', 'Proj': 'All'}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, CDictSA=None, CDictNb=None, Colis=True, a4=False, draw=True, Test=True)[source]
-

Plot the solid angle projections (integrated ‘Int’ or maximum ‘Max’) as well as the number of detectors visible from each point in the plasma

-

Mostly useful with the GDetect object, used to visualize the goemetrical coverage in terms of total solid angle and number of detectors ‘seeing’ each point for a set of detectors (see calc_SAngNb() method for details).

- --- - - - - - -
Parameters:
    -
  • Lax (None or list or plt.Axes) – Axes or list of Axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • Proj (str) – Flag indicating whether to plot the cross-section (‘Cross’) or the horizontal projection (‘Hor’)
  • -
  • Mode (str, None or float) –
    -
    Flag indicating whether to plot:
    -
      -
    • ‘Int’: the integrated value along the projected coordinates
    • -
    • ‘Max’: the maximum value along the projected coordinates
    • -
    • float: the projected coordinate at which to plot the slice (Theta or X if Proj=’Cross’, Z if Proj=’Hor’)
    • -
    • None: the slice is done in the middle of the viewing volume
    • -
    -
    -
    -
  • -
  • plotfunc (str) – Flag indicating which plotting method to use (‘scatter’, ‘contour’, ‘contourf’ or ‘imshow’)
  • -
  • DCross (float) – Resolution along the 1st cross-section coordinate (R for Type=’Tor’, Y for Type=’Lin’)
  • -
  • DXTheta (float) – Resolution along the ignorable coordinate (Theta for Type=’Tor’, X for Type=’Lin’)
  • -
  • DZ (float) – Vertical resolution (for both Types)
  • -
  • CDictSA (dict) – Properties of the solid angle plot, to be fed to the function chosen by plotfunc
  • -
  • CDictNb (dict) – Properties of the Nb plot, to be fed to the chsoen plotting routine
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
  • a4 (bool) – Flag indicating whether to use a4 dimensions to create a new figure if Lax=None
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Lax (plt.Axes or list) – List of the axes used for plotting

-
-
- -
-
-plot_Sinogram(ax=None, Proj='Cross', Elt='DLV', Ang='theta', AngUnit='rad', Sketch=True, Ddict={'lw': 1, 'c': 'k', 'ls': 'solid'}, Ldict={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, Vdict={'edgecolor': (0.8, 0.8, 0.8, 1.0), 'linewidth': 1, 'linestyle': 'solid', 'facecolor': (0.8, 0.8, 0.8, 1.0)}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, LOSRef=None, draw=True, a4=False, Test=True)[source]
-

Plot the the Detect VOS in projection space, optionally also the associated Ves object and reference LOS

-

In projection space, a VOS is a patch (as opposed to a LOS which is a point). -The patch is estimated by plotting a large number of LOS sampling the VOS and taking the convex hull of the resulting points on projection space. -Notice that this method results in irrelevant patches for VOS lying at the edges of the projection space. -See plot_Sinogram() for details.

- --- - - - - - -
Parameters:
    -
  • ax (None / plt.Axes) – Axes on which to plot the Etendue, if None a default axes is created
  • -
  • Proj (str) – Flag indicating whether to plot the traditional sinogram in a cross-section (‘Cross’) or a 3D sinogram (‘3d’), cannot be ‘3d’ if ‘D’ in Elt.
  • -
  • Elt (str) – Flags indicating whether to plot the VOS of the Detect (‘D’ in Elt => only Proj=’Cross’), the LOS (‘L’ in Elt) and the Ves (‘V’ in Elt)
  • -
  • Ang (str) – Flag indicating which angle to use for the plot, with respect to the considered line () or to the impact parameter line ()
  • -
  • AngUnit (str) – Flag indicating whether the angle should be measured in ‘rad’ or ‘deg’
  • -
  • Sketch (bool) – Flag indicating whether a small sketch illustrating the definitions of angles and impact parameter should be included
  • -
  • Ddict (dict) – Plotting properties of the VOS of the Detect, fed to plt.plot()
  • -
  • Ldict (dict) – Plotting properties of the LOS, fed to plt.plot()
  • -
  • Vdict (dict) – Plotting properties of the Ves, fed to plt.plot()
  • -
  • LegDict (None / dict) – Plotting properties of the legend, if None no legend is plotted
  • -
  • LOSRef (None / str) – Flag indicating which LOS to plot, if None self._LOSRef is used
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the created figure should have a4 dimensions (useful for printing)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used for plotting

-
-
- -
-
-refine_ConePoly(dMax=0.02, Proj='Cross', indPoly=0, Verb=True, Test=True)[source]
-

Reduce the number of points of the selected Cone_Poly projection using the provided maximum distance and checking for convexity

-

Provide a built-in method to simplify the 2 projections of the viewing cone (VOS). -In its raw form, the projection of the VOS is a polygon with potentially a high number of points (computed using matplotlib._cntr() function). -A re-sampled version of this polygon is computed by taking its convex hull and checking, for each edge, how far it is from the original edge. -Each edge (2 points) of the convex hull is then compared to the set of original edges it encloses. -If the maximum distance between this convex hull-derived edge and the original set of edges is smaller than dMax, then the convex hull-derived egde is used, otherwise the original edges are preserved. -The method does not return a value, instead it assigns the new polygon to a dedicated attribute of the object, thus ensuring that both the original and the re-sampled projections of the VOS are available.

- --- - - - -
Parameters:
    -
  • dMax (float) – Threshold absolute distance that limits the acceptable discrepancy between the original polygon and its convex hull (checked for each edge of the convex hull)
  • -
  • Proj (str) – Flag indicating to which projection of the VOS the method should be applied
  • -
  • indPoly (int) – Index of the polygon to be treated (i.e.: in case one projection of the VOS results in a list of several polygons instead of just one polygon as is usually the case)
  • -
  • Verb (bool) – Flag indicating whether a one-line comment should be printed at the end of the calculation giving the number of points of the new polygon vs the number of points of the original polygon
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False, SynthDiag=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save() -In the case of Detect and GDetect instances, there is an additional keyword argument ‘SynthDiag’ which allows to not save the pre-computed 3D mesh of the VOS for synthetic diagnostic. -Indeed, this pre-computed data is often large and results in big files. Not saving it results in significantly smaller files, and it can be re-computed when loading the instance.

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
  • SynthDiag (bool) – Flag indicating whether the pre-computed mesh for synthetic diagnostics calculations shall be saved too (can be heavy, if False, it will be re-computed when opening the saved object)
  • -
-
-
- -
-
-set_SigPrecomp(CalcPreComp=True, dX12=None, dX12Mode=None, ds=None, dsMode=None, MarginS=None, Colis=None)[source]
-

Precompute a 3D grid for fast integration of a 3D emissivity for a synthetic diagnostic approach

-

In order to accelerate the computation of synthetic signal from simulated emissivity, it is possible to pre-compute a discretisation of the VOS (mesh points + solid angle) and store it as an attribute of the Detect object. -While such pre-computation does speed-up significantly the numerical integration, it also burdens the object with heavy attributes that can make it too big to save. -Hence, the saving method has a special argument that allows to specify that these pre-computed attributes should not be saved but should instead be re-computed automatically when loading the file. -The parameters dX12, dX12Mode, ds and dsMode give the user control over how fine the discretization of the VOS should be, which affects both the accuracy of the numerical integration and the size of the resulting mesh.

- --- - - - -
Parameters:
    -
  • CalcPreComp (bool) – Flag indicating whether the pre-computation should be run
  • -
  • dX12 (list) – Array of the 2 resolutions to be used to define the grid in a plane perpendicular to the LOS
  • -
  • dX12Mode (str) – Flag specifying whether the values in dX12 are absolute distances or relative values (i.e. fraction of the total width [0;1])
  • -
  • ds (float) – Float indicating the resolution in the longitudinal direction
  • -
  • dsMode (str) – Flag specifying whether ds is an absolute distance or relative (i.e. fraction of the total length [0;1])
  • -
  • MarginS (float) – Float specifying
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
-
-
- -
- -
-
-class tofu.geom.GDetect(Id, LDetect, Type=None, Exp=None, Diag=None, shot=None, Sino_RefPt=None, LOSRef=None, arrayorder='C', Clock=False, dtime=None, dtimeIn=False, SavePath=None)[source]
-

An object grouping a list of Detect objects with some common features (e.g.: all belong to the same camera) and the same Ves object, provides methods for common computing and plotting

-

A GDetect object is a convenient tool for managing groups of detectors, applying common treatment, plotting... -It is typically suited for a camera (e.g.: a group of detectors sharing a common aperture)

- --- - - - -
Parameters:
    -
  • Id (str or tfpf.ID) – A name string or a pre-built tfpf.ID class to be used to identify this particular instance, if a string is provided, it is fed to ID
  • -
  • LDetect (list or Detect) – List of Detect instances with the same Ves instance
  • -
  • Type (None) – Not used in the current verion of tofu
  • -
  • Exp (None or str) – Experiment to which the Lens belongs, should be identical to Ves.Id.Exp if Ves is provided, if None and Ves is provided, Ves.Id.Exp is used
  • -
  • Diag (None or str) – Diagnostic to which the Lens belongs
  • -
  • shot (None or int) – Shot number from which this Lens is usable (in case its position was changed from a previous configuration)
  • -
  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value
  • -
  • Sino_RefPt (None or iterable) – If provided, forces the common Sino_RefPt to the provided value for all Detect instances
  • -
  • arrayorder (str) – Flag indicating whether the attributes of type=np.ndarray (e.g.: Poly) should be made C-contiguous (‘C’) or Fortran-contiguous (‘F’)
  • -
  • dtime (None or dtm.datetime) – A time reference to be used to identify this particular instance (used for debugging mostly)
  • -
  • dtimeIn (bool) – Flag indicating whether dtime should be included in the SaveName (used for debugging mostly)
  • -
-
-
-
-Id
-

the associated tfpf.ID object

-
- -
-
-LDetect
-

Return the list of Detect instances the GDetect object comprises

-
- -
-
-Optics
-

Return the list of optics the GDetect object comprises (either Lens or Apert)

-
- -
-
-Sino_RefPt
-

Return the coordinates (R,Z) or (Y,Z) for Ves of Type ‘Tor’ or (Y,Z) for Ves of Type ‘Lin’ of the reference point used to compute the sinogram

-
- -
-
-Ves
-

Return the Ves instance associated to the GDetect object

-
- -
-
-calc_SAngVect(Pts, In='(X, Y, Z)', Colis=True, Test=True)[source]
-

Applies calc_SAngVect() to all Detect instances

-

Return the result as two 2D arrays where the first dimension is the number of Detect instances -see calc_SAngVect() for details

-
- -
-
-calc_Sig(ff, extargs={}, Method='Vol', Mode='simps', PreComp=True, epsrel=0.0001, dX12=[0.005, 0.005], dX12Mode='abs', ds=0.005, dsMode='abs', MarginS=0.001, Colis=True, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Applies calc_Sig() to all Detect instances

-

See calc_Sig() for details -Arguments ind, Val, Crit, PreExp, PostExp, Log and InOut are fed to select()

-
- -
-
-get_GLOS(Name=None, LOSRef=None)[source]
-

Return the GLOS instance that can be built by grouping the LOS of each Detect instance

-

Can be useful for handling a GLOS instead of a GDetect (heavier) instance

- --- - - - - - -
Parameters:
    -
  • Name (None / str) – Name to be given to the GLOS instance, if None a name is built from the name of the GDetect object by appending ‘_GLOS’
  • -
  • LOSRef (None / str) – Key indicating which LOS to be used, if None the default LOSRef is used
  • -
-
Returns:

glos (GLOS) – The constructed GLOS instance

-
-
- -
-
-isInside(Points, In='(X, Y, Z)', Test=True)[source]
-

Return an array of indices indicating whether each point lies both in the cross-section and horizontal porojections of the viewing cone of each Detect

-

see isInside() for details

- --- - - - - - -
Parameters:
    -
  • Points (np.ndarray) – (2,N) or (3,N) array of coordinates of the N points to be tested
  • -
  • In (str) –
    -
    Flag indicating in which coordinate system the Points are provided, must be in [‘(R,Z)’,’(Y,Z)’,’(X,Y)’,’(X,Y,Z)’,’(R,phi,Z)’]
    -
      -
    • ‘(R,Z)’: All points are assumed to lie in the horizontal projection, for ‘Tor’ vessel type only
    • -
    • ‘(Y,Z)’: All points are assumed to lie in the horizontal projection, for ‘Lin’ vessel type only
    • -
    • ‘(X,Y)’: All points are assumed to lie in the cross-section projection
    • -
    -
    -
    -
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ind (np.ndarray) – (ND,N) array of booleans with True if a point lies inside both projections of the viewing cone, where ND is the number of Detect instances

-
-
- -
-
-nDetect
-

Return the number of Detect instances the GDetect object comprises

-
- -
-
-plot(Lax=None, Proj='All', Elt='PVC', EltLOS='LDIORP', EltOptics='P', EltVes='', Leg=None, LOSRef=None, Pdict={'lw': 2, 'c': 'k', 'ls': 'solid'}, Vdict={'color': 'r', 'lw': 2, 'ls': 'solid'}, Cdict={'edgecolors': 'k', 'antialiaseds': False, 'linestyles': '-', 'linewidths': 0.0, 'alpha': 0.2, 'facecolors': (0.8, 0.8, 0.8, 0.2)}, LVIn=0.1, LOSdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'EltVes': '', 'Proj': 'All', 'Test': True, 'Elt': 'LDIORP', 'MdictP': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictR': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Leg': '', 'Lplot': 'Tot', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'MdictI': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Ldict': {'lw': 2, 'c': 'k'}, 'MdictO': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictD': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}}, Opticsdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'Pdict': {'lw': 2, 'c': 'k', 'ls': 'solid'}, 'Vdict': {'color': 'r', 'lw': 2, 'ls': 'solid'}, 'EltVes': '', 'Leg': '', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'LVIn': 0.1, 'Test': True, 'Elt': 'PV', 'Proj': 'All'}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot all or a subset of the Detect instances in a projection or in 3D

-

See plot() for details -Arguments ind, Val, Crit, PreExp, PostExp, Log and InOut are fed to select()

- --- - - - - - -
Parameters:
    -
  • Lax (None, plt.Axes or list) – Axes or list of axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • Proj (str) – Flag indicating whether to plot the cross-section (‘Cross’), the horizontal projection (‘Hor’), both (‘All’) or a 3D representation (‘3D’)
  • -
  • Elt (str) –
    -
    Flag indicating which elements of the Detect instance to plot, each capital letter stands for an element
    -
      -
    • ‘P’: polygon
    • -
    • ‘V’: perpendicular vector
    • -
    • ‘C’: viewing cone
    • -
    -
    -
    -
  • -
  • EltLOS (None or str) – Flag indicating which elements of the LOS to plot, will be fed to LOS.plot(), if None uses the ‘Elt’ arg of LOSdict instead
  • -
  • EltOptics (None or str) – Flag indicating which elements of the Aperts to plot, will be fed to Apert.plot(), if None uses the ‘Elt’ arg of Apertdict instead
  • -
  • EltVes (None or str) – Flag indicating which elements of the Ves to plot, will be fed to plot(), if None uses the ‘Elt’ arg of Vesdict instead
  • -
  • Leg (str) – Legend to be used for the detector, if ‘’ the Detect.iD.Name is used
  • -
  • LOSRef (None or str) – Flag indicating which LOS should be represented, if None Detect._LOSRef is used
  • -
  • Pdict (dict) – Dictionary of properties for the Polygon
  • -
  • Vdict (dict) – Dictionary of properties for the Vector
  • -
  • Cdict (dict) – Dictionary of properties for the Cone
  • -
  • LVIn (float) – Length of the Vector
  • -
  • LOSdict (dict) – Dictionary of properties for the LOS if EltLOS is not ‘’, fed to LOS.plot()
  • -
  • Apertdict (dict) – Dictionary of properties for the Apert if EltOptics is not ‘’, fed to Apert.plot()
  • -
  • Vesdict (dict) – Dictionary of properties for the Ves if EltVes is not ‘’, fed to plot()
  • -
  • LegDict (dict) – Dictionary of properties for the legend, fed to plt.legend()
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the default figure should be of size a4 paper
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Lax plt.Axes or list – Axes or list of axes used for plotting

-
-
- -
-
-plot_Etend_AlongLOS(ax=None, NP=20, kMode='rel', Modes=['trapz'], RelErr=None, dX12=None, dX12Mode=None, Ratio=None, LOSRef=None, LOSPts=True, Ldict={'lw': 2, 'c': 'k', 'ls': 'solid'}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, Colis=True, draw=True, a4=True, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot the etendue of the selected LOS along it, with or without collision detection

-

The number of points along the LOS where the etendue is computed can be specified via arguments, as well as the numerical integration method. -See plot_Etendue_AlongLOS() for details -Arguments Length, NP, Modes, RelErr, dX12, dX12Mode, Ratio, Colis, LOSRef are fed to calc_Etendue_AlongLOS() -Arguments ind, Val, Crit, PreExp, PostExp, Log and InOut are fed to select()

- --- - - - - - -
Parameters:
    -
  • ax (None or plt.Axes) – Axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • NP (int) – Number of points along the LOS at which the Etendue should be computed
  • -
  • kMode (str) – Flag indicating whether the distance on the line should be plotted as abolute distance (‘abs’) or relative to the total length (‘rel’)
  • -
  • Modes (str or list) – Flag or list of flags indicating which integration method should be used
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
  • LOSRef (None or str) – Flag indicating which LOS should be used
  • -
  • Ldict (dict) – Dictionary of properties for plotting the result
  • -
  • LegDict (None / dict) – If None, no legend is plotted, else LegDict is fed to :meth:’~matplotlib.pyplot.Axes.legend’
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the created figure should have a4 dimensions (useful for printing)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used for plotting

-
-
- -
-
-plot_Etendues(Mode='Etend', Elt='', ax=None, Adict={'marker': '+', 'lw': 2, 'c': 'k', 'ls': 'None'}, Rdict={'marker': 'x', 'lw': 2, 'c': 'b', 'ls': 'None'}, Edict={'marker': 'o', 'lw': 2, 'c': 'g', 'ls': 'None'}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot the etendues of all or a subset of the Detect instances for the chosen LOS

-

A given Detect+Optics system has a VOS, under proper conditions, this VOS can be approximated by a LOS, but the choice of the LOS is not unique, there is an infinite number of possible LOS in a single VOS. -The LOS automatically computed by tofu os the ‘natural’ option : goes from the midlle of the Detect area throught the middle of the optics. -Then tofu automatically computes the associated etendue. -This methods plots all the etendues of all the chosen Detect instances for the chosen LOS, which is by default the ‘natural’ LOS computed by tofu

- --- - - - - - -
Parameters:
    -
  • Mode (str) – Flasg indicating whether to plot the etendue (‘Etend’) or a geometrical calibration factor (‘Calib’) computed as the 4pi/etendue
  • -
  • Elt (str) – Flag indicating whether to plot, in addition to the etendue, also the direct (‘A’) and reverse (‘R’) 0-order approximation of the etendue
  • -
  • ax (None or plt.Axes) – Axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • Adict (dict) – Dictionary of properties for plotting the direct 0-order approximation of the etendue (if ‘A’ in Elt), fed to plot()
  • -
  • Rdict (dict) – Dictionary of properties for plotting the reverse 0-order approximation of the etendue (if ‘R’ in Elt), fed to plot()
  • -
  • Edict (dict) – Dictionary of properties for plotting the etendue, fed to plot()
  • -
  • LegDict (dict) – If None, no legend is plotted, else LegDict is fed to :meth:’~matplotlib.pyplot.Axes.legend’
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the created figure should have a4 dimensions (useful for printing)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used for plotting

-
-
- -
-
-plot_SAngNb(Lax=None, Proj='Cross', Slice='Int', Pts=None, plotfunc='scatter', DRY=None, DXTheta=None, DZ=None, Elt='P', EltVes='P', EltLOS='', EltOptics='P', Pdict={'lw': 2, 'c': 'k', 'ls': 'solid'}, Vdict={'color': 'r', 'lw': 2, 'ls': 'solid'}, Cdict={'edgecolors': 'k', 'antialiaseds': False, 'linestyles': '-', 'linewidths': 0.0, 'alpha': 0.2, 'facecolors': (0.8, 0.8, 0.8, 0.2)}, LVIn=0.1, LOSdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'EltVes': '', 'Proj': 'All', 'Test': True, 'Elt': 'LDIORP', 'MdictP': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictR': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Leg': '', 'Lplot': 'Tot', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'MdictI': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'Ldict': {'lw': 2, 'c': 'k'}, 'MdictO': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, 'MdictD': {'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}}, Opticsdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'Pdict': {'lw': 2, 'c': 'k', 'ls': 'solid'}, 'Vdict': {'color': 'r', 'lw': 2, 'ls': 'solid'}, 'EltVes': '', 'Leg': '', 'Lax': None, 'Vesdict': {'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, 'LVIn': 0.1, 'Test': True, 'Elt': 'PV', 'Proj': 'All'}, Vesdict={'draw': True, 'LegDict': {'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, 'BsdictHor': {'c': 'b', 'ls': 'dashed'}, 'Bvdict': {'marker': 'x', 'mew': 2, 'c': 'g', 'markersize': 8, 'ls': 'dashed'}, 'Lim': [1.5707963267948966, 6.283185307179586], 'Test': True, 'Proj': 'All', 'IdictHor': {'c': 'k', 'ls': 'dashed'}, 'Elt': 'PIBsBvV', 'Pdict': None, 'Vdict': {'color': 'r', 'scale': 10}, 'Idict': {'marker': 'x', 'mew': 2, 'c': 'k', 'markersize': 8, 'ls': 'dashed'}, 'Bsdict': {'marker': 'x', 'mew': 2, 'c': 'b', 'markersize': 8, 'ls': 'dashed'}, 'Lax': None, 'BvdictHor': {'c': 'g', 'ls': 'dashed'}, 'Nstep': 50}, CDictSA=None, CDictNb=None, Colis=True, a4=False, draw=True, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot the solid angle projections (integrated ‘Int’ or maximum ‘Max’) as well as the number of detectors visible from each point in the plasma

-

See plot_SAngNb() for details -Arguments ind, Val, Crit, PreExp, PostExp, Log and InOut are fed to select()

- --- - - - - - -
Parameters:
    -
  • Lax (None or list or plt.Axes) – Axes or list of Axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • Proj (str) – Flag indicating whether to plot the cross-section (‘Cross’) or the horizontal projection (‘Hor’)
  • -
  • Mode (str, None or float) –
    -
    Flag indicating whether to plot:
    -
      -
    • ‘Int’: the integrated value along the projected coordinates
    • -
    • ‘Max’: the maximum value along the projected coordinates
    • -
    • float: the projected coordinate at which to plot the slice (Theta or X if Proj=’Cross’, Z if Proj=’Hor’)
    • -
    • None: the slice is done in the middle of the viewing volume
    • -
    -
    -
    -
  • -
  • plotfunc (str) – Flag indicating which plotting method to use (‘scatter’, ‘contour’, ‘contourf’ or ‘imshow’)
  • -
  • DCross (float) – Resolution along the 1st cross-section coordinate (R for Type=’Tor’, Y for Type=’Lin’)
  • -
  • DXTheta (float) – Resolution along the ignorable coordinate (Theta for Type=’Tor’, X for Type=’Lin’)
  • -
  • DZ (float) – Vertical resolution (for both Types)
  • -
  • CDictSA (dict) – Properties of the solid angle plot, to be fed to the function chosen by plotfunc
  • -
  • CDictNb (dict) – Properties of the Nb plot, to be fed to ...
  • -
  • Colis (bool) – Flag indicating whether collision detection should be used
  • -
  • a4 (bool) – Flag indicating whether to use a4 dimensions to create a new figure if Lax=None
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Lax plt.Axes or list List of the axes used for plotting

-
-
- -
-
-plot_Sig(ffSig, extargs={}, Method='Vol', Mode='simps', ax=None, Leg='', Sdict={'marker': '+', 'lw': 2, 'c': 'k', 'ls': 'solid'}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, draw=True, a4=False, Test=True, PreComp=True, epsrel=0.0001, dX12=[0.005, 0.005], dX12Mode='abs', ds=0.005, dsMode='abs', MarginS=0.001, Colis=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot the ignal computed for each or a subset of the Detect instances

-

If the signal is not directly provided as an array, it is computed from a function. -If ffSig is a callable function, arguments ffSig, extargs, Method, Mode, PreComp, epsrel, dX12, dX12Mode, ds, dsMode, MarginS, Colis and Test are fed to calc_Sig() -Arguments ind, Val, Crit, PreExp, PostExp, Log and InOut are fed to select()

- --- - - - - - -
Parameters:
    -
  • np.ndarray or callable (ffSig) – Either a np.ndarray containing the signal to be plotted (of shape (ND,) or (N,ND) where ND is the number of detectors to be plotted) or a callable to be fed to for computing the signal
  • -
  • ax (None or plt.Axes) – Axes to be used for plotting, if None a new figure and appropriate axes are created
  • -
  • Sdict (dict) – Dictionary of properties for plotting the signal, fed to plot()
  • -
  • Leg (str) – Label to be used for the plot
  • -
  • LegDict (dict) – If None, no legend is plotted, else LegDict is fed to :meth:’~matplotlib.pyplot.Axes.legend’
  • -
  • draw (bool) – Flag indicating whether to draw the figure
  • -
  • a4 (bool) – Flag indicating whether the created figure should have a4 dimensions (useful for printing)
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

ax (plt.Axes) – The axes used for plotting

-
-
- -
-
-plot_Sinogram(ax=None, Proj='Cross', Elt='DLV', Ang='theta', AngUnit='rad', Sketch=True, Ddict={'lw': 1, 'c': 'k', 'ls': 'solid'}, Ldict={'c': 'k', 'markersize': 8, 'lw': 2, 'mew': 2, 'ls': 'None', 'marker': 'x'}, Vdict={'edgecolor': (0.8, 0.8, 0.8, 1.0), 'linewidth': 1, 'linestyle': 'solid', 'facecolor': (0.8, 0.8, 0.8, 1.0)}, LegDict={'loc': 2, 'bbox_to_anchor': (1.01, 1), 'prop': {'size': 10}, 'ncol': 1, 'borderaxespad': 0.0, 'frameon': False}, LOSRef=None, draw=True, a4=False, Test=True, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]
-

Plot the VOS of all or of a subset of the Detect instances in projection space, optionally also the associated Ves object and reference LOS

-

See plot_Sinogram() for details -Arguments ind, Val, Crit, PreExp, PostExp, Log and InOut are fed to select()

-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False, SynthDiag=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save() -In the case of Detect and GDetect instances, there is an additional keyword argument ‘SynthDiag’ which allows to not save the pre-computed 3D mesh of the VOS for synthetic diagnostic. -Indeed, this pre-computed data is often large and results in big files. Not saving it results in significantly smaller files, and it can be re-computed when loading the instance.

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
  • SynthDiag (bool) – Flag indicating whether the pre-computed mesh for synthetic diagnostics calculations shall be saved too (can be heavy, if False, it will be re-computed when opening the saved object)
  • -
-
-
- -
-
-select(Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=<type 'bool'>)[source]
-

Return the indices or instances of all instances matching the specified criterion.

-

The selection can be done according to 2 different mechanism (1) and (2).

-

For mechanism (1): the user provides the value (Val) that the specified criterion (Crit) should take for a tofu.geom.Detect to be selected. -The criteria are typically attributes of the self.Id attribute (i.e.: name of the instance, or user-defined attributes like the camera head...)

-

For mechanism (2), used if Val=None: the user provides a str expression (or a list of such) to be fed to eval(), used to check on quantitative criteria, placed before the criterion value (e.g.: ‘not ‘ or ‘<=’). -Another str or list of str expressions can be provided that will be placed after the criterion value.

-

Other parameters are used to specify logical operators for the selection (match any or all the criterion...) and the type of output. -See select() for examples

- --- - - - - - -
Parameters:
    -
  • Crit (str) – Flag indicating which criterion to use for discrimination -Can be set to any attribute of the tofu.pathfile.ID class (e.g.: ‘Name’,’SaveName’,’SavePath’...) or any key of ID.USRdict (e.g.: ‘Exp’...)
  • -
  • Val (list, str or None) – The value to match for the chosen criterion, can be a list of different values -Used for selection mechanism (1)
  • -
  • PreExp (list, str or None) – A str of list of str expressions to be fed to eval(), used to check on quantitative criteria, placed before the criterion value (e.g.: ‘not ‘) -Used for selection mechanism (2)
  • -
  • PostExp (list, str or None) – A str of list of str expressions to be fed to eval(), used to check on quantitative criteria, placed after the criterion value (e.g.: ‘>=5.’) -Used for selection mechanism (2)
  • -
  • Log (str) – Flag indicating whether the criterion shall match all provided values or one of them (‘any’ or ‘all’)
  • -
  • InOut (str) – Flag indicating whether the returned indices are the ones matching the criterion (‘In’) or the ones not matching it (‘Out’)
  • -
  • Out (type / str) – Flag indicating in which form shall the result be returned, as an array of integer indices (int), an array of booleans (bool), a list of names (‘Names’) or a list of instances (‘Detect’)
  • -
-
Returns:

ind (list / np.ndarray) – The computed output (array of index, list of names or instances depending on parameter ‘Out’)

-
-
- -
-
-set_SigPrecomp(CalcPreComp=True, dX12=[0.005, 0.005], dX12Mode='abs', ds=0.005, dsMode='abs', MarginS=0.001, Colis=True)[source]
-

Applies set_SigPrecomp() to all Detect instances

-
- -
- +

The geometry module of tofu

+

Provides classes to model the 3D geometry of: +* the vacuum vessel and structural elements +* LOS +* apertures and detectors

1.1. Indices and tables

@@ -2168,7 +67,7 @@

1.1. Indices and tables \ No newline at end of file diff --git a/doc/build/html/Auto_tofu.pathfile.html b/doc/build/html/Auto_tofu.pathfile.html index 5d5bf47a8..ee71658ba 100644 --- a/doc/build/html/Auto_tofu.pathfile.html +++ b/doc/build/html/Auto_tofu.pathfile.html @@ -1,34 +1,24 @@ - + - - - 3. tofu.pathfile — tofu v1.1 - + + 3. tofu.pathfile — tofu v1.1 - + - - + + + + - - + @@ -57,334 +47,351 @@

Navigation

3. tofu.pathfile

Created on Wed Jul 30 14:37:31 2014

@author: didiervezinet

-
-
-tofu.pathfile.Find_Rootpath(Path='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/doc', substr='/tofu')[source]
-

Return the absolute path of the root directory of ToFu, searching for a pattern in the provided input path

- --- - - - - - -
Parameters:
    -
  • Path (str) – An absolute path in which a pattern is to be looked for
  • -
  • substr (str) – The pattern to look for
  • -
-
Returns:

root (str) – The absolute path containing the pattern

-
-
- -
-
-tofu.pathfile.get_DefaultPaths(RootPath=None, Plugin=None, lSubs=[], PathInp=None, PathObj=None, PathOut=None)[source]
-

Return the default paths for input loading, object and output saving depending on the root path used

-
- -
-
-tofu.pathfile.get_Default_dtimeFmt(dtime=None, dtFormat='D%Y%m%d_T%H%M%S')[source]
-

Return the default datetime value and format

-
- -
-
-tofu.pathfile.convert_units(P, In='cm', Out='m')[source]
-

Quickly convert distance units between meters, centimeters and millimeters

-
- -
-
-tofu.pathfile.get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2)[source]
-

Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units

-

Useful for tofu.plugins.AUG.Ves._create()

- --- - - - - - -
Parameters:
    -
  • PolyFileObj (str / tofu.geom object / np.ndarray) –
    -
    The source where the polygon is to be found, either:
    -
      -
    • str: the name of a file containing the coorindates of a polygon to be loaded with numpy.loadtxt()
    • -
    • A tofu.geom object: with attribute ‘Poly’
    • -
    • np.ndarray: an 2-dimensional array containing the 2D cartesian coordinates of a polygon
    • -
    -
    -
    -
  • -
  • SavePathInp (str / None) – The absolute path where the input file is stored
  • -
  • units (str) – Flag indicating in which units the polygon coordinates is expressed in the input file / object / array (will be converted to meters)
  • -
  • comments (str) – Parameter to be fed to numpy.loadtxt() if PolyFileObj is a file name
  • -
  • skiprows (int) – Parameter to be fed to numpy.loadtxt() if PolyFileObj is a file name
  • -
  • shape0 (int) – Specifies whether the loaded array is a (2,N) or (3,N) array (transposed it if necessary)
  • -
-
Returns:

    -
  • Poly (np.ndarray) – (2,N) np.ndarray containing the 2D cartesian coordinates of the polygon, where N is the number of points
  • -
  • addInfo (dict) – Dictionaryb containing information on the origin of the polygon, for the record (e.g.: the name and absolute path of the file from which it was extracted)
  • -
-

-
-
-
-class tofu.pathfile.ID(Cls, Name, Type=None, Deg=None, Exp=None, Diag=None, shot=None, SaveName=None, SavePath=None, USRdict=None, LObj=None, dtime=None, dtFormat='D%Y%m%d_T%H%M%S', dtimeIn=False)[source]
-

A class used by all ToFu objects as an attribute, storing all relevant data for the identification of created instances and providing default path and names for saving objects

-

Each detector created in ToFu should be identifiable thanks to user-friendly criteria, like its name, the diagnostic and experiment it is attached to, the shot number from from it was physically installed on the experiement... -Users can also freely add some information they consider relevant, such as some characteristics of the detector (size, manufacturer, date of last calibration...)

- --- - - - - - -
Parameters:
    -
  • Cls (str) –
    -
    Flag indicating which class is the object fro which the ID instance is being created, available class flags are:
    -
      -
    • From tofu.geom: ‘Ves’, ‘Struct’, ‘LOS’, ‘GLOS’, ‘Apert’, ‘Lens’, ‘Detect’ and ‘GDetect’
    • -
    • From tofu.mesh: ‘Mesh1D’, ‘Mesh2D’, ‘LBF1D’ and ‘LBF2D’ (to be finished)
    • -
    • From tofu.: (to be completed)
    • +class tofu.pathfile.ID(Cls=None, Name=None, Type=None, Deg=None, Exp=None, Diag=None, shot=None, SaveName=None, SavePath='/home/lasofivec/tofu/doc', USRdict={}, LObj=None, fromdict=None, Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'])[source] +

      A class used by all ToFu objects as an attribute

      +

      It stores all relevant data for the identification of instances +Stored info can be the name of the instance, the experiment and diagnostics +it belongs to, or other user-defined info +Also provides default names for saving the instances

      +
      +
      Parameters
      +
        +
      • Cls (str) – Class of the object on which info should be stored:

      • +
      • Name (str) – Name of the instance (user-defined) +Should be a str without space ‘ ‘ or underscore ‘_’ +(automatically removed if present)

      • +
      • Type (None / str) – Type of object (i.e.: ‘Tor’ or ‘Lin’ for a Ves)

      • +
      • Deg (None / int) – Degree of the b-splines constituting the tofu.mesh object

      • +
      • Exp (None / str) – Flag specifying the experiment (e.g.: ‘WEST’, ‘AUG’, ‘ITER’, ‘JET’…)

      • +
      • Diag (None / str) – Flag indicating the diagnostic (e.g.: ‘SXR’, ‘HXR’, ‘Bolo’…)

      • +
      • shot (None / int) – A shot number from which the instance is valid (for tracking changes)

      • +
      • SaveName (None / str) – Overrides the default file name for saving (not recommended)

      • +
      • SavePath (None / str) – Absolute path where the instance should be saved

      • +
      • USRdict (None / dict) – A user-defined dictionary containing information about the instance +All info considered relevant can be passed here +(e.g.: thickness of the diode, date of installation…)

      • +
      • LObj (None / dict / list) –

        +
        Either:
          +
        • list: list of other ID instances of objects on which the created object depends (this list will then be sorted by class and formatted into a dictionary storign key attributes)

        • +
        • dict: a ready-made such dictionary

        -
      • -
      • Name (str) – Name to be assigned to the created instance, should be a str without ‘ ‘ or ‘_’ (spaces and underscores will be automatically removed if present)
      • -
      • Type (None / str) – If provided (necessary for some objects, but not for all), specifies the Type of object (i.e.: ‘Tor’ or ‘Lin’ for a Ves instance)
      • -
      • Deg (None / int) – If provided (necessary only for objects of class ‘LBF1D’ and ‘LBF2D’), specifies the degree of the b-splines constituting the tofu.mesh object
      • -
      • Exp (None / str) – A short 3-4 letters max flag specifying the experiment to which the created instance belongs (e.g.: ‘AUG’, ‘ITER’, ‘TCV’, ‘JET’...)
      • -
      • Diag (None / str) – A short flag indicating which diagnostic the the created instance belongs to (e.g.: ‘SXR’, ‘HXR’, ‘Bolo’...)
      • -
      • shot (None / int) – A shot number from which the created instance can be considered valid (useful for tracking geometry changes in the case of Ves and Detect objects)
      • -
      • SaveName (None / str) – If provided, overrides the automatically generated name for saving the created instance (not recommended)
      • -
      • SavePath (None / str) – If provided, overrides the automatically generated path for saving the created instance
      • -
      • USRdict (None / dict) – If provided, a user-defined dictionary containing information about the instance considered relevant (e.g.: thickness of the diode, date of installation...)
      • -
      • LObj (None / dict / list) –
        -
        If provided, either
        -
          -
        • list: list of other ID instances of objects on which the created object depends (this list will then be sorted by class and formatted into a dictionary storign key attributes)
        • -
        • dict: a ready-made such dictionary
        • +

        -
      • -
      • dtime (None / dtm.datetime) – If provided, a time reference to be used to identify this particular instance (used for debugging mostly)
      • -
      • dtFormat (None / str) – If provided, the format in which dtime should be written in the automatically generated saving name for the created instance
      • -
      • dtimeIn (bool) – Flag indicating whether the dtm.datetime should be included in the automatically generated saving name for the created instance
      • -
      -
Returns:

Id ID instance – The created ID instance, with all necessary computed attributes and methods

-
-set_LObj(LObj=None)[source]
-

Set the LObj attribute to store the list of ID of other objects the created instance depends on

-

A Detect object depends on a vessel and some optics (e.g.: a list of apertures). -It is necessary that the link between the created Detect object and the already-existing Ves and Apert objects be stored somewhere, so that even after saving and closing the session, this correspondence can be retrieved and the Detect object can be re-loaded with links to the proper Ves and Apert objects, themselves beoing possibly saved elsewhere (so their respective SavePath must also be stored). -The LObj parameter does this: it stores all information necessary about each of the other objects the created instance depends on, mostly by storing their ID attributes as dictionaries.

- --- - - - -
Parameters:LObj (None / dict / list) –
-
If provided, either
-
    -
  • list: list of other ID instances of objects on which the created object depends (this list will then be sorted by class and formatted into a dictionary storign key attributes)
  • -
  • dict: a ready-made such dictionary
  • +set_LObj(LObj=None)[source] +

    Set the LObj attribute, storing objects the instance depends on

    +

    For example: +A Detect object depends on a vessel and some apertures +That link between should be stored somewhere (for saving/loading). +LObj does this: it stores the ID (as dict) of all objects depended on.

    +
    +
    Parameters
    +

    LObj (None / dict / ID / list of such) –

    +
    Provide either:
      +
    • A dict (derived from _todict())

    • +
    • A ID instance

    • +
    • A list of dict or ID instances

    -
+

+
+
-set_Name(Name, SaveName=None, dtimeIn=None)[source]
-

Set the Name of the created instance, automatically updating the SaveName

-

When the name is changed (reminding it should not include space (‘ ‘) or underscore (‘_’) characters), the name used for saving the object is automatically changed

- --- - - - -
Parameters:
    -
  • Name (str) – Name to be assigned to the created instance, should be a str without ‘ ‘ or ‘_’ (spaces and underscores will be automatically removed if present)
  • -
  • SaveName (None / str) – If provided, overrides the automatically generated name for saving the created instance (not recommended)
  • -
  • dtimeIn (None / bool) – If provided, modifies the value of dtimeIn provided upon creation of the ID object
  • +set_Name(Name, SaveName=None, Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], ForceUpdate=False)[source] +

    Set the Name of the instance, automatically updating the SaveName

    +

    The name should be a str without spaces or underscores (removed) +When the name is changed, if SaveName (i.e. the name used for saving) +was not user-defined, it is automatically updated

    +
    +
    Parameters
    +
      +
    • Name (str) – Name of the instance, without ‘ ‘ or ‘_’ (automatically removed)

    • +
    • SaveName (None / str) – If provided, overrides the default name for saving (not recommended)

    • +
    • Include (list) – Controls how te default SaveName is generated +Each element of the list is a key str indicating whether an element +should be present in the SaveName

    -
+
+
-set_SaveName(SaveName=None, dtimeIn=None)[source]
-

Enables either to automatically compute a ToFu-consistent saving name for the created instance, or to override that default saving name with the user-provided SaveName

-

When creating an object of any class, an ID object is assigned to it that automatically computes a saving name in case the user wants to save the object. -This automatically generated saving name includes not only the name given to the instance but also useful classifying info such as the class of the object, its Type, experiment, diagnostic... -It is not recommended to override this automatically generated saving name (because some routines rely on it for fast identification of saved files), but it is made possible for flexibility.

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – If provided, a str that overrides the automatically generated saving name
  • -
  • dtimeIn (None / bool) – If provided, modifies the value of dtimeIn provided upon creation of the ID object
  • +set_SaveName(SaveName=None, Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], ForceUpdate=False)[source] +

    Set the name for saving the instance (SaveName)

    +
    +
    SaveName can be either:
      +
    • provided by the user (no constraint) - not recommended

    • +
    • automatically generated from Name and key attributes (cf. Include)

    -
+
+
+
+
Parameters
+
+
+
-
-set_SavePath(SavePath=None)[source]
-

Enables to automatically generate a saving path for the created object, or to override that default path with the user-provided SavePath

-

Similarily to SaveName, ToFu automatically generates a saving path for any created object. -This saving path can be overriden if desired. -This is less crucial than SaveName, changing the SavePath has little consequences as long as you remember what you are doing.

- --- - - - -
Parameters:SavePath (None / str) – If provided, a str that overrides the automatically generated saving path
+
+set_USRdict(USRdict={})[source]
+

Set the USRdict, containing user-defined info about the instance

+

Useful for arbitrary info (e.g.: manufacturing date, material…)

+
+
Parameters
+

USRdict (dict) – A user-defined dictionary containing info about the instance

+
+
-
-
-set_USRdict(USRdict=None)[source]
-

Set the USRdict to enable the user to store arbitrary information about the instance created

-

It may sometimes be useful to store unforeseen arbitrary info about some objects created, like the manufacturing date of a diode, the material used for a filter... -The USRdict attribute is a user-defined dictionary for this purpose.

- --- - - - -
Parameters:USRdict (None / dict) – If provided, a user-defined dictionary containing information about the instance considered relevant (e.g.: thickness of the diode, date of installation...)
+
+
+tofu.pathfile.SaveName_Conv(Mod=None, Cls=None, Type=None, Name=None, Deg=None, Exp=None, Diag=None, shot=None, version=None, usr=None, Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'])[source]
+

Return a default name for saving the object

+

Includes key info for fast identification of the object from file name +Used on object creation by ID +It is recommended to use this default name.

-tofu.pathfile.CheckSameObj(obj0, obj1, LFields=None)[source]
-

Check two variable refer to the same instance of a ToFu class by checking some key attributes

-

Sometimes two different variables can refer to the same instance (for example if an object was created and assigned to obj0, then later saved and loaded and assigned to obj1). -Occasionally it may be useful to check whether two variables really represent the same instance, according to important criteria from the point of view of ToFu.

- --- - - - - - -
Parameters:
    -
  • obj0 (tofu object) – A variable refering to a ToFu object of any class
  • -
  • obj1 (tofu object) – A variable refering to a ToFu object of any class (but the same class as obj0)
  • -
  • LFields (None / str / list) –
    -
    The criteria against which the two objects are evaluated, if not None, must be str matching an attribute of the ID class or an attribute of the object class itself (or a list of such)
    -
      -
    • None: True is returned
    • -
    • str or list: tests whether the attributes have the same value or not and only returns True if all do
    • +tofu.pathfile.CheckSameObj(obj0, obj1, LFields=None)[source] +

      Check if two variables are the same instance of a ToFu class

      +

      Checks a list of attributes, provided by LField

      +
      +
      Parameters
      +
        +
      • obj0 (tofu object) – A variable refering to a ToFu object of any class

      • +
      • obj1 (tofu object) – A variable refering to a ToFu object of the same class as obj0

      • +
      • LFields (None / str / list) –

        +
        The criteria against which the two objects are evaluated:
          +
        • None: True is returned

        • +
        • str or list: tests whether all listed attributes have the same value

        -
      • +

        +
      +
      +
      Returns
      +

      A (bool) – True only is LField is None or a list of attributes that all match

      +
      +
      +
    + +
    +
    +tofu.pathfile.SelectFromListId(LId, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=<class 'bool'>)[source]
    +

    Return the indices or instances of all LOS matching criteria

    +

    The selection can be done according to 2 different mechanisms

    +

    Mechanism (1): provide the value (Val) a criterion (Crit) should match +The criteria are typically attributes of ID +(i.e.: name, or user-defined attributes like the camera head…)

    +

    Mechanism (2): (used if Val=None) +Provide a str expression (or a list of such) to be fed to eval() +Used to check on quantitative criteria.

    +
    +
      +
    • PreExp: placed before the criterion value (e.g.: ‘not ‘ or ‘<=’)

    • +
    • PostExp: placed after the criterion value

    • +
    • you can use both

    • +
    +
    +

    Other parameters are used to specify logical operators for the selection +(match any or all the criterion…) and the type of output.

    +
    +
    Parameters
    +
      +
    • Crit (str) –

      Flag indicating which criterion to use for discrimination +Can be set to:

      +
      +
        +
      • any attribute of ID +(e.g.: ‘Name’,’SaveName’,’SavePath’…)

      • +
      • any key of ID.USRdict (e.g.: ‘Exp’…)

      • +
      +
      +

    • +
    • Val (None / list / str) – The value to match for the chosen criterion, can be a list +Used for selection mechanism (1)

    • +
    • PreExp (None / list / str) – A str (or list of such) expression to be fed to eval(), +Placed before the criterion value +Used for selection mechanism (2)

    • +
    • PostExp (None / list / str) – A str (or list of such) expression to be fed to eval() +Placed after the criterion value +Used for selection mechanism (2)

    • +
    • Log (str) –

      +
      Flag indicating whether the criterion shall match:
        +
      • ’all’: all provided values

      • +
      • ’any’: at least one of them

      • +
      +
      +
      +

    • +
    • InOut (str) –

      +
      Flag indicating whether the returned indices are:
        +
      • ’In’: the ones matching the criterion

      • +
      • ’Out’: the ones not matching it

      • +
      +
      +
      +

    • +
    • Out (type / str) –

      +
      Flag indicating in which form to return the result:
        +
      • int: as an array of integer indices

      • +
      • bool: as an array of boolean indices

      • +
      • ’Name’: as a list of names

      • +
      • ’LOS’: as a list of LOS instances

      • +
      +
      +
      +

    -
Returns:

A (bool)

-
+
+
Returns
+

ind (list / np.ndarray) – The computed output, of nature defined by parameter Out

+
+
+ + +
+
+tofu.pathfile.convert_units(P, In='cm', Out='m')[source]
+

Quickly convert distance units between meters, centimeters and millimeters

+
+ +
+
+tofu.pathfile.get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2)[source]
+

Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units

+

Useful for tofu.plugins.AUG.Ves._create()

+
+
Parameters
+
    +
  • PolyFileObj (str / tofu.geom object / np.ndarray) –

    +
    The source where the polygon is to be found, either:
      +
    • str: the name of a file containing the coorindates of a polygon to be loaded with numpy.loadtxt()

    • +
    • A tofu.geom object: with attribute ‘Poly’

    • +
    • np.ndarray: an 2-dimensional array containing the 2D cartesian coordinates of a polygon

    • +
    +
    +
    +

  • +
  • SavePathInp (str / None) – The absolute path where the input file is stored

  • +
  • units (str) – Flag indicating in which units the polygon coordinates is expressed in the input file / object / array (will be converted to meters)

  • +
  • comments (str) – Parameter to be fed to numpy.loadtxt() if PolyFileObj is a file name

  • +
  • skiprows (int) – Parameter to be fed to numpy.loadtxt() if PolyFileObj is a file name

  • +
  • shape0 (int) – Specifies whether the loaded array is a (2,N) or (3,N) array (transposed it if necessary)

  • +
+
+
Returns
+

    +
  • Poly (np.ndarray) – (2,N) np.ndarray containing the 2D cartesian coordinates of the polygon, where N is the number of points

  • +
  • addInfo (dict) – Dictionaryb containing information on the origin of the polygon, for the record (e.g.: the name and absolute path of the file from which it was extracted)

  • +
+

+
+
-tofu.pathfile.Save_Generic(obj, SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save a ToFu object under file name SaveName, in folder Path, using specified mode

+tofu.pathfile.Save_Generic(obj, SaveName=None, Path='./', Mode='npz', compressed=False, Print=True)[source] +

Save a ToFu object under file name SaveName, in folder Path

ToFu provides built-in saving and loading functions for ToFu objects. -They can be saved at their default SavePath under their default SaveName or user-defined values can be forced if necessary. -Saving can be done in two ways :

+There is now only one saving mode:

    -
  • by direct object saving using cPickle (straightforward but heavy)
  • -
  • by mapping the key object attributes to a dictionary and using numpy.savez_compressed() (faster and lighter, recommended)
  • +
  • ‘npz’: saves a dict of key attributes using numpy.savez()

-

ToFu now automatically saves information on smaller objects on which the object of interest depends (like apertures for detectors), so that all info is stored in a single file. -In particular, provided the Ves object is saved separately, a whole camera can be saved in a single file (i.e.: all detectors and apertures).

- --- - - - -
Parameters:
    -
  • SaveName (str) – The name to be used to for the saved file, if None (recommended) uses obj.Id.SaveName
  • -
  • Path (str) – Path specifying where to save the file, if None (recommended) uses obj.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, may cause retro-compatibility issues with later versions)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • +
    +
    Good practices are:
      +
    • save Ves and Struct

    • +
    • intermediate optics (Apert and +Lens) generally do not need to be saved +Indeed, they will be autoamtically included in larger objects +like Detect or Cam objects

    • +
    +
    +
    +
    +
    Parameters
    +
      +
    • SaveName (str) – The file name, if None (recommended) uses obj.Id.SaveName

    • +
    • Path (str) – Path where to save the file

    • +
    • Mode (str) –

      +
      Flag specifying the saving mode
        +
      • ’npz’: Only mode currently available (‘pck’ deprecated)

      • +
      +
      +
      +

    • +
    • compressed (bool) – Indicate whether to use np.savez_compressed (slower but smaller files)

    -
+
+
-tofu.pathfile.Open(pathfileext=None, shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None, Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None, out='full', Verb=False)[source]
+tofu.pathfile.Open(pathfileext=None, shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None, Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None, out='full', Verb=False, Print=True)[source]

Open a ToFu object saved file

This generic open function identifies the required loading routine by detecting how the object was saved from the file name extension. -Also, it uses FindSolFile() to identify the relevant file in case key criteria such as shot, Deg... are provided instead of the file name itself. -Finally, once all the relevant data is loaded from the file, a ToFu object is re-created, if necessary by implicitly loading all other objects it may depend on (i.e.: vessel, apertures...)

-

If pathfileext is not provided (None), then the following keyword arguments are fed to FindSolFile(): shot, t, Dt, Mesh, Deg, Deriv, Sep, Pos

- --- - - - - - -
Parameters:
    -
  • pathfileext (None / str) – If provided, the name of the file to load
  • -
  • OutPath (None / str) – If provided, the absolute path where the file is to be found
  • -
  • ReplacePath (str) – If provided, ? (to finish)
  • -
  • Ves (None /) – If provided, the tofu.geom.Ves object that shall be used to reconstruct the object (if not provided, the appropriate vessel will be loaded).
  • -
  • out (str) – Flag indicating whether the object should be loaded completely (‘full’), in a light dismissing the heaviest attributes (‘light’) or whether only the Id or a list of Id should be returned (‘Id’), valid only for ‘.npz’
  • -
  • Verb (bool) – Flag indicating whether to pring intermediate comments on the loading procedure
  • +Also, it uses FindSolFile() to identify the relevant file in case key criteria such as shot, Deg… are provided instead of the file name itself. +Finally, once all the relevant data is loaded from the file, a ToFu object is re-created, if necessary by implicitly loading all other objects it may depend on (i.e.: vessel, apertures…)

    +

    If pathfileext is not provided (None), then the following keyword arguments are fed to FindSolFile(): shot, t, Dt, Mesh, Deg, Deriv, Sep, Pos

    +
    +
    Parameters
    +
      +
    • pathfileext (None / str) – If provided, the name of the file to load

    • +
    • OutPath (None / str) – If provided, the absolute path where the file is to be found

    • +
    • ReplacePath (str) – If provided, ? (to finish)

    • +
    • Ves (None /) – If provided, the tofu.geom.Ves object that shall be used to reconstruct the object (if not provided, the appropriate vessel will be loaded).

    • +
    • out (str) – Flag indicating whether the object should be loaded completely (‘full’), in a light dismissing the heaviest attributes (‘light’) or whether only the Id or a list of Id should be returned (‘Id’), valid only for ‘.npz’

    • +
    • Verb (bool) – Flag indicating whether to pring intermediate comments on the loading procedure

    -
Returns:

obj ToFu object – The loaded and re-created ToFu object

-
+
+
Returns
+

obj ToFu object – The loaded and re-created ToFu object

+
+

3.1. Indices and tables

@@ -395,7 +402,7 @@

3.1. Indices and tables \ No newline at end of file diff --git a/doc/build/html/Auto_tofu.plugins.AUG.html b/doc/build/html/Auto_tofu.plugins.AUG.html index e91553873..15c4dcaef 100644 --- a/doc/build/html/Auto_tofu.plugins.AUG.html +++ b/doc/build/html/Auto_tofu.plugins.AUG.html @@ -1,35 +1,24 @@ - + - - - 4.1.1. AUG — tofu v1.1 - + + 4.1.1. AUG — tofu v1.1 - + - - - + + + + - - + @@ -57,155 +46,22 @@

Navigation

4.1.1. AUG

-
-

4.1.1.1. AUG.Ves

-

Contains all functions specific to the AUG vessel (creating the Ves object from Inputs, loading pre-created Ves objects...)

-
-
-tofu.plugins.AUG.Ves.load(Name='V1', SavePathObj=None, Root='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu', Test=True)[source]
-

Load and return the selected Ves object (selected by name or file name)

-

Several Ves object might exist for the same experiment depending changes to the experiment in time for example -This function loads the one specified by its name.

- --- - - - - - -
Parameters:
    -
  • Name (str / list) – Name of the file to be loaded, or a subset of this name or a list of subsets, the file with a name matching all the subsets will be loaded. An error is issued in case of ambiguity
  • -
  • SavePathObj (str) – Absolute path where the objects can be found, if None sets to default
  • -
  • Root (str) – If SavePathObj=None, a default value is created by appending ‘/tofu/plugins/AUG/Ves/Objects/’ to Root
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Ves (tofu.geom.Ves) – The loaded Ves object

-
-
- +
+

4.1.1.1. AUG.Ves

-
-

4.1.1.2. AUG.SXR.geom

-
-
-tofu.plugins.AUG.SXR.geom.create(shot=0, VesName='V1', SavePathObj=None, Root='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu', forceshot=False, overwrite=False, save=True, dtime=None, dtFormat='D%Y%m%d_T%H%M%S', CalcEtend=True, CalcSpanImp=True, CalcCone=True, CalcPreComp=True, Calc=True, Verb=True, Etend_Method='quad', Etend_RelErr=0.001, Etend_dX12=[0.01, 0.01], Etend_dX12Mode='rel', Etend_Ratio=0.02, Colis=True, LOSRef='Cart', Cone_DRY=0.0025, Cone_DXTheta=0.0030679615757712823, Cone_DZ=0.0025, Cone_NPsi=20, Cone_Nk=60)[source]
-

Create, save and return all the GDetect objects relevant for the input shot, unless already created for a relevant reference shot

-

Create the tofu.geom.GDetect objects (i.e.: the cameras, which are groups of detectors) from geometry taken from CSX disgnostic for the proposed shot or earlier (looks for the oldest version of the matching geometry) and stores them in the SavePathObj.

-

All extra arguments are fed to Detect

- --- - - - - - -
Parameters:
    -
  • shot (int) – Shot number for which to build the geometry
  • -
  • VesName (str) – Name of the tfg.Ves object to be fed as an input to the tofu.geom.GDetect objects
  • -
  • SavePathObj (None / str) – Absolute path where the created tofu.geom.GDetect objects should be saved (if save=True), if None the default is used
  • -
  • Root (str) – If SavePathObj=None, a default value is created by appending ‘/tofu/plugins/AUG/SXR/geom/Objects/’ to Root
  • -
  • forceshot (bool) – Flag indicating whether the shot number shall be downgraded to the oldest shot with the same geometry (False) or whether the provided shot number shall be enforced (True, for all camera heads)
  • -
  • overwrite (bool) – Flag indicating whether new tofu.geom.GDetect objects shall be computed (and possibly saved) when similar ones already exist (True)
  • -
  • save (bool) – Flag indicating whether to save the created tofu.geom.GDetect objects (in SavePathObj)
  • -
  • dtime (None / dtm.datetime) – If provided (i.e.: not None), used as a label of the created tofu.geom.GDetect objects (mostly used for debugging)
  • -
  • dtFormat (str) – The time format to be used for labelling the created tofu.geom.GDetect objects (mostly used for debugging)
  • -
-
Returns:

LGD (list) – A list of all the created tfg.GDetect objects

-
-
- -
-
-tofu.plugins.AUG.SXR.geom.load(Cams=None, shot=None, SavePathObj=None, Root='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu', sort=False, out='full', Test=True)[source]
-

Load and return the desired GDetect objects (i.e.: camera heads)

-

Directly fecthes and loads the desired GDetect objects.

- --- - - - -
Parameters:
    -
  • Cams (str / list) – A name or a list of names of the camera heads to be loaded (available are [‘F’,’G’,’H1’,’H2’,’H3’,’I1’,’I2’,’I3’,’J1’,’J2’,’J3’,’K1’,’K2’,’L’,’M’])
  • -
  • shot (int / float / np.float) – A shot number indicating which version of the geometry should be loaded (the )
  • -
  • SavePathObj (None / str) – Absolute path where the created tofu.geom.GDetect objects should be saved (if save=True), if None the default is used
  • -
  • Root (str) – If SavePathObj=None, a default value is created by appending ‘/tofu/plugins/AUG/SXR/geom/Objects/’ to Root
  • -
  • sort (bool) – Flag indicating whether the loaded tofu.geom.GDetect objects shall be returned sorted by alphabetical order of the names (True) or in the same order as asked in Cams (False)
  • -
  • out (str) – Flag indicating whether the object should be loaded completely (‘full’), in a light dismissing the heaviest attributes (‘light’) or whether only the Id or a list of Id should be returned (‘Id’), valid only for ‘.npz’
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
  • Returns
  • -
  • --------
  • -
  • LGD (list / tofu.geom.GDetect) – The loaded tofu.geom.GDetect, returned as a single object if Cams was provided as a single name, as a list otherwise
  • -
-
-
- +
+

4.1.1.2. AUG.SXR.geom

-
-

4.1.1.3. AUG.SXR.data

-
-
-tofu.plugins.AUG.SXR.data.load(shot=None, Names=None, Mode='SSX', Dt=None, Join=True, tRef='fmin', Method='interp', NoGeom=True, Tofu=True, Verb=True, Test=True)[source]
-

Load SXR data from the AUG database and returns it either as numpy arrays or a ToFu-compatible object with appropriate methods

-

Part of the difficulty is that all channels do not have the same sampling frequency and time vector. -Hence, there is an option to uniformize the time base.

- --- - - - - - -
Parameters:
    -
  • shot (int) – Shot number for which the SXR data should be loaded
  • -
  • Names (None / str / list) – If provided, data is loaded only for the specified channel(s)
  • -
  • Mode (str) – Flag indicating whether data should be loaded from a down-sampled database (‘SSX’, , faster loading) or from the complete database ( depending on the channel)
  • -
  • Dt (None / iterable) – If provided, a len()=2 iterable giving the time interval of interest (recommended to avoid very large data files)
  • -
  • Join (bool) – Flag, useful when Mode=’SX’, indicating whether the different time bases of the channels shall be uniformized
  • -
  • tRef (None / str / np.ndarray) –
    -
    Flag or time vector, useful when Mode=’SX’ and Join=True, indicating which time basis should be used as a reference
    -
      -
    • ‘fmin’: the time vector of the channel presenting the smallest sampling frequency is used as a reference
    • -
    • ‘fmax’: the time vector of the channel presenting the highest sampling frequency is used as a reference
    • -
    • any channel name: the time vector of the specifiec channel is used as a reference
    • -
    • np.ndarray: the provided time vector is used as a reference
    • -
    -
    -
    -
  • -
  • Method (str) – Flag, usefule when Mode=’SX’ and Join=True, indicating how the
  • -
  • NoGeom (bool) –
    -
    Flag indicating whether the data should be stripped of its geometrical calibration factor (thus being expressed in W instead of W/m2), to allow for:
    -
      -
    • Application of a tofu-computed etendue in case of a LOS approach
    • -
    • Direct use of the signal in case of a VOS approach
    • -
    -
    -
    -
  • -
  • Tofu (bool) – Flag indicating whether the loaded data should be returned as (SXR, t, Names) where the first two are np.ndarrays and Names is a list or as a tofu.data.PreData object
  • -
  • Verb (bool) – Flag indicating whether extra comments should be printed to give feedback on the progress of the routine
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

out (tuple / tofu.data.PreData)

-
-
- +
+

4.1.1.3. AUG.SXR.data

@@ -216,12 +72,12 @@

4.1.1.4. Indices and tables \ No newline at end of file diff --git a/doc/build/html/Auto_tofu.plugins.ITER.html b/doc/build/html/Auto_tofu.plugins.ITER.html index bd7679e90..8acc57b2a 100644 --- a/doc/build/html/Auto_tofu.plugins.ITER.html +++ b/doc/build/html/Auto_tofu.plugins.ITER.html @@ -1,34 +1,23 @@ - + - - - 4.1.2. ITER — tofu v1.1 - + + 4.1.2. ITER — tofu v1.1 - + - - - + + + + - - + @@ -53,267 +42,22 @@

Navigation

4.1.2. ITER

-
-

4.1.2.1. ITER.Ves

-

Contains all functions specific to the AUG vessel (creating the Ves object from Inputs, loading pre-created Ves objects...)

-

Created on Wed May 18 2016

-

@version: 0.9 -@author: didiervezinet -@author_email: didier.vezinet@gmail.com

-
-
-tofu.plugins.ITER.Ves.create(Name='ITER_D_2N9J75 v1.7-1', Poly=['PoloidalCurvesCoordinates', 'ITER', '2N9J75', 'csv'], shot=0, SavePathInp=None, SavePathObj=None, Root='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu', save=True, skiprows=4, comments='#', units='mm', dtime=None, dtFormat='D%Y%m%d_T%H%M%S', dtimeIn=False, Test=True)[source]
-

Create and save a Ves object from givn input file or Ves object

-

A Ves object can be created from an input file, a np.ndarray or another Ves object

- --- - - - - - -
Parameters:
    -
  • Name (str) – The name to be given to the created Ves instance
  • -
  • Poly (None / str / tofu.geom.Ves / np.ndarray) –
    -
    The source where the polygon is to be found, either:
    -
      -
    • str: the name of a file containing the coordinates of a polygon to be loaded with numpy.loadtxt()
    • -
    • A tofu.geom.Ves object: to re-use its Poly attribute and build one with different name
    • -
    • np.ndarray: an 2-dimensional array containing the 2D cartesian coordinates of a polygon
    • -
    -
    -
    -
  • -
  • shot (int) – A shot number, to be used as a reference point in time, marking from when the provided geometry is valid
  • -
  • SavePathInp (None / str) – If provided, forces the routine to search for the input file at SavePathInp, if not provided SavePathInp is automatically set to default (i.e. tofu/plugin/Ves/Inputs/)
  • -
  • SavePathObj (None / str) – If provided, forces the routine to save the created instance at SavePathObj, if not provided SavePathObj is automatically set to default (i.e. tofu/plugin/Ves/Objects/)
  • -
  • Root (str) – If SavePathObj=None, a default value is created by appending ‘/tofu/plugins/ITER/Ves/Objects/’ to Root
  • -
  • save (bool) – Flag indicating whether the created Ves instance shall be saved automatically (in SavePathObj)
  • -
  • skiprows (int) – Parameter fed to np.loadtxt() for reading the polygon from a txt file
  • -
  • comments (str) – Parameter fed to np.loadtxt() for reading the polygon from a txt file
  • -
  • units (str) – Flag indicating in which units the input polygon is provided (in [‘m’,’cm’,’mm’])
  • -
  • dtime (None / dtm.datetime) – A datetime instance used for labelling the created instance (mostly used for debugging)
  • -
  • dtFormat (str) – The format of the labelling (mostly used for debugging)
  • -
  • dtimeIn (bool) – Flag indicating whether to include the label in the file name (mostly used for debugging)
  • -
  • Test (bool) – Flag indicating whether the inpurts should be checked for conformity
  • -
-
Returns:

Ves (tofu.geom.Ves) – The created tfg.Ves instance

-
-
- -
-
-tofu.plugins.ITER.Ves.load(Name=None, SavePathObj=None, Root='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu', Test=True)[source]
-

Load and return the selected Ves object (selected by name or file name)

-

Several Ves object might exist for the same experiment depending changes to the experiment in time for example -This function loads the one specified by its name.

- --- - - - - - -
Parameters:
    -
  • Name (str / list) – Name of the file to be loaded, or a subset of this name or a list of subsets, the file with a name matching all the subsets will be loaded. An error is issued in case of ambiguity (no or several matches)
  • -
  • SavePathObj (None / str) – Absolute path where the objects can be found, if None sets to default
  • -
  • Root (str) – If SavePathObj=None, a default value is created by appending ‘/tofu/plugins/AUG/Ves/Objects/’ to Root
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Ves (tofu.geom.Ves) – The loaded Ves object

-
-
- +
+

4.1.2.1. ITER.Ves

-
-

4.1.2.2. ITER.Struct

-

Contains all functions specific to the ITER structural elements

-
-
-tofu.plugins.ITER.Struct.plot(Elt='BPV', EltStruct='P', EltVes='P', Lax=None, Proj='Cross', shot=0, SavePathInp='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/tofu/plugins/ITER/Struct/Inputs/', SavePathObj='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/tofu/plugins/ITER/Struct/Objects/', Ves=None, NameVes=None, SavePathVes=None, skiprows=0, comments='#', units='mm', dtime=None, dtFormat='D%Y%m%d_T%H%M%S', dtimeIn=False, Test=True)[source]
-

Create and plot the required Struct object on the required axes

-

The coordinates of the polygons of the Struct objects are taken from SavePathInp

- --- - - - - - -
Parameters:
    -
  • Elt (str) –
    -
    Flag indicating which elements to plot, one capital letter per element
    -
      -
    • ‘B’ : the Beams
    • -
    • ‘P’ : the ports
    • -
    • ‘V’ : the associated Ves object
    • -
    -
    -
    -
  • -
  • Lax (None / plt.Axes / list) – If provided, the axes or list of axes on which the poloidal and / or horizontal projections of the structure elements shall be plotted
  • -
  • shot (int) – A shot number, to be used as a reference point in time, marking from when the provided geometry is valid
  • -
  • SavePathInp (None / str) – If provided, forces the routine to search for the input file at SavePathInp, if not provided SavePathInp is automatically set to default (i.e. tofu/plugin/Ves/Inputs/)
  • -
  • SavePathObj (None / str) – (optional) Absolute path where the created object will be saved
  • -
  • Ves (None / tofu.geom.Ves) – If provided, associates the Struct objects with this Ves object, otherwise a default Ves is loaded from SavePathVes if provided
  • -
  • NameVes (str) – Use if Ves is not provided, fed to tofu.plugins.ITER.Ves.load() for loading a default Ves
  • -
  • SavePathVes (None / str) – If provided, path from which a default Ves object can be loaded
  • -
  • skiprows (int) – Parameter fed to np.loadtxt() for reading the polygon from a txt file
  • -
  • comments (str) – Parameter fed to np.loadtxt() for reading the polygon from a txt file
  • -
  • units (str) – Flag indicating in which units the input polygon is provided (in [‘m’,’cm’,’mm’])
  • -
  • dtime (None / dtm.datetime) – A datetime instance used for labelling the created instance (mostly used for debugging)
  • -
  • dtFormat (str) – The format of the labelling (mostly used for debugging)
  • -
  • dtimeIn (bool) – Flag indicating whether to include the label in the file name (mostly used for debugging)
  • -
  • Test (bool) – Flag indicating whether the inpurts should be checked for conformity
  • -
-
Returns:

LS (list) – The list of all created tofu.geom.Struct instances

-
-
- +
+

4.1.2.2. ITER.Struct

-
-

4.1.2.3. ITER.Bolo.geom

-
-
-tofu.plugins.ITER.Bolo.geom.create_Apert(Name, Ves, Poly, shot=0, SavePathVes='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Objects_ITER/', SavePathObj='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Objects_ITER/', SavePathInp='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Inputs_ITER/', comments='#', skiprows=0, units='m', save=True)[source]
-

Create a Apert object (i.e.: aperture) with specified Name from either a file (.dat,.txt,.csv) or directly from a (2,N) or (N,2) numpy array -Object is created, Saved in SavePathObj and returned -If an input file is specified and the file name does not include an absolute path, the path specified in SavePathInp is used

- --- - - - - - -
Parameters:
    -
  • Name (str) – Name of the object to be created
  • -
  • Ves (str / tofu.geom.Ves) – Ves object to which the aperture is associated, a file name can also be used if the Ves object was previously Saved
  • -
  • Poly (str / np.ndarray) – Numpy array or input file name (fed to numpy.loadtxt) used to specify the polygon to be used (should be (2,N) or (N,2) for N points)
  • -
  • shot (int) – Shot number from which the provided geometry is valid (useful for geometry changes bewteen campaigns)
  • -
  • SavePathVes (None / str) – (optional) if Ves is a str (i.e.: file name) or a list (i.e.: list of strings contained in the file name), specifies the path at which the file is to be found
  • -
  • SavePathObj (None / str) – (optional) Absolute path where the created object will be saved
  • -
  • SavePathInp (None / str) – (optional) Absolute path where the input file is to be found
  • -
  • comments (str) – (optional) str specifying the flag for comments in the Poly file (if Poly is a file name), fed to numpy.loadtxt
  • -
  • skiprows (int) – (optional) number of rows to be skipped in the Poly file (if Poly is a file name), fed to numpy.loadtxt
  • -
  • units (str) – Flag indicating in which units the input polygon is provided (in [‘m’,’cm’,’mm’])
  • -
  • save (bool) – (optional) Flag indicating whether the created object should be Saved
  • -
  • Test (bool) – Flag indicating whether the inputs should be tested for conformity
  • -
-
Returns:

Apert (tofu.geom.Apert) – The created Apert object

-
-
- -
-
-tofu.plugins.ITER.Bolo.geom.create_Detect(Name, Ves, Poly, LApert, shot=0, SavePathVes='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Objects_ITER/', SavePathObj='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Objects_ITER/', SavePathInp='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Inputs_ITER/', comments='#', skiprows=0, Cone_DRY=0.0025, Cone_DXTheta=0.0030679615757712823, Cone_DZ=0.0025, Cone_NPsi=20, Cone_Nk=60, Synth_dX12=[0.005, 0.005], Synth_dX12Mode='abs', Synth_ds=0.005, Synth_dsMode='abs', Synth_Colis=True, Calc=True, CalcEtend=True, CalcSpanImp=True, CalcCone=True, CalcPreComp=True, save=True, save_SynthDiag=False)[source]
-

Create a tofu.geom.Detect object (i.e.: detector) with specified Name from either a file (.dat,.txt,.csv) or directly from a (2,N) or (N,2) numpy array -Object is created, optionally Saved in SavePathObj and returned -If an input file is specified and the file name does not include an absolute path, the path specified in SavePathInp is used

- --- - - - - - -
Parameters:
    -
  • Name (str) – Name of the object to be created
  • -
  • Ves (tofu.geom.Ves or str) – Ves object to which the aperture is associated, a file name can also be used if the Ves object was previously Saved
  • -
  • Poly (str or np.ndarray) – Numpy array or input file name (fed to numpy.loadtxt) used to specify the polygon to be used (should be (2,N) or (N,2) for N points)
  • -
  • LApert (list) – List of Apert objects to be associated to the detector
  • -
  • SavePathVes (None / str) – (optional) if Ves is a str (i.e.: file name) or a list (i.e.: list of strings contained in the file name), specifies the path at which the file is to be found
  • -
  • SavePathObj (str) – (optional) Absolute path where the created object will be Saved
  • -
  • SavePathInp (str) – (optional) Absolute path where the input file is to be found
  • -
  • comments (str) – (optional) str specifying the flag for comments in the Poly file (if Poly is a file name), fed to numpy.loadtxt
  • -
  • skiprows (int) – (optional) number of rows to be skipped in the Poly file (if Poly is a file name), fed to numpy.loadtxt
  • -
  • save (bool) – (optional) Flag indicating whether the created object should be Saved
  • -
  • save_SynthDiag (bool) – (optional) Flag indicating whether the pre-computed synthetic diagnostic mesh should also be saved (larger files) or whether it should be recomputed upon loading
  • -
  • compute the VOS, tofu tests all points inside a 3D grid to see if each point is visible from the detector through the apertures or not (To) –
  • -
  • Cone_DR (float) – Resolution of the grid in the R direction, in meters
  • -
  • Cone_DTheta (float) – Resolution of the grid in the toroidal direction, in radians
  • -
  • Cone_DZ (float) – Resolution of the grid in the Z direction, in meters
  • -
  • the particular case when the LOS of the detector lies entirely inside one poloidal cross-section (e.g. (In) –
  • -
  • also computes the integral in the toroidal direction of the solid angle on a regular mesh (for faster computation of the geometry assuming toroidaly invariant basis functions) (tofu) –
  • -
  • regular mesh is defined in 2D, by the distance between a mesh point and the detector (k) and by the poloidal angle between the LOS and the line going from the detector to the mesh point (psi) (This) –
  • -
  • Cone_NPsi (20) – Number of points of the regular mesh in psi direction (angle)
  • -
  • Cone_Nk (60) – Number of points of the regular mesh in k direction (distance)
  • -
  • compute synthetic signal faster for any simulated emissivity, tofu can pre-compute a 3D mesh of the VOS and store it, with the associates solid angles (To) –
  • -
  • 3D mesh is computed with respect to the LOS. One coordinate (s) is the distance along the LOS, the two others (1 and 2) are the distances in directions perpendicular to the LOS (This) –
  • -
  • Synth_dX12 (list) – Resolution of the mesh in the two directions perpendicular to the LOS
  • -
  • Synth_dX12Mode (str) – Flag indicating whether dX12 is an absolute value (‘abs’, in meters) or a fraction of the maximum local with of the VOS (‘rel’)
  • -
  • Synth_ds (float) – Resolution of the mesh in the direction parallel to the LOS
  • -
  • Synth_dsMode (str) – Flag indicating whether ds is an absolute value (‘abs’, in meters) or a fraction of the maximum local with of the VOS (‘rel’)
  • -
  • Synth_Colis (bool) – Flag indicating whether the collision detection should be activated
  • -
-
Returns:

Detect (TFG.Detect) – The created TFG.Detect object

-
-
- -
-
-tofu.plugins.ITER.Bolo.geom.create_GDetect(Name, LDetect, SavePathObj='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Objects_ITER/', save=True, save_SynthDiag=False)[source]
-

Create a tofu.geom.GDetect object (i.e.: group of detectors, or camera) with specified Name from a list of Detect objects -Object is created, optionally Saved in SavePathObj and returned

- --- - - - - - -
Parameters:
    -
  • Name (str) – Name of the object to be created
  • -
  • LDetect (list) – List of already-created Detect objects
  • -
  • SavePathObj (str) – (optional) Absolute path where the created object will be Saved
  • -
  • save (bool) – (optional) Flag indicating whether the created object should be Saved
  • -
  • save_SynthDiag (bool) – (optional) Flag indicating whether the pre-computed synthetic diagnostic mesh should also be saved (larger files) or whether it should be recomputed upon loading
  • -
-
Returns:

GD (tofu.geom.GDetect) – The created object

-
-
- -
-
-tofu.plugins.ITER.Bolo.geom.load(Name, Cls='GDetect', SavePathObj='/afs/ipp-garching.mpg.de/home/g/gav/ToFu_ITER/Objects_ITER/')[source]
-

Load the desired object, identified by name and saving path

-

Searches in SavePathObj a ToFu object of the specified class (Cls) saved under the specified name (Name). -If a single match is found, the object is loaded and returned, otherwise an error is raised

- --- - - - -
Parameters:
    -
  • Name (str) – Name of the object
  • -
  • Cls (str) – Class of the object, in [‘Ves’,’Apert’,’Detect’,’GDetect’]
  • -
  • SavePathObj (str) – Path under which the object is to be found
  • -
-
-
- +
+

4.1.2.3. ITER.Bolo.geom

@@ -324,12 +68,12 @@

4.1.2.4. Indices and tables \ No newline at end of file diff --git a/doc/build/html/Auto_tofu.plugins.html b/doc/build/html/Auto_tofu.plugins.html index f2c255070..f6c34331d 100644 --- a/doc/build/html/Auto_tofu.plugins.html +++ b/doc/build/html/Auto_tofu.plugins.html @@ -1,34 +1,24 @@ - + - - - 4. tofu.plugins — tofu v1.1 - + + 4. tofu.plugins — tofu v1.1 - + - - + + + + - - + @@ -55,7 +45,7 @@

Navigation

4. tofu.plugins

-

In an effort to adapt ToFu to several experiments and ensure a smooth use for non-specialists users, plugins can be developped to adapt ToFu to the local specificities of each laboratory or environment (local computer systems and networks, local geometry and nomenclature, local data storing systems...).

+

In an effort to adapt ToFu to several experiments and ensure a smooth use for non-specialists users, plugins can be developped to adapt ToFu to the local specificities of each laboratory or environment (local computer systems and networks, local geometry and nomenclature, local data storing systems…).

While ToFu in itself is open-source, the plugins, which concentrate everything that is machine-specific, are writen on demand and customized for the local needs, they remain on the local servers and are not provided on the GitHub page of ToFu. It is via the laboratories that you may have access to them.

The following plugins have been / are being developped:

@@ -70,16 +60,16 @@

4.1. Machine-oriented plugins

4.2. Code-oriented plugins

    -
  1. CAID
  2. +
  3. CAID

@@ -90,7 +80,7 @@

4.3. Indices and tables \ No newline at end of file diff --git a/doc/build/html/Auto_tofu.treat.html b/doc/build/html/Auto_tofu.treat.html index 00e75dcd3..6aed2370e 100644 --- a/doc/build/html/Auto_tofu.treat.html +++ b/doc/build/html/Auto_tofu.treat.html @@ -1,34 +1,24 @@ - + - - - 2. tofu.treat — tofu v1.1 - + + 2. tofu.treat — tofu v1.1 - + - - + + + + - - + @@ -53,487 +43,15 @@

Navigation

-
-

2. tofu.treat

-

Provide data handling class and methods (storing, processing, plotting...)

-
-
-class tofu.treat.PreData(data, t=None, Chans=None, Id=None, Exp='AUG', shot=None, Diag='SXR', dtime=None, dtimeIn=False, SavePath=None, LIdDet=None, DtRef=None, MovMeanfreq=100, Resamp=True, interpkind='linear', indOut=None, indCorr=None, DF=None, Harm=True, DFEx=None, HarmEx=True, lt=[], lNames=[], Calc=True)[source]
-

A class defining a data-handling object, data is stored as read-only attribute, copies of it can be modified, methods for plotting, saving...

-

The name of the class refers to Pre-treatment Data (i.e.: in the context of tomography, data that is pre-treated before being fed to an inversion algorithm). -ToFu provide a generic data-handling class, which comes a robust data storing policy: the input data is stored in a read-only attribute and the data-processing methods are used on a copy (e.g.: for computing the SVD, Fourier transform, shorten the time interval of interest, eliminate some channels...). -Furthermore, methods for interactive plotting are provided as well as a saving method

-
-
obj
- : PreData
The created instance
-
-
-
-Corr_add(Val=[], LCrit=['Name', 'Cam', 'CamHead'], indCorr=None, Calc=True)[source]
-

Add channels to the list of channels that are thought to need correction

-

When a channel is suspected to need correction (mismatching retrofit due for example to wrong calibration), it can be included in a dedicated correction list. -Channels in this list can then be discarded for the inversion, a correction coefficient can be computed from the retrofit, and the inversion can be re-done using this correction coefficient. -This list works like the list of excluded / corrupted channels self.Out_list()

- --- - - - -
Parameters:
    -
  • Val (list) – Fed to self.select(), list of values for criteria in LCrit that should be used to exclude channels (e.g.: list of channel names of camera names)
  • -
  • LCrit (list) – Fed to self.select(), list of criteria against which to select the channels matching the values in Val (should be attributes of tofu.pathfile.ID or of its USRdict attribute)
  • -
  • indCorr (None / np.ndarray) – Alternatively, you can directly pass a (N,) bool array whereN matches the number of channels and True means that a channel should be excluded, thus setting self._indCorr
  • -
  • Calc (bool) – Flag indicating whether the calculation should be triggered immediately
  • -
-
-
- -
-
-Corr_list(Out='Name')[source]
-

Return the list of channel names needing correction

-

This lists the channels indicated by self._indOut, populated using self.Out_add() and de-populated using self.In_add(). -The output can be returned as a list of channel Names

- --- - - - - - -
Parameters:Out (str) – Flag indicating in which form to return the output (fed to select())
Returns:L (list) – List of excluded channels in the required form
-
- -
-
-Corr_remove(Val=[], LCrit=['Name', 'Cam', 'CamHead'], Calc=True)[source]
-

Add channels to the list of channels to be re-inserted as valid channels

-

Works like self.In_add() (i.e.: opposite of self.Corr_add())

- --- - - - -
Parameters:
    -
  • Val (list) – Fed to self.select(), list of values for criteria in LCrit that should be used to exclude channels (e.g.: list of channel names of camera names)
  • -
  • LCrit (list) – Fed to self.select(), list of criteria against which to select the channels matching the values in Val (should be attributes of tofu.pathfile.ID or of its USRdict attribute)
  • -
  • indCorr (None / np.ndarray) – Alternatively, you can directly pass a (N,) bool array whereN matches the number of channels and True means that a channel should be excluded, thus setting self._indCorr
  • -
  • Calc (bool) – Flag indicating whether the calculation should be triggered immediately
  • -
-
-
- -
-
-In_add(LVal=[], LCrit=['Name', 'Cam', 'CamHead'], Calc=True)[source]
-

Add channels to the list of channels to be re-included as valid channels

-

Provides a mechanism opposite to Out_add(). -We you change your mind about a series of channel and think they should be re-included as valid, pass them to this method using the same arguments as self.Out_add()

- --- - - - -
Parameters:
    -
  • Val (list) – Fed to self.select(), list of values for criteria in LCrit that should be used to exclude channels (e.g.: list of channel names of camera names)
  • -
  • LCrit (list) – Fed to self.select(), list of criteria against which to select the channels matching the values in Val (should be attributes of tofu.pathfile.ID or of its USRdict attribute)
  • -
  • indOut (None / np.ndarray) – Alternatively, you can directly pass a (N,) bool array whereN matches the number of channels and True means that a channel should be excluded, thus setting self._indOut
  • -
  • Calc (bool) – Flag indicating whether the calculation should be triggered immediately
  • -
-
-
- -
-
-In_list(Out='Name')[source]
-

Return the list of included channel names (considered valid)

-

The equivalent of Out_list(), but this time returning the complementary list

- --- - - - - - -
Parameters:Out (str) – Flag indicating in which form to return the output (fed to select())
Returns:L (list) – List of excluded channels in the required form
-
- -
-
-Out_add(Val=[], LCrit=['Name', 'Cam', 'CamHead'], indOut=None, Calc=True)[source]
-

Add desired channels to the list of channels to be excluded

-

It is possible to store a list a list of channels that are thought to be corrupted or more generally that, after closer inspection, are considered not fit. -This list is then automatically passed on to further ToFu objects (e.g.: for inversions), so that the corresponding data is excluded from all further processes. -PreData provides methods to append channel names to this list (in fact you can even exclude whole cameras).

- --- - - - -
Parameters:
    -
  • Val (list) – Fed to self.select(), list of values for criteria in LCrit that should be used to exclude channels (e.g.: list of channel names of camera names)
  • -
  • LCrit (list) – Fed to self.select(), list of criteria against which to select the channels matching the values in Val (should be attributes of tofu.pathfile.ID or of its USRdict attribute)
  • -
  • indOut (None / np.ndarray) – Alternatively, you can directly pass a (N,) bool array whereN matches the number of channels and True means that a channel should be excluded, thus setting self._indOut
  • -
  • Calc (bool) – Flag indicating whether the calculation should be triggered immediately
  • -
-
-
- -
-
-Out_list(Out='Name')[source]
-

Return the list of excluded channel names (considered corrupted)

-

This lists the channels indicated by self._indOut, populated using self.Out_add() and de-populated using self.In_add(). -The output can be returned as a list of channel Names

- --- - - - - - -
Parameters:Out (str) – Flag indicating in which form to return the output (fed to select())
Returns:L (list) – List of excluded channels in the required form
-
- -
-
-interp(lt=[], lNames=[], Calc=True)[source]
-

Perform linear interpolation of data at chosen times for chosen channels

-

As opposed to self.set_t(), this method shall be used to interpolate data of a small number of channels at a small sumber of time points. -Use this to correct a small number of time points that are clearly corrupted when you think the rest shall be preserved.

-

!!! This is done with respect to the reference time vector and dataset, to avoid propagating errors through later data treatment (use self.plot(V=’Ref’) to plot the reference data set) !!!

- --- - - - -
Parameters:
    -
  • lt (list) – Times at which linear interpolation should be performed
  • -
  • lNames (list) –
    -
    Channels for which interpolation should be performed, one element per corresponding time point, elements can be:
    -
      -
    • list of str: list of channel names that should be interpolated for the corresponding time point
    • -
    • str: single channel name that should be interpolated for the corresponding time point
    • -
    • ‘All’: all channels should be interpolated for the corresponding time point
    • -
    -
    -
    -
  • -
  • Calc (bool) – Flag indicating whether data should be updated immediately
  • -
-
-

Examples

-
-
>> obj.interp(lt=[2.55, 5.10, 6.84], lNames=[[‘H_021’,’J_014’], ‘F_10’, ‘All’], Calc=True)
-
Will perform interpolation for 2 channels for the first time point, for one channel for the second, and for all channels for the last time point
-
-
- -
-
-plot(a4=False)[source]
-

Plot the signal in an interactive window, no arguments needed

-

Plot an interactive matplotlib window to explore the data

- --- - - - - - -
Parameters:a4 (bool) – Flag indicating whether the figure should be the size of a a4 sheet of paper (to facilitate printing)
Returns:Lax (list) – List of plt.Axes on which the plots are made
-
- -
-
-plot_fft(Val=None, Crit='Name', V='simple', tselect=None, Fselect=None, PreExp=None, PostExp=None, Log='or', InOut='In', SpectNorm=True, DTF=None, RatDef=100.0, Inst=True, MainF=True, ylim=(None, None), cmap=<matplotlib.colors.LinearSegmentedColormap object>, a4=False)[source]
-

Plot the power spectrum (fft) of the chosen signals

-

Computes the fft of the data and plots the power spectrum, normalized or not, for the chosen channels

-

Parameters Val, Crit, PreExp, PostExp, Log and InOut are for channel selection and are fed to select()

- --- - - - - - -
Parameters:
    -
  • V (str) – Flag indicating whether the plot should be interactive, values in [‘simple’,’inter’]
  • -
  • tselect (None /) –
  • -
  • Fselect (None /) –
  • -
  • SpectNorm (bool) – Flag, if True the power spectrum is normalised to its maximum at each time step (default: True)
  • -
  • DTF (float) – Size (in seconds) of the running time window to be used for the windowed fft
  • -
  • RatDef (float) – Used if DTF not provided, the number by which the total signal duration is divided to get a time window
  • -
  • Inst (bool) – Flag, if true, the average of the signal is substracted at each time step to emphasize high frequencies (higher than the one associated to the running time window, default: True)
  • -
  • MainF (bool) – Flag
  • -
  • ylim (tuple) – Each limit which is not None is fed to plt.Axes.set_ylim()
  • -
  • a4 (bool) – Flag, if true the figure is sized so as to fill a a4 paper sheet
  • -
-
Returns:

Lax (list) – List of plt.Axes on which the plots were made

-
-
- -
-
-plot_svd(Modes=10, NRef=None, a4=False, Test=True)[source]
-

Plot the chosen modes (topos and chronos) of the svd of the data, and the associated spectrum on a separate figure

-

Performs a svd of the data and plots the singular values, the temporal and spacial modes

-
-
Modes
- : int / iterable
-
Index of the modes to be plotted, the modes and sorted in decreasing order of singular value
-
    -
  • int : plots all modes in range(0,Modes)
  • -
  • iterable : plots all modes whose index is contained in Modes
  • -
-
-
-
-
NRef
- : None
Number of columns in the plot, if None set to len(Modes)/2 (i.e.: 2 modes plotted per axes)
-
a4
- : bool
Flag indicating whether the figure should be the size of a a4 sheet of paper (to facilitate printing)
-
Test
- : bool
Flag indicating whether the inputs should be tested for conformity
-
- --- - - - -
Returns:Lax (list) – List of plt.Axes on which the plots were made
-
- -
-
-save(SaveName=None, Path=None, Mode='npz', compressed=False)[source]
-

Save the object in folder Name, under file name SaveName, using specified mode

-

Most tofu objects can be saved automatically as numpy arrays (.npz, recommended) at the default location (recommended) by simply calling self.save()

- --- - - - -
Parameters:
    -
  • SaveName (None / str) – The name to be used for the saved file, if None (recommended) uses self.Id.SaveName
  • -
  • Path (None / str) – Path specifying where to save the file, if None (recommended) uses self.Id.SavePath
  • -
  • Mode (str) – Flag specifying whether to save the object as a numpy array file (‘.npz’, recommended) or an object using cPickle (not recommended, heavier and may cause retro-compatibility issues)
  • -
  • compressed (bool) – Flag, used when Mode=’npz’, indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files)
  • -
-
-
- -
-
-select(Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=<type 'bool'>, ToIn=False)[source]
-

Return a sub-set of the data (channels-wise selection)

-

Return an array of indices of channels selected according to the chosen criteria with chosen values -Use either Val or (PreExp and PostExp)

- --- - - - - - -
Parameters:
    -
  • Val (list or str) – List of values that the chosen criteria must match (converted to one-item list if str)
  • -
  • Crit (str) – Criterion used to select some channels, must be among their tfpf.ID class attributes (e.g.: ‘Name’, ‘SaveName’...) or IFTF.ID.USRdict (‘Cam’,...)
  • -
  • PreExp (list or str) – List of str expressions to be fed to eval(PreExp[ii]+” Detect.Crit “+PostExp[ii]) or eval(PreExp[ii]+” Detect.USRdict.Crit “+PostExp[ii])
  • -
  • PostExp (list or str) – List of str expressions to be fed to eval(PreExp[ii]+” Detect.Crit “+PostExp[ii]) or eval(PreExp[ii]+” Detect.USRdict.Crit “+PostExp[ii])
  • -
  • Log (str) – Flag (‘or’ or ‘and’) indicating whether to select the channels matching all criteria or any
  • -
  • InOut (str) – Flag (‘In’ or ‘Out’) indicating whether to select all channels matching the criterion, or all except those
  • -
  • Out (type or str) – Flag (bool, int or an attribute of tfpf.ID or tfpf.ID.USRdict) indicating whether to return an array of boolean indices or int indices, or a list of the chosen attributes (e.g.: ‘Name’)
  • -
  • ToIn (bool) – Flag indicating whether indices should be returned with respect to the channels that are considered as included only (see obj.In_list() to see these channels)
  • -
-
Returns:

ind (np.ndarray) – Indices of the selected channels, as a bool or int array

-
-

Examples

-
-
>> ind = TFT.PreData.select(Val=[‘H’,’J’], Crit=’Cam’, Log=’any’, InOut=’In’, Out=bool)
-
Will return a bool array of the indices of all channels for which ‘Cam’ is ‘H’ or ‘J’
-
>> ind = PreData.select(Crit=’Name’, PreExp=[“‘F’ in ”, “‘6’ in “], Log=’and’, InOut=’In’, Out=int)
-
Will return an int array of indices of all channels for which ‘F’ and ‘6’ are both included in the name
-
>> ind = PreData.select(Crit=’CamHead’, PreExp=[“‘F’ in ”, “‘2’ in “], Log=’any’, InOut=’Out’, Out=’Name’)
-
Will return the names (as a list) of all channels except those that have a camera head name that includes a ‘F’ or a ‘2’ (i.e.: except camera heads ‘F’ and ‘H2’, ‘I2’, ‘J2’, ‘K2’)
-
-
- -
-
-set_Dt(Dt=None, Calc=True)[source]
-

Set the time interval to which the data should be limited (does not affect the reference data)

-

While the original data set and time base are always preserved in the background, you can change your mind and focus on a smaller interval included in the original one. -This can be convenient for applying data treatment (SVD, fft...) to parts of the signal lifetime only.

- --- - - - -
Parameters:
    -
  • Dt (None / list) – The time interval of interest, as a list of len()=2 in increasing values
  • -
  • Calc (bool) – Flag indicating whether the calculation should be triggered immediately
  • -
-
-
- -
-
-set_PhysNoise(Mode='svd', Phys=[0, 1, 2, 3, 4, 5, 6, 7], DF=[10000.0, 11000.0], DFEx=None, Harm=True, HarmEx=True, Deg=0, Nbin=3, LimRatio=0.05, Plot=False)[source]
-

Use a svd or a fft to estimate the physical part of the signal and the part which can be assimilated to noise, then uses specified degree for polynomial noise model

-

This method provides an easy way to compute the noise level on each channel. -It can be done in 2 different ways:

-
-
    -
  • ‘svd’: you have to provide the mode numbers that you think can be considered as physical, the signal will be re-constructed from these and the rest discarded as noise
  • -
  • ‘fft’: you have to provide the frequency window that you think is physical (optionaly the higher harmonics can be included), the signal is re-constructed via inverse fourier and the rest discarded as noise
  • -
-
-

To help you decide which mode numbers of frequency interval to use, you can preliminarily use self.plot_svd() and self.plot_fft() to visualize the decompositions.

-

Note : this is only used to compute a noise estimate, stored separately, the total original signal is preserved

- --- - - - -
Parameters:
    -
  • Mode (str) – Flag indicating with which method should the noise be estimated (‘svd’ or ‘fft’)
  • -
  • list (DFEx) – Modes to be extracted from the svd (default: first 8 modes), use method .plot_svd() to choose the modes
  • -
  • list – 2 values delimiting a frequency interval (in Hz) from which to extract signal using a fft and rfft
  • -
  • bool (Plot) – Flag, if True all the available higher harmonics of FreqIn will also be included in the physical signal
  • -
  • list – 2 values delimiting a frequency interval (in Hz) that shall be avoided in the physical signal (relevant if some high harmonics of DF intersect DFEx)
  • -
  • bool – Flag, if True all the available higher harmonics of Freqout will also be avoided in the physical signal
  • -
  • int (Nbin) – Degree to be used for the polynomial noise model
  • -
  • int – Number of bins to be used for evaluating the noise (std) at various signal values
  • -
  • float (LimRatio) – Ratio ... to be finished...
  • -
  • bool – Flag, if True the histogram of the estimated noise is plotted
  • -
-
-

Examples

-
-
>> obj.set_PhysNoise(Mode=’svd’, Phys=[0,1,2,3,4,5], Deg=0)
-
Will take the first 6 modes of the signal svd and consider as physical, the rest is used to compute a constant (Deg=0) noise estimate on each channel
-
-
- -
-
-set_Resamp(t=None, f=None, Method='movavrg', interpkind='linear', Calc=True)[source]
-

Re-sample the data and time vector

-
-
Use a new time vector that can either be:
-
    -
  • provided directly (if t is not None)
  • -
  • computed from an input sampling frequency (if f is not None)
  • -
-
-
-

If but t and f are provided, t is used as the time vector and f is only used for the moving average

-

Then, the data is re-computed on this new time vector using either interpolation (‘interp’) or moving average (‘movavrg’)

- --- - - - -
Parameters:
    -
  • t (None / np.ndarray) –
  • -
  • f (None / int / float) –
  • -
  • Method (str) –
  • -
  • Resamp (bool) –
  • -
  • interpkind (str) –
  • -
  • Calc (bool) – Flag indicating whether the calculation should be triggered immediately
  • -
-
-
- -
-
-set_fft(DF=None, Harm=True, DFEx=None, HarmEx=True, Calc=True)[source]
-

Return the FFT-filtered signal (and the rest) in the chosen frequency window (in Hz) and in all the higher harmonics (optional)

-

Can also exclude a given interval and its higher harmonics from the filtering (optional)

- --- - - - -
Parameters:
    -
  • DF (iterable) – Iterable of len()=2, containing the lower and upper bounds of the frequency interval (Hz) to be used for filtering
  • -
  • Harm (bool) – If True all the higher harmonics of the interval DF will also be included
  • -
  • DFEx (list) – List or tuple of len()=2, containing the lower and upper bounds of the frequency interval to be excluded from filtering (in case it overlaps with some high harmonics of DF)
  • -
  • HarmEx (bool) – If True all the higher harmonics of the interval DFEx will also be excluded
  • -
-
-
- -
-
-substract_Dt(tsub=None, Calc=True)[source]
-

Allows subtraction of data at one time step from all data

-

Can be convenient for plotting background-subtracted signal (background meaning signal before a reference time step).

- --- - - - -
Parameters:
    -
  • tsub (int / float / iterable) –
    -
    A time value, or a time interval indicating which part of the signal is to be considered as reference and subtracted from the rest
    -
      -
    • int / float :
    • -
    -
    -
    -
  • -
  • Calc (bool) – Flag indicating whether data should be updated immediately
  • -
-
-
- -
- +
+

2. tofu.treat

@@ -544,7 +62,7 @@

2.1. Indices and tables \ No newline at end of file diff --git a/doc/build/html/Citation.html b/doc/build/html/Citation.html index 9a7ab54e1..ebb52ae62 100644 --- a/doc/build/html/Citation.html +++ b/doc/build/html/Citation.html @@ -1,32 +1,22 @@ - + - - - Citing ToFu: — tofu v1.1 - + + Citing ToFu: — tofu v1.1 - + - - - - + + + + + @@ -47,18 +37,16 @@

Navigation

Citing ToFu:

-

An article dedicated to describing ToFu and its capacities is in preparation, in the meantime please cite this one [1], which briefly describes it and uses it to present physics results. Since this paper may not present enough details for the interested reader, please also include a url pointing to this web-based documentation.

- - - - - -
[1]
    -
  1. Vezinet et al., ‘Non-monotonic growth rates of sawtooth precursors evidenced with a new method on ASDEX Upgrade’, Nuclear Fusion 56, 086001, 2016
  2. +

    An article dedicated to describing ToFu and its capacities is in preparation, in the meantime please cite this one 1, which briefly describes it and uses it to present physics results. Since this paper may not present enough details for the interested reader, please also include a url pointing to this web-based documentation.

    +
    +
    1
    +
      +
    1. Vezinet et al., ‘Non-monotonic growth rates of sawtooth precursors evidenced with a new method on ASDEX Upgrade’, Nuclear Fusion 56, 086001, 2016

    -
+ +

Bibtex:

-
@article{0029-5515-56-8-086001,
+
@article{0029-5515-56-8-086001,
   author={D. Vezinet and V. Igochine and M. Weiland and Q. Yu and A. Gude and D. Meshcheriakov and M. Sertoli and the Asdex Upgrade
 Team and the EUROfusion MST1 Team},
   title={Non-monotonic growth rates of sawtooth precursors evidenced with a new method on ASDEX Upgrade},
@@ -74,10 +62,10 @@ 

Citing ToFu:

Indices and tables

@@ -88,7 +76,7 @@

Indices and tables
-

Table Of Contents

+

Table of Contents

@@ -126,12 +114,12 @@

Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/Dependencies.html b/doc/build/html/Dependencies.html index ba2a30031..db52a34dd 100644 --- a/doc/build/html/Dependencies.html +++ b/doc/build/html/Dependencies.html @@ -1,32 +1,22 @@ - + - - - Dependencies — tofu v1.1 - + + Dependencies — tofu v1.1 - + - - - - + + + + + @@ -49,49 +39,50 @@

    Navigation

    Dependencies

    ToFu uses the following generic packages:

      -
    • python/2.7.3
    • -
    • ipython/1.1.0
    • -
    • dateutil/2.4.0
    • -
    • docutils/0.12.0
    • -
    • distribute/0.6.34
    • +
    • python/2.7.3

    • +
    • ipython/1.1.0

    • +
    • dateutil/2.4.0

    • +
    • docutils/0.12.0

    • +
    • distribute/0.6.34

    Scientific computing and plotting:

      -
    • numpy/1.9.1
    • -
    • scipy/0.15.1
    • -
    • matplotlib/1.2.1
    • -
    • polygon2
    • -
    • datetime
    • +
    • numpy/1.9.1

    • +
    • scipy/0.15.1

    • +
    • matplotlib/1.2.1

    • +
    • polygon2

    • +
    • datetime

    Some part of ToFu are coded using Cython, which requires Cython and a compiler:

      -
    • cython/0.19.1
    • -
    • gcc or intel
    • +
    • cython/0.19.1

    • +
    • gcc/4.8

    • +
    • intel/14.0

    Testing:

      -
    • nose/1.3.4
    • +
    • nose/1.3.4

    Documentation:

      -
    • pygments/1.5
    • +
    • pygments/1.5

    To be determined:

      -
    • pyzmq/13.0.2
    • -
    • tornado/2.4.1
    • -
    • setuptools
    • -
    • mdsplus/5.0_11
    • -
    • pip
    • -
    • git/1.8.4
    • +
    • pyzmq/13.0.2

    • +
    • tornado/2.4.1

    • +
    • setuptools

    • +
    • mdsplus/5.0_11

    • +
    • pip

    • +
    • git/1.8.4

    @@ -102,7 +93,7 @@

    Indices and tables
    -

    Table Of Contents

    +

    Table of Contents

    @@ -140,12 +131,12 @@

    Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/Todos.html b/doc/build/html/Todos.html index 3cbb1cfd5..2ae0cc775 100644 --- a/doc/build/html/Todos.html +++ b/doc/build/html/Todos.html @@ -1,32 +1,22 @@ - + - - - To do for contributors — tofu v1.1 - + + To do for contributors — tofu v1.1 - + - - - - + + + + + @@ -52,22 +42,22 @@

    Navigation

    Math and geometry:

      -
    • Write a C routine for (very) fast computation of solid angle in non-trival cases using spherical geometry and write a python / cython wrapper (weeks)
    • +
    • Write a C routine for (very) fast computation of solid angle in non-trival cases using spherical geometry and write a python / cython wrapper (weeks)

    Coding:

      -
    • Parallelize (frist CPU then GPU) the key functions of the geometry module (months)
    • -
    • Branch the meshing module to allow compatibility with CAID/Pigasus (months)
    • -
    • Branch the matrix computation module for the same reason (months)
    • -
    • Branch the inversion module for the same reason (months)
    • +
    • Parallelize (frist CPU then GPU) the key functions of the geometry module (months)

    • +
    • Branch the meshing module to allow compatibility with CAID/Pigasus (months)

    • +
    • Branch the matrix computation module for the same reason (months)

    • +
    • Branch the inversion module for the same reason (months)

    Long term:

      -
    • Create a parallel library called ToFuG, which provides all ToFu functionalities through a GUI for each ToFu module (year)
    • +
    • Create a parallel library called ToFuG, which provides all ToFu functionalities through a GUI for each ToFu module (year)

    @@ -78,7 +68,7 @@

    Long term:
    -

    Table Of Contents

    +

    Table of Contents

    @@ -118,12 +108,12 @@

    Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/Tutorial_AUG.html b/doc/build/html/Tutorial_AUG.html index 615d6ac5a..538fcb87a 100644 --- a/doc/build/html/Tutorial_AUG.html +++ b/doc/build/html/Tutorial_AUG.html @@ -1,32 +1,22 @@ - + - - - AUG-specific tutorial — tofu v1.1 - + + AUG-specific tutorial — tofu v1.1 - + - - - - + + + + + @@ -51,47 +41,47 @@

    AUG-specific tutorialHow to access the ToFu library

    The plugin for ASDEX Upgrade (AUG) is hosted on the theory (Tok) clusters of the Max-Planck Institute for Plasma Physics (IPP) in Garching. If you have an account in IPP, you can then connect to one of the tok clusters where the library is hosted, via the command:

    -
    >>> ssh toki01
    +
    >>> ssh toki01
     

    Enter your password and then you need to load the module in the terminal

    -
    >>> module load tofu
    +
    >>> module load tofu
     

    You may need to load other modules on which ToFu depends (see the dependencies).

    You can then start a ipython console and load the AUG plugin for ToFu:

    -
    >>> import tofu.plugins.AUG as tfAUG
    +
    >>> import tofu.plugins.AUG as tfAUG
     

    How to load existing geometry

    You can now load the geometry that was already computed and stored for some diagnostics (only the Soft X-Ray diagnostic at this date). -In general loading the geometry means using a method of the plugin that will load and return a list of tofu.geom.GDetect instances. -On AUG, each tofu.geom.GDetect instance corresponds to a camera head. -Since the geometry (position, aperture size...) of each camera head may change in time (changes are sometimes implemented between experimental campaigns), you can specify a shot number and the plugin will return the latest geometry that was computed before that shot number (only a few have been computed so far, but more will come).

    -
    >>> LGD = tfAUG.SXR.geom.load(shot=31801)
    +In general loading the geometry means using a method of the plugin that will load and return a list of tofu.geom.GDetect instances.
    +On AUG, each tofu.geom.GDetect instance corresponds to a camera head.
    +Since the geometry (position, aperture size…) of each camera head may change in time (changes are sometimes implemented between experimental campaigns), you can specify a shot number and the plugin will return the latest geometry that was computed before that shot number (only a few have been computed so far, but more will come).

    +
    >>> LGD = tfAUG.SXR.geom.load(shot=31801)
     
    -

    This command returns a list of tofu.geom.GDetect instances with the latest geometry computed before shot 31801.

    +

    This command returns a list of tofu.geom.GDetect instances with the latest geometry computed before shot 31801.

    How to load SXR data

    the ToFu plugin for AUG also comes with a data loading and formatting routine. In addition to a shot number and a time window, you can choose whether the data is returned as numpy arrays or as a ToFu-compatible object for data pre-treatment via the Tofu keyword argument.

    -
    >>> pre = tfAUG.SXR.data.load(shot=30801, Dt=[2.,2.01], Method='SX', Tofu=True)
    +
    >>> pre = tfAUG.SXR.data.load(shot=30801, Dt=[2.,2.01], Method='SX', Tofu=True)
     
    -

    This command will return the SXR data for shot 30801 in the [2.,2.01] s time window using diagnostic ‘SX.’ (instead of SSX), in the form of a ToFu-compatible object. +

    This command will return the SXR data for shot 30801 in the [2.,2.01] s time window using diagnostic ‘SX.’ (instead of SSX), in the form of a ToFu-compatible object. See the documentation of the method for more details.

    @@ -102,7 +92,7 @@

    Indices and tables
    -

    Table Of Contents

    +

    Table of Contents

    @@ -143,12 +133,12 @@

    Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/Tutorial_Geom_Advanced.html b/doc/build/html/Tutorial_Geom_Advanced.html index 7e8059fc7..df0336e98 100644 --- a/doc/build/html/Tutorial_Geom_Advanced.html +++ b/doc/build/html/Tutorial_Geom_Advanced.html @@ -1,32 +1,22 @@ - + - - - How to create a diagnostic geometry — tofu v1.1 - + + How to create a diagnostic geometry — tofu v1.1 - + - - - - + + + + + @@ -49,33 +39,32 @@

    Navigation

    How to create a diagnostic geometry

    It is the geometry module that provides all the necessary tools for creating a new diagnostic. A diagnostic comprises a set of detectors (ToFu creates one object for each detector and you can then group them into a larger object to represent cameras). -Each detector is basically defined by its active surface, which should be a planar polygon, and by a set of optics through which it ‘sees’ the plasma. +Each detector is basically defined by its active surface, which should be a planar polygon, and by a set of optics through which it ‘sees’ the plasma. The optics can be a converging spherical lens or an arbitrary number of apertures (of arbitrary shape). Each detector is also assigned to a vessel, which defines the linear or toroidal volume in which the plasma can exist.

    -

    The following guides you through the creation of these objects in the famous ‘hello-world’ example:

    +

    The following guides you through the creation of these objects in the famous ‘hello-world’ example:

    To find out more about what you can do with the geometry module check out the advanced tutorial.

    Creating a vessel

    If a vessel object does not exist yet, you have to create one (otherwise you can just load it an existing one). A vessel object is basically defined by a 2D simple polygon (i.e.: non self-intersecting),

    -
    -
    Open-source:
    -

    ToFu is distributed under the very permissive MIT license, thus allowing free use, keeping in mind that neither the author nor any of the laboratories in which he worked can be held responsible for unwanted behaviour or results. +

    +
    Open-source:

    ToFu is distributed under the very permissive MIT license, thus allowing free use, keeping in mind that neither the author nor any of the laboratories in which he worked can be held responsible for unwanted behaviour or results. It is instead transparency that is considered for as a warranty of quality on the long-term.

    -

    ToFu is hosted on github.

    +

    ToFu is hosted on github.

    -
    -
    Versions:
    -
    A list of the successive versions of ToFu, with a brief description can be found here.
    +
    +
    Versions:

    A list of the successive versions of ToFu, with a brief description can be found here.

    +
    -
    -
    Dependences:
    -
    ToFu uses the following python packages.
    +
    +
    Dependences:

    ToFu uses the following python packages.

    +
    -
    -
    Citing ToFu:
    -
    If you decide to use ToFu for research and published results please acknowledge this work by citing the project.
    +
    +
    Citing ToFu:

    If you decide to use ToFu for research and published results please acknowledge this work by citing the project.

    +
    -
    -
    Tutorials and how to’s:
    -
      -
    • -
      How to build a diagnostic geometry
      -

      Create apertures and detectors to test a new configuration, to apply ToFu to your own problems, to design a prospetive diagnostic...

      +
      +
      Tutorials and how to’s:
        +
      • +
        How to build a diagnostic geometry

        Create apertures and detectors to test a new configuration, to apply ToFu to your own problems, to design a prospetive diagnostic…

      • -
      • -
        How to compute integrated signal from 2D or 3D synthetic emissivity
        -

        Use an already-existing diagnostic geometry in a synthetic diagnostic approach to solve the direct problem and compute the line Of Sight and / or Volume of Sight integrated signals from a simulated emissivity field that you provide as an input.

        +
      • +
        How to compute integrated signal from 2D or 3D synthetic emissivity

        Use an already-existing diagnostic geometry in a synthetic diagnostic approach to solve the direct problem and compute the line Of Sight and / or Volume of Sight integrated signals from a simulated emissivity field that you provide as an input.

      • -
      • -
        How to compute tomographic inversions
        -

        Use existing diagnostic geometry and signals to solve the inverse problem and compute tomographic inversions using a choice of discretization basis functions and regularisation functionals.

        +
      • +
        How to compute tomographic inversions

        Use existing diagnostic geometry and signals to solve the inverse problem and compute tomographic inversions using a choice of discretization basis functions and regularisation functionals.

      • -
      • How to contribute (to do’s)

        -
      • +
      • How to contribute (to do’s)

      @@ -125,10 +107,10 @@

      Contents:

      Indices and tables

    @@ -138,7 +120,7 @@

    Indices and tables
    -

    Table Of Contents

    +

    Table of Contents

    @@ -180,12 +162,12 @@

    Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/Tutorial_Geom_HowToCreateGeometry.html b/doc/build/html/Tutorial_Geom_HowToCreateGeometry.html index 9973b455b..c63cf3a00 100644 --- a/doc/build/html/Tutorial_Geom_HowToCreateGeometry.html +++ b/doc/build/html/Tutorial_Geom_HowToCreateGeometry.html @@ -1,32 +1,22 @@ - + - - - How to create a diagnostic geometry — tofu v1.1 - + + How to create a diagnostic geometry — tofu v1.1 - + - - - - + + + + + @@ -49,16 +39,16 @@

    Navigation

    How to create a diagnostic geometry

    It is the geometry module that provides all the necessary tools for creating a new diagnostic. A diagnostic comprises a set of detectors (ToFu creates one object for each detector and you can then group them into a larger object to represent cameras). -Each detector is basically defined by its active surface, which should be a planar polygon, and by a set of optics through which it ‘sees’ the plasma. +Each detector is basically defined by its active surface, which should be a planar polygon, and by a set of optics through which it ‘sees’ the plasma. The optics can be a converging spherical lens or an arbitrary number of apertures (of arbitrary shape). Each detector is also assigned to a vessel, which defines the linear or toroidal volume in which the plasma can exist.

    -

    The following guides you through the creation of these objects in the famous ‘hello-world’ example:

    +

    The following guides you through the creation of these objects in the famous ‘hello-world’ example:

    To find out more about what you can do with the geometry module check out the advanced tutorial.

    -

    As a pre-requisite, let’s load some basic useful libraries in a ipython session, as well as the geometry module of ToFu:

    -
    >>> import numpy as np
    +

    As a pre-requisite, let’s load some basic useful libraries in a ipython session, as well as the geometry module of ToFu:

    +
    >>> import numpy as np
     >>> import matplotlib.pyplot as plt
     >>> plt.ion()
    ->>> # tofu-specific
    +>>> # tofu-specific
     >>> import tofu.geom as tfg
     
    @@ -67,79 +57,80 @@

    Creating, plotting and saving a vessel
    >>> # Define the center, radius and lower limit
    +

    Let’s define the polygon limiting the vessel as a circle with a divertor-like shape at the bottom:

    +
    >>> # Define the center, radius and lower limit
     >>> R0, Z0, rad, ZL = 2., 0., 1., -0.85
    ->>> # Define the key points in the divertor region below ZL
    +>>> # Define the key points in the divertor region below ZL
     >>> Div_R, Div_Z = [R0-0.2, R0, R0+0.2], [-1.2, -0.9, -1.2]
    ->>> # Find the angles corresponding to ZL and span the rest
    +>>> # Find the angles corresponding to ZL and span the rest
     >>> thet1 = np.arcsin((ZL-Z0)/rad)
     >>> thet2 = np.pi - thet1
     >>> thet = np.linspace(thet1,thet2,100)
    ->>> # Assemble the polygon
    +>>> # Assemble the polygon
     >>> poly_R = np.append(R0+rad*np.cos(thet), Div_R)
     >>> poly_Z = np.append(Z0+rad*np.sin(thet), Div_Z)
    ->>> # Plot for checking
    ->>> f, l, a = plt.figure(facecolor='w', figsize=(6,6)), plt.plot(poly_R, poly_Z), plt.axis('equal')
    +>>> # Plot for checking
    +>>> f, l, a = plt.figure(facecolor='w', figsize=(6,6)), plt.plot(poly_R, poly_Z), plt.axis('equal')
     
    Polygon used for defining the vaccum vessel where the plasma may live -

    Polygon used for defining the vaccum vessel where the plasma may live

    +

    Polygon used for defining the vaccum vessel where the plasma may live

    Notice that the polygon does not have to be closed, ToFu will anyway check that and close it automatically if necessary

    -

    Now let’s feed this 2D polygon to the appropriate ToFu class and specify that it should be a toroidal type (if linear type is chosen, the length should be specified by the ‘DLong’ keyword argument). -ToFu also asks for a name to be associated to this instance, and an experiment (‘Exp’) and a shot number (useful when the same experiment changes geometry in time).

    -
    >>> # Create a toroidal Ves instance with name 'World', associated to experiment 'Misc' (for 'Miscellaneous') and shot number 0
    ->>> ves = tfg.Ves('HelloWorld', [poly_R,poly_Z], Type='Tor', Exp='Misc', shot=0)
    +

    Now let’s feed this 2D polygon to the appropriate ToFu class and specify that it should be a toroidal type (if linear type is chosen, the length should be specified by the ‘DLong’ keyword argument). +ToFu also asks for a name to be associated to this instance, and an experiment (‘Exp’) and a shot number (useful when the same experiment changes geometry in time).

    +
    >>> # Create a toroidal Ves instance with name 'World', associated to experiment 'Misc' (for 'Miscellaneous') and shot number 0
    +>>> ves = tfg.Ves(Name='HelloWorld', Poly=[poly_R,poly_Z], Type='Tor', Exp='Misc', shot=0)
     
    -

    Now the vessel instance is created. I provides you with several key attributes and methods (see Ves for details). -Among them the Id attribute is itself a class instance that contains all useful information about this vessel instance for identification, saving... In particular, that’s where the name, the default saving path, the Type, the experiment, the shot number... are all stored. -A default name for saving was also created that automatically includes not only the name you gave but also the module from which this instance was created (tofu.geom or tfg), the type of object, the experiment, the shot number... +

    Now the vessel instance is created. I provides you with several key attributes and methods (see Ves for details). +Among them the Id attribute is itself a class instance that contains all useful information about this vessel instance for identification, saving… In particular, that’s where the name, the default saving path, the Type, the experiment, the shot number… are all stored. +A default name for saving was also created that automatically includes not only the name you gave but also the module from which this instance was created (tofu.geom or tfg), the type of object, the experiment, the shot number… This recommended default pattern is useful for quick identification of saved object, it is advised not to modify it.

    -
    >>> print ves.Id.SaveName
    +
    >>> print(ves.Id.SaveName)
     TFG_VesTor_Misc_World_sh0
     
    -

    Now, we can simply visualise the created vessel by using the dedicated method (keyword argument ‘Elt’ specifies the elements of the instance we want to plot, typically one letter corresponds to one element, here we just want the polygon):

    -
    >>> # Plot the polygon, by default in two projections (cross-section and horizontal) and return the list of axes
    ->>> Lax = ves.plot(Elt='P')
    +

    Now, we can simply visualise the created vessel by using the dedicated method (keyword argument ‘Elt’ specifies the elements of the instance we want to plot, typically one letter corresponds to one element, here we just want the polygon):

    +
    >>> # Plot the polygon, by default in two projections (cross-section and horizontal) and return the list of axes
    +>>> Lax = ves.plot(element='P')
     
    The created vessel instance, plotted in cross-section and horizontal projections -

    The created vessel instance, plotted in cross-section and horizontal projections

    +

    The created vessel instance, plotted in cross-section and horizontal projections

    Since the vessel is an important object (it defines where the plasma can live), all the other ToFu objects rely on it. It is thus important that you save it so that it can be used by other ToFu objects when necessary.

    -
    >>> ves.save(Path='./')
    +
    >>> ves.save(Path='./')
     

    This method will save the instance as a numpy compressed file (.npz), using the path and file name found in ves.Id.SavePath and ves.Id.SaveName. While it is highly recommended to stick to the default value for the SaveName, but you can easily modify the saving path if you want by specifying it using keyword argument Path.

    -
    -

    Creating, plotting and saving structural elements

    +
    +

    Creating, plotting and saving structural elements and configurations

    Unlike the vessel, which is important for physics reasons, the structural elements that ToFu allows to create are purely for illustrative purposes. They are entirely passive and have no effect whatsoever on the computation of the volume of sight of the detectors or on the plasma volume and are just made available for illustrations.

    -

    Like for a vessel, a structural element is mostly defined by a 2D polygon. If a vessel instance is provided, the type of the structural element (toroidal or linear) is automatically the same as the type of the vessel, otherwise the type must be specified. -For plotting, structural elements that enclose the entirety of a vessel are automatically transparent, and gray if they don’t.

    -
    >>> # Define two polygons, one that does not enclose the vessel and one that does
    +

    Like for a vessel, a structural element is mostly defined by a 2D polygon. If a vessel instance is provided, the type of the structural element (toroidal or linear) is automatically the same as the type of the vessel, otherwise the type must be specified.

    +

    A configuration, short for geometrical configuration is a set of vessel, and structural elements.

    +
    >>> # Define two polygons, one that does not enclose the vessel and one that does
     >>> thet = np.linspace(0.,2.*np.pi,100)
     >>> poly1 = [[2.5,3.5,3.5,2.5],[0.,0.,0.5,0.5]]
     >>> poly2 = [R0+1.5*np.cos(thet),1.5*np.sin(thet)]
    ->>> # Create the structural elements with the appropriate ToFu class, specifying the experiment and a shot number for keeping track of changes
    ->>> s1 = tfg.Struct('S1', poly1, Ves=ves, Exp='Misc', shot=0)
    ->>> s2 = tfg.Struct('S2', poly2, Ves=ves, Exp='Misc', shot=0)
    ->>> # Plot them on top of the vessel
    ->>> Lax = ves.plot(Elt='P')
    ->>> # Re-use the same list of axes to overlay the plots
    ->>> Lax = s1.plot(Lax=Lax)
    ->>> Lax = s2.plot(Lax=Lax)
    +>>> # Create the structural elements with the appropriate ToFu class, specifying the experiment and a shot number for keeping track of changes
    +>>> s1 = tfg.PFC(Name='S1', Poly=poly1, Exp='Misc', shot=0)
    +>>> # now we create a structure that is not continuous along phi
    +>>> s2 = tfg.PFC(Name='S2', Poly=poly2, Exp='Misc', shot=0, Lim=[[0., np.pi], [np.pi/2.,np.pi*3./2.]])
    +>>> # Creating a configuration with vessel and structures
    +>>> config = tf.geom.Config(Name="test", Exp="Misc", lStruct=[ves,s1,s2])
    +>>> config.set_colors_random() # to see different colors
    +>>> config.plot()
    +>>> config.save()
     
    -The created structural elements, plotted over the structural elements on both projections -

    The created structural elements, plotted over the structural elements on both projections

    +The created structural elements, plotted over the structural elements on both projections +

    The created structural elements, plotted over the structural elements on both projections

    It is not necessary for ToFu (since structural elements are used by no other objects) but for convenience you can save a structral element using the same save() method as for any other object.

    @@ -147,87 +138,66 @@

    Creating, plotting and saving structural elementsCreating apertures

    An aperture is also mosly defined by a planar polygon, except that the polygon coordinates should be provided in 3D cartesian coordinates (even though the polygon is planar, it mey not live in the same plane as other apertures or as the detector).

    We can easily define two different polygons for two different apertures

    -
    >>> # Define the planes in which they will live by a point (O) and a vector (n)
    +
    >>> # Define the planes in which they will live by a point (O) and a vector (n)
     >>> O1, n1 = (3.0,0.00,0.52), (-1.,0.1,-0.9)
     >>> O2, n2 = (2.9,0.01,0.48), (-1.,0.0,-1.0)
    ->>> # Compute local orthogonal basis vectors in the planes
    +>>> # Compute local orthogonal basis vectors in the planes
     >>> e11, e21 = np.cross(n1,(0.,0.,1.)), np.cross(n2,(0.,0.,1.))
     >>> e12, e22 = np.cross(e11,n1), np.cross(e21,n2)
    ->>> # Normalize
    +>>> # Normalize
     >>> e11, e12 = e11/np.linalg.norm(e11), e12/np.linalg.norm(e12)
     >>> e21, e22 = e21/np.linalg.norm(e21), e22/np.linalg.norm(e22)
    ->>> # Implement the planar polygons 2D coordinates
    +>>> # Implement the planar polygons 2D coordinates
     >>> p1_2D = 0.005*np.array([[-1.,1.,1.,-1],[-1.,-1.,1.,1.]])
     >>> p2_2D = 0.01*np.array([[-1.,1.,1.,-1],[-1.,-1.,1.,1.]])
    ->>> # Compute the 3D coordinates
    +>>> # Compute the 3D coordinates
     >>> p1 = [O1[0] + e11[0]*p1_2D[0,:] + e12[0]*p1_2D[1,:], O1[1] + e11[1]*p1_2D[0,:] + e12[1]*p1_2D[1,:], O1[2] + e11[2]*p1_2D[0,:] + e12[2]*p1_2D[1,:]]
     >>> p2 = [O2[0] + e21[0]*p2_2D[0,:] + e22[0]*p2_2D[1,:], O2[1] + e21[1]*p2_2D[0,:] + e22[1]*p2_2D[1,:], O2[2] + e21[2]*p2_2D[0,:] + e22[2]*p2_2D[1,:]]
    ->>> # Create the apertures, specifying also the diagnostic the apertures belong to
    ->>> a1 = tfg.Apert('A1', p1, Ves=ves, Exp='Misc', shot=0, Diag='misc')
    ->>> a2 = tfg.Apert('A2', p2, Ves=ves, Exp='Misc', shot=0, Diag='misc')
    ->>> # Plot them, both the polygon and the vector, with the associated vessel (using EltVes), in 3D
    ->>> Lax = a1.plot(Elt='PV', EltVes='P')
    ->>> Lax = a2.plot(Lax=Lax, Elt='PV')
    +>>> # Create the apertures, specifying also the diagnostic the apertures belong to
    +>>> a1 = tfg.Apert('A1', p1, Ves=ves, Exp='Misc', shot=0, Diag='misc')
    +>>> a2 = tfg.Apert('A2', p2, Ves=ves, Exp='Misc', shot=0, Diag='misc')
    +>>> # Plot them, both the polygon and the vector, with the associated vessel (using EltVes), in 3D
    +>>> Lax = a1.plot(Elt='PV', EltVes='P')
    +>>> Lax = a2.plot(Lax=Lax, Elt='PV')
     
    The created apertures, plotted over the vessel on both projections -

    The created apertures, plotted over the vessel on both projections

    +

    The created apertures, plotted over the vessel on both projections

    ToFu allows you to save the apertures, if you wish, but if you created then only to pass tem on to detectors, you can also skip saving them. Indeed, once the detector associated to these apertures is created, you will save the detector object instead, and ToFu will automatically store all information about the apertures (everything necessary to re-create them when loading the detector object).

    -
    -

    Creating, plotting and saving detectors objects

    -

    A detector object is defined in the same way as an aperture, except that it needs to know which optics it is associated to. The optics can be either a converging spherical lens or, as in this case, a list of apertures. -In the folloing we will thus create two detectors (re-using the same planes as for the apertures for simplicity, but they could lie in any plane).

    -
    >>> # Choose different reference points for the 2 planes
    ->>> Od1, Od2 = (3.05,0.00,0.54), (3.05,0.00,0.50)
    ->>> # Implement the planar polygons 2D coordinates
    ->>> pd1_2D = 0.005*np.array([[-1.,1.,1.,-1],[-1.,-1.,1.,1.]])
    ->>> pd2_2D = 0.005*np.array([[-1.,1.,1.,-1],[-1.,-1.,1.,1.]])
    ->>> # Compute the 3D coordinates
    ->>> pd1 = [Od1[0] + e11[0]*pd1_2D[0,:] + e12[0]*pd1_2D[1,:], Od1[1] + e11[1]*pd1_2D[0,:] + e12[1]*pd1_2D[1,:], Od1[2] + e11[2]*pd1_2D[0,:] + e12[2]*pd1_2D[1,:]]
    ->>> pd2 = [Od2[0] + e21[0]*pd2_2D[0,:] + e22[0]*pd2_2D[1,:], Od2[1] + e21[1]*pd2_2D[0,:] + e22[1]*pd2_2D[1,:], Od2[2] + e21[2]*pd2_2D[0,:] + e22[2]*pd2_2D[1,:]]
    ->>> # Create the detectors, specifying also the diagnostic and the Optics
    ->>> d1 = tfg.Detect('D1', pd1, Optics=[a1,a2], Ves=ves, Exp='Misc', shot=0, Diag='misc')
    ->>> d2 = tfg.Detect('D2', pd2, Optics=[a2], Ves=ves, Exp='Misc', shot=0, Diag='misc')
    +
    +

    Creating cameras

    +

    Creating 1D cameras

    +
    >>> cam1d = tf.geom.utils.create_CamLOS1D(config=config, P=[3.,0,-0.5], N12=100, F=0.1, D12=0.1, angs=[np.pi,0,0], Name='', Exp='Misc', Diag='')
    +>>> cam1d.plot()
    +>>> cam1d.plot_touch() # for an interactive plot (helpful to see each LOS)
     
    -

    The computation of the detectors may take a while (~3 min) because ToFu automatically computes the natural Line Of Sight (LOS) and its etendue, the Volume Of Sight (VOS), a pre-computed 3D grid of the VOS for faster computation of synthetic signal... -Some of these automatic computations can be de-activacted using the proper keyword arguments, or the resolution of the discretization can downgraded for faster computation (see Detect for details).

    -

    A Detect object is at the core of the added value of ToFu: all relevant quantities are automatically computed, and can be obtained and plotted via attributes and methods.

    -
    >>> # Plot the detectors, specifying we want not only the polygon but also the perpendicular vector and the viewing cone ('C'), as well as elements of the LOS, Optics and vessel
    ->>> Lax = d1.plot(Elt='PVC', EltOptics='P', EltLOS='L', EltVes='P')
    ->>> Lax = d2.plot(Lax=Lax, Elt='PVC', EltOptics='P', EltLOS='L')
    -
    +
    +Plot of a 1D Camera
    -
    -The created detectors, with associated apertures and vessel, on both projections -

    The created detectors, with associated apertures and vessel, on both projections

    +
    +Interactive plot of a 1D Camera
    -

    Using d1.save() would save detector 1 and all necessary info about its associated optics (i.e.:apertures) will also be included in the file so it is not necessary to save the apertures separately (unless you need to for something else). -Usually, tomography diagnostics do not have a few but many different detectors, grouped in cameras (often a group of detectors sharing a common aperture). -ToFu provides an GDetect object that allows you to group a list of detectors and treat them like a single object (each method is automatically applied to all the detectors included in the GDetect object).

    -
    -
    -

    Creating, plotting and saving GDetect objects

    -

    Once several Detect objects are created, they can be fed to a GDetect object to be handle as a single object.

    -
    >>> # Create the group of detectors by feeding a list of detectors
    ->>> gd = tfg.GDetect('GD', [d1,d2], Exp='Misc', shot=0)
    ->>> # Plot the group of detectors as a single set
    ->>> Lax = gd.plot(Elt='PVC', EltOptics='P', EltLOS='L', EltVes='P')
    +

    Creating 2D cameras. We are going to create a 2D camera with a slight rotation of the angles of sight to have a more tangential view of the tokamak and the structures.

    +
    >>> cam2 = tf.geom.utils.create_CamLOS2D(config=config, P=[3.,0,-0.5], N12=100, F=0.1, D12=0.1, angs=[np.pi,0.2,0], Name='', Exp='Misc', Diag='')
    +>>> cam2.plot_touch() # also interactive ! click on the left plot and see for yourself!
     
    -

    The last command yields the same result as the previous figure.

    -

    Congratulations ! You completed the basic tutorial for getting started and creating your own geometry, take you time now to explore all the methods and attributes of the classes introduced in tofu.geom.

    +
    +Interactive plot of a 2D Camera +
    +

    Congratulations ! You completed the basic tutorial for getting started and creating your own geometry, take you time now to explore all the methods and attributes of the classes introduced in tofu.geom.

    @@ -238,14 +208,13 @@

    Indices and tables @@ -281,12 +250,12 @@

    Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/Tutorial_Geom_SynthDiag_Basic.html b/doc/build/html/Tutorial_Geom_SynthDiag_Basic.html index 7f9f28e32..75a60d81f 100644 --- a/doc/build/html/Tutorial_Geom_SynthDiag_Basic.html +++ b/doc/build/html/Tutorial_Geom_SynthDiag_Basic.html @@ -1,32 +1,22 @@ - + - - - How to compute integrated signal from synthetic emissivity — tofu v1.1 - + + How to compute integrated signal from synthetic emissivity — tofu v1.1 - + - - - - + + + + + @@ -47,63 +37,61 @@

    Navigation

    How to compute integrated signal from synthetic emissivity

    -

    We are assuming here that you have access to an existing geometry (i.e. to Detect or GDetect objects that you or someone else created or that you can load). +

    We are assuming here that you have access to an existing geometry (i.e. to Detect or GDetect objects that you or someone else created or that you can load). It if is not the case you should first create the geometry you need, by following the basic geometry tutorial.

    We are also assuming that you have a code that can produce as output a simulated isotropic emissivity. Either directly or by spacial interpolation, you should be able to write a python function that computes an emissivity value in any arbitrary point inside the vessel volume.

    As a prerequisite load the necessary modules:

    -
    >>> import numpy as np
    +
    >>> import numpy as np
     >>> import matplotlib.pyplot as plt
     >>> plt.ion()
    ->>> # tofu-specific
    +>>> # tofu-specific
     >>> import tofu.pathfile as tfpf
     

    Writing the input function

    -

    In the following, all is done assuming gd is a GDetect object, but the same would apply if it is just a Detect object. -If the GDetect object you want to use is not already existing in your session, you can load it (with its absolute path and file name) using the tofu.pathfile.Open() function or a dedicated plugin function.

    -

    Instances of GDetect have a method called calc_Sig(), which takes as input ff a python function able to evaluate the emissivity value in any number of points provided in 3D cartesian coordinates.

    -
    -
    This function should obey the following constraints:
    -
      -
    • It is a callable with one input argument and optionally keyword arguments
    • -
    • The input argument is a (3,N) numpy.ndarray, where N is the number of points at which one wants to evaluate the emissivity, provided in 3D cartesian coordinates (X,Y,Z)
    • +

      In the following, all is done assuming gd is a GDetect object, but the same would apply if it is just a Detect object. +If the GDetect object you want to use is not already existing in your session, you can load it (with its absolute path and file name) using the tofu.pathfile.Open() function or a dedicated plugin function.

      +

      Instances of GDetect have a method called calc_Sig(), which takes as input ff a python function able to evaluate the emissivity value in any number of points provided in 3D cartesian coordinates.

      +
      +
      This function should obey the following constraints:
        +
      • It is a callable with one input argument and optionally keyword arguments

      • +
      • The input argument is a (3,N) numpy.ndarray, where N is the number of points at which one wants to evaluate the emissivity, provided in 3D cartesian coordinates (X,Y,Z)

      Hence, suppose that we simulate a 2D (i.e.: invariant along the 3rd dimension) gaussian emissivity centered on point (2.,0.), we can define ff as

      -
      >>> def ff(Pts, A=1., DR=1., DZ=1.):
      +
      >>> def ff(Pts, A=1., DR=1., DZ=1.):
       >>>     R = np.hypot(Pts[0,:],Pts[1,:])
       >>>     Z = Pts[2,:]
       >>>     Emiss = A*np.exp(-(R-2.)**2/DR**2 - (Z-0.)**2/DZ**2)
       >>>     return Emiss
       
      -
      -
      What will happen when we feed ff to calc_Sig() depends on the choice of method for the integration:
      -
        -
      • If we want a volumic integration, the VOS of each detector will be discretized and ff will be called to evaluate the emissivity at each point before perfoming the integration
      • -
      • If a Line Of Sight integration is desired, only the LOS is discretized for integration and the result is multiplied by the etendue
      • +
        +
        What will happen when we feed ff to calc_Sig() depends on the choice of method for the integration:
          +
        • If we want a volumic integration, the VOS of each detector will be discretized and ff will be called to evaluate the emissivity at each point before perfoming the integration

        • +
        • If a Line Of Sight integration is desired, only the LOS is discretized for integration and the result is multiplied by the etendue

        By default, the method uses a pre-computed discretization of the VOS (because re-computing the solid angle for each point every time is costly), but this feature can be suppressed by setting PreComp=False if you want to use customized integration parameters. For example, in both cases, the numerical integration can be done by choosing the resolution of the discretization, or by using an iterative algorithm that only stops when the required relative error on the integral value is reached. In our case:

        -
        >>> # Compute synthetic signal using a volume approach with resolution-fixed numerical integration method
        ->>> sigVOS, ldet = gd.calc_Sig(ff, extargs={'A':1.,'DR':1.,'DZ':1.}, Method='Vol', Mode='simps', PreComp=False)
        ->>> sigLOS, ldet = gd.calc_Sig(ff, extargs={'A':1.}, Method='LOS', Mode='quad', PreComp=False)
        +
        >>> # Compute synthetic signal using a volume approach with resolution-fixed numerical integration method
        +>>> sigVOS, ldet = gd.calc_Sig(ff, extargs={'A':1.,'DR':1.,'DZ':1.}, Method='Vol', Mode='simps', PreComp=False)
        +>>> sigLOS, ldet = gd.calc_Sig(ff, extargs={'A':1.}, Method='LOS', Mode='quad', PreComp=False)
         >>> print sigVOS, sigLOS
         [[  1.31675917e-06   1.40620027e-06]] [[  1.31408026e-06   1.39941326e-06]]
         
        -

        Notice that when using the ‘quad’ numerical integration method, only one extra argument can be passed on to ff. +

        Notice that when using the ‘quad’ numerical integration method, only one extra argument can be passed on to ff. Notice the small differences in the volume and LOS approaches, due to the small non-zero second derivative of the emissivity field and to boundary effects (where there is small partial obstruction of the VOS).

        If your code gives a tabulated emissivity field

        Then you simply have to include an intermediate function that interpolates your emissivity field to compute it at any point. Like in the following example:

        -
        >>> def ff(Pts):
        +
        >>> def ff(Pts):
         >>>     R = np.hypot(Pts[0,:],Pts[1,:])
         >>>     Z = Pts[2,:]
         >>>     Emiss = ff_interp(R,Z)
        @@ -114,16 +102,16 @@ 

        If your code gives a tabulated emissivity field

        Plotting the result

        -

        The plot_Sig() method provides a way of plotting the result, either by feeding it the output signal of calc_Sig() or directly ff (in which case it simply calls plot_Sig() for you). -This feature is only available for GDetect objects since the signal of a single detector is just a single value that does not really require plotting...

        +

        The plot_Sig() method provides a way of plotting the result, either by feeding it the output signal of calc_Sig() or directly ff (in which case it simply calls plot_Sig() for you). +This feature is only available for GDetect objects since the signal of a single detector is just a single value that does not really require plotting…

        @@ -134,7 +122,7 @@

        Indices and tables
        -

        Table Of Contents

        +

        Table of Contents

        @@ -175,12 +163,12 @@

        Navigation

      • modules |
      • - +
      \ No newline at end of file diff --git a/doc/build/html/Tutorial_ITER.html b/doc/build/html/Tutorial_ITER.html index c8f0f0cb4..2409529b1 100644 --- a/doc/build/html/Tutorial_ITER.html +++ b/doc/build/html/Tutorial_ITER.html @@ -1,32 +1,22 @@ - + - - - ITER-specific tutorial — tofu v1.1 - + + ITER-specific tutorial — tofu v1.1 - + - - - - + + + + + @@ -51,37 +41,37 @@

      ITER-specific tutorialHow to access the ToFu library

      The plugin for ITER is hosted on the theory (Tok) clusters of the Max-Planck Institute for Plasma Physics (IPP) in Garching. If you have an account in IPP, you can then connect to one of the tok clusters where the library is hosted, via the command:

      -
      >>> ssh toki01
      +
      >>> ssh toki01
       

      Enter your password and then you need to load the module in the terminal

      -
      >>> module load tofu
      +
      >>> module load tofu
       

      You may need to load other modules on which ToFu depends (see the dependencies).

      You can then start a ipython console and load the AUG plugin for ToFu:

      -
      >>> import tofu.plugins.ITER as tfITER
      +
      >>> import tofu.plugins.ITER as tfITER
       

      How to load existing geometry

      You can now load the geometry that was already computed and stored for some diagnostics (only the Soft X-Ray diagnostic at this date). -In general loading the geometry means using a method of the plugin that will load and return a list of tofu.geom.GDetect instances. -On AUG, each tofu.geom.GDetect instance corresponds to a camera head. -Since the geometry (position, aperture size...) of each camera head may change in time (changes are sometimes implemented between experimental campaigns), you can specify a shot number and the plugin will return the latest geometry that was computed before that shot number (only a few have been computed so far, but more will come).

      -
      >>> LGD = tfAUG.SXR.geom.load(shot=31801)
      +In general loading the geometry means using a method of the plugin that will load and return a list of tofu.geom.GDetect instances.
      +On AUG, each tofu.geom.GDetect instance corresponds to a camera head.
      +Since the geometry (position, aperture size…) of each camera head may change in time (changes are sometimes implemented between experimental campaigns), you can specify a shot number and the plugin will return the latest geometry that was computed before that shot number (only a few have been computed so far, but more will come).

      +
      >>> LGD = tfAUG.SXR.geom.load(shot=31801)
       
      -

      This command returns a list of tofu.geom.GDetect instances with the latest geometry computed before shot 31801.

      +

      This command returns a list of tofu.geom.GDetect instances with the latest geometry computed before shot 31801.

      @@ -92,7 +82,7 @@

      Indices and tables
      -

      Table Of Contents

      +

      Table of Contents

      @@ -132,12 +122,12 @@

      Navigation

    • modules |
    • - +
    \ No newline at end of file diff --git a/doc/build/html/Versions.html b/doc/build/html/Versions.html index 59bee1393..ae7f306a0 100644 --- a/doc/build/html/Versions.html +++ b/doc/build/html/Versions.html @@ -1,32 +1,22 @@ - + - - - Versions of ToFu: — tofu v1.1 - + + Versions of ToFu: — tofu v1.1 - + - - - - + + + + + @@ -50,10 +40,9 @@

    Versions of ToFu:semantic versioning and the module metadata is implemented according to PEP426.

    The following only lists the versions advanced enough for release:

    -
      -
    • -
      1.1.0 (default)
      -

      This is the first version released in open-source, it only includes the geometry module (for diagnostic designing and synthetic diagnostic) and the pre-treatment module (for data handling)

      +

    @@ -75,7 +64,7 @@

    Indices and tables
    -

    Table Of Contents

    +

    Table of Contents

    @@ -113,12 +102,12 @@

    Navigation

  • modules |
  • - +
    \ No newline at end of file diff --git a/doc/build/html/_images/cam1d_plot.png b/doc/build/html/_images/cam1d_plot.png new file mode 100644 index 000000000..6a32fad6e Binary files /dev/null and b/doc/build/html/_images/cam1d_plot.png differ diff --git a/doc/build/html/_images/cam1d_plot_touch.png b/doc/build/html/_images/cam1d_plot_touch.png new file mode 100644 index 000000000..c8a4c375b Binary files /dev/null and b/doc/build/html/_images/cam1d_plot_touch.png differ diff --git a/doc/build/html/_images/cam2d_plot_touch.png b/doc/build/html/_images/cam2d_plot_touch.png new file mode 100644 index 000000000..4ac8635bb Binary files /dev/null and b/doc/build/html/_images/cam2d_plot_touch.png differ diff --git a/doc/build/html/_images/config_plot.png b/doc/build/html/_images/config_plot.png new file mode 100644 index 000000000..9480f8698 Binary files /dev/null and b/doc/build/html/_images/config_plot.png differ diff --git a/doc/build/html/_modules/index.html b/doc/build/html/_modules/index.html index a069b46ad..7e420bd1c 100644 --- a/doc/build/html/_modules/index.html +++ b/doc/build/html/_modules/index.html @@ -1,32 +1,22 @@ - + - - - Overview: module code — tofu v1.1 - + + Overview: module code — tofu v1.1 - + - - - - + + + + + @@ -46,15 +36,7 @@

    Navigation

    @@ -63,13 +45,13 @@

    All modules for which code is available

    \ No newline at end of file diff --git a/doc/build/html/_modules/tofu/pathfile.html b/doc/build/html/_modules/tofu/pathfile.html index fd6d62b43..cad8f8521 100644 --- a/doc/build/html/_modules/tofu/pathfile.html +++ b/doc/build/html/_modules/tofu/pathfile.html @@ -1,33 +1,22 @@ - + - - - tofu.pathfile — tofu v1.1 - + + tofu.pathfile — tofu v1.1 - + - - - - - + + + + + @@ -48,30 +37,41 @@

    Navigation

    Source code for tofu.pathfile

    -# -*- coding: utf-8 -*-
    +# -*- coding: utf-8 -*-
     """
     Created on Wed Jul 30 14:37:31 2014
     
     @author: didiervezinet
     """
    -
    -import os                   # For accessing cuurent working direcVesy
    -import cPickle as pck       # For saving / loading objects
    -import numpy as np
    -import datetime as dtm
    +# Built-in
    +import os                   # For accessing cuurent working direcVesy
    +import subprocess
     import getpass
     import inspect
     import warnings
     
    -# ToFu specific
    -from tofu.defaults import dtmFormat as TFDdtmFormat
    -
    -
    -__author__ = "Didier Vezinet"
    -__all__ = ["Find_Rootpath","get_DefaultPaths","get_Default_dtimeFmt","_get_PathFileExt_FromName","convert_units","get_PolyFromPolyFileObj",
    -           "ID",
    -           "CheckSameObj","Save_Generic","Open"]
    +# Common
    +import numpy as np
    +import datetime as dtm
     
    +# ToFu specific
    +from tofu import __version__
    +
    +__author__ = "Didier Vezinet"
    +__all__ = ["ID",
    +           "SaveName_Conv","CheckSameObj","SelectFromListId",
    +           "get_InfoFromFileName","get_FileFromInfos",
    +           "convert_units","get_PolyFromPolyFileObj",
    +           "Save_Generic","Open"]
    +
    +dModes = {'geom':'TFG', 'data':'TFD'}
    +lCls = ['Ves','Struct',
    +        'Rays','LOS','LOSCam1D','LOSCam2D',
    +        'GDetect','Detect','Cam1D','Cam2D',
    +        'Data']
    +dPref = {'Exp':'Exp','Diag':'Dg','shot':'sh','Deg':'Deg',
    +         'version':'Vers','usr':'U'}
    +defInclude = ['Mod','Cls','Type','Exp','Deg','Diag','Name','shot']
     
     """
     ###############################################################################
    @@ -82,93 +82,14 @@ 

    Source code for tofu.pathfile

     ###############################################################################
     """
     
    -
    -
    [docs]def Find_Rootpath(Path=os.getcwd(),substr='/tofu'): - """ - Return the absolute path of the root directory of ToFu, searching for a pattern in the provided input path - - Parameters - ---------- - Path : str - An absolute path in which a pattern is to be looked for - substr : str - The pattern to look for - - Returns - ------- - root : str - The absolute path containing the pattern - - """ - indstr = Path.find(substr) - if indstr==-1: - substr = substr.lower() - indstr = Path.find(substr) - root = Path[:indstr] + substr - return root
    - - - -
    [docs]def get_DefaultPaths(RootPath=None, Plugin=None, lSubs=[], PathInp=None, PathObj=None, PathOut=None): - """ - Return the default paths for input loading, object and output saving depending on the root path used - """ - assert RootPath is None or type(RootPath) is str, "Arg RootPath must be a str !" - assert Plugin is None or type(Plugin) is str, "Arg Plugin must be a str !" - assert all([ss is None or type(ss) is str for ss in [PathInp, PathObj, PathOut]]), "Args PathInp, PathObj, PathOut must be None or str !" - assert type(lSubs) is list and all([type(ss) is str for ss in lSubs]) - - if RootPath is None: - RootPath = Find_Rootpath() - for pp, ss in [(PathInp,'Inputs'), (PathObj,'Objects'), (PathOut,'Outputs')]: - if pp is None: - pp = str(RootPath) - if not Plugin is None: - pp = pp + '/' + Plugin - for sub in lSubs: - pp = pp + '/' + sub - pp = pp + '/' + ss - - return PathInp+'/', PathObj+'/', PathOut+'/'
    - - -
    [docs]def get_Default_dtimeFmt(dtime=None, dtFormat=TFDdtmFormat): - """ - Return the default datetime value and format - """ - if dtime is None: - dtime = dtm.datetime.now() - elif type(dtime) is str: - dtime = dtm.strptime(dtime,dtFormat) - return dtime, dtFormat
    - - -def _get_PathFileExt_FromName(Name=None, Path=os.getcwd(), Lstr=[]): # Used in tofu.plugin.ITER.Ves.create() - """ Retrieve PathFileExt from a Name, in Path if absolute path not specified in Name, with possible TFMod and ext options """ - if not Name is None and '/' in Name: - PathFileExt = Name - else: - LF = os.listdir(Path) - if type(Name) is str: - Lstr.append(Name) - elif type(Name) is list: - Lstr = Lstr+Name - if not Lstr==[]: - LF = [ff for ff in LF if all([ss in ff for ss in Lstr])] - assert len(LF)==1, "Several or no possibility for "+str(Name)+" in "+Path+" with "+str(Lstr)+" LF = "+str(LF) - PathFileExt = Path + LF[0] - return PathFileExt - - - def _set_arrayorder(obj, arrayorder): - assert arrayorder in ['C','F'], "Arg arrayorder must be in ['C','F']" + assert arrayorder in ['C','F'], "Arg arrayorder must be in ['C','F']" Lattr = dir(obj) for aa in Lattr: bb = getattr(obj,aa) if type(bb) is np.array and bb.ndim>1: try: - if arrayorder=='C': + if arrayorder=='C': setattr(obj,aa,np.ascontiguousarray(bb)) else: setattr(obj,aa,np.asfortranarray(bb)) @@ -177,18 +98,18 @@

    Source code for tofu.pathfile

         obj._arrayorder = arrayorder
     
     
    -
    [docs]def convert_units(P, In='cm', Out='m'): +
    [docs]def convert_units(P, In='cm', Out='m'): """ Quickly convert distance units between meters, centimeters and millimeters """ - c = {'m':{'mm':1000.,'cm':100.,'m':1.}, - 'cm':{'mm':10.,'cm':1.,'m':0.01}, - 'mm':{'mm':1.,'cm':0.1,'m':0.001}} + c = {'m':{'mm':1000.,'cm':100.,'m':1.}, + 'cm':{'mm':10.,'cm':1.,'m':0.01}, + 'mm':{'mm':1.,'cm':0.1,'m':0.001}} return c[In][Out]*P
    -
    [docs]def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2): +
    [docs]def get_PolyFromPolyFileObj(PolyFileObj, SavePathInp=None, units='m', comments='#', skiprows=0, shape0=2): """ Return a polygon as a np.ndarray, extracted from a txt file or from a ToFu object, with appropriate units Useful for :meth:`tofu.plugins.AUG.Ves._create()` @@ -219,23 +140,23 @@

    Source code for tofu.pathfile

             Dictionaryb containing information on the origin of the polygon, for the record (e.g.: the name and absolute path of the file from which it was extracted)
     
         """
    -    assert type(PolyFileObj) in [list,str] or hasattr(PolyFileObj,"Poly") or np.asarray(PolyFileObj).ndim==2, "Arg PolyFileObj must be str (PathFileExt), a ToFu object with attribute Poly or an iterable convertible to 2d np.ndarray !"
    +    assert type(PolyFileObj) in [list,str] or hasattr(PolyFileObj,"Poly") or np.asarray(PolyFileObj).ndim==2, "Arg PolyFileObj must be str (PathFileExt), a ToFu object with attribute Poly or an iterable convertible to 2d np.ndarray !"
     
    -    # Load PolyFileObj if file and check shape
    +    # Load PolyFileObj if file and check shape
         addInfo = {}
         if type(PolyFileObj) in [list,str]:
    -        PathFileExt = _get_PathFileExt_FromName(PolyFileObj, Path=SavePathInp, Lstr=[])
    -        # Include PathFileExt in ID for tracability
    -        addInfo = {'Input':PathFileExt}
    -        PolyFileObj = np.loadtxt(PathFileExt, dtype=float, comments=comments, delimiter=None, converters=None, skiprows=skiprows, usecols=None, unpack=False, ndmin=2)
    -    elif hasattr(PolyFileObj,"Poly"):
    -        addInfo = {'Input':PolyFileObj.Id.SaveName}
    +        PathFileExt = get_FileFromInfos(Path=SavePathInp, Name=PolyFileObj)
    +        # Include PathFileExt in ID for tracability
    +        addInfo = {'Input':PathFileExt}
    +        PolyFileObj = np.loadtxt(PathFileExt, dtype=float, comments=comments, delimiter=None, converters=None, skiprows=skiprows, usecols=None, unpack=False, ndmin=2)
    +    elif hasattr(PolyFileObj,"Poly"):
    +        addInfo = {'Input':PolyFileObj.Id.SaveName}
             PolyFileObj = PolyFileObj.Poly
     
         Poly = np.asarray(PolyFileObj)
    -    assert Poly.ndim==2 and 2 in Poly.shape and max(Poly.shape)>=3 and not np.any(np.isnan(Poly)), "Arg np.asarray(PolyFileObj) must be a (2,N) or (N,2) np.ndarray with non NaNs !"
    +    assert Poly.ndim==2 and shape0 in Poly.shape and max(Poly.shape)>=3 and not np.any(np.isnan(Poly)), "Arg np.asarray(PolyFileObj) must be a (2,N) or (N,2) np.ndarray with non NaNs !"
         Poly = Poly if Poly.shape[0]==shape0 else Poly.T
    -    Poly = convert_units(Poly, In=units, Out='m')
    +    Poly = convert_units(Poly, In=units, Out='m')
         return Poly, addInfo
    @@ -252,15 +173,16 @@

    Source code for tofu.pathfile

     ###############################################################################
     """
     
    -
    +# Deprecated ???
     def _check_NotNone(Dict):
         for aa in Dict.keys():
    -        assert not Dict[aa] is None, "Arg "+aa+" must not be None !"
    +        assert not Dict[aa] is None, "Arg "+aa+" must not be None !"
     
     
    +# Deprecated ???
     def _get_FromItself(obj, Dict):
         for aa in Dict.keys():
    -        if Dict[aa] is None:
    +        if Dict[aa] is None:
                 try:
                     Dict[aa] = getattr(obj,aa)
                 except:
    @@ -269,7 +191,6 @@ 

    Source code for tofu.pathfile

     
     
     
    -
     """
     ###############################################################################
     ###############################################################################
    @@ -279,204 +200,228 @@ 

    Source code for tofu.pathfile

     ###############################################################################
     """
     
    -
    +# Deprecated ????
     
    [docs]class ID(object): - """ A class used by all ToFu objects as an attribute, storing all relevant data for the identification of created instances and providing default path and names for saving objects + """ A class used by all ToFu objects as an attribute - Each detector created in ToFu should be identifiable thanks to user-friendly criteria, like its name, the diagnostic and experiment it is attached to, the shot number from from it was physically installed on the experiement... - Users can also freely add some information they consider relevant, such as some characteristics of the detector (size, manufacturer, date of last calibration...) + It stores all relevant data for the identification of instances + Stored info can be the name of the instance, the experiment and diagnostics + it belongs to, or other user-defined info + Also provides default names for saving the instances Parameters ---------- Cls : str - Flag indicating which class is the object fro which the ID instance is being created, available class flags are: - - From :mod:`tofu.geom`: 'Ves', 'Struct', 'LOS', 'GLOS', 'Apert', 'Lens', 'Detect' and 'GDetect' - - From :mod:`tofu.mesh`: 'Mesh1D', 'Mesh2D', 'LBF1D' and 'LBF2D' (to be finished) - - From :mod:`tofu.`: (to be completed) + Class of the object on which info should be stored: Name : str - Name to be assigned to the created instance, should be a str without ' ' or '_' (spaces and underscores will be automatically removed if present) + Name of the instance (user-defined) + Should be a str without space ' ' or underscore '_' + (automatically removed if present) Type : None / str - If provided (necessary for some objects, but not for all), specifies the Type of object (i.e.: 'Tor' or 'Lin' for a Ves instance) + Type of object (i.e.: 'Tor' or 'Lin' for a :class:`~tofu.geom.Ves`) Deg : None / int - If provided (necessary only for objects of class 'LBF1D' and 'LBF2D'), specifies the degree of the b-splines constituting the :mod:`tofu.mesh` object + Degree of the b-splines constituting the :mod:`tofu.mesh` object Exp : None / str - A short 3-4 letters max flag specifying the experiment to which the created instance belongs (e.g.: 'AUG', 'ITER', 'TCV', 'JET'...) + Flag specifying the experiment (e.g.: 'WEST', 'AUG', 'ITER', 'JET'...) Diag : None / str - A short flag indicating which diagnostic the the created instance belongs to (e.g.: 'SXR', 'HXR', 'Bolo'...) + Flag indicating the diagnostic (e.g.: 'SXR', 'HXR', 'Bolo'...) shot : None / int - A shot number from which the created instance can be considered valid (useful for tracking geometry changes in the case of Ves and Detect objects) + A shot number from which the instance is valid (for tracking changes) SaveName : None / str - If provided, overrides the automatically generated name for saving the created instance (not recommended) + Overrides the default file name for saving (not recommended) SavePath : None / str - If provided, overrides the automatically generated path for saving the created instance + Absolute path where the instance should be saved USRdict : None / dict - If provided, a user-defined dictionary containing information about the instance considered relevant (e.g.: thickness of the diode, date of installation...) + A user-defined dictionary containing information about the instance + All info considered relevant can be passed here + (e.g.: thickness of the diode, date of installation...) LObj : None / dict / list - If provided, either + Either: - list: list of other ID instances of objects on which the created object depends (this list will then be sorted by class and formatted into a dictionary storign key attributes) - dict: a ready-made such dictionary - dtime : None / dtm.datetime - If provided, a time reference to be used to identify this particular instance (used for debugging mostly) - dtFormat : None / str - If provided, the format in which dtime should be written in the automatically generated saving name for the created instance - dtimeIn : bool - Flag indicating whether the dtm.datetime should be included in the automatically generated saving name for the created instance - - Returns - ------- - Id ID instance - The created ID instance, with all necessary computed attributes and methods """ - def __init__(self, Cls, Name, Type=None, Deg=None, Exp=None, Diag=None, shot=None, SaveName=None, SavePath=None, USRdict=None, LObj=None, dtime=None, dtFormat=TFDdtmFormat, dtimeIn=False): - assert type(Exp) is str, "Arg Exp must be a str !" - assert type(Cls) is str, "Arg Cls must be a str !" - assert shot is None or type(shot) is int, "Arg shot must be a int !" - assert Diag is None or type(Diag) is str, "Arg Diag must be a str !" - assert Type is None or type(Type) is str, "Arg Type must be a str !" - - self._Exp = Exp - self._Cls = Cls - self._Type = Type - self._Deg = Deg - self._Diag = Diag - self._shot = shot - self._set_dtime(dtime=dtime, dtFormat=dtFormat, dtimeIn=dtimeIn) - self.set_Name(Name, SaveName=SaveName) - self.set_SavePath(SavePath=SavePath) - self._LObj = {} - self.set_LObj(LObj) - self.set_USRdict(USRdict) + def __init__(self, Cls=None, Name=None, Type=None, Deg=None, + Exp=None, Diag=None, shot=None, SaveName=None, + SavePath=os.path.abspath('./'), + USRdict={}, LObj=None, fromdict=None, + Include=defInclude): + + if fromdict is None: + assert Cls is not None + assert Name is not None + self._check_inputs(Cls=Cls, Name=Name, Type=Type, Deg=Deg, + Exp=Exp, Diag=Diag, shot=shot, SaveName=SaveName, + SavePath=SavePath, USRdict=USRdict, + Include=Include) + + # Try to get the user name + self._version = __version__ + try: + self._usr = getpass.getuser() + except: + self._usr = None - def _set_dtime(self,dtime=None, dtFormat=TFDdtmFormat, dtimeIn=False): - assert dtime is None or isinstance(dtime,dtm.datetime), "Arg dtime must be a dtm.datetime instance !" - if dtime is None: - dtime = dtm.datetime.now() - self._dtime = dtime - self._dtFormat = dtFormat - self._dtimeIn = dtimeIn + # Set fixed attributes + self._Mod, self._Cls = _extract_ModClsFrom_class(Cls) + self._Type, self._SavePath = Type, SavePath + self._Exp, self._Diag, self._shot = Exp, Diag, shot + self._Deg = Deg -
    [docs] def set_Name(self, Name, SaveName=None, dtimeIn=None): - """ Set the Name of the created instance, automatically updating the SaveName + # Set variable attributes + self.set_Name(Name, SaveName=SaveName, Include=Include) - When the name is changed (reminding it should not include space (' ') or underscore ('_') characters), the name used for saving the object is automatically changed + self._LObj = {} + self.set_LObj(LObj) + self.set_USRdict(USRdict) + else: + self._fromdict(fromdict) + + def _fromdict(self, fd): + self._check_inputs(fromdict=fd) + # Set fixed attributes + self._Mod, self._Cls, self._Type = fd['Mod'], fd['Cls'], fd['Type'] + self._Exp, self._Diag, self._shot = fd['Exp'], fd['Diag'], fd['shot'] + self._Deg, self._SavePath = fd['Deg'], fd['SavePath'] + self._version, self._usr = fd['version'], fd['usr'] + self._USRdict = fd['USRdict'] + self._LObj = fd['LObj'] + # Set variable attributes + self._Name, self._SaveName = fd['Name'], fd['SaveName'] + # Check the original tofu version against the current version + if not self._version==__version__: + Str = self._Name+" was created from a different ToFu version !\n" + Str += "original : %s\n"%self._version + Str += "current : %s"%__version__ + warnings.warn(Str) + + def _todict(self): + d = {'Mod':self._Mod, 'Cls':self.Cls, 'Type':self.Type, + 'Name':self.Name, 'SaveName':self.SaveName, + 'SavePath':self.SavePath, 'Exp':self.Exp, 'Diag':self.Diag, + 'shot':self.shot, 'Deg':self._Deg, 'version':self._version, + 'usr':self._usr, 'USRdict':self.USRdict, 'LObj':self.LObj} + return d + + def _check_inputs(self, Cls=None, Name=None, Type=None, Deg=None, + Exp=None, Diag=None, shot=None, SaveName=None, + SavePath=None, USRdict=None, LObj=None, version=None, + usr=None, fromdict=None, Include=None): + _ID_check_inputs(Cls=Cls, Name=Name, Type=Type, Deg=Deg, Exp=Exp, + Diag=Diag, shot=shot, SaveName=SaveName, + SavePath=SavePath, USRdict=USRdict, LObj=LObj, + version=version, usr=usr, fromdict=fromdict, + Include=Include) + +
    [docs] def set_Name(self, Name, SaveName=None, + Include=defInclude, + ForceUpdate=False): + """ Set the Name of the instance, automatically updating the SaveName + + The name should be a str without spaces or underscores (removed) + When the name is changed, if SaveName (i.e. the name used for saving) + was not user-defined, it is automatically updated Parameters ---------- Name : str - Name to be assigned to the created instance, should be a str without ' ' or '_' (spaces and underscores will be automatically removed if present) + Name of the instance, without ' ' or '_' (automatically removed) SaveName : None / str - If provided, overrides the automatically generated name for saving the created instance (not recommended) - dtimeIn : None / bool - If provided, modifies the value of dtimeIn provided upon creation of the ID object + If provided, overrides the default name for saving (not recommended) + Include: list + Controls how te default SaveName is generated + Each element of the list is a key str indicating whether an element + should be present in the SaveName """ - assert type(Name) is str, "ID.Name must be assigned to a str !" + self._check_inputs(Name=Name, SaveName=SaveName, Include=Include) self._Name = Name - self.set_SaveName(SaveName=SaveName, dtimeIn=dtimeIn)
    + self.set_SaveName(SaveName=SaveName, Include=Include, + ForceUpdate=ForceUpdate)
    -
    [docs] def set_SaveName(self,SaveName=None, dtimeIn=None): - """ Enables either to automatically compute a ToFu-consistent saving name for the created instance, or to override that default saving name with the user-provided SaveName +
    [docs] def set_SaveName(self,SaveName=None, + Include=defInclude, + ForceUpdate=False): + """ Set the name for saving the instance (SaveName) - When creating an object of any class, an ID object is assigned to it that automatically computes a saving name in case the user wants to save the object. - This automatically generated saving name includes not only the name given to the instance but also useful classifying info such as the class of the object, its Type, experiment, diagnostic... - It is not recommended to override this automatically generated saving name (because some routines rely on it for fast identification of saved files), but it is made possible for flexibility. + SaveName can be either: + - provided by the user (no constraint) - not recommended + - automatically generated from Name and key attributes (cf. Include) Parameters ---------- - SaveName : None / str - If provided, a str that overrides the automatically generated saving name - dtimeIn : None / bool - If provided, modifies the value of dtimeIn provided upon creation of the ID object - + SaveName : None / str + If provided, overrides the default name for saving (not recommended) + Include : list + Controls how te default SaveName is generated + Each element of the list is a key str indicating whether an element + should be present in the SaveName + ForceUpdate : bool + Flag indicating the behaviour when SaveName=None: + - True : A new SaveName is generated, overriding the old one + - False : The former SaveName is preserved (default) """ - assert SaveName is None or type(SaveName) is str, "ID.SaveName must be assigned to a str !" - dtimeIn = self._dtimeIn if dtimeIn is None else dtimeIn - if SaveName is None: - self._SaveName = SaveName_Conv(self._Exp, self.Cls, self._Type, self._Deg, self._Diag, self._Name, shot=self._shot, dtime=self._dtime, Format=self._dtFormat, dtimeIn=dtimeIn) + self._check_inputs(SaveName=SaveName, Include=Include) + if not hasattr(self,'_SaveName_usr'): + self._SaveName_usr = (SaveName is not None) + # If SaveName provided by user, override + if SaveName is not None: + self._SaveName = SaveName + self._SaveName_usr = True else: - self._SaveName = SaveName
    - -
    [docs] def set_SavePath(self,SavePath=None): - """ Enables to automatically generate a saving path for the created object, or to override that default path with the user-provided SavePath - - Similarily to SaveName, ToFu automatically generates a saving path for any created object. - This saving path can be overriden if desired. - This is less crucial than SaveName, changing the SavePath has little consequences as long as you remember what you are doing. + # Don't update if former is user-defined and ForceUpdate is False + # Override if previous was: + # automatic or (user-defined but ForceUpdate is True) + if (not self._SaveName_usr) or (self._SaveName_usr and ForceUpdate): + SN = SaveName_Conv(Mod=self._Mod, Cls=self.Cls, Type=self.Type, + Name=self.Name, Deg=self._Deg, Exp=self.Exp, + Diag=self.Diag, shot=self.shot, + version=self._version, usr=self._usr, + Include=Include) + self._SaveName = SN + self._SaveName_usr = False
    + +
    [docs] def set_LObj(self,LObj=None): + """ Set the LObj attribute, storing objects the instance depends on + + For example: + A Detect object depends on a vessel and some apertures + That link between should be stored somewhere (for saving/loading). + LObj does this: it stores the ID (as dict) of all objects depended on. Parameters ---------- - SavePath : None / str - If provided, a str that overrides the automatically generated saving path + LObj : None / dict / :class:`~tofu.pathfile.ID` / list of such + Provide either: + - A dict (derived from :meth:`~tofu.pathfile.ID._todict`) + - A :class:`~tofu.pathfile.ID` instance + - A list of dict or :class:`~tofu.pathfile.ID` instances """ - assert SavePath is None or type(SavePath) is str, "ID.SavePath must be assigned to a str !" - if SavePath is None: - SavePath = Find_Rootpath()+'/Objects_'+self.Exp+'/' if not self.Cls in ['PreData','Sol2D'] else Find_Rootpath()+'/Outputs_'+self.Exp+'/' - self._SavePath = SavePath.replace('//','/')
    + self._LObj = {} + if LObj is not None: + if type(LObj) is not list: + LObj = [LObj] + for ii in range(0,len(LObj)): + if type(LObj[ii]) is ID: + LObj[ii] = LObj[ii]._todict() + ClsU = list(set([oo['Cls'] for oo in LObj])) + for c in ClsU: + self._LObj[c] = [oo for oo in LObj if oo['Cls']==c]
    -
    [docs] def set_LObj(self,LObj=None): - """ Set the LObj attribute to store the list of ID of other objects the created instance depends on +
    [docs] def set_USRdict(self,USRdict={}): + """ Set the USRdict, containing user-defined info about the instance - A Detect object depends on a vessel and some optics (e.g.: a list of apertures). - It is necessary that the link between the created Detect object and the already-existing Ves and Apert objects be stored somewhere, so that even after saving and closing the session, this correspondence can be retrieved and the Detect object can be re-loaded with links to the proper Ves and Apert objects, themselves beoing possibly saved elsewhere (so their respective SavePath must also be stored). - The LObj parameter does this: it stores all information necessary about each of the other objects the created instance depends on, mostly by storing their ID attributes as dictionaries. + Useful for arbitrary info (e.g.: manufacturing date, material...) Parameters ---------- - LObj : None / dict / list - If provided, either - - list: list of other ID instances of objects on which the created object depends (this list will then be sorted by class and formatted into a dictionary storign key attributes) - - dict: a ready-made such dictionary + USRdict : dict + A user-defined dictionary containing info about the instance """ - assert LObj is None or type(LObj) is dict or (type(LObj) is list and all([isinstance(oo,ID) for oo in LObj])), "Arg LObj must be a list of ID instances !" - if type(LObj) is list: - LCls = [oo.Cls for oo in LObj] - ClsU = list(set(LCls)) - for Cls in ClsU: - self._LObj[Cls] = {'Exp':[oo.Exp for oo in LObj if oo.Cls==Cls], 'Name':[oo.Name for oo in LObj if oo.Cls==Cls], 'SaveName':[oo.SaveName for oo in LObj if oo.Cls==Cls], - 'SavePath':[oo.SavePath for oo in LObj if oo.Cls==Cls], 'Type':[oo.Type for oo in LObj if oo.Cls==Cls], 'Diag':[oo.Diag for oo in LObj if oo.Cls==Cls], - 'shot':[oo.shot for oo in LObj if oo.Cls==Cls], - 'dtFormat':[oo._dtFormat for oo in LObj if oo.Cls==Cls], 'dtime':[oo.dtime.strftime(oo._dtFormat) for oo in LObj if oo.Cls==Cls], - 'USRdict':[oo._USRdict for oo in LObj if oo.Cls==Cls], 'LObj':[oo._LObj for oo in LObj if oo.Cls==Cls]} - elif type(LObj) is dict: - self._LObj = LObj
    - - def get_LObjasLId(self,Cls=None): - if Cls is None: - Cls = sorted([self._LObj.keys()]) - Cls = [Cls] if type(Cls) is str else Cls - DId = {} - for ii in range(0,len(Cls)): - lid = [] - keys = self._LObj[Cls[ii]].keys() - for jj in range(0,len(self._LObj[Cls[ii]]['Exp'])): - dd = {} - for kk in keys: - dd[kk] = self._LObj[Cls[ii]][kk][jj] - name = dd['Name'] - del dd['Name'], dd['dtime'] - lid.append(ID(Cls[ii], name, **dd)) - DId[Cls[ii]] = lid - return DId - - -
    [docs] def set_USRdict(self,USRdict=None): - """ Set the USRdict to enable the user to store arbitrary information about the instance created - - It may sometimes be useful to store unforeseen arbitrary info about some objects created, like the manufacturing date of a diode, the material used for a filter... - The USRdict attribute is a user-defined dictionary for this purpose. - - Parameters - ---------- - USRdict : None / dict - If provided, a user-defined dictionary containing information about the instance considered relevant (e.g.: thickness of the diode, date of installation...) - - """ - assert USRdict is None or type(USRdict) is dict, "Arg USRdict must be a dictionnary !" - USRdict = {} if USRdict is None else USRdict + self._check_inputs(USRdict=USRdict) self._USRdict = USRdict
    @property @@ -485,12 +430,12 @@

    Source code for tofu.pathfile

         @property
         def Name(self):
             return self._Name
    -    @Name.setter
    -    def Name(self,Val):
    -        self.set_Name(Val)
         @property
         def NameLTX(self):
    -        return r"$"+self.Name.replace('_','\_')+r"$"
    +        return r"$"+self.Name.replace('_','\_')+r"$"
    +    @property
    +    def Exp(self):
    +        return self._Exp
         @property
         def Diag(self):
             return self._Diag
    @@ -503,265 +448,331 @@ 

    Source code for tofu.pathfile

         @property
         def SaveName(self):
             return self._SaveName
    -    @SaveName.setter
    -    def SaveName(self,Val):
    -        self.set_SaveName(Val)
         @property
         def SavePath(self):
             return self._SavePath
    -    @SavePath.setter
    -    def SavePath(self,Val):
    -        self.set_SavePath(Val)
    -    @property
    -    def dtime(self):
    -        return self._dtime
    -    @property
    -    def Exp(self):
    -        return self._Exp
         @property
         def LObj(self):
             return self._LObj
         @property
         def USRdict(self):
    -        return self._USRdict
    -    @USRdict.setter
    -    def USRdict(self, Val):
    -        self.set_USRdict(Val)
    +        return self._USRdict
    - def todict(self): - return _Id_todict(self)
    -def SaveName_Conv(Exp, Cls, Type, Deg, Diag, Name, shot=None, dtime=None, Format="D%Y%m%d_T%H%M%S", dtimeIn=False): - """ Create a default name for saving the object, including key info for fast identification of the object class, type, experiement... - When create a ToFu object, this function called by the ID class to generate a default name for saving the object. - This automatically generated name includes all key info about the object, in addition to its user-defined name. +# Deprecated ???? +def _ID_check_inputs(Mod=None, Cls=None, Name=None, Type=None, Deg=None, + Exp=None, Diag=None, shot=None, SaveName=None, SavePath=None, + USRdict=None, LObj=None, version=None, usr=None, + fromdict=None, Include=None): + if Mod is not None: + assert type(Mod) is str + assert Mod in dModes.keys() + if Cls is not None: + assert type(Cls) in [str,type] + if type(Cls) is type: + assert 'tofu.' in str(Cls) + assert any([ss in str(Cls) for ss in dModes.keys()]) + assert any([ss in str(Cls) for ss in lCls]) + else: + assert Cls in lCls + Lstr = [Name,Type,Exp,Diag,SaveName,SavePath,version,usr] + for ss in Lstr: + assert ss is None or type(ss) is str + Lint = [Deg,shot] + for ii in Lint: + assert ii is None or (type(ii) is int and ii>=0) + if USRdict is not None: + assert type(USRdict) is dict + if Include is not None: + IR = ['Mod','Cls','Type','Name']+list(dPref.keys()) + assert type(Include) in ['str',list,tuple] + if type(Include) is str: + assert Include in IR + else: + for ss in Include: + assert ss in IR, "%s not in "%ss + str(IR) + if LObj is not None: + assert type(LObj) in [dict,list,ID] + if type(LObj) is list: + assert all([type(oo) in [dict,ID] for oo in LObj]) + if fromdict is not None: + assert type(fromdict) is dict + k = ['Cls','Name','SaveName','SavePath','Type','Deg','Exp','Diag', + 'shot','dUSR','version','usr','lObj'] + K = fromdict.keys() + for kk in k: + assert kk in K, "%s missing from provided dict !"%kk + + +# Deprecated ???? +def _extract_ModClsFrom_class(Cls): + strc = str(Cls) + ind0 = strc.index('tofu.')+5 + indeol = strc.index("'>") + strc = strc[ind0:indeol] + indp = strc.index('.') + Mod = strc[:indp] + strc = strc[indp+1:][::-1] + cls = strc[:strc.index('.')][::-1] + return Mod, cls + + + +
    [docs]def SaveName_Conv(Mod=None, Cls=None, Type=None, Name=None, Deg=None, + Exp=None, Diag=None, shot=None, version=None, usr=None, + Include=defInclude): + """ Return a default name for saving the object + + Includes key info for fast identification of the object from file name + Used on object creation by :class:`~tofu.pathfile.ID` It is recommended to use this default name. - Parameters - ---------- - Exp : None / str - A short 3-4 letters max flag specifying the experiment to which the created instance belongs (e.g.: 'AUG', 'ITER', 'TCV', 'JET'...) - Cls : None / str - Flag indicating which class is the object fro which the ID instance is being created, available class flags are: - - From :mod:`tofu.geom`: 'Ves', 'Struct', 'LOS', 'GLOS', 'Apert', 'Lens', 'Detect' and 'GDetect' - - From :mod:`tofu.mesh`: 'Mesh1D', 'Mesh2D', 'LBF1D' and 'LBF2D' (to be finished) - - From :mod:`tofu.`: (to be completed) - Type : None / str - If provided (necessary for some objects, but not for all), specifies the Type of object (i.e.: 'Tor' or 'Lin' for a Ves instance) - Deg : None / int - If provided (necessary only for objects of class 'LBF1D' and 'LBF2D'), specifies the degree of the b-splines constituting the :mod:`tofu.mesh` object - Diag : None / str - A short flag indicating which diagnostic the the created instance belongs to (e.g.: 'SXR', 'HXR', 'Bolo'...) - Name : str - Name to be assigned to the created instance, should be a str without ' ' or '_' (spaces and underscores will be automatically removed if present) - shot : None / int - A shot number from which the created instance can be considered valid (useful for tracking geometry changes in the case of Ves and Detect objects) - dtime : None / dtm.datetime - If provided, a time reference to be used to identify this particular instance (used for debugging mostly) - Format : None / str - If provided, the format in which dtime should be written in the automatically generated saving name for the created instance - dtimeIn : bool - Flag indicating whether the dtm.datetime should be included in the automatically generated saving name for the created instance - - Returns - ------- - SVN : str - The automatically generated saving name - """ - if Cls in ['Ves','Struct','LOS','GLOS','Lens','Apert','Detect','GDetect']: - Mod = 'TFG' - elif Cls in ['Mesh1D','Mesh2D','Mesh3D','LBF1D','LBF2D','LBF3D']: - Mod = 'TFM' - elif Cls in ['Eq2D']: - Mod = 'TFEq' - elif Cls in ['GMat2D','GMat3D']: - Mod = 'TFMC' - elif Cls in ['Corresp','PreData']: - Mod = 'TFT' - elif Cls=='Sol2D': - Mod = 'TFI' - if not isinstance(dtime,dtm.datetime): - dtime = dtm.datetime.now() - ClsType = Cls if Type is None else Cls+Type - if Cls=='PreData': - Elts = [(ClsType,''),(Exp,''),(Deg,'D'),(Diag,'Dg'),(shot,'sh'),(Name,'')] + Modstr = dModes[Mod] if Mod is not None else None + Include = defInclude if Include is None else Include + if Cls is not None and Type is not None and 'Type' in Include: + Clsstr = Cls+Type + else: + Clsstr = Cls + Dict = {'Mod':Modstr, 'Cls':Clsstr, 'Name':Name} + for ii in Include: + if not ii in ['Mod','Cls','Type','Name']: + Dict[ii] = None + if ii=='Deg' and Deg is not None: + Dict[ii] = dPref[ii]+'{0:02.0f}'.format(Deg) + elif ii=='shot' and shot is not None: + Dict[ii] = dPref[ii]+'{0:05.0f}'.format(shot) + elif not ii in ['Mod','Cls','Type','Name'] and eval(ii+' is not None'): + Dict[ii] = dPref[ii]+eval(ii) + if 'Data' in Cls: + Order = ['Mod','Cls','Exp','Deg','Diag','shot','Name','version','usr'] else: - Elts = [(ClsType,''),(Exp,''),(Deg,'D'),(Diag,'Dg'),(Name,''),(shot,'sh')] - SVN = Mod - for ii in range(0,len(Elts)): - SVN = SVN + '_' + Elts[ii][1] + str(Elts[ii][0]).replace('_','') if not Elts[ii][0] is None else SVN - if dtimeIn: - SVN = SVN+'_'+dtime.strftime(Format) - SVN = SVN.replace('__','_') - if Cls in ['PreData','Sol2D']: - SVN = SVN + '_U' + getpass.getuser() - return SVN + Order = ['Mod','Cls','Exp','Deg','Diag','Name','shot','version','usr'] + SVN = "" + for ii in range(0,len(Order)): + if Order[ii] in Include and Dict[Order[ii]] is not None: + SVN += '_' + Dict[Order[ii]] + SVN = SVN.replace('__','_') + if SVN[0]=='_': + SVN = SVN[1:] + return SVN
    -# Checking several instances are the same object -
    [docs]def CheckSameObj(obj0, obj1, LFields=None): - """ Check two variable refer to the same instance of a ToFu class by checking some key attributes - Sometimes two different variables can refer to the same instance (for example if an object was created and assigned to obj0, then later saved and loaded and assigned to obj1). - Occasionally it may be useful to check whether two variables really represent the same instance, according to important criteria from the point of view of ToFu. +
    [docs]def CheckSameObj(obj0, obj1, LFields=None): + """ Check if two variables are the same instance of a ToFu class + + Checks a list of attributes, provided by LField Parameters ---------- obj0 : tofu object A variable refering to a ToFu object of any class obj1 : tofu object - A variable refering to a ToFu object of any class (but the same class as obj0) + A variable refering to a ToFu object of the same class as obj0 LFields : None / str / list - The criteria against which the two objects are evaluated, if not None, must be str matching an attribute of the ID class or an attribute of the object class itself (or a list of such) + The criteria against which the two objects are evaluated: - None: True is returned - - str or list: tests whether the attributes have the same value or not and only returns True if all do + - str or list: tests whether all listed attributes have the same value Returns ------- A : bool + True only is LField is None or a list of attributes that all match """ - assert LFields is None or type(LFields) is str or (type(LFields) is list and all([type(ss) is str for ss in LFields])), "Arg LFields must be a str or a list of str !" - if LFields is None: - return True - if not type(LFields) is list: - LFields = [LFields] - ind = [False for ii in range(0,len(LFields))] - for ii in range(0,len(LFields)): - assert LFields[ii] in dir(obj0.Id)+dir(obj0), LFields[ii]+" not in "+obj0.Id.Name+" !" - assert LFields[ii] in dir(obj1.Id)+dir(obj1), LFields[ii]+" not in "+obj1.Id.Name+" !" - if LFields[ii] in dir(obj0): - ind[ii] = np.all(getattr(obj0,LFields[ii])==getattr(obj1,LFields[ii])) - else: - ind[ii] = getattr(obj0.Id,LFields[ii])==getattr(obj1.Id,LFields[ii]) - A = all(ind) + A = True + if LField is not None and obj0.__class__==obj1.__class__: + assert type(LFields) in [str,list] + if type(LFields) is str: + LFields = [LFields] + assert all([type(s) is str for s in LFields]) + ind = [False for ii in range(0,len(LFields))] + Dir0 = dir(obj0.Id)+dir(obj0) + Dir1 = dir(obj1.Id)+dir(obj1) + for ii in range(0,len(LFields)): + assert LFields[ii] in Dir0, LFields[ii]+" not in "+obj0.Id.Name + assert LFields[ii] in Dir1, LFields[ii]+" not in "+obj1.Id.Name + if hasattr(obj0,LFields[ii]): + ind[ii] = np.all(getattr(obj0,LFields[ii])==getattr(obj1,LFields[ii])) + else: + ind[ii] = getattr(obj0.Id,LFields[ii])==getattr(obj1.Id,LFields[ii]) + A = all(ind) return A
    -def SelectFromIdLObj(IdLObjCls, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=bool): - """ To do (deprecated ?) - """ - assert type(Crit) is str or (type(Crit) is list and all([type(cc) is str for cc in Crit])), "Arg Crit must be a str or list of str !" - assert all([rr is None or type(rr) is str or (type(rr) is list and all([type(ee) is str for ee in rr])) for rr in [PreExp,PostExp]]), "Args PreExp and PostExp must be a str or list of str !" - assert Log in ['any','all'], "Arg Log must be in ['and','or'] !" - assert InOut in ['In','Out'], "Arg InOut must be in ['In','Out'] !" - NObj = len(IdLObjCls['Name']) - if Val is None and PreExp is None and PostExp is None: - ind = np.ones((1,NObj),dtype=bool) - elif not Val is None: - if type(Val) is str: - Val=[Val] - N = len(Val) - ind = np.zeros((N,NObj),dtype=bool) - if Crit in dir(ID): - for ii in range(0,N): - ind[ii,:] = np.asarray([idd==Val[ii] for idd in IdLObjCls[Crit]],dtype=bool) - else: - for ii in range(0,N): - ind[ii,:] = np.asarray([idd[Crit]==Val[ii] for idd in IdLObjCls['USRdict']],dtype=bool) - else: - if type(PreExp) is str: - PreExp = [PreExp] - if type(PostExp) is str: - PostExp = [PostExp] - if PreExp is None: - PreExp = ["" for ss in PostExp] - if PostExp is None: - PostExp = ["" for ss in PreExp] - assert len(PreExp)==len(PostExp), "Arg Exp must be a list of same length as Crit !" - N = len(PreExp) - ind = np.zeros((N,NObj),dtype=bool) - if Crit in dir(ID): - for ii in range(0,N): - ind[ii,:] = np.asarray([eval(PreExp[ii]+" idd "+PostExp[ii]) for idd in IdLObjCls[Crit]],dtype=bool) - else: - for ii in range(0,N): - ind[ii,:] = np.asarray([eval(PreExp[ii]+" idd[Crit] "+PostExp[ii]) for idd in IdLObjCls['USRdict']],dtype=bool) - ind = np.any(ind,axis=0) if Log=='any' else np.all(ind,axis=0) - if InOut=='Out': - ind = ~ind - if Out==bool: - return ind - elif Out==int: - return ind.nonzero()[0] - else: - if Out in dir(ID): - return [IdLObjCls[Out][ii] for ii in ind.nonzero()[0]] - else: - return [IdLObjCls['USRdict'][ii][Out] for ii in ind.nonzero()[0]] +""" Not used ? +def SelectFromIdLObj(IdLObjCls, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=bool): + # To do (deprecated ?) + assert type(Crit) is str or (type(Crit) is list and all([type(cc) is str for cc in Crit])), "Arg Crit must be a str or list of str !" + assert all([rr is None or type(rr) is str or (type(rr) is list and all([type(ee) is str for ee in rr])) for rr in [PreExp,PostExp]]), "Args PreExp and PostExp must be a str or list of str !" + assert Log in ['any','all'], "Arg Log must be in ['and','or'] !" + assert InOut in ['In','Out'], "Arg InOut must be in ['In','Out'] !" + NObj = len(IdLObjCls['Name']) + if Val is None and PreExp is None and PostExp is None: + ind = np.ones((1,NObj),dtype=bool) + elif not Val is None: + if type(Val) is str: + Val=[Val] + N = len(Val) + ind = np.zeros((N,NObj),dtype=bool) + if Crit in dir(ID): + for ii in range(0,N): + ind[ii,:] = np.asarray([idd==Val[ii] for idd in IdLObjCls[Crit]],dtype=bool) + else: + for ii in range(0,N): + ind[ii,:] = np.asarray([idd[Crit]==Val[ii] for idd in IdLObjCls['USRdict']],dtype=bool) + else: + if type(PreExp) is str: + PreExp = [PreExp] + if type(PostExp) is str: + PostExp = [PostExp] + if PreExp is None: + PreExp = ["" for ss in PostExp] + if PostExp is None: + PostExp = ["" for ss in PreExp] + assert len(PreExp)==len(PostExp), "Arg Exp must be a list of same length as Crit !" + N = len(PreExp) + ind = np.zeros((N,NObj),dtype=bool) + if Crit in dir(ID): + for ii in range(0,N): + ind[ii,:] = np.asarray([eval(PreExp[ii]+" idd "+PostExp[ii]) for idd in IdLObjCls[Crit]],dtype=bool) + else: + for ii in range(0,N): + ind[ii,:] = np.asarray([eval(PreExp[ii]+" idd[Crit] "+PostExp[ii]) for idd in IdLObjCls['USRdict']],dtype=bool) + ind = np.any(ind,axis=0) if Log=='any' else np.all(ind,axis=0) + if InOut=='Out': + ind = ~ind + if Out==bool: + return ind + elif Out==int: + return ind.nonzero()[0] + else: + if Out in dir(ID): + return [IdLObjCls[Out][ii] for ii in ind.nonzero()[0]] + else: + return [IdLObjCls['USRdict'][ii][Out] for ii in ind.nonzero()[0]] +""" -def SelectFromListId(LId, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In', Out=bool): - """ Select the ID instances in the provided list that match the criteria and return their index or other attributes - Return - Parameters - ---------- - LId : list - Val : None / str / list - Crit : str - PreExp : None / str +
    [docs]def SelectFromListId(LId, Val=None, Crit='Name', + PreExp=None, PostExp=None, Log='any', + InOut='In', Out=bool): + """ Return the indices or instances of all LOS matching criteria - PostExp : None / str + The selection can be done according to 2 different mechanisms - Log : str + Mechanism (1): provide the value (Val) a criterion (Crit) should match + The criteria are typically attributes of :class:`~tofu.pathfile.ID` + (i.e.: name, or user-defined attributes like the camera head...) - InOut : str + Mechanism (2): (used if Val=None) + Provide a str expression (or a list of such) to be fed to eval() + Used to check on quantitative criteria. + - PreExp: placed before the criterion value (e.g.: 'not ' or '<=') + - PostExp: placed after the criterion value + - you can use both - Out : type / str + Other parameters are used to specify logical operators for the selection + (match any or all the criterion...) and the type of output. + Parameters + ---------- + Crit : str + Flag indicating which criterion to use for discrimination + Can be set to: + - any attribute of :class:`~tofu.pathfile.ID` + (e.g.: 'Name','SaveName','SavePath'...) + - any key of ID.USRdict (e.g.: 'Exp'...) + Val : None / list / str + The value to match for the chosen criterion, can be a list + Used for selection mechanism (1) + PreExp : None / list / str + A str (or list of such) expression to be fed to eval(), + Placed before the criterion value + Used for selection mechanism (2) + PostExp : None / list / str + A str (or list of such) expression to be fed to eval() + Placed after the criterion value + Used for selection mechanism (2) + Log : str + Flag indicating whether the criterion shall match: + - 'all': all provided values + - 'any': at least one of them + InOut : str + Flag indicating whether the returned indices are: + - 'In': the ones matching the criterion + - 'Out': the ones not matching it + Out : type / str + Flag indicating in which form to return the result: + - int: as an array of integer indices + - bool: as an array of boolean indices + - 'Name': as a list of names + - 'LOS': as a list of :class:`~tofu.geom.LOS` instances Returns ------- - ind : np.ndarray / list - + ind : list / np.ndarray + The computed output, of nature defined by parameter Out """ - assert type(Crit) is str or (type(Crit) is list and all([type(cc) is str for cc in Crit])), "Arg Crit must be a str or list of str !" - assert all([rr is None or type(rr) is str or (type(rr) is list and all([type(ee) is str for ee in rr])) for rr in [PreExp,PostExp]]), "Args PreExp and PostExp must be a str or list of str !" - assert Log in ['any','all'], "Arg Log must be in ['any','all'] !" - assert InOut in ['In','Out'], "Arg InOut must be in ['In','Out'] !" - if Val is None and PreExp is None and PostExp is None: + C0 = type(Crit) is str + C1 = type(Crit) is list and all([type(cc) is str for cc in Crit]) + assert C0 or C1, "Arg Crit must be a str or list of str !" + for rr in [PreExp,PostExp]: + if rr is not None: + C0 = type(rr) is str + C1 = type(rr) is list and all([type(ee) is str for ee in rr]) + assert C0 or C1, "Args %S must be a str or list of str !"%rr + assert Log in ['any','all'], "Arg Log must be in ['any','all'] !" + assert InOut in ['In','Out'], "Arg InOut must be in ['In','Out'] !" + if Val is None and PreExp is None and PostExp is None: ind = np.ones((1,len(LId)),dtype=bool) - elif not Val is None: + elif not Val is None: if type(Val) is str: Val=[Val] N = len(Val) ind = np.zeros((N,len(LId)),dtype=bool) if Crit in dir(ID): for ii in range(0,N): - ind[ii,:] = np.asarray([getattr(iid,Crit)==Val[ii] for iid in LId],dtype=bool) + ind[ii,:] = np.asarray([getattr(iid,Crit)==Val[ii] + for iid in LId],dtype=bool) else: for ii in range(0,N): - ind[ii,:] = np.asarray([iid.USRdict[Crit]==Val[ii] for iid in LId],dtype=bool) + ind[ii,:] = np.asarray([iid.USRdict[Crit]==Val[ii] + for iid in LId],dtype=bool) else: if type(PreExp) is str: PreExp = [PreExp] if type(PostExp) is str: PostExp = [PostExp] - if PreExp is None: - PreExp = ["" for ss in PostExp] - if PostExp is None: - PostExp = ["" for ss in PreExp] - assert len(PreExp)==len(PostExp), "Arg Exp must be a list of same length as Crit !" + if PreExp is None: + PreExp = ["" for ss in PostExp] + if PostExp is None: + PostExp = ["" for ss in PreExp] + assert len(PreExp)==len(PostExp), "len(PreExp) should be =len(PostExp)" N = len(PreExp) ind = np.zeros((N,len(LId)),dtype=bool) if Crit in dir(ID): for ii in range(0,N): - ind[ii,:] = np.asarray([eval(PreExp[ii]+" getattr(iid,Crit) "+PostExp[ii]) for iid in LId],dtype=bool) + List = [eval(PreExp[ii]+" getattr(iid,'%s') "%Crit+PostExp[ii]) + for iid in LId] + ind[ii,:] = np.array(List,dtype=bool) else: for ii in range(0,N): - ind[ii,:] = np.asarray([eval(PreExp[ii]+" iid.USRdict[Crit] "+PostExp[ii]) for iid in LId],dtype=bool) - ind = np.any(ind,axis=0) if Log=='any' else np.all(ind,axis=0) - if InOut=='Out': + List = [eval(PreExp[ii]+" iid.USRdict['%s'] "%Crit+PostExp[ii]) + for iid in LId] + ind[ii,:] = np.asarray(List,dtype=bool) + ind = np.any(ind,axis=0) if Log=='any' else np.all(ind,axis=0) + if InOut=='Out': ind = ~ind if Out==int: ind = ind.nonzero()[0] @@ -769,24 +780,24 @@

    Source code for tofu.pathfile

             ind = [getattr(LId[ii],Out) for ii in ind.nonzero()[0]]
         elif Out is not bool and Out in LId[0].USRdict.keys():
             ind = [LId[ii].USRdict[Out] for ii in ind.nonzero()[0]]
    -    return ind
    +    return ind
    -def _Id_todict(Id): - IdTxt = {'Cls':Id.Cls, 'Name':Id.Name, 'SaveName':Id.SaveName, 'SavePath':Id.SavePath, 'Diag':Id.Diag, 'Type':Id.Type, 'shot':Id.shot, 'Exp':Id.Exp} - Iddtime = {'dtime':Id.dtime, 'dtFormat':Id._dtFormat, 'dtimeIn':Id._dtimeIn} - IdLobjUsr = {'LObj':Id.LObj, 'USRdict':Id.USRdict} - return [IdTxt,Iddtime,IdLobjUsr] +#def _Id_todict(Id): +# IdTxt = {'version':Id._version, 'Cls':Id.Cls, 'Name':Id.Name, 'SaveName':Id.SaveName, 'SavePath':Id.SavePath, 'Diag':Id.Diag, 'Type':Id.Type, 'shot':Id.shot, 'Exp':Id.Exp} +# Iddtime = {'dtime':Id.dtime, 'dtFormat':Id._dtFormat} +# IdLobjUsr = {'LObj':Id.LObj, 'USRdict':Id.USRdict} +# return [IdTxt,Iddtime,IdLobjUsr] -def _Id_recreateFromdict(IdS): - Id = ID(Cls=IdS[0]['Cls'], Type=IdS[0]['Type'], Exp=IdS[0]['Exp'], Diag=IdS[0]['Diag'], shot=IdS[0]['shot'], Name=IdS[0]['Name'], SaveName=IdS[0]['SaveName'], SavePath=IdS[0]['SavePath'], - dtime=IdS[1]['dtime'], dtFormat=IdS[1]['dtFormat'], dtimeIn=IdS[1]['dtimeIn'], - LObj=IdS[2]['LObj'], USRdict=IdS[2]['USRdict']) - return Id +#def _Id_recreateFromdict(IdS): +# Id = ID(Cls=IdS[0]['Cls'], Type=IdS[0]['Type'], Exp=IdS[0]['Exp'], Diag=IdS[0]['Diag'], shot=IdS[0]['shot'], Name=IdS[0]['Name'], SaveName=IdS[0]['SaveName'], SavePath=IdS[0]['SavePath'], +# dtime=IdS[1]['dtime'], dtFormat=IdS[1]['dtFormat'], +# LObj=IdS[2]['LObj'], USRdict=IdS[2]['USRdict'], version=IdS[0]['version']) +# return Id @@ -802,11 +813,12 @@

    Source code for tofu.pathfile

     """
     
     
    -###########################
    -#   IDentify a Sol2D file
    -###########################
    +###########################
    +#   Identify a Sol2D file
    +###########################
    +
     
    -def FindSolFile(shot=0, t=0, Dt=None, Mesh='Rough1', Deg=2, Deriv='D2N2', Sep=True, Pos=True, OutPath='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/src/Outputs_AUG/'):
    +def FindSolFile(shot=0, t=0, Dt=None, Mesh='Rough1', Deg=2, Deriv='D2N2', Sep=True, Pos=True, OutPath='/afs/ipp-garching.mpg.de/home/d/didiv/Python/tofu/src/Outputs_AUG/'):
         """ Identify the good Sol2D saved file in a given folder (OutPath), based on key ToFu criteria
     
         When trying to load a Sol2D object (i.e.: solution of a tomographic inversion), it may be handy to provide the key parameters (shot, time, mesh name, degree of basis functions, regularisation functional) instead of copy-pasting the full file name.
    @@ -840,262 +852,341 @@ 

    Source code for tofu.pathfile

             The matching file name, if any
     
         """
    -    assert None in [t,Dt] and not (t is None and Dt is None), "Arg t or Dt must be None, but not both !"
    -    LF = [ff for ff in os.listdir(OutPath) if 'TFI_Sol2D_AUG_SXR' in ff]
    -    LF = [ff for ff in LF if all([ss in ff for ss in ['_'+str(shot)+'_', '_'+Mesh+'_D'+str(Deg), '_Deriv'+Deriv+'_Sep'+str(Sep)+'_Pos'+str(Pos)]])]
    +    assert None in [t,Dt] and not (t is None and Dt is None), "Arg t or Dt must be None, but not both !"
    +    LF = [ff for ff in os.listdir(OutPath) if 'TFI_Sol2D_AUG_SXR' in ff]
    +    LF = [ff for ff in LF if all([ss in ff for ss in ['_'+str(shot)+'_', '_'+Mesh+'_D'+str(Deg), '_Deriv'+Deriv+'_Sep'+str(Sep)+'_Pos'+str(Pos)]])]
         if len(LF)==0:
    -        print "No matching Sol2D file in ", OutPath
    -        out = None
    -    LDTstr = [ff[ff.index('_Dt')+3:ff.index('s_')] for ff in LF]
    +        print("No matching Sol2D file in ", OutPath)
    +        out = None
    +    LDTstr = [ff[ff.index('_Dt')+3:ff.index('s_')] for ff in LF]
         LDTstr = [(ss[:7],ss[8:]) for ss in LDTstr]
    -    if t is None:
    -        LF = [LF[ii] for ii in range(0,len(LF)) if LDTstr[ii][0]+'-'+LDTstr[ii][1]=='{0:07.4f}-{1:07.4f}'.format(Dt[0],Dt[1])]
    -    elif Dt is None:
    +    if t is None:
    +        LF = [LF[ii] for ii in range(0,len(LF)) if LDTstr[ii][0]+'-'+LDTstr[ii][1]=='{0:07.4f}-{1:07.4f}'.format(Dt[0],Dt[1])]
    +    elif Dt is None:
             LF = [LF[ii] for ii in range(0,len(LF)) if t>=float(LDTstr[ii][0]) and t<=float(LDTstr[ii][1])]
         if len(LF)==0:
    -        print "No matching Sol2D file in ", OutPath
    -        out = None
    +        print("No matching Sol2D file in ", OutPath)
    +        out = None
         elif len(LF)>1:
    -        print "Several matching Sol2D files in ", OutPath
    -        print LF
    -        out = None
    +        print("Several matching Sol2D files in ", OutPath)
    +        print(LF)
    +        out = None
         else:
             out = LF[0]
         return out
     
     
    -
    -def _get_ClsFromName(PathFileExt):
    -    assert type(PathFileExt) is str, "Arg PathFileExt must be a str !"
    -    LCls = ['Ves','LOS','GLOS','Apert','Lens','Detect','GDetect','Mesh1D','Mesh2D','BF1D','BF2D','PreData','Sol2D']
    -    Found = False
    -    for nn in LCls:
    -        if '_'+nn+'_' in PathFileExt:
    -            Found = True
    -            break
    -    assert Found, "Class could not be identified in "+PathFileExt
    -    return nn
    -
    -
    -
    -###########################
    -#   Saving
    -###########################
    -
    -
    -
    [docs]def Save_Generic(obj, SaveName=None, Path=None, Mode='npz', compressed=False): - """ Save a ToFu object under file name SaveName, in folder Path, using specified mode +def get_InfoFromFileName(PathFileExt): + assert type(PathFileExt) is str, "Arg PathFileExt must be a str !" + + # Prepare input (extract file name) + pfe = PathFileExt[::-1] + ind0 = pfe.index('.') + ind1 = pfe.index('/') + f = pfe[ind0:ind1][::-1] + + dout = {} + # Extracting Module and Class + mod = [] + cls = [cc for cc in lCls if cc in f] + assert len(mod) in [0,1], "Several modules found !" + assert len(cls) in [0,1], "Several classes found !" + if len(mod)==1: + dout['Mod'] = mod[0] + if len(cls)==1: + dout['Cls'] = cls[0] + + # Extracting other parameters + for ii in dPref.keys(): + if ii in f: + sub = f[f.index(dPref[ii])+len(dPref[ii]):] + if '_' in f: + ind = f.index('_') + else: + ind = f.index('.') + dout[ii] = sub[:ind] + if ii in ['Deg','shot']: + dout[ii] = int(dout[ii]) + + return dout + + +# Replaces _get_PathFileExt_FromName() +def get_FileFromInfos(Path='./', Mod=None, Cls=None, Type=None, Name=None, + Exp=None, Diag=None, shot=None, Deg=None, + version=None, usr=None): + assert type(Path) is str + ld = os.listdir(Path) + ld = [l for l in ld if '.npz' if l] + lstr = [Mod,Cls,Type,Name] + for ii in range(0,len(lstr)): + if lstr[ii] is not None: + ld = [l for l in ld if lstr[ii] in l] + for k in dPref.keys(): + if eval('k is not None'): + v = eval('k') + if k=='shot': + v = '{0:05.0f}'.format(v) + if k=='Deg': + v = '{0:02.0f}'.format(v) + ld = [l for l in ld if v in l] + assert len(ld)==1, "None or several matching files found in %s"%Path + return os.path.join(Path,ld[0]) + + + +########################### +# Saving +########################### + +# Deprecated ??? +
    [docs]def Save_Generic(obj, SaveName=None, Path='./', + Mode='npz', compressed=False, Print=True): + """ Save a ToFu object under file name SaveName, in folder Path ToFu provides built-in saving and loading functions for ToFu objects. - They can be saved at their default SavePath under their default SaveName or user-defined values can be forced if necessary. - Saving can be done in two ways : - - by direct object saving using cPickle (straightforward but heavy) - - by mapping the key object attributes to a dictionary and using :meth:`numpy.savez_compressed()` (faster and lighter, recommended) + There is now only one saving mode: + - 'npz': saves a dict of key attributes using :meth:`numpy.savez` - ToFu now automatically saves information on smaller objects on which the object of interest depends (like apertures for detectors), so that all info is stored in a single file. - In particular, provided the Ves object is saved separately, a whole camera can be saved in a single file (i.e.: all detectors and apertures). + Good practices are: + - save :class:`~tofu.geom.Ves` and :class:`~tofu.geom.Struct` + - intermediate optics (:class:`~tofu.geom.Apert` and + :class:`~tofu.geom.Lens`) generally do not need to be saved + Indeed, they will be autoamtically included in larger objects + like Detect or Cam objects Parameters ---------- SaveName : str - The name to be used to for the saved file, if None (recommended) uses obj.Id.SaveName + The file name, if None (recommended) uses obj.Id.SaveName Path : str - Path specifying where to save the file, if None (recommended) uses obj.Id.SavePath + Path where to save the file Mode : str - Flag specifying whether to save the object as a numpy array file ('.npz', recommended) or an object using cPickle (not recommended, may cause retro-compatibility issues with later versions) + Flag specifying the saving mode + - 'npz': Only mode currently available ('pck' deprecated) compressed : bool - Flag, used when Mode='npz', indicating whether to use np.savez or np.savez_compressed (slower saving and loading but smaller files) + Indicate whether to use np.savez_compressed (slower but smaller files) """ - if Path is None: + assert type(obj.__class__) is type + if SaveName is not None: + C = type(SaveName) is str and not (SaveName[-4]=='.') + assert C, "SaveName should not include the extension !" + assert Path is None or type(Path) is str + assert Mode in ['npz'] + assert type(compressed) is bool + assert type(Print) is bool + if Path is None: Path = obj.Id.SavePath else: - assert type(Path) is str, "Arg Path must be a str !" - obj._Id.SavePath = Path - if SaveName is None: + obj._Id._SavePath = Path + if Mode=='npz': + Ext = '.npz' + if SaveName is None: SaveName = obj.Id.SaveName else: - assert type(SaveName) is str, "Arg SaveName must be a str !" - obj.Id.SaveName = SaveName - Ext = '.npz' if 'npz' in Mode else '.pck' - pathfileext = Path+SaveName+Ext - if '.npz' in Ext: + obj._Id.set_SaveName(SaveName) + pathfileext = os.path.join(Path,SaveName+Ext) + if Ext=='.npz': _save_np(obj, pathfileext, compressed=compressed) - else: - _save_object(obj, pathfileext) - print("Saved in : "+pathfileext)
    - - -def _save_object(obj,pathfileext): - if 'TFM' in pathfileext: - obj.LFunc = None - with open(pathfileext, 'wb') as output: - pck.dump(obj, output, -1) + if Print: + print("Saved in : "+pathfileext)
    -def _convert_Detect2Ldict(obj): - # Store LOS data - llos = obj.LOS.keys() - LOSprops = {'Keys':llos, 'Id':[obj.LOS[kk]['LOS'].Id.todict() for kk in llos], 'Du':[(obj.LOS[kk]['LOS'].D,obj.LOS[kk]['LOS'].u) for kk in llos]} - lprops = obj.LOS[kk].keys() - for pp in lprops: - if not pp=='LOS': - LOSprops[pp] = [obj.LOS[kk][pp] for kk in llos] - - # Get all attributes - lAttr = dir(obj) - Sino, Span, Cone, SAng, SynthDiag, Res = {}, {}, {}, {}, {}, {} - - # Store Sino data - for pp in lAttr: - #print inspect.ismethod(getattr(obj,pp)), type(getattr(obj,pp)), pp - if not inspect.ismethod(getattr(obj,pp)): - if '_Sino' in pp: - Sino[pp] = getattr(obj,pp) - elif '_Span' in pp: - Span[pp] = getattr(obj,pp) - elif '_Cone' in pp: - Cone[pp] = getattr(obj,pp) - elif '_SAng' in pp: - SAng[pp] = getattr(obj,pp) - elif '_SynthDiag' in pp: - SynthDiag[pp] = getattr(obj,pp) - elif '_Res' in pp: - Res[pp] = getattr(obj,pp) - - - # Store Optics key parameters (for re-creating if not saved independantly) - Optics = [] - if len(obj.Optics)>0: - if obj.OpticsType=='Apert': - for aa in obj.Optics: - Optics.append({'Id':aa.Id.todict(), 'Poly':aa.Poly, 'arrayorder':aa._arrayorder, 'Clock':aa._Clock}) - elif obj.OpticsType=='Lens': - ln = obj.Optics[0] - Optics.append({'Id':ln.Id.todict(), 'O':ln.O, 'nIn':ln.nIn, 'Rad':ln.Rad, 'F1':ln.F1, 'F2':ln.F2, 'R1':ln.R1, 'R2':ln.R2, 'dd':ln.dd, 'Type':ln.Type, 'arrayorder':ln._arrayorder, 'Clock':ln._Clock}) - - return LOSprops, Sino, Span, Cone, SAng, SynthDiag, Res, Optics - - - -def _convert_PreData2Ldict(obj): - Init = {'data':obj._dataRef, 't':obj._tRef, 'Chans':obj._ChansRef, 'DtRef':obj._DtRef} - PhysNoiseParam = None if obj._PhysNoise is None else obj._PhysNoise['Param'].update(obj._NoiseModel['Par']) - Update = {'Dt':obj.Dt, 'Resamp_t':obj._Resamp_t, 'Resamp_f':obj._Resamp_f, 'Resamp_Method':obj._Resamp_Method, 'Resamp_interpkind':obj._Resamp_interpkind, - 'indOut':obj._indOut, 'indCorr':obj._indCorr, 'interp_lt':obj._interp_lt, 'interp_lNames':obj._interp_lNames, 'Subtract_tsub':obj._Subtract_tsub, - 'FFTPar':obj._FFTPar, 'PhysNoiseParam':PhysNoiseParam} - return Init, Update - +""" +def _convert_Detect2Ldict(obj): + # Store LOS data + llos = obj.LOS.keys() + LOSprops = {'Keys':llos, 'Id':[obj.LOS[kk]['LOS'].Id.todict() for kk in llos], 'Du':[(obj.LOS[kk]['LOS'].D,obj.LOS[kk]['LOS'].u) for kk in llos]} + lprops = obj.LOS[kk].keys() + for pp in lprops: + if not pp=='LOS': + LOSprops[pp] = [obj.LOS[kk][pp] for kk in llos] + + # Get all attributes + lAttr = dir(obj) + Sino, Span, Cone, SAng, SynthDiag, Res = {}, {}, {}, {}, {}, {} + + # Store Sino data + for pp in lAttr: + #print( inspect.ismethod(getattr(obj,pp)), type(getattr(obj,pp)), pp + if not inspect.ismethod(getattr(obj,pp)): + if '_Sino' in pp: + Sino[pp] = getattr(obj,pp) + elif '_Span' in pp: + Span[pp] = getattr(obj,pp) + elif '_Cone' in pp: + Cone[pp] = getattr(obj,pp) + elif '_SAng' in pp: + SAng[pp] = getattr(obj,pp) + elif '_SynthDiag' in pp: + SynthDiag[pp] = getattr(obj,pp) + elif '_Res' in pp: + Res[pp] = getattr(obj,pp) + + + # Store Optics key parameters (for re-creating if not saved independantly) + Optics = [] + if len(obj.Optics)>0: + if obj.OpticsType=='Apert': + for aa in obj.Optics: + Optics.append({'Id':aa.Id.todict(), 'Poly':aa.Poly, 'arrayorder':aa._arrayorder, 'Clock':aa._Clock}) + elif obj.OpticsType=='Lens': + ln = obj.Optics[0] + Optics.append({'Id':ln.Id.todict(), 'O':ln.O, 'nIn':ln.nIn, 'Rad':ln.Rad, 'F1':ln.F1, 'F2':ln.F2, 'R1':ln.R1, 'R2':ln.R2, 'dd':ln.dd, 'Type':ln.Type, 'arrayorder':ln._arrayorder, 'Clock':ln._Clock}) + + return LOSprops, Sino, Span, Cone, SAng, SynthDiag, Res, Optics + + + +def _convert_PreData2Ldict(obj): + Init = {'data':obj._dataRef, 't':obj._tRef, 'Chans':obj._ChansRef, 'DtRef':obj._DtRef} + PhysNoiseParam = None if obj._PhysNoise is None else obj._PhysNoise['Param'].update(obj._NoiseModel['Par']) + Update = {'Dt':obj.Dt, 'Resamp_t':obj._Resamp_t, 'Resamp_f':obj._Resamp_f, 'Resamp_Method':obj._Resamp_Method, 'Resamp_interpkind':obj._Resamp_interpkind, + 'indOut':obj._indOut, 'indCorr':obj._indCorr, 'interp_lt':obj._interp_lt, 'interp_lNames':obj._interp_lNames, 'Subtract_tsub':obj._Subtract_tsub, + 'FFTPar':obj._FFTPar, 'PhysNoiseParam':PhysNoiseParam} + return Init, Update +""" -def _save_np(obj, pathfileext, compressed=False): +def _save_np(obj, pathfileext, compressed=False): func = np.savez_compressed if compressed else np.savez + dId = obj.Id._todict() + + # tofu.geom + if obj.Id.Cls=='Ves': + func(pathfileext, Id=dId, arrayorder=obj._arrayorder, Clock=obj._Clock, + Poly=obj.Poly, Lim=obj.Lim, Sino_RefPt=obj.sino['RefPt'], + Sino_NP=obj.sino['NP']) + + elif obj.Id.Cls=='Struct': + func(pathfileext, Id=dId, arrayorder=obj._arrayorder, Clock=obj._Clock, + Poly=obj.Poly, Lim=obj.Lim, mobile=obj._mobile) + + elif obj.Id.Cls in ['Rays','LOS','LOSCam1D','LOSCam2D']: + func(pathfileext, Id=dId, extra=obj._extra, + geom=obj.geom, sino=obj.sino, dchans=obj.dchans) + + elif obj.Id.Cls in ['Data','Data1D','Data2D']: + dsave = obj._todict() + if dsave['geom'] is not None and dsave['geom']['LCam'] is not None: + LCam = [] + for cc in dsave['geom']['LCam']: + pathS = cc['Id']['SavePath'] + pathN = cc['Id']['SaveName'] + LCam.append(os.path.join(pathS,pathN+'.npz')) + dsave['geom'] = LCam + elif dsave['geom'] is not None: + geom = [] + if dsave['geom']['Ves'] is not None: + pathS = dsave['geom']['Ves']['Id']['SavePath'] + pathN = dsave['geom']['Ves']['Id']['SaveName'] + Ves = os.path.join(pathS,pathN+'.npz') + geom += [Ves] + if dsave['geom']['LStruct'] is not None: + for ss in dsave['geom']['LStruct']: + sf = os.path.join(ss['Id']['SavePath'], + ss['Id']['SaveName']+'.npz') + geom += [sf] + dsave['geom'] = geom + func(pathfileext, **dsave) - Idsave = obj.Id.todict() - - # tofu.geom - if obj.Id.Cls=='Ves': - func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, Poly=obj.Poly, DLong=obj.DLong, Sino_RefPt=obj.Sino_RefPt, Sino_NP=obj.Sino_NP) - - if obj.Id.Cls=='Struct': - func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, Poly=obj.Poly, DLong=obj.DLong) - - elif obj.Id.Cls=='LOS': - func(pathfileext, Idsave=Idsave, Du=obj.Du, Sino_RefPt=obj.Sino_RefPt, arrayorder=obj._arrayorder, Clock=obj._Clock) - - elif obj.Id.Cls=='GLOS': - LIdLOS = [ll.Id.todict() for ll in obj.LLOS] - LDs, Lus = np.array([ll.D for ll in obj.LLOS]).T, np.array([ll.u for ll in obj.LLOS]).T - func(pathfileext, Idsave=Idsave, LIdLOS=LIdLOS, LDs=LDs, Lus=Lus, Sino_RefPt=obj.Sino_RefPt, arrayorder=obj._arrayorder, Clock=obj._Clock) - - elif obj.Id.Cls=='Lens': - func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, O=obj.O, nIn=obj.nIn, Rad=[obj.Rad], F1=[obj.F1], F2=[obj.F2], R1=[obj.R1], R2=[obj.R2], dd=[obj.dd]) - - elif obj.Id.Cls=='Apert': - func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, Poly=obj.Poly) - - elif obj.Id.Cls=='Detect': - LOSprops, Sino, Span, Cone, SAng, SynthDiag, Res, Optics = _convert_Detect2Ldict(obj) - func(pathfileext, Idsave=Idsave, Poly=obj.Poly, Rad=obj.Rad, BaryS=obj.BaryS, nIn=obj.nIn, arrayorder=obj._arrayorder, Clock=obj._Clock, Sino_RefPt=obj.Sino_RefPt, LOSNP=[obj._LOS_NP], - LOSprops=[LOSprops], Sino=[Sino], Span=[Span], Cone=[Cone], SAng=[SAng], SynthDiag=[SynthDiag], Res=[Res], Optics=[Optics]) - - elif obj.Id.Cls=='GDetect': - LDetsave, LDetSynthRes = [], [] - for ii in range(0,obj.nDetect): - ddIdsave = obj.LDetect[ii].Id.todict() - LOSprops, Sino, Span, Cone, SAng, SynthDiag, Res, Optics = _convert_Detect2Ldict(obj.LDetect[ii]) - dd = dict(Idsave=ddIdsave, Poly=obj.LDetect[ii].Poly, Rad=obj.LDetect[ii].Rad, BaryS=obj.LDetect[ii].BaryS, nIn=obj.LDetect[ii].nIn, arrayorder=obj._arrayorder, Clock=obj._Clock, Sino_RefPt=obj.Sino_RefPt, - LOSNP=[obj.LDetect[ii]._LOS_NP], LOSprops=[LOSprops], Sino=[Sino], Span=[Span], Cone=[Cone], SAng=[SAng], Optics=[Optics]) - LDetsave.append(dd) - LDetSynthRes.append({'SynthDiag':[SynthDiag],'Res':[Res]}) - Res, lAttr = {}, dir(obj) - for pp in lAttr: - if not inspect.ismethod(getattr(obj,pp)) and '_Res' in pp: - Res[pp] = getattr(obj,pp) - func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, Sino_RefPt=obj.Sino_RefPt, LOSRef=obj._LOSRef, Res=[Res], LDetsave=LDetsave, LDetSynthRes=LDetSynthRes) - - # tofu.Eq - elif obj.Id.Cls=='Eq2D': - np.savez(pathfileext, Idsave=Idsave, **obj._Tab) - - # tofu.mesh - elif obj.Id.Cls=='Mesh1D': - func(pathfileext, Idsave=Idsave, Knots=obj.Knots) - - elif obj.Id.Cls=='Mesh2D': - SubMinds = [{'Name':kk, 'ind':obj._SubMesh[kk]['ind']} for kk in obj._SubMesh.keys()] - func(pathfileext, Idsave=Idsave, Knots=[obj.MeshX1.Knots,obj.MeshX2.Knots], SubMinds=SubMinds, IndBg=obj._get_CentBckg()[1]) - - elif obj.Id.Cls=='BF2D': - Id = np.array(['BF2D',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) - IdMesh = np.array(['Mesh2D',obj.Mesh.Id.Name,obj.Mesh.Id.SaveName,obj.Mesh.Id.SavePath,obj.Mesh.Id._dtFormat],dtype=str) - dtime, dtimeMesh = np.array([obj.Id._dtime],dtype=object), np.array([obj.Mesh.Id._dtime],dtype=object) - USR = np.asarray(obj.Id.USRdict) - func(pathfileext, Id=Id, IdMesh=IdMesh, dtime=dtime, IdUSR=USR, dtimeMesh=dtimeMesh, KnotsR=obj.Mesh.MeshR.Knots, KnotsZ=obj.Mesh.MeshZ.Knots, Deg=np.array([obj.Deg],dtype=int), Ind=obj.Mesh._get_CentBckg()[1]) - - # tofu.matcomp - elif obj.Id.Cls=='GMat2D': - Id = np.array(['GMat2D',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) - dtime = np.array([obj.Id._dtime],dtype=object) - USR = np.asarray(obj.Id.USRdict) - IdObj, IdObjUSR = save_np_IdObj(obj.Id) - CompParamVal = np.array([obj._Mat_epsrel, obj._Mat_SubP, obj._Mat_SubTheta, obj._indMat_SubP, obj._MatLOS_epsrel, obj._MatLOS_SubP, int(obj._Mat_Fast)]) - CompParamStr = np.array([obj._Mat_Mode, obj._Mat_SubMode, obj._Mat_SubThetaMode, obj._MatLOS_Mode, obj._MatLOS_SubMode]) - func(pathfileext, Id=Id, dtime=dtime, IdUSR=USR, Ves=IdObj[2], VesUSR=IdObjUSR[2], LDetect=IdObj[1], BF2=IdObj[0], BF2USR=IdObjUSR[0], LDetectUSR=IdObjUSR[1], CompParamVal=CompParamVal, - CompParamStr=CompParamStr, indMat=obj._indMat, Matdata=obj._Mat_csr.data, Matind=obj._Mat_csr.indices, Matindpr=obj._Mat_csr.indptr, Matshape=obj._Mat_csr.shape, - MatLOSdata=obj._MatLOS_csr.data, MatLOSind=obj._MatLOS_csr.indices, MatLOSindpr=obj._MatLOS_csr.indptr, MatLOSshape=obj._MatLOS_csr.shape, - BF2Par=np.array([obj._BF2_Deg,obj._BF2_NFunc,obj._BF2_NCents]), LD_nD=obj._LD_nDetect) - - # tofu.treat - elif obj.Id.Cls=='PreData': - Init, Update = _convert_PreData2Ldict(obj) - func(pathfileext, Idsave=Idsave, Init=[Init], Update=[Update]) - - #Id = np.array(['PreData',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) - #dtime = np.array([obj.Id._dtime],dtype=object) - #USR = np.asarray(obj.Id.USRdict) - #IdObj, IdObjUSR = save_np_IdObj(obj.Id) - #StrPar = np.asarray([obj._Exp, obj._interpkind]) - #func(pathfileext, Id=Id, dtime=dtime, IdUSR=USR, LDetect=IdObj[0], LDetectUSR=IdObjUSR[0], - # DLPar=obj._DLPar, shot=obj._shot, StrPar=StrPar, Dt=obj._Dt, DtMarg=obj._DtMargin, MovMeanfreq=obj._MovMeanfreq, Resamp=obj._Resamp, - # indOut=obj._indOut, indCorr=obj._indCorr, PhysNoise=obj._PhysNoise, NoiseMod=obj._NoiseModel, interp_lt=obj._interp_lt, interp_lN=obj._interp_lNames) - - # tofu.inv - elif obj.Id.Cls=='Sol2D': - Id = np.array(['Sol2D',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) - dtime = np.array([obj.Id._dtime],dtype=object) - USR = np.asarray(obj.Id.USRdict) - IdObj, IdObjUSR = save_np_IdObj(obj.Id) - try: - timing = obj._timing - except Exception: - timing = obj._t2 - func(pathfileext, Id=Id, dtime=dtime, IdUSR=USR, PreData=IdObj[2], PreDataUSR=IdObjUSR[2], GMat2D=IdObj[1], GMatUSR=IdObjUSR[1], BF2D=IdObj[0], BF2DUSR=IdObjUSR[0], - InvParam=obj.InvParam, shot=obj.shot, LNames=obj._LNames, Run=obj._run, - LOS=obj._LOS, data=obj._data, t=obj._t, Coefs=obj._Coefs, sigma=obj._sigma, Mu=obj._Mu, Chi2N=obj._Chi2N, R = obj._R, Nit=obj._Nit, Spec=obj._Spec, t2=timing, PostTreat=obj._PostTreat) - + """ + elif obj.Id.Cls=='GLOS': + LIdLOS = [ll.Id.todict() for ll in obj.LLOS] + LDs, Lus = np.array([ll.D for ll in obj.LLOS]).T, np.array([ll.u for ll in obj.LLOS]).T + func(pathfileext, Idsave=Idsave, LIdLOS=LIdLOS, LDs=LDs, Lus=Lus, Sino_RefPt=obj.Sino_RefPt, arrayorder=obj._arrayorder, Clock=obj._Clock) + + elif obj.Id.Cls=='Lens': + func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, O=obj.O, nIn=obj.nIn, Rad=[obj.Rad], F1=[obj.F1], F2=[obj.F2], R1=[obj.R1], R2=[obj.R2], dd=[obj.dd]) + + elif obj.Id.Cls=='Apert': + func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, Poly=obj.Poly) + + elif obj.Id.Cls=='Detect': + LOSprops, Sino, Span, Cone, SAng, SynthDiag, Res, Optics = _convert_Detect2Ldict(obj) + VesCalc = {'SavePath':None} if (not hasattr(obj,'_VesCalc') or obj._VesCalc is None) else {'SavePath':obj._VesCalc.Id.SavePath, 'SaveName':obj._VesCalc.Id.SaveName} + func(pathfileext, Idsave=Idsave, Poly=obj.Poly, Rad=obj.Rad, BaryS=obj.BaryS, nIn=obj.nIn, arrayorder=obj._arrayorder, Clock=obj._Clock, Sino_RefPt=obj.Sino_RefPt, LOSNP=[obj._LOS_NP], + LOSprops=[LOSprops], Sino=[Sino], Span=[Span], Cone=[Cone], SAng=[SAng], SynthDiag=[SynthDiag], Res=[Res], Optics=[Optics], VesCalc=[VesCalc]) + + elif obj.Id.Cls=='GDetect': + LDetsave, LDetSynthRes = [], [] + for ii in range(0,obj.nDetect): + ddIdsave = obj.LDetect[ii].Id.todict() + LOSprops, Sino, Span, Cone, SAng, SynthDiag, Res, Optics = _convert_Detect2Ldict(obj.LDetect[ii]) + VesCalc = {'SavePath':None} if (not hasattr(obj.LDetect[ii],'_VesCalc') or obj.LDetect[ii]._VesCalc is None) else {'SavePath':obj.LDetect[ii]._VesCalc.Id.SavePath, 'SaveName':obj.LDetect[ii]._VesCalc.Id.SaveName} + dd = dict(Idsave=ddIdsave, Poly=obj.LDetect[ii].Poly, Rad=obj.LDetect[ii].Rad, BaryS=obj.LDetect[ii].BaryS, nIn=obj.LDetect[ii].nIn, arrayorder=obj._arrayorder, Clock=obj._Clock, Sino_RefPt=obj.Sino_RefPt, + LOSNP=[obj.LDetect[ii]._LOS_NP], LOSprops=[LOSprops], Sino=[Sino], Span=[Span], Cone=[Cone], SAng=[SAng], Optics=[Optics], VesCalc=[VesCalc]) + LDetsave.append(dd) + LDetSynthRes.append({'SynthDiag':[SynthDiag],'Res':[Res]}) + Res, lAttr = {}, dir(obj) + for pp in lAttr: + if not inspect.ismethod(getattr(obj,pp)) and '_Res' in pp: + Res[pp] = getattr(obj,pp) + func(pathfileext, Idsave=Idsave, arrayorder=obj._arrayorder, Clock=obj._Clock, Sino_RefPt=obj.Sino_RefPt, LOSRef=obj._LOSRef, Res=[Res], LDetsave=LDetsave, LDetSynthRes=LDetSynthRes) + + # tofu.Eq + elif obj.Id.Cls=='Eq2D': + np.savez(pathfileext, Idsave=Idsave, **obj._Tab) + + # tofu.mesh + elif obj.Id.Cls=='Mesh1D': + func(pathfileext, Idsave=Idsave, Knots=obj.Knots) + + elif obj.Id.Cls=='Mesh2D': + SubMinds = [{'Name':kk, 'ind':obj._SubMesh[kk]['ind']} for kk in obj._SubMesh.keys()] + func(pathfileext, Idsave=Idsave, Knots=[obj.MeshX1.Knots,obj.MeshX2.Knots], SubMinds=SubMinds, IndBg=obj._get_CentBckg()[1]) + + elif obj.Id.Cls=='BF2D': + Id = np.array(['BF2D',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) + IdMesh = np.array(['Mesh2D',obj.Mesh.Id.Name,obj.Mesh.Id.SaveName,obj.Mesh.Id.SavePath,obj.Mesh.Id._dtFormat],dtype=str) + dtime, dtimeMesh = np.array([obj.Id._dtime],dtype=object), np.array([obj.Mesh.Id._dtime],dtype=object) + USR = np.asarray(obj.Id.USRdict) + func(pathfileext, Id=Id, IdMesh=IdMesh, dtime=dtime, IdUSR=USR, dtimeMesh=dtimeMesh, KnotsR=obj.Mesh.MeshR.Knots, KnotsZ=obj.Mesh.MeshZ.Knots, Deg=np.array([obj.Deg],dtype=int), Ind=obj.Mesh._get_CentBckg()[1]) + + # tofu.matcomp + elif obj.Id.Cls=='GMat2D': + Id = np.array(['GMat2D',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) + dtime = np.array([obj.Id._dtime],dtype=object) + USR = np.asarray(obj.Id.USRdict) + IdObj, IdObjUSR = save_np_IdObj(obj.Id) + CompParamVal = np.array([obj._Mat_epsrel, obj._Mat_SubP, obj._Mat_SubTheta, obj._indMat_SubP, obj._MatLOS_epsrel, obj._MatLOS_SubP, int(obj._Mat_Fast)]) + CompParamStr = np.array([obj._Mat_Mode, obj._Mat_SubMode, obj._Mat_SubThetaMode, obj._MatLOS_Mode, obj._MatLOS_SubMode]) + func(pathfileext, Id=Id, dtime=dtime, IdUSR=USR, Ves=IdObj[2], VesUSR=IdObjUSR[2], LDetect=IdObj[1], BF2=IdObj[0], BF2USR=IdObjUSR[0], LDetectUSR=IdObjUSR[1], CompParamVal=CompParamVal, + CompParamStr=CompParamStr, indMat=obj._indMat, Matdata=obj._Mat_csr.data, Matind=obj._Mat_csr.indices, Matindpr=obj._Mat_csr.indptr, Matshape=obj._Mat_csr.shape, + MatLOSdata=obj._MatLOS_csr.data, MatLOSind=obj._MatLOS_csr.indices, MatLOSindpr=obj._MatLOS_csr.indptr, MatLOSshape=obj._MatLOS_csr.shape, + BF2Par=np.array([obj._BF2_Deg,obj._BF2_NFunc,obj._BF2_NCents]), LD_nD=obj._LD_nDetect) + + # tofu.treat + elif obj.Id.Cls=='PreData': + Init, Update = _convert_PreData2Ldict(obj) + func(pathfileext, Idsave=Idsave, Init=[Init], Update=[Update]) + + #Id = np.array(['PreData',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) + #dtime = np.array([obj.Id._dtime],dtype=object) + #USR = np.asarray(obj.Id.USRdict) + #IdObj, IdObjUSR = save_np_IdObj(obj.Id) + #StrPar = np.asarray([obj._Exp, obj._interpkind]) + #func(pathfileext, Id=Id, dtime=dtime, IdUSR=USR, LDetect=IdObj[0], LDetectUSR=IdObjUSR[0], + # DLPar=obj._DLPar, shot=obj._shot, StrPar=StrPar, Dt=obj._Dt, DtMarg=obj._DtMargin, MovMeanfreq=obj._MovMeanfreq, Resamp=obj._Resamp, + # indOut=obj._indOut, indCorr=obj._indCorr, PhysNoise=obj._PhysNoise, NoiseMod=obj._NoiseModel, interp_lt=obj._interp_lt, interp_lN=obj._interp_lNames) + + # tofu.inv + elif obj.Id.Cls=='Sol2D': + Id = np.array(['Sol2D',obj.Id.Name,obj.Id.SaveName,obj.Id.SavePath,obj.Id._dtFormat,obj.Id._Diag,str(obj.Id._shot), [obj.Id.Type], obj.Id.Exp],dtype=str) + dtime = np.array([obj.Id._dtime],dtype=object) + USR = np.asarray(obj.Id.USRdict) + IdObj, IdObjUSR = save_np_IdObj(obj.Id) + try: + timing = obj._timing + except Exception: + timing = obj._t2 + func(pathfileext, Id=Id, dtime=dtime, IdUSR=USR, PreData=IdObj[2], PreDataUSR=IdObjUSR[2], GMat2D=IdObj[1], GMatUSR=IdObjUSR[1], BF2D=IdObj[0], BF2DUSR=IdObjUSR[0], + InvParam=obj.InvParam, shot=obj.shot, LNames=obj._LNames, Run=obj._run, + LOS=obj._LOS, data=obj._data, t=obj._t, Coefs=obj._Coefs, sigma=obj._sigma, Mu=obj._Mu, Chi2N=obj._Chi2N, R = obj._R, Nit=obj._Nit, Spec=obj._Spec, t2=timing, PostTreat=obj._PostTreat) + """ def save_np_IdObj(Id): """ (to do) """ @@ -1105,7 +1196,7 @@

    Source code for tofu.pathfile

             kk = sorted(Id.LObj[Keys[ii]].keys())
             Larr, LarrUSR = [], []
             for jj in range(0,len(kk)):
    -            if kk[jj]=='USRdict':
    +            if kk[jj]=='USRdict':
                     LarrUSR.append(np.asarray([Id.LObj[Keys[ii]][kk[jj]]],dtype=object))
                 else:
                     Larr.append(np.asarray([Id.LObj[Keys[ii]][kk[jj]]],dtype=str))
    @@ -1115,12 +1206,16 @@ 

    Source code for tofu.pathfile

     
     
     
    -###########################
    -#   Opening
    -###########################
     
    +###########################
    +#   Opening
    +###########################
     
    -
    [docs]def Open(pathfileext=None, shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None, Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None, out='full', Verb=False): + +
    [docs]def Open(pathfileext=None, + shot=None, t=None, Dt=None, Mesh=None, Deg=None, Deriv=None, + Sep=True, Pos=True, OutPath=None, ReplacePath=None, Ves=None, + out='full', Verb=False, Print=True): """ Open a ToFu object saved file This generic open function identifies the required loading routine by detecting how the object was saved from the file name extension. @@ -1150,115 +1245,121 @@

    Source code for tofu.pathfile

             The loaded and re-created ToFu object
     
         """
    -    assert None in [pathfileext,shot] and not (pathfileext is None and shot is None), "Arg pathfileext or shot must be None, but not both !"
    -    if pathfileext is None:
    -        File = FindSolFile(shot=shot, t=t, Dt=Dt, Mesh=Mesh, Deg=Deg, Deriv=Deriv, Sep=Sep, Pos=Pos, OutPath=OutPath)
    -        if File is None:
    +    assert None in [pathfileext,shot] and not (pathfileext is None and shot is None), "Arg pathfileext or shot must be None, but not both !"
    +    if pathfileext is None:
    +        File = FindSolFile(shot=shot, t=t, Dt=Dt, Mesh=Mesh, Deg=Deg,
    +                           Deriv=Deriv, Sep=Sep, Pos=Pos, OutPath=OutPath)
    +        if File is None:
                 return File
    -        pathfileext = OutPath+File
    -    assert '.npz' in pathfileext or '.pck' in pathfileext, "Arg pathfileext must contain '.npz' or .pck !"
    -
    -    if '.npz' in pathfileext:
    -        obj = _open_np(pathfileext, Ves=Ves, ReplacePath=ReplacePath, out=out, Verb=Verb)
    -    else:
    -        obj = _open_object(pathfileext)
    -    print("Loaded :  "+pathfileext)
    +        pathfileext = os.path.join(OutPath,File)
    +    C = any([ss in pathfileext for ss in ['.npz']])
    +    assert C, "Arg pathfileext must contain '.npz' !"
    +
    +    if '.npz' in pathfileext:
    +        obj = _open_np(pathfileext, Ves=Ves, ReplacePath=ReplacePath,
    +                       out=out, Verb=Verb, Print=Print)
    +    if Print:
    +        print("Loaded :  "+pathfileext)
         return obj
    - -def _open_object(pathfileext): - with Open(pathfileext, 'rb') as input: - obj = pck.load(input) - if 'TFM' in pathfileext: - obj.set_BasisFunc(obj.Deg) - return obj - - -def open_np_IdObj(LCls=None,LIdArr=None,LIdUSR=None): +def open_np_IdObj(LCls=None,LIdArr=None,LIdUSR=None): LIdObj = [] - if not LIdArr is None: - assert type(LIdArr) is list and type(LCls) is list, "Args LCls and LIdArr must be lists !" + if not LIdArr is None: + assert type(LIdArr) is list and type(LCls) is list, "Args LCls and LIdArr must be lists !" NObj = len(LIdArr) for ii in range(0,NObj): no = LIdArr[ii].shape[1] for jj in range(0,no): - if not LIdUSR is None and not LIdUSR[ii][0][jj] is None: + if not LIdUSR is None and not LIdUSR[ii][0][jj] is None: LIdObj.append(ID(LCls[ii],str(LIdArr[ii][1,jj]),SaveName=str(LIdArr[ii][2,jj]), SavePath=str(LIdArr[ii][3,jj]), Exp=str(LIdArr[ii][0,jj]), dtime=dtm.datetime.strptime(str(LIdArr[ii][5,jj]),str(LIdArr[ii][4,jj])), dtFormat=str(LIdArr[ii][4,jj]), USRdict=LIdUSR[ii][0][jj])) else: LIdObj.append(ID(LCls[ii],str(LIdArr[ii][1,jj]),SaveName=str(LIdArr[ii][2,jj]), SavePath=str(LIdArr[ii][3,jj]), Exp=str(LIdArr[ii][0,jj]), dtime=dtm.datetime.strptime(str(LIdArr[ii][5,jj]),str(LIdArr[ii][4,jj])), dtFormat=str(LIdArr[ii][4,jj]))) return LIdObj -def _tryloadVes(Id, Ves=None): - if not Ves is None: - if type(Ves) is TFG.Ves and Id.LObj['Ves']['SavePath'][0]==Ves.Id.SavePath and Id.LObj['Ves']['SaveName'][0]==Ves.Id.SaveName: - return Ves +def _tryloadVesStruct(Id, VesStruct=None, Print=True): + if hasattr(VesStruct,'__iter__') and VesStruct[0].Id.Cls=='Ves': + return VesStruct[0], VesStruct[1] else: - try: - PathFileExt = Id.LObj['Ves']['SavePath'][0]+Id.LObj['Ves']['SaveName'][0]+'.npz' - Ves = Open(PathFileExt) - except: - warnings.warn(Id.Name +" : associated Ves object could not be loaded from "+PathFileExt) - return Ves - -def _tryLoadOpticsElseCreate(Id, Opt=None, Ves=None, Verb=False): + Ves, LStruct = None, None + if 'Ves' in Id.LObj.keys(): + PathFileExt = os.path.join(Id.LObj['Ves'][0]['SavePath'], + Id.LObj['Ves'][0]['SaveName']+'.npz') + try: + Ves = Open(PathFileExt, Print=Print) + except: + Str = " : associated Ves/Struct could not be loaded from " + warnings.warn(Id.Name + Str + PathFileExt) + if 'Struct' in Id.LObj.keys(): + LStruct = [] + for ss in Id.LObj['Struct']: + PathFileExt = os.path.join(ss['SavePath'], + ss['SaveName']+'.npz') + try: + LStruct.append(Open(PathFileExt, Print=Print)) + except: + Str = " : associated Ves/Struct could not be loaded from " + warnings.warn(Id.Name + Str +PathFileExt) + return Ves, LStruct + +def _tryLoadOpticsElseCreate(Id, Opt=None, Ves=None, Verb=False): import tofu.geom as TFG - if 'Apert' in Id.LObj.keys(): + if 'Apert' in Id.LObj.keys(): Optics = [] - for ii in range(0,len(Id.LObj['Apert']['SaveName'])): + for ii in range(0,len(Id.LObj['Apert']['SaveName'])): try: - PathFileExt = Id.LObj['Apert']['SavePath'][ii]+Id.LObj['Apert']['SaveName'][ii]+'.npz' + PathFileExt = Id.LObj['Apert']['SavePath'][ii]+Id.LObj['Apert']['SaveName'][ii]+'.npz' aa = Open(PathFileExt, Ves=Ves) Optics.append(aa) except Exception: - if not Opt is None: - assert type(Ves) is TFG.Ves, "Arg Ves must be a TFG.Ves instance !" + if not Opt is None: + assert type(Ves) is TFG.Ves, "Arg Ves must be a TFG.Ves instance !" if Verb: - print(Id.Name +" : no saved Apert => creating the associated Apert object !") - ind = [jj for jj in range(0,len(Opt)) if Opt[jj]['Id'][0]['SaveName']==Id.LObj['Apert']['SaveName'][ii] and Opt[jj]['Id'][0]['SavePath']==Id.LObj['Apert']['SavePath'][ii]] - assert len(ind)==1, "Several possible solutions !" + print(Id.Name +" : no saved Apert => creating the associated Apert object !") + ind = [jj for jj in range(0,len(Opt)) if Opt[jj]['Id'][0]['SaveName']==Id.LObj['Apert']['SaveName'][ii] and Opt[jj]['Id'][0]['SavePath']==Id.LObj['Apert']['SavePath'][ii]] + assert len(ind)==1, "Several possible solutions !" ind = ind[0] - iid = _Id_recreateFromdict(Opt[ind]['Id']) - aa = TFG.Apert(iid, Opt[ind]['Poly'], Ves=Ves, arrayorder=Opt[ind]['arrayorder'], Clock=Opt[ind]['Clock']) + iid = _Id_recreateFromdict(Opt[ind]['Id']) + aa = TFG.Apert(iid, Opt[ind]['Poly'], Ves=Ves, arrayorder=Opt[ind]['arrayorder'], Clock=Opt[ind]['Clock']) Optics.append(aa) else: - warnings.warn(Id.Name +" : associated Apert object could not be loaded from "+PathFileExt) - elif 'Lens' in Id.LObj.keys(): + warnings.warn(Id.Name +" : associated Apert object could not be loaded from "+PathFileExt) + elif 'Lens' in Id.LObj.keys(): try: - PathFileExt = Id.LObj['Lens']['SavePath'][0]+Id.LObj['Lens']['SaveName'][0]+'.npz' + PathFileExt = Id.LObj['Lens']['SavePath'][0]+Id.LObj['Lens']['SaveName'][0]+'.npz' Optics = Open(PathFileExt, Ves=Ves) except Exception: - if not Opt is None: - assert type(Ves) is TFG.Ves, "Arg Ves must be a TFG.Ves instance !" + if not Opt is None: + assert type(Ves) is TFG.Ves, "Arg Ves must be a TFG.Ves instance !" if Verb: - print(Id.Name +" : no saved Lens => creating the associated Lens object !") - iid = _Id_recreateFromdict(Opt[0]['Id']) - aa = TFG.Lens(iid, Opt[0]['O'], Opt[0]['nIn'], Opt[0]['Rad'], Opt[0]['F1'], F2=Opt[0]['F2'], R1=Opt[0]['R1'], R2=Opt[0]['R2'], dd=Opt[0]['dd'], Type=Opt[0]['Type'], Ves=Ves, - arrayorder=Opt[0]['arrayorder'], Clock=Opt[0]['Clock']) + print(Id.Name +" : no saved Lens => creating the associated Lens object !") + iid = _Id_recreateFromdict(Opt[0]['Id']) + aa = TFG.Lens(iid, Opt[0]['O'], Opt[0]['nIn'], Opt[0]['Rad'], Opt[0]['F1'], F2=Opt[0]['F2'], R1=Opt[0]['R1'], R2=Opt[0]['R2'], dd=Opt[0]['dd'], Type=Opt[0]['Type'], Ves=Ves, + arrayorder=Opt[0]['arrayorder'], Clock=Opt[0]['Clock']) Optics = aa else: - warnings.warn(Id.Name +" : associated Lens object could not be loaded from "+PathFileExt) + warnings.warn(Id.Name +" : associated Lens object could not be loaded from "+PathFileExt) return Optics def _resetDetectAttr(obj, Out): import tofu.geom as TFG - # Re-creating LOS + # Re-creating LOS LOS = {} - kkeys = Out['LOSprops'].keys() - for ii in range(0,len(Out['LOSprops']['Keys'])): - idlos = _Id_recreateFromdict(Out['LOSprops']['Id'][ii]) - los = TFG.LOS(idlos, Out['LOSprops']['Du'][ii], Ves=obj.Ves, Sino_RefPt=obj.Sino_RefPt) - LOS[Out['LOSprops']['Keys'][ii]] = {'LOS':los} + kkeys = Out['LOSprops'].keys() + for ii in range(0,len(Out['LOSprops']['Keys'])): + idlos = _Id_recreateFromdict(Out['LOSprops']['Id'][ii]) + los = TFG.LOS(idlos, Out['LOSprops']['Du'][ii], Ves=obj.Ves, Sino_RefPt=obj.Sino_RefPt) + LOS[Out['LOSprops']['Keys'][ii]] = {'LOS':los} for jj in range(0,len(kkeys)): - if not kkeys[jj] in ['Keys','Id','Du']: - LOS[Out['LOSprops']['Keys'][ii]][kkeys[jj]] = Out['LOSprops'][kkeys[jj]][ii] + if not kkeys[jj] in ['Keys','Id','Du']: + LOS[Out['LOSprops']['Keys'][ii]][kkeys[jj]] = Out['LOSprops'][kkeys[jj]][ii] obj._LOS = LOS - # Re-assigning tabulated data - fields = ['Sino', 'Span', 'Cone', 'SAng', 'SynthDiag', 'Res'] + # Re-assigning tabulated data + fields = ['Sino', 'Span', 'Cone', 'SAng', 'SynthDiag', 'Res'] for ff in fields: for kk in Out[ff].keys(): setattr(obj,kk,Out[ff][kk]) @@ -1268,210 +1369,282 @@

    Source code for tofu.pathfile

     
     
     def _get_light_SynthDiag_Res():
    -    SynthDiag = {'_SynthDiag_Done':False, '_SynthDiag_ds':None, '_SynthDiag_dsMode':None, '_SynthDiag_MarginS':None, '_SynthDiag_dX12':None, '_SynthDiag_dX12Mode':None, '_SynthDiag_Colis':None,
    -                 '_SynthDiag_Points':None, '_SynthDiag_SAng':None, '_SynthDiag_Vect':None, '_SynthDiag_dV':None}
    -    Res = {'_Res_Mode':None, '_Res_Amp':None, '_Res_Deg':None,
    -           '_Res_Pts':None, '_Res_Res':None, '_Res_CrossMesh':None, '_Res_CrossMeshMode':None,
    -           '_Res_steps':None, '_Res_Thres':None, '_Res_ThresMode':None, '_Res_ThresMin':None,
    -           '_Res_IntResCross':None, '_Res_IntResCrossMode':None, '_Res_IntResLong':None, '_Res_IntResLongMode':None, '_Res_IntNtt':None,
    -           '_Res_EqName': None,
    -           '_Res_Done': False}
    +    SynthDiag = {'_SynthDiag_Done':False, '_SynthDiag_ds':None, '_SynthDiag_dsMode':None, '_SynthDiag_MarginS':None, '_SynthDiag_dX12':None, '_SynthDiag_dX12Mode':None, '_SynthDiag_Colis':None,
    +                 '_SynthDiag_Points':None, '_SynthDiag_SAng':None, '_SynthDiag_Vect':None, '_SynthDiag_dV':None}
    +    Res = {'_Res_Mode':None, '_Res_Amp':None, '_Res_Deg':None,
    +           '_Res_Pts':None, '_Res_Res':None, '_Res_CrossMesh':None, '_Res_CrossMeshMode':None,
    +           '_Res_steps':None, '_Res_Thres':None, '_Res_ThresMode':None, '_Res_ThresMin':None,
    +           '_Res_IntResCross':None, '_Res_IntResCrossMode':None, '_Res_IntResLong':None, '_Res_IntResLongMode':None, '_Res_IntNtt':None,
    +           '_Res_EqName': None,
    +           '_Res_Done': False}
     
         return SynthDiag, Res
     
     
     
     
    -def _open_np(pathfileext, Ves=None, ReplacePath=None, out='full', Verb=False):
    -
    -    if 'TFG' in pathfileext:
    -        import tofu.geom as TFG
    -    elif 'TFEq' in pathfileext:
    -        import tofu.Eq as tfEq
    -    elif 'TFM' in pathfileext:
    -        import tofu.mesh as TFM
    -    elif 'TFMC' in pathfileext:
    -        import tofu.matcomp as TFMC
    -    elif 'TFT' in pathfileext:
    -        import tofu.treat as tft
    -    elif 'TFI' in pathfileext:
    -        import tofu.inv as TFI
    -
    -    Out = np.load(pathfileext,mmap_mode=None)
    -    Id = _Id_recreateFromdict(Out['Idsave'])
    -    if out=='Id':
    +def _open_np(pathfileext, Ves=None,
    +             ReplacePath=None, out='full', Verb=False, Print=True):
    +
    +    if 'TFG' in pathfileext:
    +        import tofu.geom as tfg
    +    elif 'TFD' in pathfileext:
    +        import tofu.data as tfd
    +    #elif 'TFEq' in pathfileext:
    +    #    import tofu.Eq as tfEq
    +    #elif 'TFM' in pathfileext:
    +    #    import tofu.mesh as TFM
    +    #elif 'TFMC' in pathfileext:
    +    #    import tofu.matcomp as TFMC
    +    #elif 'TFT' in pathfileext:
    +    #    import tofu.treat as tft
    +    #elif 'TFI' in pathfileext:
    +    #    import tofu.inv as TFI
    +
    +    try:
    +        Out = np.load(pathfileext,mmap_mode=None)
    +    except UnicodeError:
    +        Out = np.load(pathfileext,mmap_mode=None, encoding='latin1')
    +    Id = ID(fromdict=Out['Id'].tolist())
    +    if out=='Id':
             return Id
     
    -    if Id.Cls == 'Ves':
    -        obj = TFG.Ves(Id, Out['Poly'], Type=Id.Type, Exp=Id.Exp, DLong=Out['DLong'].tolist(), Clock=bool(Out['Clock']), arrayorder=str(Out['arrayorder']), Sino_RefPt=Out['Sino_RefPt'], Sino_NP=int(Out['Sino_NP']),
    -                      SavePath=Id.SavePath, dtime=Id.dtime, dtimeIn=Id._dtimeIn)
    -
    -    elif Id.Cls == 'Struct':
    -        Ves = _tryloadVes(Id)
    -        obj = TFG.Struct(Id, Out['Poly'], Type=Id.Type, Exp=Id.Exp, DLong=Out['DLong'].tolist(), Ves=Ves, Clock=bool(Out['Clock']), arrayorder=str(Out['arrayorder']),
    -                         SavePath=Id.SavePath, dtime=Id.dtime, dtimeIn=Id._dtimeIn)
    -
    -    elif Id.Cls == 'LOS':
    -        Ves = _tryloadVes(Id)
    -        obj = TFG.LOS(Id, tuple(Out['Du']), Type=Id.Type, Ves=Ves, Sino_RefPt=Out['Sino_RefPt'], arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']), Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot,
    -                      SavePath=Id.SavePath, dtime=Id.dtime, dtimeIn=Id._dtimeIn)
    -    elif Id.Cls == 'GLOS':
    -        Ves = _tryloadVes(Id)
    -        LLOS, IdLOS = [], Id.LObj['LOS']
    -        for ii in range(0,len(IdLOS['Name'])):
    -            Idl = _Id_recreateFromdict(Out['LIdLOS'][ii])
    -            ll = TFG.LOS(Idl, Du=(Out['LDs'][:,ii],Out['Lus'][:,ii]), Ves=Ves, Sino_RefPt=Out['Sino_RefPt'], arrayorder=str(Out['arrayorder']))
    -            LLOS.append(ll)
    -        obj = TFG.GLOS(Id, LLOS, Ves=Ves, Type=Id.Type, Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot, Sino_RefPt=Out['Sino_RefPt'], SavePath=Id.SavePath, arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']),
    -                       dtime=Id.dtime, dtimeIn=Id._dtimeIn)
    -
    -    elif Id.Cls == 'Lens':
    -        Ves = _tryloadVes(Id, Ves=Ves)
    -        obj = TFG.Lens(Id, Out['O'], Out['nIn'], Out['Rad'][0], Out['F1'][0], F2=Out['F2'][0], Type=Id.Type, R1=Out['R1'][0], R2=Out['R2'][0], dd=Out['dd'][0], Ves=Ves,
    -                Exp=Id.Exp, Clock=bool(Out['Clock']), Diag=Id.Diag, shot=Id.shot, arrayorder=str(Out['arrayorder']), SavePath=Id.SavePath, dtime=Id.dtime, dtimeIn=Id._dtimeIn)
    -
    -    elif Id.Cls == 'Apert':
    -        Ves = _tryloadVes(Id, Ves=Ves)
    -        obj = TFG.Apert(Id, Out['Poly'], Clock=bool(Out['Clock']), arrayorder=str(Out['arrayorder']), Ves=Ves, Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot, dtime=Id.dtime, dtimeIn=Id._dtimeIn)
    -
    -    elif Id.Cls == 'Detect':
    -        Ves = _tryloadVes(Id, Ves=Ves)
    -        LOSprops, Sino, Span, Cone, SAng, Opt = Out['LOSprops'][0], Out['Sino'][0], Out['Span'][0], Out['Cone'][0], Out['SAng'][0], Out['Optics'][0]
    -        (SynthDiag,Res) = (Out['SynthDiag'][0],Out['Res'][0]) if out=='full' else _get_light_SynthDiag_Res()
    -        Optics = _tryLoadOpticsElseCreate(Id, Opt=Opt, Ves=Ves, Verb=Verb)
    -
    -        Poly = Out['Poly'] if type(Optics) is list else dict(Rad=float(Out['Rad']),O=Out['BaryS'],nIn=Out['nIn'])
    -        obj = TFG.Detect(Id, Poly, Optics=Optics, Ves=Ves, Sino_RefPt=Sino['_Sino_RefPt'], CalcEtend=False, CalcSpanImp=False, CalcCone=False, CalcPreComp=False, Calc=True, Verb=Verb,
    -                         arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']))
    -        obj = _resetDetectAttr(obj, {'LOSprops':LOSprops, 'Sino':Sino, 'Span':Span, 'Cone':Cone, 'SAng':SAng, 'SynthDiag':SynthDiag, 'Res':Res, 'Optics':Opt})
    -        obj._LOS_NP = Out['LOSNP']
    -        if obj._SynthDiag_Done and obj._SynthDiag_Points is None:
    -            obj.set_SigPrecomp()
    -
    -    elif Id.Cls == 'GDetect':
    -        LDetsave = list(Out['LDetsave'])
    -        LDet = []
    -        Ves = _tryloadVes(Id, Ves=Ves)
    -        if out=='light':
    -            SynthDiag, Res = _get_light_SynthDiag_Res()
    +    if Id.Cls == 'Ves':
    +        Lim = None if Out['Lim'].tolist() is None else Out['Lim']
    +        obj = tfg.Ves(Id, Out['Poly'], Lim=Lim, Type=Id.Type,
    +                      Clock=bool(Out['Clock']),
    +                      arrayorder=str(Out['arrayorder']),
    +                      Sino_RefPt=Out['Sino_RefPt'], Sino_NP=int(Out['Sino_NP']))
    +
    +    elif Id.Cls == 'Struct':
    +        Lim = None if Out['Lim'].tolist() is None else Out['Lim']
    +        obj = tfg.Struct(Id, Out['Poly'], Type=Id.Type, Lim=Lim,
    +                         Clock=bool(Out['Clock']),
    +                         arrayorder=str(Out['arrayorder']),
    +                         mobile=Out['mobile'].tolist())
    +
    +    elif Id.Cls in ['Rays','LOS','LOSCam1D','LOSCam2D']:
    +        Ves, LStruct = _tryloadVesStruct(Id, Print=Print)
    +        dobj = {'Id':Id._todict(), 'dchans':Out['dchans'].tolist(),
    +                'geom':Out['geom'].tolist(),
    +                'sino':Out['sino'].tolist()}
    +        if 'extra' in Out.keys():
    +            dobj['extra'] = Out['extra'].tolist()
    +        if Ves is None:
    +            dobj['Ves'] = None
             else:
    -            LDetSynthRes = Out['LDetSynthRes']
    -        for ii in range(0,len(LDetsave)):
    -            ddIdsave = _Id_recreateFromdict(LDetsave[ii]['Idsave'])
    -            LOSprops, Sino, Span, Cone, SAng, Opt = LDetsave[ii]['LOSprops'][0], LDetsave[ii]['Sino'][0], LDetsave[ii]['Span'][0], LDetsave[ii]['Cone'][0], LDetsave[ii]['SAng'][0], LDetsave[ii]['Optics'][0]
    -            if out=='full':
    -                SynthDiag, Res = LDetSynthRes[ii]['SynthDiag'][0], LDetSynthRes[ii]['Res'][0]
    -            Optics = _tryLoadOpticsElseCreate(ddIdsave, Opt=Opt, Ves=Ves, Verb=Verb)
    -            Poly = LDetsave[ii]['Poly'] if type(Optics) is list else dict(Rad=float(LDetsave[ii]['Rad']),O=LDetsave[ii]['BaryS'],nIn=LDetsave[ii]['nIn'])
    -            dd = TFG.Detect(ddIdsave, Poly, Optics=Optics, Ves=Ves, Sino_RefPt=Out['Sino_RefPt'], CalcEtend=False, CalcSpanImp=False, CalcCone=False, CalcPreComp=False, Calc=True, Verb=Verb,
    -                            arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']))
    -            dd = _resetDetectAttr(dd, {'LOSprops':LOSprops, 'Sino':Sino, 'Span':Span, 'Cone':Cone, 'SAng':SAng, 'SynthDiag':SynthDiag, 'Res':Res, 'Optics':Opt})
    -            dd._LOS_NP = LDetsave[ii]['LOSNP']
    -            if dd._SynthDiag_Done and dd._SynthDiag_Points is None:
    -                dd.set_SigPrecomp()
    -            LDet.append(dd)
    -        obj = TFG.GDetect(Id, LDet, Type=Id.Type, Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot, dtime=Id.dtime, dtimeIn=Id._dtimeIn, Sino_RefPt=Out['Sino_RefPt'], LOSRef=str(Out['LOSRef']),
    -                          arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']), SavePath=Id.SavePath)
    -        Res = Out['Res'][0] if out=='full' else Res
    -        for kk in Res.keys():
    -            setattr(obj,kk,Res[kk])
    -
    -    elif Id.Cls=='Eq2D':
    -        Sep = [np.array(ss) for ss in Out['Sep'].tolist()]
    -        obj = tfEq.Eq2D(Id, Out['PtsCross'], t=Out['t'], MagAx=Out['MagAx'], Sep=Sep, rho_p=Out['rho_p'].tolist(), rho_t=Out['rho_t'].tolist(), surf=Out['surf'].tolist(), vol=Out['vol'].tolist(),
    -                        q=Out['q'].tolist(), jp=Out['jp'].tolist(), pf=Out['pf'].tolist(), tf=Out['tf'].tolist(), theta=Out['theta'].tolist(), thetastar=Out['thetastar'].tolist(),
    -                        BTX=Out['BTX'].tolist(), BRY=Out['BRY'].tolist(), BZ=Out['BZ'].tolist(), Ref=str(Out['Ref']))
    -
    -    elif Id.Cls=='Mesh1D':
    -        obj = TFM.Mesh1D(Id, Out['Knots'])
    -
    -    elif Id.Cls=='Mesh2D':
    -        obj = TFM.Mesh2D(Id, [Out['Knots'][0],Out['Knots'][1]])
    -        obj = TFM.Mesh2D(Id, Knots=obj, ind=Out['IndBg'])
    -        for ii in range(0,len(Out['SubMinds'])):
    -            obj.add_SubMesh(Name=Out['SubMinds'][ii]['Name'], ind=Out['SubMinds'][ii]['ind'])
    -
    -    elif Id.Cls=='Metric1D':
    -        obj = TFM.Metric1D(Id)
    -
    -    elif Id.Cls=='Metric2D':
    -        obj = TFM.Metric2D(Id)
    -
    -
    -    elif Id.Cls in 'BF2D':
    -        IdMesh = ID(str(Out['IdMesh'][0]), str(Out['IdMesh'][1]), SaveName=str(Out['IdMesh'][2]), SavePath=str(Out['IdMesh'][3]), dtime=Out['dtimeMesh'][0], dtFormat=str(Out['IdMesh'][4]))
    -        M2 = TFM.Mesh2D(IdMesh, Knots=[Out['KnotsR'],Out['KnotsZ']])
    -        M2bis = TFM.Mesh2D(IdMesh,Knots=M2,Ind=Out['Ind'])
    -        obj = TFM.BF2D(Id, M2bis, int(Out['Deg'][0]))
    -    elif Id.Cls=='GMat2D':
    -        import ToFu_MatComp as TFMC
    -        import scipy.sparse as scpsp
    -        Id.set_LObj(open_np_IdObj(['Ves','BF2D','Detect'], [Out['Ves'],Out['BF2'],Out['LDetect']], [Out['VesUSR'],Out['BF2USR'],Out['LDetectUSR']]))
    -        Mat = scpsp.csr_matrix((Out['Matdata'], Out['Matind'], Out['Matindpr']), shape=Out['Matshape'])
    -        MatLOS = scpsp.csr_matrix((Out['MatLOSdata'], Out['MatLOSind'], Out['MatLOSindpr']), shape=Out['MatLOSshape'])
    -        obj = TFMC.GMat2D(Id, None, None, Mat=None, indMat=None, MatLOS=None, Calcind=False, Calc=False, CalcLOS=False)
    -        obj._init_CompParam(Mode=str(Out['CompParamStr'][0]), epsrel=Out['CompParamVal'][0], SubP=Out['CompParamVal'][1], SubMode=str(Out['CompParamStr'][1]), SubTheta=Out['CompParamVal'][2], SubThetaMode=str(Out['CompParamStr'][2]), Fast=bool(Out['CompParamVal'][-1]), SubPind=Out['CompParamVal'][3], ModeLOS=str(Out['CompParamStr'][3]), epsrelLOS=Out['CompParamVal'][4], SubPLOS=Out['CompParamVal'][5], SubModeLOS=str(Out['CompParamStr'][4]))
    -        obj._BF2 = None
    -        obj._BF2_Deg = int(Out['BF2Par'][0])
    -        obj._BF2_NCents = int(Out['BF2Par'][2])
    -        obj._BF2_NFunc = int(Out['BF2Par'][1])
    -        obj._Ves = None
    -        obj._LD = None
    -        obj._LD_nDetect = int(Out['LD_nD'])
    -        obj._set_indMat(indMat=Out['indMat'], Verb=False)
    -        obj._set_MatLOS(MatLOS=MatLOS, Verb=False)
    -        obj._set_Mat(Mat=Mat, Verb=False)
    -
    -
    -
    -    elif Id.Cls=='PreData':
    -        LIdDet = Id.get_LObjasLId('Detect') if 'Detect' in Id.LObj.keys() else None
    -        Init, Update = Out['Init'][0], Out['Update'][0]
    -        obj = tft.PreData(Init['data'], Id=Id, t=Init['t'], Chans=Init['Chans'], DtRef=Init['DtRef'], LIdDet=LIdDet)
    -        obj.set_Dt(Update['Dt'], Calc=False)
    -        obj.set_Resamp(t=Update['Resamp_t'], f=Update['Resamp_f'], Method=Update['Resamp_Method'], interpkind=Update['Resamp_interpkind'], Calc=False)
    -        obj.Out_add(indOut=Update['indOut'], Calc=False)
    -        obj.Corr_add(indCorr=Update['indCorr'], Calc=False)
    -        obj.interp(lt=Update['interp_lt'], lNames=Update['interp_lNames'], Calc=False)
    -        obj.substract_Dt(tsub=Update['Subtract_tsub'], Calc=False)
    -        obj.set_fft(Calc=True, **Update['FFTPar'])
    -        if not Update['PhysNoiseParam'] is None:
    -            Method = 'svd' if 'Modes' in Update['PhysNoiseParam'].keys() else 'fft'
    -            obj.set_PhysNoise(**Update['PhysNoiseParam'].update({'Method':Method}))
    -
    -
    -        #Id.set_LObj(open_np_IdObj(['Detect'],[Out['LDetect']], [Out['LDetectUSR']]))
    -        #obj = TFT.PreData(Id=Id, shot=int(Out['shot']), DLPar=Out['DLPar'].item(), Exp=str(Out['StrPar'][0]), Dt=list(Out['Dt']), DtMargin=float(Out['DtMarg']), MovMeanfreq=float(Out['MovMeanfreq']), Resamp=bool(Out['Resamp']),
    -        #        interpkind=str(Out['StrPar'][1]), indOut=Out['indOut'], indCorr=Out['indCorr'], lt=Out['interp_lt'], lNames=Out['interp_lN'].tolist(), Test=True)
    -        #if not Out['PhysNoise'].item() is None:
    -        #    obj.set_PhysNoise(Deg=int(Out['NoiseMod'].item()['Deg']), Nbin=int(Out['NoiseMod'].item()['Nbin']), LimRatio=float(Out['NoiseMod'].item()['LimRatio']), **Out['PhysNoise'].item()['Param'])
    -
    -
    -    elif Id.Cls=='Sol2D':
    -        Id.set_LObj(open_np_IdObj(['PreData','GMat2D','BF2D'],[Out['PreData'], Out['GMat2D'], Out['BF2D']], [Out['PreDataUSR'],Out['GMatUSR'],Out['BF2DUSR']]))
    -        GMSaveName = Id.LObj['GMat2D']['SaveName'][0]
    -        try:
    -            GMat = Open(Id.LObj['GMat2D']['SavePath'][0]+GMSaveName+'.npz')
    -        except Exception:
    -            GMSaveName = GMSaveName[:GMSaveName.index('All_')+4]+'sh'+GMSaveName[GMSaveName.index('All_')+4:]
    -            GMat = Open(Id.LObj['GMat2D']['SavePath'][0]+GMSaveName+'.npz')
    -        obj = TFI.Sol2D(Id, PreData=None, GMat=GMat, InvParam=Out['InvParam'].item(), SVesePreData=False, SVeseGMat=True, SVeseBF=True)
    -        obj._PreData = None
    -        obj._GMat = obj.GMat.get_SubGMat2D(Val=list(Out['LNames']), Crit='Name',InOut='In')
    -        obj._shot = int(Out['shot'])
    -        try:
    -            obj._LNames = Out['LNames'].tolist()
    -        except Exception:
    -            obj._LNames = obj.PreData.In_list()
    -        obj._run = bool(Out['Run'])
    -        if bool(Out['Run']):
    -            obj._LOS = bool(Out['LOS'])
    -            obj._t, obj._data = Out['t'], Out['data']
    -            obj._Coefs, obj._sigma = Out['Coefs'], Out['sigma']
    -            obj._Mu, obj._Chi2N, obj._R, obj._Nit = Out['Mu'], Out['Chi2N'], Out['R'], Out['Nit']
    -            obj._Spec = list(Out['Spec'])
    -            obj._timing = Out['t2']
    -            obj._PostTreat = list(Out['PostTreat'])
    +            dobj['Ves'] = Ves._todict()
    +        if LStruct is None:
    +            dobj['LStruct'] = None
    +        else:
    +            dobj['LStruct'] = [ss._todict() for ss in LStruct]
    +        if Id.Cls=='Rays':
    +            obj = tfg.Rays(fromdict=dobj)
    +        elif Id.Cls=='LOSCam1D':
    +            obj = tfg.LOSCam1D(fromdict=dobj)
    +        elif Id.Cls=='LOSCam2D':
    +            obj = tfg.LOSCam2D(fromdict=dobj)
    +
    +    elif Id.Cls in ['Data1D','Data2D']:
    +        dobj = {'Id':Id._todict(), 'Ref':Out['Ref'].tolist(),
    +                'dunits':Out['dunits'].tolist(), 'fft':Out['fft'].tolist(),
    +                'data0':Out['data0'].tolist(), 'CamCls':Out['CamCls'].tolist()}
    +        indt = None if Out['indt'].tolist() is None else Out['indt']
    +        indch = None if Out['indch'].tolist() is None else Out['indch']
    +        if Out['geom'].tolist() is None:
    +            geom = None
    +        else:
    +            if 'Cam' in Out['geom'][0]:
    +                LCam = [Open(ss)._todict() for ss in Out['geom']]
    +                geom = {'LCam':LCam}
    +            else:
    +                Ves = Open(Out['geom'][0])._todict()
    +                if len(Out['geom'])>1:
    +                    LStruct = [Open(ss)._todict() for ss in Out['geom'][1:]]
    +                else:
    +                    LStruct = None
    +                    geom = {'LCam':None, 'Ves':Ves, 'LStruct':LStruct}
    +        dobj['indt'] = indt
    +        dobj['indch'] = indch
    +        dobj['geom'] = geom
    +        if 'dMag' in Out.keys():
    +            dMag = Out['dMag'].tolist()
    +        else:
    +            dMag = None
    +        dobj['dMag'] = dMag
    +        if Id.Cls=='Data1D':
    +            obj = tfd.Data1D(fromdict=dobj)
    +        elif Id.Cls=='Data2D':
    +            obj = tfd.Data2D(fromdict=dobj)
    +
    +    """
    +    elif Id.Cls == 'GLOS':
    +        Ves = _tryloadVes(Id)
    +        LLOS, IdLOS = [], Id.LObj['LOS']
    +        for ii in range(0,len(IdLOS['Name'])):
    +            Idl = _Id_recreateFromdict(Out['LIdLOS'][ii])
    +            ll = TFG.LOS(Idl, Du=(Out['LDs'][:,ii],Out['Lus'][:,ii]), Ves=Ves, Sino_RefPt=Out['Sino_RefPt'], arrayorder=str(Out['arrayorder']))
    +            LLOS.append(ll)
    +        obj = TFG.GLOS(Id, LLOS, Ves=Ves, Type=Id.Type, Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot, Sino_RefPt=Out['Sino_RefPt'], SavePath=Id.SavePath, arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']),
    +                       dtime=Id.dtime)
    +
    +    elif Id.Cls == 'Lens':
    +        Ves = _tryloadVes(Id, Ves=Ves)
    +        obj = TFG.Lens(Id, Out['O'], Out['nIn'], Out['Rad'][0], Out['F1'][0], F2=Out['F2'][0], Type=Id.Type, R1=Out['R1'][0], R2=Out['R2'][0], dd=Out['dd'][0], Ves=Ves,
    +                Exp=Id.Exp, Clock=bool(Out['Clock']), Diag=Id.Diag, shot=Id.shot, arrayorder=str(Out['arrayorder']), SavePath=Id.SavePath, dtime=Id.dtime)
    +
    +    elif Id.Cls == 'Apert':
    +        Ves = _tryloadVes(Id, Ves=Ves)
    +        obj = TFG.Apert(Id, Out['Poly'], Clock=bool(Out['Clock']), arrayorder=str(Out['arrayorder']), Ves=Ves, Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot, dtime=Id.dtime)
    +
    +    elif Id.Cls == 'Detect':
    +        Ves = _tryloadVes(Id, Ves=Ves)
    +        if 'VesCalc'in Out.keys() and Out['VesCalc'][0]['SavePath'] is not None:
    +            VesCalc = Open(Out['VesCalc'][0]['SavePath']+Out['VesCalc'][0]['SaveName']+'.npz')
    +        else:
    +            VesCalc = None
    +        LOSprops, Sino, Span, Cone, SAng, Opt = Out['LOSprops'][0], Out['Sino'][0], Out['Span'][0], Out['Cone'][0], Out['SAng'][0], Out['Optics'][0]
    +        (SynthDiag,Res) = (Out['SynthDiag'][0],Out['Res'][0]) if out=='full' else _get_light_SynthDiag_Res()
    +        Optics = _tryLoadOpticsElseCreate(Id, Opt=Opt, Ves=Ves, Verb=Verb)
    +
    +        Poly = Out['Poly'] if type(Optics) is list else dict(Rad=float(Out['Rad']),O=Out['BaryS'],nIn=Out['nIn'])
    +        obj = TFG.Detect(Id, Poly, Optics=Optics, Ves=Ves, VesCalc=VesCalc, Sino_RefPt=Sino['_Sino_RefPt'], CalcEtend=False, CalcSpanImp=False, CalcCone=False, CalcPreComp=False, Calc=True, Verb=Verb,
    +                         arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']))
    +        obj = _resetDetectAttr(obj, {'LOSprops':LOSprops, 'Sino':Sino, 'Span':Span, 'Cone':Cone, 'SAng':SAng, 'SynthDiag':SynthDiag, 'Res':Res, 'Optics':Opt})
    +        obj._LOS_NP = Out['LOSNP']
    +        if obj._SynthDiag_Done and obj._SynthDiag_Points is None:
    +            obj.set_SigPrecomp()
    +
    +    elif Id.Cls == 'GDetect':
    +        LDetsave = list(Out['LDetsave'])
    +        LDet = []
    +        Ves = _tryloadVes(Id, Ves=Ves)
    +        if out=='light':
    +            SynthDiag, Res = _get_light_SynthDiag_Res()
    +        else:
    +            LDetSynthRes = Out['LDetSynthRes']
    +        for ii in range(0,len(LDetsave)):
    +            ddIdsave = _Id_recreateFromdict(LDetsave[ii]['Idsave'])
    +            if 'VesCalc'in LDetsave[ii].keys() and LDetsave[ii]['VesCalc'][0]['SavePath'] is not None:
    +                VesCalc = Open(LDetsave[ii]['VesCalc'][0]['SavePath']+LDetsave[ii]['VesCalc'][0]['SaveName']+'.npz')
    +            else:
    +                VesCalc = None
    +            LOSprops, Sino, Span, Cone, SAng, Opt = LDetsave[ii]['LOSprops'][0], LDetsave[ii]['Sino'][0], LDetsave[ii]['Span'][0], LDetsave[ii]['Cone'][0], LDetsave[ii]['SAng'][0], LDetsave[ii]['Optics'][0]
    +            if out=='full':
    +                SynthDiag, Res = LDetSynthRes[ii]['SynthDiag'][0], LDetSynthRes[ii]['Res'][0]
    +            Optics = _tryLoadOpticsElseCreate(ddIdsave, Opt=Opt, Ves=Ves, Verb=Verb)
    +            Poly = LDetsave[ii]['Poly'] if type(Optics) is list else dict(Rad=float(LDetsave[ii]['Rad']),O=LDetsave[ii]['BaryS'],nIn=LDetsave[ii]['nIn'])
    +            Sino_RefPt = None if Out['Sino_RefPt'].shape==() else Out['Sino_RefPt']
    +            dd = TFG.Detect(ddIdsave, Poly, Optics=Optics, Ves=Ves, VesCalc=VesCalc, Sino_RefPt=Sino_RefPt, CalcEtend=False, CalcSpanImp=False, CalcCone=False, CalcPreComp=False, Calc=True, Verb=Verb,
    +                            arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']))
    +            dd = _resetDetectAttr(dd, {'LOSprops':LOSprops, 'Sino':Sino, 'Span':Span, 'Cone':Cone, 'SAng':SAng, 'SynthDiag':SynthDiag, 'Res':Res, 'Optics':Opt})
    +            dd._LOS_NP = LDetsave[ii]['LOSNP']
    +            if dd._SynthDiag_Done and dd._SynthDiag_Points is None:
    +                dd.set_SigPrecomp()
    +            LDet.append(dd)
    +        obj = TFG.GDetect(Id, LDet, Type=Id.Type, Exp=Id.Exp, Diag=Id.Diag, shot=Id.shot, dtime=Id.dtime, Sino_RefPt=Out['Sino_RefPt'], LOSRef=str(Out['LOSRef']),
    +                          arrayorder=str(Out['arrayorder']), Clock=bool(Out['Clock']), SavePath=Id.SavePath)
    +        Res = Out['Res'][0] if out=='full' else Res
    +        for kk in Res.keys():
    +            setattr(obj,kk,Res[kk])
    +
    +    elif Id.Cls=='Eq2D':
    +        Sep = [np.array(ss) for ss in Out['Sep'].tolist()]
    +        obj = tfEq.Eq2D(Id, Out['PtsCross'], t=Out['t'], MagAx=Out['MagAx'], Sep=Sep, rho_p=Out['rho_p'].tolist(), rho_t=Out['rho_t'].tolist(), surf=Out['surf'].tolist(), vol=Out['vol'].tolist(),
    +                        q=Out['q'].tolist(), jp=Out['jp'].tolist(), pf=Out['pf'].tolist(), tf=Out['tf'].tolist(), theta=Out['theta'].tolist(), thetastar=Out['thetastar'].tolist(),
    +                        BTX=Out['BTX'].tolist(), BRY=Out['BRY'].tolist(), BZ=Out['BZ'].tolist(), Ref=str(Out['Ref']))
    +
    +    elif Id.Cls=='Mesh1D':
    +        obj = TFM.Mesh1D(Id, Out['Knots'])
    +
    +    elif Id.Cls=='Mesh2D':
    +        obj = TFM.Mesh2D(Id, [Out['Knots'][0],Out['Knots'][1]])
    +        obj = TFM.Mesh2D(Id, Knots=obj, ind=Out['IndBg'])
    +        for ii in range(0,len(Out['SubMinds'])):
    +            obj.add_SubMesh(Name=Out['SubMinds'][ii]['Name'], ind=Out['SubMinds'][ii]['ind'])
    +
    +    elif Id.Cls=='Metric1D':
    +        obj = TFM.Metric1D(Id)
    +
    +    elif Id.Cls=='Metric2D':
    +        obj = TFM.Metric2D(Id)
    +
    +
    +    elif Id.Cls in 'BF2D':
    +        IdMesh = ID(str(Out['IdMesh'][0]), str(Out['IdMesh'][1]), SaveName=str(Out['IdMesh'][2]), SavePath=str(Out['IdMesh'][3]), dtime=Out['dtimeMesh'][0], dtFormat=str(Out['IdMesh'][4]))
    +        M2 = TFM.Mesh2D(IdMesh, Knots=[Out['KnotsR'],Out['KnotsZ']])
    +        M2bis = TFM.Mesh2D(IdMesh,Knots=M2,Ind=Out['Ind'])
    +        obj = TFM.BF2D(Id, M2bis, int(Out['Deg'][0]))
    +    elif Id.Cls=='GMat2D':
    +        import ToFu_MatComp as TFMC
    +        import scipy.sparse as scpsp
    +        Id.set_LObj(open_np_IdObj(['Ves','BF2D','Detect'], [Out['Ves'],Out['BF2'],Out['LDetect']], [Out['VesUSR'],Out['BF2USR'],Out['LDetectUSR']]))
    +        Mat = scpsp.csr_matrix((Out['Matdata'], Out['Matind'], Out['Matindpr']), shape=Out['Matshape'])
    +        MatLOS = scpsp.csr_matrix((Out['MatLOSdata'], Out['MatLOSind'], Out['MatLOSindpr']), shape=Out['MatLOSshape'])
    +        obj = TFMC.GMat2D(Id, None, None, Mat=None, indMat=None, MatLOS=None, Calcind=False, Calc=False, CalcLOS=False)
    +        obj._init_CompParam(Mode=str(Out['CompParamStr'][0]), epsrel=Out['CompParamVal'][0], SubP=Out['CompParamVal'][1], SubMode=str(Out['CompParamStr'][1]), SubTheta=Out['CompParamVal'][2], SubThetaMode=str(Out['CompParamStr'][2]), Fast=bool(Out['CompParamVal'][-1]), SubPind=Out['CompParamVal'][3], ModeLOS=str(Out['CompParamStr'][3]), epsrelLOS=Out['CompParamVal'][4], SubPLOS=Out['CompParamVal'][5], SubModeLOS=str(Out['CompParamStr'][4]))
    +        obj._BF2 = None
    +        obj._BF2_Deg = int(Out['BF2Par'][0])
    +        obj._BF2_NCents = int(Out['BF2Par'][2])
    +        obj._BF2_NFunc = int(Out['BF2Par'][1])
    +        obj._Ves = None
    +        obj._LD = None
    +        obj._LD_nDetect = int(Out['LD_nD'])
    +        obj._set_indMat(indMat=Out['indMat'], Verb=False)
    +        obj._set_MatLOS(MatLOS=MatLOS, Verb=False)
    +        obj._set_Mat(Mat=Mat, Verb=False)
    +
    +
    +
    +    elif Id.Cls=='PreData':
    +        LIdDet = Id.get_LObjasLId('Detect') if 'Detect' in Id.LObj.keys() else None
    +        Init, Update = Out['Init'][0], Out['Update'][0]
    +        obj = tft.PreData(Init['data'], Id=Id, t=Init['t'], Chans=Init['Chans'], DtRef=Init['DtRef'], LIdDet=LIdDet)
    +        obj.set_Dt(Update['Dt'], Calc=False)
    +        obj.set_Resamp(t=Update['Resamp_t'], f=Update['Resamp_f'], Method=Update['Resamp_Method'], interpkind=Update['Resamp_interpkind'], Calc=False)
    +        obj.Out_add(indOut=Update['indOut'], Calc=False)
    +        obj.Corr_add(indCorr=Update['indCorr'], Calc=False)
    +        obj.interp(lt=Update['interp_lt'], lNames=Update['interp_lNames'], Calc=False)
    +        obj.substract_Dt(tsub=Update['Subtract_tsub'], Calc=False)
    +        obj.set_fft(Calc=True, **Update['FFTPar'])
    +        if not Update['PhysNoiseParam'] is None:
    +            Method = 'svd' if 'Modes' in Update['PhysNoiseParam'].keys() else 'fft'
    +            obj.set_PhysNoise(**Update['PhysNoiseParam'].update({'Method':Method}))
    +
    +
    +        #Id.set_LObj(open_np_IdObj(['Detect'],[Out['LDetect']], [Out['LDetectUSR']]))
    +        #obj = TFT.PreData(Id=Id, shot=int(Out['shot']), DLPar=Out['DLPar'].item(), Exp=str(Out['StrPar'][0]), Dt=list(Out['Dt']), DtMargin=float(Out['DtMarg']), MovMeanfreq=float(Out['MovMeanfreq']), Resamp=bool(Out['Resamp']),
    +        #        interpkind=str(Out['StrPar'][1]), indOut=Out['indOut'], indCorr=Out['indCorr'], lt=Out['interp_lt'], lNames=Out['interp_lN'].tolist(), Test=True)
    +        #if not Out['PhysNoise'].item() is None:
    +        #    obj.set_PhysNoise(Deg=int(Out['NoiseMod'].item()['Deg']), Nbin=int(Out['NoiseMod'].item()['Nbin']), LimRatio=float(Out['NoiseMod'].item()['LimRatio']), **Out['PhysNoise'].item()['Param'])
    +
    +
    +    elif Id.Cls=='Sol2D':
    +        Id.set_LObj(open_np_IdObj(['PreData','GMat2D','BF2D'],[Out['PreData'], Out['GMat2D'], Out['BF2D']], [Out['PreDataUSR'],Out['GMatUSR'],Out['BF2DUSR']]))
    +        GMSaveName = Id.LObj['GMat2D']['SaveName'][0]
    +        try:
    +            GMat = Open(Id.LObj['GMat2D']['SavePath'][0]+GMSaveName+'.npz')
    +        except Exception:
    +            GMSaveName = GMSaveName[:GMSaveName.index('All_')+4]+'sh'+GMSaveName[GMSaveName.index('All_')+4:]
    +            GMat = Open(Id.LObj['GMat2D']['SavePath'][0]+GMSaveName+'.npz')
    +        obj = TFI.Sol2D(Id, PreData=None, GMat=GMat, InvParam=Out['InvParam'].item(), SVesePreData=False, SVeseGMat=True, SVeseBF=True)
    +        obj._PreData = None
    +        obj._GMat = obj.GMat.get_SubGMat2D(Val=list(Out['LNames']), Crit='Name',InOut='In')
    +        obj._shot = int(Out['shot'])
    +        try:
    +            obj._LNames = Out['LNames'].tolist()
    +        except Exception:
    +            obj._LNames = obj.PreData.In_list()
    +        obj._run = bool(Out['Run'])
    +        if bool(Out['Run']):
    +            obj._LOS = bool(Out['LOS'])
    +            obj._t, obj._data = Out['t'], Out['data']
    +            obj._Coefs, obj._sigma = Out['Coefs'], Out['sigma']
    +            obj._Mu, obj._Chi2N, obj._R, obj._Nit = Out['Mu'], Out['Chi2N'], Out['R'], Out['Nit']
    +            obj._Spec = list(Out['Spec'])
    +            obj._timing = Out['t2']
    +            obj._PostTreat = list(Out['PostTreat'])
    +    """
         return obj
     
     
    @@ -1485,13 +1658,13 @@ 

    Source code for tofu.pathfile

           
         
       
     
    \ No newline at end of file
    diff --git a/doc/build/html/_static/basic.css b/doc/build/html/_static/basic.css
    index 2b513f0c9..c41d718e4 100644
    --- a/doc/build/html/_static/basic.css
    +++ b/doc/build/html/_static/basic.css
    @@ -4,7 +4,7 @@
      *
      * Sphinx stylesheet -- basic theme.
      *
    - * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
    + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
      * :license: BSD, see LICENSE for details.
      *
      */
    @@ -81,10 +81,26 @@ div.sphinxsidebar input {
         font-size: 1em;
     }
     
    +div.sphinxsidebar #searchbox form.search {
    +    overflow: hidden;
    +}
    +
     div.sphinxsidebar #searchbox input[type="text"] {
    -    width: 170px;
    +    float: left;
    +    width: 80%;
    +    padding: 0.25em;
    +    box-sizing: border-box;
     }
     
    +div.sphinxsidebar #searchbox input[type="submit"] {
    +    float: left;
    +    width: 20%;
    +    border-left: none;
    +    padding: 0.25em;
    +    box-sizing: border-box;
    +}
    +
    +
     img {
         border: 0;
         max-width: 100%;
    @@ -122,6 +138,8 @@ ul.keywordmatches li.goodmatch a {
     
     table.contentstable {
         width: 90%;
    +    margin-left: auto;
    +    margin-right: auto;
     }
     
     table.contentstable p.biglink {
    @@ -149,9 +167,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 {
    @@ -183,8 +206,20 @@ div.genindex-jumpbox {
         padding: 0.4em;
     }
     
    +/* -- domain module index --------------------------------------------------- */
    +
    +table.modindextable td {
    +    padding: 2px;
    +    border-collapse: collapse;
    +}
    +
     /* -- general body styles --------------------------------------------------- */
     
    +div.body {
    +    min-width: 450px;
    +    max-width: 800px;
    +}
    +
     div.body p, div.body dd, div.body li, div.body blockquote {
         -moz-hyphens: auto;
         -ms-hyphens: auto;
    @@ -196,6 +231,16 @@ a.headerlink {
         visibility: hidden;
     }
     
    +a.brackets:before,
    +span.brackets > a:before{
    +    content: "[";
    +}
    +
    +a.brackets:after,
    +span.brackets > a:after {
    +    content: "]";
    +}
    +
     h1:hover > a.headerlink,
     h2:hover > a.headerlink,
     h3:hover > a.headerlink,
    @@ -217,10 +262,6 @@ div.body td {
         text-align: left;
     }
     
    -.field-list ul {
    -    padding-left: 1em;
    -}
    -
     .first {
         margin-top: 0 !important;
     }
    @@ -248,6 +289,12 @@ img.align-center, .figure.align-center, object.align-center {
       margin-right: auto;
     }
     
    +img.align-default, .figure.align-default {
    +  display: block;
    +  margin-left: auto;
    +  margin-right: auto;
    +}
    +
     .align-left {
         text-align: left;
     }
    @@ -256,6 +303,10 @@ img.align-center, .figure.align-center, object.align-center {
         text-align: center;
     }
     
    +.align-default {
    +    text-align: center;
    +}
    +
     .align-right {
         text-align: right;
     }
    @@ -322,6 +373,16 @@ table.docutils {
         border-collapse: collapse;
     }
     
    +table.align-center {
    +    margin-left: auto;
    +    margin-right: auto;
    +}
    +
    +table.align-default {
    +    margin-left: auto;
    +    margin-right: auto;
    +}
    +
     table caption span.caption-number {
         font-style: italic;
     }
    @@ -337,10 +398,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;
     }
    @@ -359,6 +416,16 @@ table.citation td {
         border-bottom: none;
     }
     
    +th > p:first-child,
    +td > p:first-child {
    +    margin-top: 0px;
    +}
    +
    +th > p:last-child,
    +td > p:last-child {
    +    margin-bottom: 0px;
    +}
    +
     /* -- figures --------------------------------------------------------------- */
     
     div.figure {
    @@ -377,6 +444,34 @@ 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;
    +}
    +
    +/* -- hlist styles ---------------------------------------------------------- */
    +
    +table.hlist td {
    +    vertical-align: top;
    +}
    +
     
     /* -- other body styles ----------------------------------------------------- */
     
    @@ -400,11 +495,57 @@ ol.upperroman {
         list-style: upper-roman;
     }
     
    +li > p:first-child {
    +    margin-top: 0px;
    +}
    +
    +li > p:last-child {
    +    margin-bottom: 0px;
    +}
    +
    +dl.footnote > dt,
    +dl.citation > dt {
    +    float: left;
    +}
    +
    +dl.footnote > dd,
    +dl.citation > dd {
    +    margin-bottom: 0em;
    +}
    +
    +dl.footnote > dd:after,
    +dl.citation > dd:after {
    +    content: "";
    +    clear: both;
    +}
    +
    +dl.field-list {
    +    display: flex;
    +    flex-wrap: wrap;
    +}
    +
    +dl.field-list > dt {
    +    flex-basis: 20%;
    +    font-weight: bold;
    +    word-break: break-word;
    +}
    +
    +dl.field-list > dt:after {
    +    content: ":";
    +}
    +
    +dl.field-list > dd {
    +    flex-basis: 70%;
    +    padding-left: 1em;
    +    margin-left: 0em;
    +    margin-bottom: 0em;
    +}
    +
     dl {
         margin-bottom: 15px;
     }
     
    -dd p {
    +dd > p:first-child {
         margin-top: 0px;
     }
     
    @@ -418,24 +559,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;
     }
    @@ -482,6 +618,12 @@ dl.glossary dt {
         font-style: oblique;
     }
     
    +.classifier:before {
    +    font-style: normal;
    +    margin: 0.5em;
    +    content: ":";
    +}
    +
     abbr, acronym {
         border-bottom: dotted 1px;
         cursor: help;
    @@ -494,6 +636,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;
    @@ -585,6 +734,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/doc/build/html/_static/classic.css b/doc/build/html/_static/classic.css
    index d98894b3f..8c6dae44c 100644
    --- a/doc/build/html/_static/classic.css
    +++ b/doc/build/html/_static/classic.css
    @@ -1,10 +1,10 @@
     /*
    - * default.css_t
    + * classic.css_t
      * ~~~~~~~~~~~~~
      *
    - * Sphinx stylesheet -- default theme.
    + * Sphinx stylesheet -- classic theme.
      *
    - * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
    + * :copyright: Copyright 2007-2019 by the Sphinx team, see AUTHORS.
      * :license: BSD, see LICENSE for details.
      *
      */
    diff --git a/doc/build/html/_static/doctools.js b/doc/build/html/_static/doctools.js
    index 816349563..b33f87fcb 100644
    --- a/doc/build/html/_static/doctools.js
    +++ b/doc/build/html/_static/doctools.js
    @@ -4,7 +4,7 @@
      *
      * Sphinx JavaScript utilities for all documentation.
      *
    - * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
    + * :copyright: Copyright 2007-2019 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,54 @@ 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;
    +      if (pos >= 0 &&
    +          !jQuery(node.parentNode).hasClass(className) &&
    +          !jQuery(node.parentNode).hasClass("nohighlight")) {
    +        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 rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    +          var bbox = node.parentElement.getBBox();
    +          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);
    +          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,28 +149,30 @@ var Documentation = {
         this.fixFirefoxAnchorBug();
         this.highlightSearchWords();
         this.initIndexTable();
    -    
    +    if (DOCUMENTATION_OPTIONS.NAVIGATION_WITH_KEYS) {
    +      this.initOnKeyListeners();
    +    }
       },
     
       /**
        * 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)];
       },
    @@ -180,7 +207,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);
    @@ -216,7 +243,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');
    @@ -248,7 +275,7 @@ 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('/');
    @@ -284,4 +311,4 @@ _ = Documentation.gettext;
     
     $(document).ready(function() {
       Documentation.init();
    -});
    \ No newline at end of file
    +});
    diff --git a/doc/build/html/_static/file.png b/doc/build/html/_static/file.png
    index 254c60bfb..a858a410e 100644
    Binary files a/doc/build/html/_static/file.png and b/doc/build/html/_static/file.png differ
    diff --git a/doc/build/html/_static/jquery.js b/doc/build/html/_static/jquery.js
    index ab28a2472..644d35e27 100644
    --- a/doc/build/html/_static/jquery.js
    +++ b/doc/build/html/_static/jquery.js
    @@ -1,4 +1,4 @@
    -/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
    -!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b){return b.toUpperCase()};m.fn=m.prototype={jquery:l,constructor:m,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=m.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return m.each(this,a,b)},map:function(a){return this.pushStack(m.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},m.extend=m.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||m.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(m.isPlainObject(c)||(b=m.isArray(c)))?(b?(b=!1,f=a&&m.isArray(a)?a:[]):f=a&&m.isPlainObject(a)?a:{},g[d]=m.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},m.extend({expando:"jQuery"+(l+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===m.type(a)},isArray:Array.isArray||function(a){return"array"===m.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return!m.isArray(a)&&a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==m.type(a)||a.nodeType||m.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(k.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&m.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(o,"ms-").replace(p,q)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=r(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:function(a){return null==a?"":(a+"").replace(n,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(r(Object(a))?m.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=r(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),m.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||m.guid++,e):void 0},now:function(){return+new Date},support:k}),m.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function r(a){var b=a.length,c=m.type(a);return"function"===c||m.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var s=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u="sizzle"+-new Date,v=a.document,w=0,x=0,y=gb(),z=gb(),A=gb(),B=function(a,b){return a===b&&(l=!0),0},C="undefined",D=1<<31,E={}.hasOwnProperty,F=[],G=F.pop,H=F.push,I=F.push,J=F.slice,K=F.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},L="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",M="[\\x20\\t\\r\\n\\f]",N="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=N.replace("w","w#"),P="\\["+M+"*("+N+")(?:"+M+"*([*^$|!~]?=)"+M+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+O+"))|)"+M+"*\\]",Q=":("+N+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+P+")*)|.*)\\)|)",R=new RegExp("^"+M+"+|((?:^|[^\\\\])(?:\\\\.)*)"+M+"+$","g"),S=new RegExp("^"+M+"*,"+M+"*"),T=new RegExp("^"+M+"*([>+~]|"+M+")"+M+"*"),U=new RegExp("="+M+"*([^\\]'\"]*?)"+M+"*\\]","g"),V=new RegExp(Q),W=new RegExp("^"+O+"$"),X={ID:new RegExp("^#("+N+")"),CLASS:new RegExp("^\\.("+N+")"),TAG:new RegExp("^("+N.replace("w","w*")+")"),ATTR:new RegExp("^"+P),PSEUDO:new RegExp("^"+Q),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+M+"*(even|odd|(([+-]|)(\\d*)n|)"+M+"*(?:([+-]|)"+M+"*(\\d+)|))"+M+"*\\)|)","i"),bool:new RegExp("^(?:"+L+")$","i"),needsContext:new RegExp("^"+M+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+M+"*((?:-\\d)?\\d*)"+M+"*\\)|)(?=[^-]|$)","i")},Y=/^(?:input|select|textarea|button)$/i,Z=/^h\d$/i,$=/^[^{]+\{\s*\[native \w/,_=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,ab=/[+~]/,bb=/'|\\/g,cb=new RegExp("\\\\([\\da-f]{1,6}"+M+"?|("+M+")|.)","ig"),db=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{I.apply(F=J.call(v.childNodes),v.childNodes),F[v.childNodes.length].nodeType}catch(eb){I={apply:F.length?function(a,b){H.apply(a,J.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function fb(a,b,d,e){var f,h,j,k,l,o,r,s,w,x;if((b?b.ownerDocument||b:v)!==n&&m(b),b=b||n,d=d||[],!a||"string"!=typeof a)return d;if(1!==(k=b.nodeType)&&9!==k)return[];if(p&&!e){if(f=_.exec(a))if(j=f[1]){if(9===k){if(h=b.getElementById(j),!h||!h.parentNode)return d;if(h.id===j)return d.push(h),d}else if(b.ownerDocument&&(h=b.ownerDocument.getElementById(j))&&t(b,h)&&h.id===j)return d.push(h),d}else{if(f[2])return I.apply(d,b.getElementsByTagName(a)),d;if((j=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return I.apply(d,b.getElementsByClassName(j)),d}if(c.qsa&&(!q||!q.test(a))){if(s=r=u,w=b,x=9===k&&a,1===k&&"object"!==b.nodeName.toLowerCase()){o=g(a),(r=b.getAttribute("id"))?s=r.replace(bb,"\\$&"):b.setAttribute("id",s),s="[id='"+s+"'] ",l=o.length;while(l--)o[l]=s+qb(o[l]);w=ab.test(a)&&ob(b.parentNode)||b,x=o.join(",")}if(x)try{return I.apply(d,w.querySelectorAll(x)),d}catch(y){}finally{r||b.removeAttribute("id")}}}return i(a.replace(R,"$1"),b,d,e)}function gb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function hb(a){return a[u]=!0,a}function ib(a){var b=n.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function jb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function kb(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||D)-(~a.sourceIndex||D);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function lb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function mb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function nb(a){return hb(function(b){return b=+b,hb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function ob(a){return a&&typeof a.getElementsByTagName!==C&&a}c=fb.support={},f=fb.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},m=fb.setDocument=function(a){var b,e=a?a.ownerDocument||a:v,g=e.defaultView;return e!==n&&9===e.nodeType&&e.documentElement?(n=e,o=e.documentElement,p=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){m()},!1):g.attachEvent&&g.attachEvent("onunload",function(){m()})),c.attributes=ib(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=ib(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=$.test(e.getElementsByClassName)&&ib(function(a){return a.innerHTML="
    ",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=ib(function(a){return o.appendChild(a).id=u,!e.getElementsByName||!e.getElementsByName(u).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==C&&p){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(cb,db);return function(a){var c=typeof a.getAttributeNode!==C&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==C?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==C&&p?b.getElementsByClassName(a):void 0},r=[],q=[],(c.qsa=$.test(e.querySelectorAll))&&(ib(function(a){a.innerHTML="",a.querySelectorAll("[msallowclip^='']").length&&q.push("[*^$]="+M+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||q.push("\\["+M+"*(?:value|"+L+")"),a.querySelectorAll(":checked").length||q.push(":checked")}),ib(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&q.push("name"+M+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||q.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),q.push(",.*:")})),(c.matchesSelector=$.test(s=o.matches||o.webkitMatchesSelector||o.mozMatchesSelector||o.oMatchesSelector||o.msMatchesSelector))&&ib(function(a){c.disconnectedMatch=s.call(a,"div"),s.call(a,"[s!='']:x"),r.push("!=",Q)}),q=q.length&&new RegExp(q.join("|")),r=r.length&&new RegExp(r.join("|")),b=$.test(o.compareDocumentPosition),t=b||$.test(o.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},B=b?function(a,b){if(a===b)return l=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===v&&t(v,a)?-1:b===e||b.ownerDocument===v&&t(v,b)?1:k?K.call(k,a)-K.call(k,b):0:4&d?-1:1)}:function(a,b){if(a===b)return l=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],i=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:k?K.call(k,a)-K.call(k,b):0;if(f===g)return kb(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)i.unshift(c);while(h[d]===i[d])d++;return d?kb(h[d],i[d]):h[d]===v?-1:i[d]===v?1:0},e):n},fb.matches=function(a,b){return fb(a,null,null,b)},fb.matchesSelector=function(a,b){if((a.ownerDocument||a)!==n&&m(a),b=b.replace(U,"='$1']"),!(!c.matchesSelector||!p||r&&r.test(b)||q&&q.test(b)))try{var d=s.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return fb(b,n,null,[a]).length>0},fb.contains=function(a,b){return(a.ownerDocument||a)!==n&&m(a),t(a,b)},fb.attr=function(a,b){(a.ownerDocument||a)!==n&&m(a);var e=d.attrHandle[b.toLowerCase()],f=e&&E.call(d.attrHandle,b.toLowerCase())?e(a,b,!p):void 0;return void 0!==f?f:c.attributes||!p?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},fb.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},fb.uniqueSort=function(a){var b,d=[],e=0,f=0;if(l=!c.detectDuplicates,k=!c.sortStable&&a.slice(0),a.sort(B),l){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return k=null,a},e=fb.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=fb.selectors={cacheLength:50,createPseudo:hb,match:X,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(cb,db),a[3]=(a[3]||a[4]||a[5]||"").replace(cb,db),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||fb.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&fb.error(a[0]),a},PSEUDO:function(a){var b,c=!a[6]&&a[2];return X.CHILD.test(a[0])?null:(a[3]?a[2]=a[4]||a[5]||"":c&&V.test(c)&&(b=g(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(cb,db).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=y[a+" "];return b||(b=new RegExp("(^|"+M+")"+a+"("+M+"|$)"))&&y(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==C&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=fb.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),s=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&s){k=q[u]||(q[u]={}),j=k[a]||[],n=j[0]===w&&j[1],m=j[0]===w&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[w,n,m];break}}else if(s&&(j=(b[u]||(b[u]={}))[a])&&j[0]===w)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(s&&((l[u]||(l[u]={}))[a]=[w,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||fb.error("unsupported pseudo: "+a);return e[u]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?hb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=K.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:hb(function(a){var b=[],c=[],d=h(a.replace(R,"$1"));return d[u]?hb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:hb(function(a){return function(b){return fb(a,b).length>0}}),contains:hb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:hb(function(a){return W.test(a||"")||fb.error("unsupported lang: "+a),a=a.replace(cb,db).toLowerCase(),function(b){var c;do if(c=p?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===o},focus:function(a){return a===n.activeElement&&(!n.hasFocus||n.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return Z.test(a.nodeName)},input:function(a){return Y.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:nb(function(){return[0]}),last:nb(function(a,b){return[b-1]}),eq:nb(function(a,b,c){return[0>c?c+b:c]}),even:nb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:nb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:nb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:nb(function(a,b,c){for(var d=0>c?c+b:c;++db;b++)d+=a[b].value;return d}function rb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=x++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[w,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[u]||(b[u]={}),(h=i[d])&&h[0]===w&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function sb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function tb(a,b,c){for(var d=0,e=b.length;e>d;d++)fb(a,b[d],c);return c}function ub(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function vb(a,b,c,d,e,f){return d&&!d[u]&&(d=vb(d)),e&&!e[u]&&(e=vb(e,f)),hb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||tb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:ub(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=ub(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?K.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=ub(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):I.apply(g,r)})}function wb(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],h=g||d.relative[" "],i=g?1:0,k=rb(function(a){return a===b},h,!0),l=rb(function(a){return K.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==j)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>i;i++)if(c=d.relative[a[i].type])m=[rb(sb(m),c)];else{if(c=d.filter[a[i].type].apply(null,a[i].matches),c[u]){for(e=++i;f>e;e++)if(d.relative[a[e].type])break;return vb(i>1&&sb(m),i>1&&qb(a.slice(0,i-1).concat({value:" "===a[i-2].type?"*":""})).replace(R,"$1"),c,e>i&&wb(a.slice(i,e)),f>e&&wb(a=a.slice(e)),f>e&&qb(a))}m.push(c)}return sb(m)}function xb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,h,i,k){var l,m,o,p=0,q="0",r=f&&[],s=[],t=j,u=f||e&&d.find.TAG("*",k),v=w+=null==t?1:Math.random()||.1,x=u.length;for(k&&(j=g!==n&&g);q!==x&&null!=(l=u[q]);q++){if(e&&l){m=0;while(o=a[m++])if(o(l,g,h)){i.push(l);break}k&&(w=v)}c&&((l=!o&&l)&&p--,f&&r.push(l))}if(p+=q,c&&q!==p){m=0;while(o=b[m++])o(r,s,g,h);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=G.call(i));s=ub(s)}I.apply(i,s),k&&!f&&s.length>0&&p+b.length>1&&fb.uniqueSort(i)}return k&&(w=v,j=t),r};return c?hb(f):f}return h=fb.compile=function(a,b){var c,d=[],e=[],f=A[a+" "];if(!f){b||(b=g(a)),c=b.length;while(c--)f=wb(b[c]),f[u]?d.push(f):e.push(f);f=A(a,xb(e,d)),f.selector=a}return f},i=fb.select=function(a,b,e,f){var i,j,k,l,m,n="function"==typeof a&&a,o=!f&&g(a=n.selector||a);if(e=e||[],1===o.length){if(j=o[0]=o[0].slice(0),j.length>2&&"ID"===(k=j[0]).type&&c.getById&&9===b.nodeType&&p&&d.relative[j[1].type]){if(b=(d.find.ID(k.matches[0].replace(cb,db),b)||[])[0],!b)return e;n&&(b=b.parentNode),a=a.slice(j.shift().value.length)}i=X.needsContext.test(a)?0:j.length;while(i--){if(k=j[i],d.relative[l=k.type])break;if((m=d.find[l])&&(f=m(k.matches[0].replace(cb,db),ab.test(j[0].type)&&ob(b.parentNode)||b))){if(j.splice(i,1),a=f.length&&qb(j),!a)return I.apply(e,f),e;break}}}return(n||h(a,o))(f,b,!p,e,ab.test(a)&&ob(b.parentNode)||b),e},c.sortStable=u.split("").sort(B).join("")===u,c.detectDuplicates=!!l,m(),c.sortDetached=ib(function(a){return 1&a.compareDocumentPosition(n.createElement("div"))}),ib(function(a){return a.innerHTML="","#"===a.firstChild.getAttribute("href")})||jb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&ib(function(a){return a.innerHTML="",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||jb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),ib(function(a){return null==a.getAttribute("disabled")})||jb(L,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),fb}(a);m.find=s,m.expr=s.selectors,m.expr[":"]=m.expr.pseudos,m.unique=s.uniqueSort,m.text=s.getText,m.isXMLDoc=s.isXML,m.contains=s.contains;var t=m.expr.match.needsContext,u=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,v=/^.[^:#\[\.,]*$/;function w(a,b,c){if(m.isFunction(b))return m.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return m.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(v.test(b))return m.filter(b,a,c);b=m.filter(b,a)}return m.grep(a,function(a){return m.inArray(a,b)>=0!==c})}m.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?m.find.matchesSelector(d,a)?[d]:[]:m.find.matches(a,m.grep(b,function(a){return 1===a.nodeType}))},m.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(m(a).filter(function(){for(b=0;e>b;b++)if(m.contains(d[b],this))return!0}));for(b=0;e>b;b++)m.find(a,d[b],c);return c=this.pushStack(e>1?m.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(w(this,a||[],!1))},not:function(a){return this.pushStack(w(this,a||[],!0))},is:function(a){return!!w(this,"string"==typeof a&&t.test(a)?m(a):a||[],!1).length}});var x,y=a.document,z=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,A=m.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:z.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||x).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof m?b[0]:b,m.merge(this,m.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:y,!0)),u.test(c[1])&&m.isPlainObject(b))for(c in b)m.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=y.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return x.find(a);this.length=1,this[0]=d}return this.context=y,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):m.isFunction(a)?"undefined"!=typeof x.ready?x.ready(a):a(m):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),m.makeArray(a,this))};A.prototype=m.fn,x=m(y);var B=/^(?:parents|prev(?:Until|All))/,C={children:!0,contents:!0,next:!0,prev:!0};m.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!m(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),m.fn.extend({has:function(a){var b,c=m(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(m.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=t.test(a)||"string"!=typeof a?m(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&m.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?m.unique(f):f)},index:function(a){return a?"string"==typeof a?m.inArray(this[0],m(a)):m.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(m.unique(m.merge(this.get(),m(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function D(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}m.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return m.dir(a,"parentNode")},parentsUntil:function(a,b,c){return m.dir(a,"parentNode",c)},next:function(a){return D(a,"nextSibling")},prev:function(a){return D(a,"previousSibling")},nextAll:function(a){return m.dir(a,"nextSibling")},prevAll:function(a){return m.dir(a,"previousSibling")},nextUntil:function(a,b,c){return m.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return m.dir(a,"previousSibling",c)},siblings:function(a){return m.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return m.sibling(a.firstChild)},contents:function(a){return m.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:m.merge([],a.childNodes)}},function(a,b){m.fn[a]=function(c,d){var e=m.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=m.filter(d,e)),this.length>1&&(C[a]||(e=m.unique(e)),B.test(a)&&(e=e.reverse())),this.pushStack(e)}});var E=/\S+/g,F={};function G(a){var b=F[a]={};return m.each(a.match(E)||[],function(a,c){b[c]=!0}),b}m.Callbacks=function(a){a="string"==typeof a?F[a]||G(a):m.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){m.each(b,function(b,c){var d=m.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&m.each(arguments,function(a,c){var d;while((d=m.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?m.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},m.extend({Deferred:function(a){var b=[["resolve","done",m.Callbacks("once memory"),"resolved"],["reject","fail",m.Callbacks("once memory"),"rejected"],["notify","progress",m.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return m.Deferred(function(c){m.each(b,function(b,f){var g=m.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&m.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?m.extend(a,d):d}},e={};return d.pipe=d.then,m.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&m.isFunction(a.promise)?e:0,g=1===f?a:m.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&m.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var H;m.fn.ready=function(a){return m.ready.promise().done(a),this},m.extend({isReady:!1,readyWait:1,holdReady:function(a){a?m.readyWait++:m.ready(!0)},ready:function(a){if(a===!0?!--m.readyWait:!m.isReady){if(!y.body)return setTimeout(m.ready);m.isReady=!0,a!==!0&&--m.readyWait>0||(H.resolveWith(y,[m]),m.fn.triggerHandler&&(m(y).triggerHandler("ready"),m(y).off("ready")))}}});function I(){y.addEventListener?(y.removeEventListener("DOMContentLoaded",J,!1),a.removeEventListener("load",J,!1)):(y.detachEvent("onreadystatechange",J),a.detachEvent("onload",J))}function J(){(y.addEventListener||"load"===event.type||"complete"===y.readyState)&&(I(),m.ready())}m.ready.promise=function(b){if(!H)if(H=m.Deferred(),"complete"===y.readyState)setTimeout(m.ready);else if(y.addEventListener)y.addEventListener("DOMContentLoaded",J,!1),a.addEventListener("load",J,!1);else{y.attachEvent("onreadystatechange",J),a.attachEvent("onload",J);var c=!1;try{c=null==a.frameElement&&y.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!m.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}I(),m.ready()}}()}return H.promise(b)};var K="undefined",L;for(L in m(k))break;k.ownLast="0"!==L,k.inlineBlockNeedsLayout=!1,m(function(){var a,b,c,d;c=y.getElementsByTagName("body")[0],c&&c.style&&(b=y.createElement("div"),d=y.createElement("div"),d.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",c.appendChild(d).appendChild(b),typeof b.style.zoom!==K&&(b.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",k.inlineBlockNeedsLayout=a=3===b.offsetWidth,a&&(c.style.zoom=1)),c.removeChild(d))}),function(){var a=y.createElement("div");if(null==k.deleteExpando){k.deleteExpando=!0;try{delete a.test}catch(b){k.deleteExpando=!1}}a=null}(),m.acceptData=function(a){var b=m.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var M=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,N=/([A-Z])/g;function O(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(N,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:M.test(c)?m.parseJSON(c):c}catch(e){}m.data(a,b,c)}else c=void 0}return c}function P(a){var b;for(b in a)if(("data"!==b||!m.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function Q(a,b,d,e){if(m.acceptData(a)){var f,g,h=m.expando,i=a.nodeType,j=i?m.cache:a,k=i?a[h]:a[h]&&h; -if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){m.isArray(b)?b=b.concat(m.map(b,m.camelCase)):b in d?b=[b]:(b=m.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!P(d):!m.isEmptyObject(d))return}(c||(delete g[h].data,P(g[h])))&&(f?m.cleanData([a],!0):k.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}m.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?m.cache[a[m.expando]]:a[m.expando],!!a&&!P(a)},data:function(a,b,c){return Q(a,b,c)},removeData:function(a,b){return R(a,b)},_data:function(a,b,c){return Q(a,b,c,!0)},_removeData:function(a,b){return R(a,b,!0)}}),m.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=m.data(f),1===f.nodeType&&!m._data(f,"parsedAttrs"))){c=g.length;while(c--)g[c]&&(d=g[c].name,0===d.indexOf("data-")&&(d=m.camelCase(d.slice(5)),O(f,d,e[d])));m._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){m.data(this,a)}):arguments.length>1?this.each(function(){m.data(this,a,b)}):f?O(f,a,m.data(f,a)):void 0},removeData:function(a){return this.each(function(){m.removeData(this,a)})}}),m.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=m._data(a,b),c&&(!d||m.isArray(c)?d=m._data(a,b,m.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=m.queue(a,b),d=c.length,e=c.shift(),f=m._queueHooks(a,b),g=function(){m.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return m._data(a,c)||m._data(a,c,{empty:m.Callbacks("once memory").add(function(){m._removeData(a,b+"queue"),m._removeData(a,c)})})}}),m.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.lengthh;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},W=/^(?:checkbox|radio)$/i;!function(){var a=y.createElement("input"),b=y.createElement("div"),c=y.createDocumentFragment();if(b.innerHTML="
    a",k.leadingWhitespace=3===b.firstChild.nodeType,k.tbody=!b.getElementsByTagName("tbody").length,k.htmlSerialize=!!b.getElementsByTagName("link").length,k.html5Clone="<:nav>"!==y.createElement("nav").cloneNode(!0).outerHTML,a.type="checkbox",a.checked=!0,c.appendChild(a),k.appendChecked=a.checked,b.innerHTML="",k.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,c.appendChild(b),b.innerHTML="",k.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,k.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){k.noCloneEvent=!1}),b.cloneNode(!0).click()),null==k.deleteExpando){k.deleteExpando=!0;try{delete b.test}catch(d){k.deleteExpando=!1}}}(),function(){var b,c,d=y.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(k[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),k[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var X=/^(?:input|select|textarea)$/i,Y=/^key/,Z=/^(?:mouse|pointer|contextmenu)|click/,$=/^(?:focusinfocus|focusoutblur)$/,_=/^([^.]*)(?:\.(.+)|)$/;function ab(){return!0}function bb(){return!1}function cb(){try{return y.activeElement}catch(a){}}m.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=m.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof m===K||a&&m.event.triggered===a.type?void 0:m.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(E)||[""],h=b.length;while(h--)f=_.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=m.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=m.event.special[o]||{},l=m.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&m.expr.match.needsContext.test(e),namespace:p.join(".")},i),(n=g[o])||(n=g[o]=[],n.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?n.splice(n.delegateCount++,0,l):n.push(l),m.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,n,o,p,q,r=m.hasData(a)&&m._data(a);if(r&&(k=r.events)){b=(b||"").match(E)||[""],j=b.length;while(j--)if(h=_.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=m.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,n=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=n.length;while(f--)g=n[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(n.splice(f,1),g.selector&&n.delegateCount--,l.remove&&l.remove.call(a,g));i&&!n.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||m.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)m.event.remove(a,o+b[j],c,d,!0);m.isEmptyObject(k)&&(delete r.handle,m._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,n,o=[d||y],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||y,3!==d.nodeType&&8!==d.nodeType&&!$.test(p+m.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[m.expando]?b:new m.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:m.makeArray(c,[b]),k=m.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!m.isWindow(d)){for(i=k.delegateType||p,$.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||y)&&o.push(l.defaultView||l.parentWindow||a)}n=0;while((h=o[n++])&&!b.isPropagationStopped())b.type=n>1?i:k.bindType||p,f=(m._data(h,"events")||{})[b.type]&&m._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&m.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&m.acceptData(d)&&g&&d[p]&&!m.isWindow(d)){l=d[g],l&&(d[g]=null),m.event.triggered=p;try{d[p]()}catch(r){}m.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=m.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(m._data(this,"events")||{})[a.type]||[],k=m.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=m.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((m.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?m(c,this).index(i)>=0:m.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h]","i"),hb=/^\s+/,ib=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,jb=/<([\w:]+)/,kb=/\s*$/g,rb={option:[1,""],legend:[1,"
    ","
    "],area:[1,"",""],param:[1,"",""],thead:[1,"","
    "],tr:[2,"","
    "],col:[2,"","
    "],td:[3,"","
    "],_default:k.htmlSerialize?[0,"",""]:[1,"X
    ","
    "]},sb=db(y),tb=sb.appendChild(y.createElement("div"));rb.optgroup=rb.option,rb.tbody=rb.tfoot=rb.colgroup=rb.caption=rb.thead,rb.th=rb.td;function ub(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==K?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==K?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||m.nodeName(d,b)?f.push(d):m.merge(f,ub(d,b));return void 0===b||b&&m.nodeName(a,b)?m.merge([a],f):f}function vb(a){W.test(a.type)&&(a.defaultChecked=a.checked)}function wb(a,b){return m.nodeName(a,"table")&&m.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function xb(a){return a.type=(null!==m.find.attr(a,"type"))+"/"+a.type,a}function yb(a){var b=pb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function zb(a,b){for(var c,d=0;null!=(c=a[d]);d++)m._data(c,"globalEval",!b||m._data(b[d],"globalEval"))}function Ab(a,b){if(1===b.nodeType&&m.hasData(a)){var c,d,e,f=m._data(a),g=m._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)m.event.add(b,c,h[c][d])}g.data&&(g.data=m.extend({},g.data))}}function Bb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!k.noCloneEvent&&b[m.expando]){e=m._data(b);for(d in e.events)m.removeEvent(b,d,e.handle);b.removeAttribute(m.expando)}"script"===c&&b.text!==a.text?(xb(b).text=a.text,yb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),k.html5Clone&&a.innerHTML&&!m.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&W.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}m.extend({clone:function(a,b,c){var d,e,f,g,h,i=m.contains(a.ownerDocument,a);if(k.html5Clone||m.isXMLDoc(a)||!gb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(tb.innerHTML=a.outerHTML,tb.removeChild(f=tb.firstChild)),!(k.noCloneEvent&&k.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||m.isXMLDoc(a)))for(d=ub(f),h=ub(a),g=0;null!=(e=h[g]);++g)d[g]&&Bb(e,d[g]);if(b)if(c)for(h=h||ub(a),d=d||ub(f),g=0;null!=(e=h[g]);g++)Ab(e,d[g]);else Ab(a,f);return d=ub(f,"script"),d.length>0&&zb(d,!i&&ub(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,l,n=a.length,o=db(b),p=[],q=0;n>q;q++)if(f=a[q],f||0===f)if("object"===m.type(f))m.merge(p,f.nodeType?[f]:f);else if(lb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(jb.exec(f)||["",""])[1].toLowerCase(),l=rb[i]||rb._default,h.innerHTML=l[1]+f.replace(ib,"<$1>")+l[2],e=l[0];while(e--)h=h.lastChild;if(!k.leadingWhitespace&&hb.test(f)&&p.push(b.createTextNode(hb.exec(f)[0])),!k.tbody){f="table"!==i||kb.test(f)?""!==l[1]||kb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)m.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}m.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),k.appendChecked||m.grep(ub(p,"input"),vb),q=0;while(f=p[q++])if((!d||-1===m.inArray(f,d))&&(g=m.contains(f.ownerDocument,f),h=ub(o.appendChild(f),"script"),g&&zb(h),c)){e=0;while(f=h[e++])ob.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=m.expando,j=m.cache,l=k.deleteExpando,n=m.event.special;null!=(d=a[h]);h++)if((b||m.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)n[e]?m.event.remove(d,e):m.removeEvent(d,e,g.handle);j[f]&&(delete j[f],l?delete d[i]:typeof d.removeAttribute!==K?d.removeAttribute(i):d[i]=null,c.push(f))}}}),m.fn.extend({text:function(a){return V(this,function(a){return void 0===a?m.text(this):this.empty().append((this[0]&&this[0].ownerDocument||y).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=wb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?m.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||m.cleanData(ub(c)),c.parentNode&&(b&&m.contains(c.ownerDocument,c)&&zb(ub(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&m.cleanData(ub(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&m.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return m.clone(this,a,b)})},html:function(a){return V(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(fb,""):void 0;if(!("string"!=typeof a||mb.test(a)||!k.htmlSerialize&&gb.test(a)||!k.leadingWhitespace&&hb.test(a)||rb[(jb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(ib,"<$1>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(m.cleanData(ub(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,m.cleanData(ub(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,l=this.length,n=this,o=l-1,p=a[0],q=m.isFunction(p);if(q||l>1&&"string"==typeof p&&!k.checkClone&&nb.test(p))return this.each(function(c){var d=n.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(l&&(i=m.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=m.map(ub(i,"script"),xb),f=g.length;l>j;j++)d=i,j!==o&&(d=m.clone(d,!0,!0),f&&m.merge(g,ub(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,m.map(g,yb),j=0;f>j;j++)d=g[j],ob.test(d.type||"")&&!m._data(d,"globalEval")&&m.contains(h,d)&&(d.src?m._evalUrl&&m._evalUrl(d.src):m.globalEval((d.text||d.textContent||d.innerHTML||"").replace(qb,"")));i=c=null}return this}}),m.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){m.fn[a]=function(a){for(var c,d=0,e=[],g=m(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),m(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Cb,Db={};function Eb(b,c){var d,e=m(c.createElement(b)).appendTo(c.body),f=a.getDefaultComputedStyle&&(d=a.getDefaultComputedStyle(e[0]))?d.display:m.css(e[0],"display");return e.detach(),f}function Fb(a){var b=y,c=Db[a];return c||(c=Eb(a,b),"none"!==c&&c||(Cb=(Cb||m("