tofu.geom package

The geometry module of tofu

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

Submodules

tofu.geom._GG module

tofu.geom._GG.ConvertImpact_Theta2Xi(theta, pP, pN, sort=True)
tofu.geom._GG.Dust_calc_SolidAngle(pos, r, pts, approx=True, out_coefonly=False, VType='Tor', VPoly=None, VIn=None, VLim=None, LSPoly=None, LSLim=None, LSVIn=None, Forbid=True, Test=True)

Compute the solid angle of a moving particle of varying radius as seen from any number of pixed points

Can be done w/o the approximation that r<<d If Ves (and optionally LSPoly) are provided, takes into account vignetting

tofu.geom._GG.LOS_Calc_PInOut_VesStruct(ray_orig, ray_vdir, ves_poly, ves_norm, lstruct_nlim=None, ves_lims=None, lstruct_polyx=None, lstruct_polyy=None, lstruct_lims=None, lstruct_normx=None, lstruct_normy=None, lnvert=None, nstruct_tot=0, nstruct_lim=0, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', forbid=True, test=True, num_threads=16)

Computes the entry and exit point of all provided LOS for the provided vessel polygon (toroidal or linear) with its associated structures. Return the normal vector at impact and the index of the impact segment

Parameters
  • ray_orig ((3, nlos) double array) – LOS origin points coordinates

  • ray_vdir ((3, nlos) double array) – LOS normalized direction vector

  • ves_poly ((2, num_vertex) double array) – Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the Vessel

  • ves_norm ((2, num_vertex-1) double array) – Normal vectors going “inwards” of the edges of the Polygon defined by ves_poly

  • nstruct_tot (int) – Total number of structures (counting each limited structure as one)

  • ves_lims (array) – Contains the limits min and max of vessel

  • lstruct_polyx (array) – List of x coordinates of the vertices of all structures on poloidal plane If no structures : None

  • lstruct_polyy (array) – List of y coordinates of the vertices of all structures on poloidal plane If no structures : None

  • lstruct_lims (array) – List of limits of all structures If no structures : None

  • lstruct_nlim (array of ints) – List of number of limits for all structures If no structures : None

  • lstruct_normx (array) – List of x coordinates of “inwards” normal vectors of the polygon of all the structures If no structures : None

  • lstruct_normy (array) – List of y coordinates of “inwards” normal vectors of the polygon of all the structures If no structures : None

  • rmin (double) – Minimal radius of vessel to take into consideration

  • eps_<val> (double) – Small value, acceptance of error

  • ves_type (string) – Type of vessel (“Tor” or “Lin”)

  • forbid (bool) – Should we forbid values behind visible radius ? (see rmin)

  • test (bool) – Should we run tests ?

  • num_threads (int) – The num_threads argument indicates how many threads the team should consist of. If not given, OpenMP will decide how many threads to use. Typically this is the number of cores available on the machine.

Returns

  • coeff_inter_in ((nlos) array) – scalars level of “in” intersection of the LOS (if k=0 at origin)

  • coeff_inter_out ((nlos) array) – scalars level of “out” intersection of the LOS (if k=0 at origin)

  • vperp_out ((3, nlos) array) – Coordinates of the normal vector of impact of the LOS (NaN if none)

  • ind_inter_out ((3, nlos)) – Index of structure impacted by LOS: ind_inter_out[:,ind_los]=(i,j,k) where k is the index of edge impacted on the j-th sub structure of the structure number i. If the LOS impacted the vessel i=j=0

tofu.geom._GG.LOS_Calc_kMinkMax_VesStruct(ray_orig, ray_vdir, ves_poly, ves_norm, num_surf, lnvert, ves_lims=None, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', forbid=True, test=True, num_threads=16)

Computes the entry and exit point of all provided LOS for the provided polygons (toroidal or linear) of IN structures (non-solid, or empty inside for the LOS). Attention: the surfaces can be limited, but they all have to have the same limits defined by (ves_lims) Return the set of kmin / kmax for each In struct and for each LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

num_surfint

number of surfaxes, aka ‘in’ structures or ‘vessels’

ves_poly(num_surf, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the in structures

ves_norm(num_surf, 2, num_vertex-1) double array

Normal vectors going “inwards” of the edges of the Polygon defined by ves_poly

ves_limsarray

Contains the limits min and max of vessel

rmindouble

Minimal radius of vessel to take into consideration

eps<val>double

Small value, acceptance of error

vtypestring

Type of vessel (“Tor” or “Lin”)

forbidbool

Should we forbid values behind visible radius ? (see rmin)

testbool

Should we run tests ?

num_threadsint

The num_threads argument indicates how many threads the team should consist of. If not given, OpenMP will decide how many threads to use. Typically this is the number of cores available on the machine.

Returns

  • coeff_inter_in ((num_surf, nlos) array) – scalars level of “in” intersection of the LOS (if k=0 at origin) for each surface [kmin(surf0, los0), kmin(surf0, los1), …, kmin(surf1, los0),….]

  • coeff_inter_out ((num_surf, nlos) array) – scalars level of “out” intersection of the LOS (if k=0 at origin) for each surface [kmax(surf0, los0), kmax(surf0, los1), …, kmax(surf1, los0),….]

tofu.geom._GG.LOS_areVis_PtsFromPts_VesStruct(pts1, pts2, ves_poly=None, ves_norm=None, dist=None, ves_lims=None, lstruct_nlim=None, lstruct_polyx=None, lstruct_polyy=None, lstruct_lims=None, lstruct_normx=None, lstruct_normy=None, lnvert=None, nstruct_tot=0, nstruct_lim=0, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='tor', forbid=True, test=True, num_threads=16)

Return an array of booleans indicating whether each point in pts1 can see each point in pts2 considering vignetting a given configuration.

pts1 : (3, npts1) cartesian coordinates of viewing points pts2 : (3, npts2) cartesian coordinates of points to check if viewable dist : optional argument : distance between the points pts1, pts2 ves_* : vessel descriptors (poly, norm, limits) lstruct_* : config’s structure descriptors (poly, limits, norms,

number of structures, …)

eps_* : values of precision in each direction forbid : boolean if true forbids checking “behind” the tokamak test : boolean check if input is valid or not num_threads : number of threads for parallelization

Output:
are_seen: (npts1, npts2) array of ints indicating if viewing points pts1

can see the other points pts2. are_seen[i,j] = 1 if pts1[i] sees point pts2[j]

0 else

tofu.geom._GG.LOS_calc_signal(func, ray_orig, ray_vdir, res, lims, dmethod='abs', method='sum', ani=False, t=None, fkwdargs={}, minimize='calls', Test=True, num_threads=16)

Compute the synthetic signal, minimizing either function calls or memory Params ===== func : python function st. func(pts, t=None, vect=None) => data

with ptsndarray (3, npts) - points where function is evaluated

vect : ndarray(3, npts) - if anisotropic signal vector of emiss. t: ndarray(m) - times where to compute the function

returns: datandarray(nt,nraf) if nt = 1, the array must be 2D

values of func at pts, at given time

func is the function to be integrated along the LOS

ray_orig: ndarray (3, nlos) LOS origins ray_vdir: ndarray (3, nlos) LOS directional vector res: double or list of doubles

If res is a single double: discretization step for all LOS. Else res should be a list of size nlos with the discretization step for each nlos.

lims: (2, nlos) double array

For each nlos, it given the maximum and minimum limits of the ray

dmethod: string

type of discretization step: ‘abs’ for absolute or ‘rel’ for relative

method: string

method of quadrature on the LOS

anibool

to indicate if emission is anisotropic or not

tNone or array-like

times where to integrate

minimize: string

“calls” : we use algorithm to minimize the calls to ‘func’ (default) “memory”: we use algorithm to minimize memory used “hybrid”: a mix of both methods

Testbool

we test if the inputs are giving in a proper way.

num_threads: int

number of threads if we want to parallelize the code.

tofu.geom._GG.LOS_get_sample(nlos, dL, los_lims, dmethod='abs', method='sum', Test=True, num_threads=16)

Return the sampled line, with the specified method - ‘sum’ : return N segments centers - ‘simps’: return N+1 egdes, N even (for scipy.integrate.simps) - ‘romb’ : return N+1 edges, N+1 = 2**k+1 (for scipy.integrate.romb)

The dmethod defines if the discretization step given is absolute (‘abs’) or relative (‘rel’)

dL: double or list of doubles

If dL is a single double: discretization step for all LOS. Else dL should be a list of size nlos with the discretization step for each nlos.

los_lims: (2, nlos) double array

For each nlos, it given the maximum and minimum limits of the ray

dmethod: string

type of discretization step: ‘abs’ for absolute or ‘rel’ for relative

method: string

method of quadrature on the LOS

Test: bool

to indicate if tests should be done or not

k, res, lind = Los_get_sample(…) nbrepet = np.r_[lind[0], np.diff(lind), k.size - lind[-1]] kus = k * np.repeat(ray_vdir, nbrepet, axis=1) Pts = np.repeat(ray_orig, nbrepet, axis=1) + kus

tofu.geom._GG.LOS_isVis_PtFromPts_VesStruct(pt0, pt1, pt2, pts, dist=None, ves_poly=None, ves_norm=None, ves_lims=None, lstruct_nlim=None, lstruct_polyx=None, lstruct_polyy=None, lstruct_lims=None, lstruct_normx=None, lstruct_normy=None, lnvert=None, nstruct_tot=0, nstruct_lim=0, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', forbid=True, test=True, num_threads=16)

Return an array of booleans indicating whether each point in pts is visible from the point P = [pt0, pt1, pt2] considering vignetting a given configuration.

pt0 : x - coordinate of the viewing point P pt1 : y - coordinate of the viewing point P pt2 : z - coordinate of the viewing point P pts : (3, npts) cartesian coordinates of points to check if viewable dist : optional argument : distance between points and P ves_* : vessel descriptors (poly, norm, limits) lstruct_* : config’s structure descriptors (poly, limits, norms,

number of structures, …)

eps_* : values of precision in each direction forbid : boolean if true forbids checking “behind” the tokamak test : boolean check if input is valid or not num_threads : number of threads for parallelization

Output:
is_seen: (npts1) array of ints indicating if viewing point P

can see the other points pts. is_seen[i] = 1 if P sees point pts[i]

0 else

tofu.geom._GG.LOS_sino(D, u, RZ, kOut, Mode='LOS', VType='Tor', try_new_algo=True)
tofu.geom._GG.LOS_sino_findRootkPMin_Tor(uParN, uN, Sca, RZ0, RZ1, ScaP, DParN, kOut, D0, D1, D2, u0, u1, u2, Mode='LOS')

Rendre “vectoriel” sur LOS et sur les cercles (deux boucles “for”) intersection ligne et cercle double uParN : composante de u parallel au plan (x,y)

double uN : uz double Sca : ??? produit scalaire … ? double RZ0 : Grand rayon du cercle double RZ1 : Z => cercle est centré au point (0, 0, RZ1) et rayon RZ0 double ScaP : …. ? double DParN : D origine de LOS…. ? N => norme de la composante du vecteur OD double kOut : kmax où on peut trouver un résultat double D0, double D1, double D2 : composantes de D (origine LOS) double u0, double u1, double u2 : composantes de U (direction LOS) str Mode=’LOS’ : si LOS pas de sol après kmax)

::: Faire une fonction double mais qui renvoit QUE un tableau de bool avec true si la distance est plus petite qu’un certain eps, false sinon. TODO: ……….. @LM

tofu.geom._GG.Poly_VolAngTor(Poly)
tofu.geom._GG.Poly_isClockwise(Poly)

Assuming 2D closed Poly ! http://www.faqs.org/faqs/graphics/algorithms-faq/ Find the lowest vertex (or, if there is more than one vertex with the same lowest coordinate, the rightmost of those vertices) and then take the cross product of the edges before and after it. Both methods are O(n) for n vertices, but it does seem a waste to add up the total area when a single cross product (of just the right edges) suffices. Code for this is available at ftp://cs.smith.edu/pub/code/polyorient.C (2K).

tofu.geom._GG.Sino_ImpactEnv(RZ, Poly, NP=50, Test=True)

Computes impact parameters of a Tor enveloppe (a Tor is a closed 2D polygon)

D. VEZINET, Aug. 2014 :param RZ: (2,) array indicating the reference impact point :type RZ: np.ndarray :param Poly: (2,N) array containing the coordinatesof a closed polygon :type Poly: np.ndarray :param NP: Number of indicating the number of points used for discretising theta between 0 and pi :type NP: int

Returns

theta

tofu.geom._GG._Ves_Smesh_Lin_SubFromD_cython(XMinMax, dL, dX, VPoly, DX=None, DY=None, DZ=None, DIn=0.0, VIn=None, margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DX,DY,DZ), for the desired resolution (dX,dL)

tofu.geom._GG._Ves_Smesh_Lin_SubFromInd_cython(XMinMax, dL, dX, VPoly, ind, DIn=0.0, VIn=None, margin=1e-09)

Return the desired surfacic submesh indicated by ind, for the desired resolution (dX,dL)

tofu.geom._GG._Ves_Smesh_TorStruct_SubFromD_cython(PhiMinMax, dL, dRPhi, VPoly, DR=None, DZ=None, DPhi=None, DIn=0.0, VIn=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DR,DZ,DPhi), for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Smesh_TorStruct_SubFromInd_cython(PhiMinMax, dL, dRPhi, VPoly, ind, DIn=0.0, VIn=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DR,DZ,DPhi) for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Smesh_Tor_SubFromD_cython(dL, dRPhi, VPoly, DR=None, DZ=None, DPhi=None, DIn=0.0, VIn=None, PhiMinMax=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DR,DZ,DPhi) for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Smesh_Tor_SubFromInd_cython(dL, dRPhi, VPoly, ind, DIn=0.0, VIn=None, PhiMinMax=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired submesh indicated by the (numerical) indices, for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Vmesh_Lin_SubFromD_cython(dX, dY, dZ, XMinMax, YMinMax, ZMinMax, DX=None, DY=None, DZ=None, limit_vpoly=None, margin=1e-09)

Return the desired submesh indicated by the limits (DX,DY,DZ), for the desired resolution (dX,dY,dZ)

tofu.geom._GG._Ves_Vmesh_Lin_SubFromInd_cython(dX, dY, dZ, XMinMax, YMinMax, ZMinMax, ind, margin=1e-09)

Return the desired submesh indicated by the limits (DX,DY,DZ), for the desired resolution (dX,dY,dZ)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromD_cython(rstep, zstep, phistep, RMinMax, ZMinMax, DR=None, DZ=None, DPhi=None, limit_vpoly=None, out_format='(X,Y,Z)', margin=1e-09, num_threads=48)

Returns the desired submesh indicated by the limits (DR,DZ,DPhi), for the desired resolution (rstep,zstep,dRphi).

Parameters
  • (double) (phistep) –

  • (double)

  • (double)

  • RMinMax (array specifying the limits min and max in r) –

  • ZMinMax (array specifying the limits min and max in z) –

  • DR (array specifying the actual sub-volume limits to get in r) –

  • DZ (array specifying the actual sub-volume limits to get in z) –

  • DPhi (array specifying the actual sub-volume limits to get in phi) –

  • limit_vpoly (array-like defining the (R,Z) coordinates of the poloidal) – cut of the limiting flux surface

  • out_format(string) (either "(X,Y,Z)" or "(R,Z,Phi)" for cartesian or) – polar coordinates

  • margin(double) (tolerance error.) – Defaults to |_VSMALL|

Returns

  • pts ((3, npts) array in out_format (cartesian or polar) of) – discretized volume

  • res3d ((npts) resolution on each point)

  • ind ((npts) indices to reconstruct the points in 3D (useful only if) – limit_vpoly is not none)

  • reso_r ((double) resolution on r (constant))

  • reso_z ((double) resolution on z (constant))

  • reso_phi ((sz_r) array, resolution R*dPhi, phi resolution on each R)

  • sz_r ((int) number of points in r)

  • sz_z ((int) number of points in z)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromD_cython_old(dR, dZ, dRPhi, RMinMax, ZMinMax, DR=None, DZ=None, DPhi=None, VPoly=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired submesh indicated by the limits (DR,DZ,DPhi), for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromInd_cython(rstep, zstep, phistep, RMinMax, ZMinMax, ind, Out='(X,Y,Z)', margin=1e-09, num_threads=48)

Return the desired submesh indicated by the (numerical) indices, for the desired resolution (rstep, zstep, phistep)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromInd_cython_old(dR, dZ, dRPhi, RMinMax, ZMinMax, ind, Out='(X,Y,Z)', margin=1e-09)

Return the desired submesh indicated by the (numerical) indices, for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_isInside(pts, ves_poly, ves_lims=None, nlim=0, ves_type='Tor', in_format='(X,Y,Z)', test=True)

Checks if points Pts are in vessel VPoly. VPoly should be CLOSED

tofu.geom._GG._Ves_meshCross_FromInd(MinMax1, MinMax2, d1, d2, ind, dSMode='abs', margin=1e-09)
tofu.geom._GG.comp_dist_los_circle(ray_vdir, ray_orig, radius, circ_z, norm_dir=- 1.0)

This function computes the intersection of a Ray (or Line Of Sight) and a circle in 3D. It returns kmin and dist. Where kmin is the coefficient such that the ray of origin O = [ori1, ori2, ori3] and of directional vector D = [dir1, dir2, dir3] is closest to the circle

of radius radius and centered (0, 0, circ_z) at the point

P = O + kmin * D. And distance the distance between the two closest points (line closest and circle closest) The variable norm_dir is the squared norm of the direction of the ray. Params ===== ray_vdir: (3) double array

ray’s director vector V such that P in Ray iff P(t) = O + t*V

ray_orig(3) double array

ray’s origin coordinates O such that P in Ray iff P(t) = O + t*V

radiusdouble

radius r of horizontal circle centered in (0,0,circ_z)

circ_zdouble

3rd coordinate of horizontal circle centered in (0,0,circ_z) of radius r

norm_dirdouble (optional)

If for computation reasons it makes sense, you can pass the norm of the director vector

Returns

  • result (double (2) array) –

    • result[0] will contain the k coefficient to find the line point closest

    closest point - result[1] will contain the DISTANCE from line closest point to circle to the circle

  • This is the PYTHON function, use only if you need this computation from

  • Python, if you need it from cython, use dist_los_circle_core

tofu.geom._GG.comp_dist_los_circle_vec(nlos, ncircles, dirs, oris, circle_radius, circle_z, norm_dir=None, num_threads=48)

This function computes the intersection of a Ray (or Line Of Sight) and a circle in 3D. It returns kmin, the coefficient such that the ray of origin O = [ori1, ori2, ori3] and of directional vector D = [dir1, dir2, dir3] is closest to the circle of radius radius and centered (0, 0, circ_z) at the point P = O + kmin * D. The variable norm_dir is the squared norm of the direction of the ray. This is the vectorial version, we expect the directions and origins to be: dirs = [[dir1_los1, dir2_los1, dir3_los1], [dir1_los2,…] oris = [[ori1_los1, ori2_los1, ori3_los1], [ori1_los2,…] :returns: * res ((2, nlos, ncircles)) – res = [res_k, res_d] where res_k is a (nlos, ncircles) numpy array

with the k coefficients for each LOS where the minimum distance to each circle is reached is met for each circle, and res_d is a (nlos, ncircles) numpy array with the distance between each LOS to each circle

  • This is the PYTHON function, use only if you need this computation from

  • Python, if you need it from cython, use dist_los_circle_core

tofu.geom._GG.comp_dist_los_vpoly(ray_orig, ray_vdir, ves_poly, disc_step=0.1, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', num_threads=16, debug=False, debug_nlos=- 1)

This function computes the distance (and the associated k) between nlos Rays (or LOS) and an IN structure (a polygon extruded around the axis (0,0,1), eg. a flux surface). For more details on the algorithm please see PDF: <name_of_pdf>.pdf #TODO

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

ves_poly(2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the Vessel

eps_<val>double

Small value, acceptance of error

Returns

  • kmin_vpoly ((nlos) double array) – Of the form [k_0, k_1, …, k_n], where k_i is the coefficient such that the i-th ray (LOS) is closest to the extruded polygon at the point P_i = orig[i] + kmin[i] * vdir[i]

  • dist_vpoly ((nlos) double array) – distance[i] is the distance from P_i to the extruded polygon.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use simple_dist_los_vpoly_core

tofu.geom._GG.comp_dist_los_vpoly_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)

This function computes the distance (and the associated k) between nlos Rays (or LOS) and several IN structures (polygons extruded around the axis (0,0,1), eg. flux surfaces). For more details on the algorithm please see PDF: <name_of_pdf>.pdf #TODO

nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

from inner to outer

eps_<val>double

Small value, acceptance of error

Returns

  • kmin_vpoly ((npoly, nlos) double array) – Of the form [k_00, k_01, …, k_0n, k_10, k_11, …, k_1n, …] where k_ij is the coefficient for the j-th flux surface such that the i-th ray (LOS) is closest to the extruded polygon at the point P_i = orig[i] + kmin[i] * vdir[i]

  • dist_vpoly ((npoly, nlos) double array) – distance[i * num_poly + j] is the distance from P_i to the i-th extruded poly.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use comp_dist_los_vpoly_vec_core

tofu.geom._GG.coord_shift(points, in_format='(X,Y,Z)', out_format='(R,Z)', cross_format=None)

Check the shape of an array of points coordinates and/or converts from 2D to 3D, 3D to 2D, cylindrical to cartesian… (CrossRef is an angle (Tor) or a distance (X for Lin))

tofu.geom._GG.discretize_line1d(LMinMax, dstep, DL=None, Lim=True, mode='abs', margin=1e-09)

Discretize a 1D segment LMin-LMax. If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if mode is “rel” (relative), the meshing step is relative to the segments norm (ie. the actual discretization step will be (LMax - LMin)/dstep). It is possible to only one to discretize the segment on a sub-domain. If so, the sub-domain limits are given in DL. :param LMinMax: Gives the limits LMin and LMax of the segment. LMinMax = [LMin, LMax] :type LMinMax: (2)-double array :param dstep: Step of discretization, can be absolute (default) or relative :type dstep: double :param DL: Sub domain of discretization. If not None and if Lim, LMinMax = DL

(can be only on one limit and can be bigger or smaller than original). Actual desired limits

Parameters
  • Lim ((optional) bool) – Indicated if the subdomain should be taken into account

  • mode ((optional) string) – If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if “rel” (relative), the meshing step is relative to the segments norm (the actual discretization step will be (LMax - LMin)/dstep).

  • margin ((optional) double) – Margin value for cell length

Returns

  • ldiscret (double array) – array of the discretized coordinates on the segment of desired limits

  • resolution (double) – step of discretization

  • lindex (int array) – array of the indices corresponding to ldiscret with respects to the original segment LMinMax (if no DL, from 0 to N-1)

  • N (int64) – Number of points on LMinMax segment

tofu.geom._GG.discretize_segment2d(LMinMax1, LMinMax2, dstep1, dstep2, D1=None, D2=None, mode='abs', VPoly=None, margin=1e-09)

Discretizes a 2D segment where the 1st coordinates are defined in LMinMax1 and the second ones in LMinMax2. The refinement in x is defined by dstep1, and dstep2 defines the resolution on y. Optionnally you can give a VPoly to which the discretized in which the segment has to be included. This function is basically a generalization of discretize_line1d. :param LMinMax1: Gives the limits LMin and LMax of the x coordinates of the segment.

LMinMax1 = [xmin, xmax]

Parameters
  • LMinMax2 ((2)-double array) – Gives the limits LMin and LMax of the y coordinates of the segment. LMinMax2 = [ymin, ymax]

  • dstep2 (dstep1 or) – Step of discretization, can be absolute (default) or relative

  • D2 (D1 or) – Sub domain of discretization. If not None and if Lim, LMinMax = DL (can be only on one limit and can be bigger or smaller than original). Actual desired limits

  • mode ((optional) string) – If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if “rel” (relative), the meshing step is relative to the segments norm (the actual discretization step will be (LMax - LMin)/dstep).

  • margin ((optional) double) – Margin value for cell length

  • VPoly ((optional) 2d double array) – If present, we check that the discretized segment is included in the path defined by VPoly.

Returns

  • ldiscret (double 2d array) – array of the discretized coordinates on the segment of desired limits

  • resolution (double array) – step of discretization on 2d (typically resolution-on-x*resolution-on-y)

  • lindex (int array) – array of the indices corresponding to ldiscret with respects to the original segment LMinMax (if no DL, from 0 to N-1)

  • resol1 (double) – Smallest resolution on x

  • resol2 (double) – Smallest resolution on y

tofu.geom._GG.discretize_vpoly(VPoly, dL, mode='abs', D1=None, D2=None, margin=1e-09, DIn=0.0, VIn=None)

Discretizes a VPoly (2D polygon of a cross section in (R,Z) coordinates). The refinement on R and Z is defined dL. Optionnally you can give a coefficient (DIn) and the normal vectors going inwards the VPoly (VIn), and the result will be slightly shifted inwards (or outwards if DIn<0) of DIn*VIn. :param VPoly: Coordinates of the vertices of the Polygon defining the 2D poloidal

cut of the Vessel

Parameters
  • dL (double) – Step of discretization, can be absolute (default) or relative

  • D2 (D1 or) – Sub domain of discretization. (can be only on one limit and can be bigger or smaller than original). Actual desired limits

  • mode ((optional) string) – If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if “rel” (relative), the meshing step is relative to the segments norm

  • margin ((optional) double) – Margin value for cell length

Returns

  • return PtsCross, resol, ind_arr, N_arr, Rref_arr, VPolybis

  • PtsCross (double 2d array) – array of the discretized coordinates of the VPoly

  • resol (double 1d array) – step of discretization on 2d

  • ind_arr (int 1d array) – array of the indices corresponding to ldiscret with respects to the original VPoly

  • N_arr (int 1d array) – number of cells on each segment of the VPoly

  • Rref_arr (double 1d array) – reference Radius coordinates, not shifted even if DIn <> 0. If DIn == 0, then Rref_arr = PtsCross[0, …]

  • VPolybis

tofu.geom._GG.integrate1d(y, dx, t=None, method='sum')

Generic integration method [‘sum’,’simps’,’romb’]

Not used internally Useful when the sampling points need to be interpolated via equilibrium

tofu.geom._GG.is_close_los_circle(ray_vdir, ray_orig, radius, circ_z, eps, norm_dir=- 1.0)

This function checks if at maximum a LOS is at a distance epsilon form a cirlce The result is True when distance < epsilon — This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use is_los_close_circle_core

tofu.geom._GG.is_close_los_circle_vec(nlos, ncircles, epsilon, dirs, oris, circle_radius, circle_z, norm_dir=None, num_threads=48)

This function checks if at maximum a LOS is at a distance epsilon form a cirlce. Vectorial version The result is True when distance < epsilon — This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use is_los_close_circle_core

tofu.geom._GG.is_close_los_vpoly_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, epsilon, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)

This function tests if the distance between nlos Rays (or LOS) and several IN structures (polygons extruded around the axis (0,0,1), eg. flux surfaces) is smaller than epsilon. For more details on the algorithm please see PDF: <name_of_pdf>.pdf #TODO

nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

and the first one is the smallest one

epsilondouble

Value for testing if distance < epsilon

eps_<val>double

Small value, acceptance of error

Returns

are_close ((npoly * nlos) bool array) – are_close[i * num_poly + j] indicates if distance between i-th LOS and j-th poly are closer than epsilon. (True if distance<epsilon)

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use is_close_los_vpoly_vec_core

tofu.geom._GG.poly_area(poly, npts)
tofu.geom._GG.poly_area_and_barycenter(poly, npts)
tofu.geom._GG.triangulate_by_earclipping(poly)
tofu.geom._GG.vignetting(ray_orig, ray_vdir, vignett_poly, lnvert, num_threads=16)
ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

vignett_poly(num_vign, 3, num_vertex) double list of arrays

Coordinates of the vertices of the Polygon defining the 3D vignett. POLY CLOSED

lnvert(num_vign) long array

Number of vertices for each vignett (without counting the rebound)

Returns

goes_through ((num_vign, nlos) bool array) – Indicates for each vignett if each LOS wents through or not

tofu.geom._GG.which_los_closer_vpoly_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)
nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

and the first one is the smallest one

eps_<val>double

Small value, acceptance of error

Returns

ind_close_los ((npoly) int array) – Of the form [ind_0, ind_1, …, ind_(npoly-1)] where ind_i is the coefficient for the i-th flux surface such that the ind_i-th ray (LOS) is closest to the extruded polygon among all other LOS without going over it.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use which_los_closer_vpoly_vec_core

tofu.geom._GG.which_vpoly_closer_los_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)
nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

and the first one is the smallest one

eps_<val>double

Small value, acceptance of error

Returns

ind_close_los ((nlos) int array) – Of the form [ind_0, ind_1, …, ind_(nlos-1)] where ind_i is the coefficient for the i-th LOS (ray) such that the ind_i-th poly (flux surface) is closest to the LOS among all other poly without going over it.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use which_vpoly_closer_los_vec_core

tofu.geom._GG module

tofu.geom._GG.ConvertImpact_Theta2Xi(theta, pP, pN, sort=True)
tofu.geom._GG.Dust_calc_SolidAngle(pos, r, pts, approx=True, out_coefonly=False, VType='Tor', VPoly=None, VIn=None, VLim=None, LSPoly=None, LSLim=None, LSVIn=None, Forbid=True, Test=True)

Compute the solid angle of a moving particle of varying radius as seen from any number of pixed points

Can be done w/o the approximation that r<<d If Ves (and optionally LSPoly) are provided, takes into account vignetting

tofu.geom._GG.LOS_Calc_PInOut_VesStruct(ray_orig, ray_vdir, ves_poly, ves_norm, lstruct_nlim=None, ves_lims=None, lstruct_polyx=None, lstruct_polyy=None, lstruct_lims=None, lstruct_normx=None, lstruct_normy=None, lnvert=None, nstruct_tot=0, nstruct_lim=0, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', forbid=True, test=True, num_threads=16)

Computes the entry and exit point of all provided LOS for the provided vessel polygon (toroidal or linear) with its associated structures. Return the normal vector at impact and the index of the impact segment

Parameters
  • ray_orig ((3, nlos) double array) – LOS origin points coordinates

  • ray_vdir ((3, nlos) double array) – LOS normalized direction vector

  • ves_poly ((2, num_vertex) double array) – Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the Vessel

  • ves_norm ((2, num_vertex-1) double array) – Normal vectors going “inwards” of the edges of the Polygon defined by ves_poly

  • nstruct_tot (int) – Total number of structures (counting each limited structure as one)

  • ves_lims (array) – Contains the limits min and max of vessel

  • lstruct_polyx (array) – List of x coordinates of the vertices of all structures on poloidal plane If no structures : None

  • lstruct_polyy (array) – List of y coordinates of the vertices of all structures on poloidal plane If no structures : None

  • lstruct_lims (array) – List of limits of all structures If no structures : None

  • lstruct_nlim (array of ints) – List of number of limits for all structures If no structures : None

  • lstruct_normx (array) – List of x coordinates of “inwards” normal vectors of the polygon of all the structures If no structures : None

  • lstruct_normy (array) – List of y coordinates of “inwards” normal vectors of the polygon of all the structures If no structures : None

  • rmin (double) – Minimal radius of vessel to take into consideration

  • eps_<val> (double) – Small value, acceptance of error

  • ves_type (string) – Type of vessel (“Tor” or “Lin”)

  • forbid (bool) – Should we forbid values behind visible radius ? (see rmin)

  • test (bool) – Should we run tests ?

  • num_threads (int) – The num_threads argument indicates how many threads the team should consist of. If not given, OpenMP will decide how many threads to use. Typically this is the number of cores available on the machine.

Returns

  • coeff_inter_in ((nlos) array) – scalars level of “in” intersection of the LOS (if k=0 at origin)

  • coeff_inter_out ((nlos) array) – scalars level of “out” intersection of the LOS (if k=0 at origin)

  • vperp_out ((3, nlos) array) – Coordinates of the normal vector of impact of the LOS (NaN if none)

  • ind_inter_out ((3, nlos)) – Index of structure impacted by LOS: ind_inter_out[:,ind_los]=(i,j,k) where k is the index of edge impacted on the j-th sub structure of the structure number i. If the LOS impacted the vessel i=j=0

tofu.geom._GG.LOS_Calc_kMinkMax_VesStruct(ray_orig, ray_vdir, ves_poly, ves_norm, num_surf, lnvert, ves_lims=None, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', forbid=True, test=True, num_threads=16)

Computes the entry and exit point of all provided LOS for the provided polygons (toroidal or linear) of IN structures (non-solid, or empty inside for the LOS). Attention: the surfaces can be limited, but they all have to have the same limits defined by (ves_lims) Return the set of kmin / kmax for each In struct and for each LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

num_surfint

number of surfaxes, aka ‘in’ structures or ‘vessels’

ves_poly(num_surf, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the in structures

ves_norm(num_surf, 2, num_vertex-1) double array

Normal vectors going “inwards” of the edges of the Polygon defined by ves_poly

ves_limsarray

Contains the limits min and max of vessel

rmindouble

Minimal radius of vessel to take into consideration

eps<val>double

Small value, acceptance of error

vtypestring

Type of vessel (“Tor” or “Lin”)

forbidbool

Should we forbid values behind visible radius ? (see rmin)

testbool

Should we run tests ?

num_threadsint

The num_threads argument indicates how many threads the team should consist of. If not given, OpenMP will decide how many threads to use. Typically this is the number of cores available on the machine.

Returns

  • coeff_inter_in ((num_surf, nlos) array) – scalars level of “in” intersection of the LOS (if k=0 at origin) for each surface [kmin(surf0, los0), kmin(surf0, los1), …, kmin(surf1, los0),….]

  • coeff_inter_out ((num_surf, nlos) array) – scalars level of “out” intersection of the LOS (if k=0 at origin) for each surface [kmax(surf0, los0), kmax(surf0, los1), …, kmax(surf1, los0),….]

tofu.geom._GG.LOS_areVis_PtsFromPts_VesStruct(pts1, pts2, ves_poly=None, ves_norm=None, dist=None, ves_lims=None, lstruct_nlim=None, lstruct_polyx=None, lstruct_polyy=None, lstruct_lims=None, lstruct_normx=None, lstruct_normy=None, lnvert=None, nstruct_tot=0, nstruct_lim=0, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='tor', forbid=True, test=True, num_threads=16)

Return an array of booleans indicating whether each point in pts1 can see each point in pts2 considering vignetting a given configuration.

pts1 : (3, npts1) cartesian coordinates of viewing points pts2 : (3, npts2) cartesian coordinates of points to check if viewable dist : optional argument : distance between the points pts1, pts2 ves_* : vessel descriptors (poly, norm, limits) lstruct_* : config’s structure descriptors (poly, limits, norms,

number of structures, …)

eps_* : values of precision in each direction forbid : boolean if true forbids checking “behind” the tokamak test : boolean check if input is valid or not num_threads : number of threads for parallelization

Output:
are_seen: (npts1, npts2) array of ints indicating if viewing points pts1

can see the other points pts2. are_seen[i,j] = 1 if pts1[i] sees point pts2[j]

0 else

tofu.geom._GG.LOS_calc_signal(func, ray_orig, ray_vdir, res, lims, dmethod='abs', method='sum', ani=False, t=None, fkwdargs={}, minimize='calls', Test=True, num_threads=16)

Compute the synthetic signal, minimizing either function calls or memory Params ===== func : python function st. func(pts, t=None, vect=None) => data

with ptsndarray (3, npts) - points where function is evaluated

vect : ndarray(3, npts) - if anisotropic signal vector of emiss. t: ndarray(m) - times where to compute the function

returns: datandarray(nt,nraf) if nt = 1, the array must be 2D

values of func at pts, at given time

func is the function to be integrated along the LOS

ray_orig: ndarray (3, nlos) LOS origins ray_vdir: ndarray (3, nlos) LOS directional vector res: double or list of doubles

If res is a single double: discretization step for all LOS. Else res should be a list of size nlos with the discretization step for each nlos.

lims: (2, nlos) double array

For each nlos, it given the maximum and minimum limits of the ray

dmethod: string

type of discretization step: ‘abs’ for absolute or ‘rel’ for relative

method: string

method of quadrature on the LOS

anibool

to indicate if emission is anisotropic or not

tNone or array-like

times where to integrate

minimize: string

“calls” : we use algorithm to minimize the calls to ‘func’ (default) “memory”: we use algorithm to minimize memory used “hybrid”: a mix of both methods

Testbool

we test if the inputs are giving in a proper way.

num_threads: int

number of threads if we want to parallelize the code.

tofu.geom._GG.LOS_get_sample(nlos, dL, los_lims, dmethod='abs', method='sum', Test=True, num_threads=16)

Return the sampled line, with the specified method - ‘sum’ : return N segments centers - ‘simps’: return N+1 egdes, N even (for scipy.integrate.simps) - ‘romb’ : return N+1 edges, N+1 = 2**k+1 (for scipy.integrate.romb)

The dmethod defines if the discretization step given is absolute (‘abs’) or relative (‘rel’)

dL: double or list of doubles

If dL is a single double: discretization step for all LOS. Else dL should be a list of size nlos with the discretization step for each nlos.

los_lims: (2, nlos) double array

For each nlos, it given the maximum and minimum limits of the ray

dmethod: string

type of discretization step: ‘abs’ for absolute or ‘rel’ for relative

method: string

method of quadrature on the LOS

Test: bool

to indicate if tests should be done or not

k, res, lind = Los_get_sample(…) nbrepet = np.r_[lind[0], np.diff(lind), k.size - lind[-1]] kus = k * np.repeat(ray_vdir, nbrepet, axis=1) Pts = np.repeat(ray_orig, nbrepet, axis=1) + kus

tofu.geom._GG.LOS_isVis_PtFromPts_VesStruct(pt0, pt1, pt2, pts, dist=None, ves_poly=None, ves_norm=None, ves_lims=None, lstruct_nlim=None, lstruct_polyx=None, lstruct_polyy=None, lstruct_lims=None, lstruct_normx=None, lstruct_normy=None, lnvert=None, nstruct_tot=0, nstruct_lim=0, rmin=- 1.0, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', forbid=True, test=True, num_threads=16)

Return an array of booleans indicating whether each point in pts is visible from the point P = [pt0, pt1, pt2] considering vignetting a given configuration.

pt0 : x - coordinate of the viewing point P pt1 : y - coordinate of the viewing point P pt2 : z - coordinate of the viewing point P pts : (3, npts) cartesian coordinates of points to check if viewable dist : optional argument : distance between points and P ves_* : vessel descriptors (poly, norm, limits) lstruct_* : config’s structure descriptors (poly, limits, norms,

number of structures, …)

eps_* : values of precision in each direction forbid : boolean if true forbids checking “behind” the tokamak test : boolean check if input is valid or not num_threads : number of threads for parallelization

Output:
is_seen: (npts1) array of ints indicating if viewing point P

can see the other points pts. is_seen[i] = 1 if P sees point pts[i]

0 else

tofu.geom._GG.LOS_sino(D, u, RZ, kOut, Mode='LOS', VType='Tor', try_new_algo=True)
tofu.geom._GG.LOS_sino_findRootkPMin_Tor(uParN, uN, Sca, RZ0, RZ1, ScaP, DParN, kOut, D0, D1, D2, u0, u1, u2, Mode='LOS')

Rendre “vectoriel” sur LOS et sur les cercles (deux boucles “for”) intersection ligne et cercle double uParN : composante de u parallel au plan (x,y)

double uN : uz double Sca : ??? produit scalaire … ? double RZ0 : Grand rayon du cercle double RZ1 : Z => cercle est centré au point (0, 0, RZ1) et rayon RZ0 double ScaP : …. ? double DParN : D origine de LOS…. ? N => norme de la composante du vecteur OD double kOut : kmax où on peut trouver un résultat double D0, double D1, double D2 : composantes de D (origine LOS) double u0, double u1, double u2 : composantes de U (direction LOS) str Mode=’LOS’ : si LOS pas de sol après kmax)

::: Faire une fonction double mais qui renvoit QUE un tableau de bool avec true si la distance est plus petite qu’un certain eps, false sinon. TODO: ……….. @LM

tofu.geom._GG.Poly_VolAngTor(Poly)
tofu.geom._GG.Poly_isClockwise(Poly)

Assuming 2D closed Poly ! http://www.faqs.org/faqs/graphics/algorithms-faq/ Find the lowest vertex (or, if there is more than one vertex with the same lowest coordinate, the rightmost of those vertices) and then take the cross product of the edges before and after it. Both methods are O(n) for n vertices, but it does seem a waste to add up the total area when a single cross product (of just the right edges) suffices. Code for this is available at ftp://cs.smith.edu/pub/code/polyorient.C (2K).

tofu.geom._GG.Sino_ImpactEnv(RZ, Poly, NP=50, Test=True)

Computes impact parameters of a Tor enveloppe (a Tor is a closed 2D polygon)

D. VEZINET, Aug. 2014 :param RZ: (2,) array indicating the reference impact point :type RZ: np.ndarray :param Poly: (2,N) array containing the coordinatesof a closed polygon :type Poly: np.ndarray :param NP: Number of indicating the number of points used for discretising theta between 0 and pi :type NP: int

Returns

theta

tofu.geom._GG._Ves_Smesh_Lin_SubFromD_cython(XMinMax, dL, dX, VPoly, DX=None, DY=None, DZ=None, DIn=0.0, VIn=None, margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DX,DY,DZ), for the desired resolution (dX,dL)

tofu.geom._GG._Ves_Smesh_Lin_SubFromInd_cython(XMinMax, dL, dX, VPoly, ind, DIn=0.0, VIn=None, margin=1e-09)

Return the desired surfacic submesh indicated by ind, for the desired resolution (dX,dL)

tofu.geom._GG._Ves_Smesh_TorStruct_SubFromD_cython(PhiMinMax, dL, dRPhi, VPoly, DR=None, DZ=None, DPhi=None, DIn=0.0, VIn=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DR,DZ,DPhi), for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Smesh_TorStruct_SubFromInd_cython(PhiMinMax, dL, dRPhi, VPoly, ind, DIn=0.0, VIn=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DR,DZ,DPhi) for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Smesh_Tor_SubFromD_cython(dL, dRPhi, VPoly, DR=None, DZ=None, DPhi=None, DIn=0.0, VIn=None, PhiMinMax=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired surfacic submesh indicated by the limits (DR,DZ,DPhi) for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Smesh_Tor_SubFromInd_cython(dL, dRPhi, VPoly, ind, DIn=0.0, VIn=None, PhiMinMax=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired submesh indicated by the (numerical) indices, for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Vmesh_Lin_SubFromD_cython(dX, dY, dZ, XMinMax, YMinMax, ZMinMax, DX=None, DY=None, DZ=None, limit_vpoly=None, margin=1e-09)

Return the desired submesh indicated by the limits (DX,DY,DZ), for the desired resolution (dX,dY,dZ)

tofu.geom._GG._Ves_Vmesh_Lin_SubFromInd_cython(dX, dY, dZ, XMinMax, YMinMax, ZMinMax, ind, margin=1e-09)

Return the desired submesh indicated by the limits (DX,DY,DZ), for the desired resolution (dX,dY,dZ)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromD_cython(rstep, zstep, phistep, RMinMax, ZMinMax, DR=None, DZ=None, DPhi=None, limit_vpoly=None, out_format='(X,Y,Z)', margin=1e-09, num_threads=48)

Returns the desired submesh indicated by the limits (DR,DZ,DPhi), for the desired resolution (rstep,zstep,dRphi).

Parameters
  • (double) (phistep) –

  • (double)

  • (double)

  • RMinMax (array specifying the limits min and max in r) –

  • ZMinMax (array specifying the limits min and max in z) –

  • DR (array specifying the actual sub-volume limits to get in r) –

  • DZ (array specifying the actual sub-volume limits to get in z) –

  • DPhi (array specifying the actual sub-volume limits to get in phi) –

  • limit_vpoly (array-like defining the (R,Z) coordinates of the poloidal) – cut of the limiting flux surface

  • out_format(string) (either "(X,Y,Z)" or "(R,Z,Phi)" for cartesian or) – polar coordinates

  • margin(double) (tolerance error.) – Defaults to |_VSMALL|

Returns

  • pts ((3, npts) array in out_format (cartesian or polar) of) – discretized volume

  • res3d ((npts) resolution on each point)

  • ind ((npts) indices to reconstruct the points in 3D (useful only if) – limit_vpoly is not none)

  • reso_r ((double) resolution on r (constant))

  • reso_z ((double) resolution on z (constant))

  • reso_phi ((sz_r) array, resolution R*dPhi, phi resolution on each R)

  • sz_r ((int) number of points in r)

  • sz_z ((int) number of points in z)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromD_cython_old(dR, dZ, dRPhi, RMinMax, ZMinMax, DR=None, DZ=None, DPhi=None, VPoly=None, Out='(X,Y,Z)', margin=1e-09)

Return the desired submesh indicated by the limits (DR,DZ,DPhi), for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromInd_cython(rstep, zstep, phistep, RMinMax, ZMinMax, ind, Out='(X,Y,Z)', margin=1e-09, num_threads=48)

Return the desired submesh indicated by the (numerical) indices, for the desired resolution (rstep, zstep, phistep)

tofu.geom._GG._Ves_Vmesh_Tor_SubFromInd_cython_old(dR, dZ, dRPhi, RMinMax, ZMinMax, ind, Out='(X,Y,Z)', margin=1e-09)

Return the desired submesh indicated by the (numerical) indices, for the desired resolution (dR,dZ,dRphi)

tofu.geom._GG._Ves_isInside(pts, ves_poly, ves_lims=None, nlim=0, ves_type='Tor', in_format='(X,Y,Z)', test=True)

Checks if points Pts are in vessel VPoly. VPoly should be CLOSED

tofu.geom._GG._Ves_meshCross_FromInd(MinMax1, MinMax2, d1, d2, ind, dSMode='abs', margin=1e-09)
tofu.geom._GG.comp_dist_los_circle(ray_vdir, ray_orig, radius, circ_z, norm_dir=- 1.0)

This function computes the intersection of a Ray (or Line Of Sight) and a circle in 3D. It returns kmin and dist. Where kmin is the coefficient such that the ray of origin O = [ori1, ori2, ori3] and of directional vector D = [dir1, dir2, dir3] is closest to the circle

of radius radius and centered (0, 0, circ_z) at the point

P = O + kmin * D. And distance the distance between the two closest points (line closest and circle closest) The variable norm_dir is the squared norm of the direction of the ray. Params ===== ray_vdir: (3) double array

ray’s director vector V such that P in Ray iff P(t) = O + t*V

ray_orig(3) double array

ray’s origin coordinates O such that P in Ray iff P(t) = O + t*V

radiusdouble

radius r of horizontal circle centered in (0,0,circ_z)

circ_zdouble

3rd coordinate of horizontal circle centered in (0,0,circ_z) of radius r

norm_dirdouble (optional)

If for computation reasons it makes sense, you can pass the norm of the director vector

Returns

  • result (double (2) array) –

    • result[0] will contain the k coefficient to find the line point closest

    closest point - result[1] will contain the DISTANCE from line closest point to circle to the circle

  • This is the PYTHON function, use only if you need this computation from

  • Python, if you need it from cython, use dist_los_circle_core

tofu.geom._GG.comp_dist_los_circle_vec(nlos, ncircles, dirs, oris, circle_radius, circle_z, norm_dir=None, num_threads=48)

This function computes the intersection of a Ray (or Line Of Sight) and a circle in 3D. It returns kmin, the coefficient such that the ray of origin O = [ori1, ori2, ori3] and of directional vector D = [dir1, dir2, dir3] is closest to the circle of radius radius and centered (0, 0, circ_z) at the point P = O + kmin * D. The variable norm_dir is the squared norm of the direction of the ray. This is the vectorial version, we expect the directions and origins to be: dirs = [[dir1_los1, dir2_los1, dir3_los1], [dir1_los2,…] oris = [[ori1_los1, ori2_los1, ori3_los1], [ori1_los2,…] :returns: * res ((2, nlos, ncircles)) – res = [res_k, res_d] where res_k is a (nlos, ncircles) numpy array

with the k coefficients for each LOS where the minimum distance to each circle is reached is met for each circle, and res_d is a (nlos, ncircles) numpy array with the distance between each LOS to each circle

  • This is the PYTHON function, use only if you need this computation from

  • Python, if you need it from cython, use dist_los_circle_core

tofu.geom._GG.comp_dist_los_vpoly(ray_orig, ray_vdir, ves_poly, disc_step=0.1, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', num_threads=16, debug=False, debug_nlos=- 1)

This function computes the distance (and the associated k) between nlos Rays (or LOS) and an IN structure (a polygon extruded around the axis (0,0,1), eg. a flux surface). For more details on the algorithm please see PDF: <name_of_pdf>.pdf #TODO

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

ves_poly(2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the Vessel

eps_<val>double

Small value, acceptance of error

Returns

  • kmin_vpoly ((nlos) double array) – Of the form [k_0, k_1, …, k_n], where k_i is the coefficient such that the i-th ray (LOS) is closest to the extruded polygon at the point P_i = orig[i] + kmin[i] * vdir[i]

  • dist_vpoly ((nlos) double array) – distance[i] is the distance from P_i to the extruded polygon.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use simple_dist_los_vpoly_core

tofu.geom._GG.comp_dist_los_vpoly_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)

This function computes the distance (and the associated k) between nlos Rays (or LOS) and several IN structures (polygons extruded around the axis (0,0,1), eg. flux surfaces). For more details on the algorithm please see PDF: <name_of_pdf>.pdf #TODO

nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

from inner to outer

eps_<val>double

Small value, acceptance of error

Returns

  • kmin_vpoly ((npoly, nlos) double array) – Of the form [k_00, k_01, …, k_0n, k_10, k_11, …, k_1n, …] where k_ij is the coefficient for the j-th flux surface such that the i-th ray (LOS) is closest to the extruded polygon at the point P_i = orig[i] + kmin[i] * vdir[i]

  • dist_vpoly ((npoly, nlos) double array) – distance[i * num_poly + j] is the distance from P_i to the i-th extruded poly.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use comp_dist_los_vpoly_vec_core

tofu.geom._GG.coord_shift(points, in_format='(X,Y,Z)', out_format='(R,Z)', cross_format=None)

Check the shape of an array of points coordinates and/or converts from 2D to 3D, 3D to 2D, cylindrical to cartesian… (CrossRef is an angle (Tor) or a distance (X for Lin))

tofu.geom._GG.discretize_line1d(LMinMax, dstep, DL=None, Lim=True, mode='abs', margin=1e-09)

Discretize a 1D segment LMin-LMax. If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if mode is “rel” (relative), the meshing step is relative to the segments norm (ie. the actual discretization step will be (LMax - LMin)/dstep). It is possible to only one to discretize the segment on a sub-domain. If so, the sub-domain limits are given in DL. :param LMinMax: Gives the limits LMin and LMax of the segment. LMinMax = [LMin, LMax] :type LMinMax: (2)-double array :param dstep: Step of discretization, can be absolute (default) or relative :type dstep: double :param DL: Sub domain of discretization. If not None and if Lim, LMinMax = DL

(can be only on one limit and can be bigger or smaller than original). Actual desired limits

Parameters
  • Lim ((optional) bool) – Indicated if the subdomain should be taken into account

  • mode ((optional) string) – If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if “rel” (relative), the meshing step is relative to the segments norm (the actual discretization step will be (LMax - LMin)/dstep).

  • margin ((optional) double) – Margin value for cell length

Returns

  • ldiscret (double array) – array of the discretized coordinates on the segment of desired limits

  • resolution (double) – step of discretization

  • lindex (int array) – array of the indices corresponding to ldiscret with respects to the original segment LMinMax (if no DL, from 0 to N-1)

  • N (int64) – Number of points on LMinMax segment

tofu.geom._GG.discretize_segment2d(LMinMax1, LMinMax2, dstep1, dstep2, D1=None, D2=None, mode='abs', VPoly=None, margin=1e-09)

Discretizes a 2D segment where the 1st coordinates are defined in LMinMax1 and the second ones in LMinMax2. The refinement in x is defined by dstep1, and dstep2 defines the resolution on y. Optionnally you can give a VPoly to which the discretized in which the segment has to be included. This function is basically a generalization of discretize_line1d. :param LMinMax1: Gives the limits LMin and LMax of the x coordinates of the segment.

LMinMax1 = [xmin, xmax]

Parameters
  • LMinMax2 ((2)-double array) – Gives the limits LMin and LMax of the y coordinates of the segment. LMinMax2 = [ymin, ymax]

  • dstep2 (dstep1 or) – Step of discretization, can be absolute (default) or relative

  • D2 (D1 or) – Sub domain of discretization. If not None and if Lim, LMinMax = DL (can be only on one limit and can be bigger or smaller than original). Actual desired limits

  • mode ((optional) string) – If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if “rel” (relative), the meshing step is relative to the segments norm (the actual discretization step will be (LMax - LMin)/dstep).

  • margin ((optional) double) – Margin value for cell length

  • VPoly ((optional) 2d double array) – If present, we check that the discretized segment is included in the path defined by VPoly.

Returns

  • ldiscret (double 2d array) – array of the discretized coordinates on the segment of desired limits

  • resolution (double array) – step of discretization on 2d (typically resolution-on-x*resolution-on-y)

  • lindex (int array) – array of the indices corresponding to ldiscret with respects to the original segment LMinMax (if no DL, from 0 to N-1)

  • resol1 (double) – Smallest resolution on x

  • resol2 (double) – Smallest resolution on y

tofu.geom._GG.discretize_vpoly(VPoly, dL, mode='abs', D1=None, D2=None, margin=1e-09, DIn=0.0, VIn=None)

Discretizes a VPoly (2D polygon of a cross section in (R,Z) coordinates). The refinement on R and Z is defined dL. Optionnally you can give a coefficient (DIn) and the normal vectors going inwards the VPoly (VIn), and the result will be slightly shifted inwards (or outwards if DIn<0) of DIn*VIn. :param VPoly: Coordinates of the vertices of the Polygon defining the 2D poloidal

cut of the Vessel

Parameters
  • dL (double) – Step of discretization, can be absolute (default) or relative

  • D2 (D1 or) – Sub domain of discretization. (can be only on one limit and can be bigger or smaller than original). Actual desired limits

  • mode ((optional) string) – If mode is “abs” (absolute), then the segment will be discretized in cells each of size dstep. Else, if “rel” (relative), the meshing step is relative to the segments norm

  • margin ((optional) double) – Margin value for cell length

Returns

  • return PtsCross, resol, ind_arr, N_arr, Rref_arr, VPolybis

  • PtsCross (double 2d array) – array of the discretized coordinates of the VPoly

  • resol (double 1d array) – step of discretization on 2d

  • ind_arr (int 1d array) – array of the indices corresponding to ldiscret with respects to the original VPoly

  • N_arr (int 1d array) – number of cells on each segment of the VPoly

  • Rref_arr (double 1d array) – reference Radius coordinates, not shifted even if DIn <> 0. If DIn == 0, then Rref_arr = PtsCross[0, …]

  • VPolybis

tofu.geom._GG.integrate1d(y, dx, t=None, method='sum')

Generic integration method [‘sum’,’simps’,’romb’]

Not used internally Useful when the sampling points need to be interpolated via equilibrium

tofu.geom._GG.is_close_los_circle(ray_vdir, ray_orig, radius, circ_z, eps, norm_dir=- 1.0)

This function checks if at maximum a LOS is at a distance epsilon form a cirlce The result is True when distance < epsilon — This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use is_los_close_circle_core

tofu.geom._GG.is_close_los_circle_vec(nlos, ncircles, epsilon, dirs, oris, circle_radius, circle_z, norm_dir=None, num_threads=48)

This function checks if at maximum a LOS is at a distance epsilon form a cirlce. Vectorial version The result is True when distance < epsilon — This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use is_los_close_circle_core

tofu.geom._GG.is_close_los_vpoly_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, epsilon, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)

This function tests if the distance between nlos Rays (or LOS) and several IN structures (polygons extruded around the axis (0,0,1), eg. flux surfaces) is smaller than epsilon. For more details on the algorithm please see PDF: <name_of_pdf>.pdf #TODO

nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

and the first one is the smallest one

epsilondouble

Value for testing if distance < epsilon

eps_<val>double

Small value, acceptance of error

Returns

are_close ((npoly * nlos) bool array) – are_close[i * num_poly + j] indicates if distance between i-th LOS and j-th poly are closer than epsilon. (True if distance<epsilon)

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use is_close_los_vpoly_vec_core

tofu.geom._GG.poly_area(poly, npts)
tofu.geom._GG.poly_area_and_barycenter(poly, npts)
tofu.geom._GG.triangulate_by_earclipping(poly)
tofu.geom._GG.vignetting(ray_orig, ray_vdir, vignett_poly, lnvert, num_threads=16)
ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS normalized direction vector

vignett_poly(num_vign, 3, num_vertex) double list of arrays

Coordinates of the vertices of the Polygon defining the 3D vignett. POLY CLOSED

lnvert(num_vign) long array

Number of vertices for each vignett (without counting the rebound)

Returns

goes_through ((num_vign, nlos) bool array) – Indicates for each vignett if each LOS wents through or not

tofu.geom._GG.which_los_closer_vpoly_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)
nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

and the first one is the smallest one

eps_<val>double

Small value, acceptance of error

Returns

ind_close_los ((npoly) int array) – Of the form [ind_0, ind_1, …, ind_(npoly-1)] where ind_i is the coefficient for the i-th flux surface such that the ind_i-th ray (LOS) is closest to the extruded polygon among all other LOS without going over it.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use which_los_closer_vpoly_vec_core

tofu.geom._GG.which_vpoly_closer_los_vec(nvpoly, nlos, ray_orig, ray_vdir, ves_poly, eps_uz=1e-06, eps_a=1e-09, eps_vz=1e-09, eps_b=1e-09, eps_plane=1e-09, ves_type='Tor', algo_type='simple', num_threads=16)
nvpolyint

Number of flux surfaces

nlosint

Number of LOS

ray_orig(3, nlos) double array

LOS origin points coordinates

ray_vdir(3, nlos) double array

LOS direction vector

ves_poly(num_pol, 2, num_vertex) double array

Coordinates of the vertices of the Polygon defining the 2D poloidal cut of the different IN surfaces WARNING : we suppose all poly are nested in each other,

and the first one is the smallest one

eps_<val>double

Small value, acceptance of error

Returns

ind_close_los ((nlos) int array) – Of the form [ind_0, ind_1, …, ind_(nlos-1)] where ind_i is the coefficient for the i-th LOS (ray) such that the ind_i-th poly (flux surface) is closest to the LOS among all other poly without going over it.

— This is the PYTHON function, use only if you need this computation from Python, if you need it from cython, use which_vpoly_closer_los_vec_core

tofu.geom._basic_geom_tools module

tofu.geom._basic_geom_tools module

tofu.geom._comp module

This module is the computational part of the geometrical module of ToFu

tofu.geom._comp.LOS_CrossProj(VType, Ds, us, kOuts, proj='All', multi=False, num_threads=16, return_pts=False, Test=True)[source]

Compute the parameters to plot the poloidal projection of the LOS

tofu.geom._comp.LOS_PRMin(Ds, us, kOut=None, Eps=1e-12, squeeze=True, Test=True)[source]

Compute the point on the LOS where the major radius is minimum

tofu.geom._comp.LOS_calc_signal(ff, D, u, dL, DL=None, dLMode='abs', method='romb', Test=True)[source]
tofu.geom._comp.LOS_get_sample(D, u, dL, DL=None, dLMode='abs', method='sum', Test=True)[source]

Return the sampled line, with the specified method

‘linspace’: return the N+1 edges, including the first and last point ‘sum’ : return the N middle of the segments ‘simps’: return the N+1 egdes, where N has to be even

(scipy.simpson requires an even number of intervals)

‘romb’return the N+1 edges, where N+1 = 2**k+1

(fed to scipy.romb for integration)

tofu.geom._comp._Struct_get_phithetaproj(ax=None, poly_closed=None, lim=None, noccur=0)[source]
tofu.geom._comp._Struct_set_Poly(Poly, pos=None, extent=None, arrayorder='C', Type='Tor', Clock=False)[source]

Compute geometrical attributes of a Struct object

tofu.geom._comp._Ves_get_InsideConvexPoly(Poly, P2Min, P2Max, BaryS, RelOff=0.05, ZLim='Def', Spline=True, Splprms=[100.0, 2.0, 3], NP=100, Plot=False, Test=True)[source]
tofu.geom._comp._Ves_get_sampleCross(VPoly, Min1, Max1, Min2, Max2, res=None, domain=None, resMode=None, ind=None, margin=1e-09, mode='flat')[source]
tofu.geom._comp._Ves_get_sampleEdge(VPoly, res=None, domain=None, resMode=None, offsetIn=0.0, VIn=None, margin=1e-09)[source]
tofu.geom._comp._Ves_get_sampleS(VPoly, res=None, domain=None, resMode='abs', ind=None, offsetIn=0.0, VIn=None, VType='Tor', VLim=None, nVLim=None, returnas='(X,Y,Z)', margin=1e-09, Multi=False, Ind=None)[source]

Sample the surface

tofu.geom._comp._Ves_get_sampleV(VPoly, Min1, Max1, Min2, Max2, res=None, domain=None, resMode=None, ind=None, VType='Tor', VLim=None, returnas='(X,Y,Z)', margin=1e-09, algo='new', num_threads=48)[source]

Sample the volume

tofu.geom._comp._Ves_get_sample_checkinputs(res=None, domain=None, resMode=None, ind=None, which='volume')[source]

Check inputs for all sampling routines

tofu.geom._comp._check_float(var=None, varname=None, vardef=None)[source]
tofu.geom._comp._get_phithetaproj_dist(poly_closed, ax, Dtheta, nDtheta, Dphi, nDphi, theta, phi, ntheta, nphi, noccur)[source]
tofu.geom._comp._get_pts_from_path_svg(path_str=None, res=None)[source]
tofu.geom._comp.get_paths_from_svg(pfe=None, res=None, r0=None, z0=None, point_ref1=None, point_ref2=None, length_ref=None, scale=None, verb=None)[source]

tofu.geom._comp_optics module

tofu.geom._comp_optics.CrystBragg_get_noute1e2_from_psitheta(nout, e1, e2, psi=None, dtheta=None, e1e2=None, sameshape=None, extenthalf_psi=None, extenthalf_dtheta=None, ntheta=None, npsi=None, include_summit=None)[source]
tofu.geom._comp_optics.CrystBragg_sample_outline_plot_sphrect(center, nout, e1, e2, rcurve, extenthalf, res=None)[source]

Get the set of points in (x, y, z) coordinates sampling the crystal outline

tofu.geom._comp_optics.CrystBragg_sample_outline_sphrect(extent_psi, extent_dtheta, npsi=None, ntheta=None, include_summit=None)[source]
tofu.geom._comp_optics._are_broadcastable(**kwdargs)[source]
tofu.geom._comp_optics._calc_braggphi_from_pts_summits(pts=None, summits=None, vin=None, ve1=None, ve2=None)[source]
tofu.geom._comp_optics._calc_spect1d_from_data2d(ldata, lamb, phi, nlambfit=None, nphifit=None, spect1d=None, mask=None, vertsum1d=None)[source]
tofu.geom._comp_optics._check_bool(var, vardef=None, varname=None)[source]
tofu.geom._comp_optics._check_dthetapsi(dtheta=None, psi=None, extenthalf_psi=None, extenthalf_dtheta=None, ntheta=None, npsi=None, include_summit=None)[source]
tofu.geom._comp_optics._checkformat_pts(pts=None)[source]
tofu.geom._comp_optics._checkformat_xixj(xi, xj)[source]
tofu.geom._comp_optics.calc_braggphi_from_xixjpts(pts=None, xi=None, xj=None, det=None, summit=None, nin=None, e1=None, e2=None, grid=None)[source]

Return bragg phi for pts or (xj, xi) seen from (summit, nin, e1, e2)

Either provide:

pts => (3, npts) xi, xj => pts with shape (3, nxi, nxj)

summit, nin, e1, e2 must have the same shape (3, nsumm)

bragg.shape = (nsum, )

if grid is True:

all pts evaluated for all summ/nin return (nsumm, npts) or (nsum, nxi, nxj) arrays

else:

each pts has a unique corresponding summ/nin (except possibly ndtheta) return (npts,) or (nxi, nxj) arrays

or (npts, ndtheta) or (nxi, nxj, ndtheta) arrays

tofu.geom._comp_optics.calc_dthetapsiphi_from_lambpts(pts, bragg, summit=None, rcurve=None, nout=None, e1=None, e2=None, extenthalf=None, ndtheta=None, grid=None)[source]

Return (dtheta, psi) of pts on crystal where bragg diffraction happens

For given pts and lamb/bragg

For each pts/lamb, there may be up to 2 arcs on the crystal Only returns valid solution (inside extenthalf), with nan elsewhere

psi and dtheta returned as (nlamb, npts, 2, ndtheta) arrays

Here nout, e1, e2 are at the unique crystal summit!

tofu.geom._comp_optics.calc_meridional_sagital_focus(rcurve=None, bragg=None, alpha=None, use_non_parallelism=None, verb=None)[source]
tofu.geom._comp_optics.calc_xixj_from_braggphi(det_cent=None, det_nout=None, det_ei=None, det_ej=None, det_outline=None, summit=None, nout=None, e1=None, e2=None, bragg=None, phi=None, option=None, strict=None)[source]

Several options for shapes

de_cent, det_nout, det_ei and det_ej are always of shape (3,)

option:
0:

(summit, e1, e2).shape = (3,) (bragg, phi).shape = (nbragg,) => (xi, xj).shape = (nbragg,)

1:

(summit, e1, e2).shape = (3, nlamb, npts, nbragg) (bragg, phi).shape = (nlamb, npts, nbragg) => (xi, xj).shape = (nlamb, npts, nbragg)

tofu.geom._comp_optics.checkformat_vectang(Z, nn, frame_cent, frame_ang)[source]
tofu.geom._comp_optics.get_approx_detector_rel(rcurve, bragg, braggref=None, xiref=None, bragg01=None, dist01=None, tangent_to_rowland=None)[source]

Return the approximative detector position on the Rowland circle relatively to the Bragg crystal. Possibility to define tangential position of the detector to the Rowland circle or not. On WEST, the maximum non-parallelism between two halves can be up to few arcmin so here, doesn’t need to define the precise location of the detector The bragg angle is provided and naturally defined as the angle between the emissed photon vector and the crystal mesh. So, if non parallelism approuved, bragg is relative to the vector basis dmat(nout,e1,e2). The position of the detector, relatively to the crystal, will be so in another Rowland circle with its center shifted from the original one.

tofu.geom._comp_optics.get_bragg_from_lamb(lamb, d, n=None)[source]

n*lamb = 2d*sin(bragg) The angle bragg is defined as the angle of incidence of the emissed photon vector and the crystal mesh, and not the crystal dioptre. For record, both are parallel and coplanar when is defined parallelism into the crystal.

tofu.geom._comp_optics.get_det_abs_from_rel(det_dist, n_crystdet_rel, det_nout_rel, det_ei_rel, summit, nout, e1, e2, ddist=None, di=None, dj=None, dtheta=None, dpsi=None, tilt=None)[source]

Return the absolute detector position, according to tokamak’s frame, on the Rowland circle from its relative position to the Bragg crystal. If non parallelism approuved, bragg is relative to the vector basis dmat(nout,e1,e2). The position of the detector, relatively to the crystal, will be so in another Rowland circle with its center shifted from the original one.

tofu.geom._comp_optics.get_e1e2_detectorplane(nn, nIn)[source]
tofu.geom._comp_optics.get_lamb_from_bragg(bragg, d, n=None)[source]

n*lamb = 2d*sin(bragg) The angle bragg is defined as the angle of incidence of the emissed photon vector and the crystal mesh, and not the crystal dioptre. For record, both are parallel and coplanar when is defined parallelism into the crystal.

tofu.geom._comp_optics.get_lambphifit(lamb, phi, nxi, nxj)[source]
tofu.geom._comp_optics.get_rowland_dist_from_bragg(bragg=None, rcurve=None)[source]
tofu.geom._comp_optics.get_vectors_from_angles(alpha, beta, nout, e1, e2)[source]

Return new unit vectors according to alpha and beta entries from user caused by the non parallelism assumed on the crystal.

tofu.geom._comp_solidangles module

tofu.geom._comp_solidangles._check_calc_solidangle_particle(traj=None, pts=None, rad=None, config=None, approx=None, aniso=None, block=None)[source]
tofu.geom._comp_solidangles.calc_solidangle_particle(pts=None, part_traj=None, part_radius=None, config=None, approx=None, aniso=None, block=None)[source]

Compute the solid angle subtended by a particle along a trajectory

The particle has radius r, and trajectory (array of points) traj It is observed from pts (array of points)

traj and pts are (3, N) and (3, M) arrays of cartesian coordinates

approx = True => use approximation aniso = True => return also unit vector of emission block = True consider LOS collisions (with Ves, Struct…)

if block:

config used for LOS collisions

Parameters
  • pts (np.ndarray) – Array of (3, M) pts coordinates (X, Y, Z) representing the points from which the particle is observed

  • part_traj (np.ndarray) – Array of (3, N) pts coordinates (X, Y, Z) representing the particle positions

  • part_radius (float / np.ndarray) –

    Unique of multiple values for the radius of the spherical particle

    if multiple, rad is a np.ndarray of shape (N,)

  • config (None / tf.geom.Config) – if block = True, solid angles are non-zero only if the field of view is not blocked bya structural element in teh chamber

  • approx (None / bool) – Flag indicating whether to compute the solid angle using an 1st-order series development (in whichcase the solid angle becomes proportional to the radius of the particle, see Notes_Upgrades/)

  • aniso (None / bool) – Flag indicating whether to consider anisotropic emissivity, meaning the routine must also compute and return the unit vector directing the flux from each pts to each position on the trajectory of the particle

  • block (None / bool) – Flag indicating whether to check for vignetting by structural elements provided by config

  • Return

  • -------

  • sang (np.ndarray) – (N, M) Array of floats, solid angles

tofu.geom._comp_solidangles.calc_solidangle_particle_integ(part_traj=None, part_radius=None, config=None, approx=True, block=True, resolution=None, DR=None, DZ=None, DPhi=None)[source]

tofu.geom._core module

This module is the geometrical part of the ToFu general package It includes all functions and object classes necessary for tomography on Tokamaks

class tofu.geom._core.CamLOS1D(dgeom=None, lOptics=None, Etendues=None, Surfaces=None, config=None, dchans=None, Id=None, Name=None, Exp=None, shot=None, Diag=None, sino_RefPt=None, fromdict=None, sep=None, method='optimized', SavePath='/home/lasofivec/tofu/doc/source', color=None)[source]

Bases: tofu.geom._core.Rays

_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (0.0, 0.0, 0.0, 1)}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (0.8, 0.8, 0.8, 1.0), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dP': {'color': 'k', 'lw': 2}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'color': 'k', 'lw': 2}}}
_dstrip = {'allowed': [0, 1, 2, 3, 4], 'strip': None}
get_summary(sep='  ', line='-', just='l', table_sep=None, verb=True, return_=False)[source]
save_to_imas(ids=None, shot=None, run=None, refshot=None, refrun=None, user=None, database=None, version=None, occ=None, dryrun=False, deep=True, restore_size=True, verb=True, config_description_2d=None, config_occ=None)[source]
class tofu.geom._core.CamLOS2D(dgeom=None, lOptics=None, Etendues=None, Surfaces=None, config=None, dchans=None, dX12='geom', Id=None, Name=None, Exp=None, shot=None, Diag=None, sino_RefPt=None, fromdict=None, sep=None, method='optimized', SavePath='/home/lasofivec/tofu/doc/source', color=None)[source]

Bases: tofu.geom._core.Rays

_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (0.0, 0.0, 0.0, 1)}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (0.8, 0.8, 0.8, 1.0), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dP': {'color': 'k', 'lw': 2}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'color': 'k', 'lw': 2}}}
_dstrip = {'allowed': [0, 1, 2, 3, 4], 'strip': None}
_isImage()[source]
property dX12
get_X12plot(plot='imshow')[source]
get_summary(sep='  ', line='-', just='l', table_sep=None, verb=True, return_=False)[source]
class tofu.geom._core.CoilCS(nturns=None, superconducting=None, active=None, temperature_nominal=None, mag_field_max=None, current_lim_max=None, **kwdargs)[source]

Bases: tofu.geom._core.CoilPF

_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (1.0, 0.0, 0.0, 1)}, 'dphys': {}, 'dreflect': {'Type': 'specular'}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (1.0, 0.0, 0.0, 1), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dP': {'ec': 'k', 'fc': (1.0, 0.0, 0.0, 1), 'linewidth': 1}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'ec': 'none', 'fc': (1.0, 0.0, 0.0, 1)}}}
_dstrip = {'allowed': [0, 1, 2], 'strip': None}
class tofu.geom._core.CoilPF(nturns=None, superconducting=None, active=None, temperature_nominal=None, mag_field_max=None, current_lim_max=None, **kwdargs)[source]

Bases: tofu.geom._core.StructOut

classmethod _checkformat_inputs_dmag(nturns=None, superconducting=None, temperature_nominal=None, mag_field_max=None, current_lim_max=None, active=None)[source]
_color = 'r'
_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (1.0, 0.0, 0.0, 1)}, 'dphys': {}, 'dreflect': {'Type': 'specular'}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (1.0, 0.0, 0.0, 1), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dP': {'ec': 'k', 'fc': (1.0, 0.0, 0.0, 1), 'linewidth': 1}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'ec': 'none', 'fc': (1.0, 0.0, 0.0, 1)}}}
_dstrip = {'allowed': [0, 1, 2], 'strip': None}
_from_dict(fd)[source]
static _get_keys_dmag()[source]
static _get_largs_dmag()[source]
_init(nturns=None, superconducting=None, active=None, **kwdargs)[source]

To be overloaded

_rebuild_dmag(lkeep=['nturns', 'superconducting', 'active'])[source]
_reset()[source]

To be overloaded

_strip(strip=0)[source]
_strip_dmag(lkeep=['nturns', 'superconducting', 'active'])[source]
classmethod _strip_init()[source]
_to_dict()[source]
property current
property dmag
get_summary(sep='  ', line='-', just='l', table_sep=None, verb=True, return_=False)[source]

Summary description of the object content

property nturns
set_current(current=None)[source]

Set the current circulating on the coil (A)

set_dmag(superconducting=None, nturns=None, active=None)[source]
strip(strip=0)[source]

Remove non-essential attributes to save memory / disk usage

Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes

See the difference by doing:

> self.get_nbytes() > self.strip(-1) > self.get_nbytes()

Parameters

strip (int) –

Flag indicating how much to strip from the object

0: Make complete (retrieve all attributes) 1: Remove dsino and dmag expendables 2: Remove also dgeom, dphys and dmisc expendables

-1: Equivalent to strip=2

class tofu.geom._core.Config(lStruct=None, Lim=None, dextraprop=None, Id=None, Name=None, Exp=None, shot=None, Type=None, SavePath='/home/lasofivec/tofu/doc/source', SavePath_Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], fromdict=None, sep=None)[source]

Bases: tofu.utils.ToFuObject

property Lim
classmethod _checkformat_fromdict_dStruct(dStruct)[source]
classmethod _checkformat_inputs_Id(Id=None, Name=None, Type=None, Exp=None, shot=None, include=None, **kwdargs)[source]
_checkformat_inputs_Struct(struct, err=True)[source]
_checkformat_inputs_dStruct(lStruct=None, Lim=None)[source]
_checkformat_inputs_dextraprop(dextraprop=None)[source]
_checkformat_inputs_dsino(RefPt=None, nP=None)[source]
_checkformat_inputs_extraval(extraval, key='', multi=True, size=None)[source]
_ddef = {'Id': {'Exp': 'Dummy', 'Type': 'Tor', 'include': ['Mod', 'Cls', 'Exp', 'Name', 'shot', 'version'], 'shot': 0}, 'dStruct': {'dextraprop': {'visible': True}, 'order': ['PlasmaDomain', 'Ves', 'PFC', 'CoilPF', 'CoilCS']}}
_dstrip = {'allowed': [0, 1, 2, 3], 'strip': None}
_dynamicattr()[source]
static _errmsg_dStruct(lStruct)[source]
static _from_SOLEDGE_extract_dict(pfe=None)[source]
_from_dict(fd)[source]
_get_extraprop(pp, k0=None, k1=None)[source]
static _get_keys_dStruct()[source]
static _get_keys_dextraprop()[source]
static _get_keys_dsino()[source]
static _get_largs_dStruct()[source]
static _get_largs_dextraprop()[source]
static _get_largs_dsino()[source]
_get_phithetaproj_dist(refpt=None, ntheta=None, nphi=None, theta=None, phi=None)[source]
_init(lStruct=None, Lim=None, dextraprop=None, **kwdargs)[source]

To be overloaded

_lclsstr = ['PlasmaDomain', 'Ves', 'PFC', 'CoilPF', 'CoilCS']
_reflect_Types(indout=None, Type=None, nRays=None)[source]

Return an array indicating the Type of reflection for each LOS

Return a (nRays,) np.ndarray of int indices, each index corresponds to:
  • 0: specular reflections

  • 1: diffusive reflections

  • 2: ccube reflections (corner cube)

If indout is provided, the Types are computed according to the information stored in each corresponding Struct

If Type is provided, the Type is forced (user-defined) for all LOS

_reflect_geom(u=None, vperp=None, indout=None, Type=None)[source]
_reset()[source]

To be overloaded

_set_color(k0, val)[source]
_set_dStruct(lStruct=None, Lim=None)[source]
_set_dextraprop(dextraprop=None)[source]
_set_extraprop(pp, val, k0=None, k1=None)[source]
_strip(strip=0, force=False, verb=True)[source]
_strip_dStruct(strip=0, force=False, verb=True)[source]
_strip_dextraprop(strip=0)[source]
_strip_dsino(lkeep=['RefPt', 'nP'])[source]
classmethod _strip_init()[source]
_to_SOLEDGE3X_get_data(type_extraprop=None, matlab_version=None, matlab_platform=None)[source]
_to_dict()[source]
add_Struct(struct=None, Cls=None, Name=None, Poly=None, shot=None, Lim=None, Type=None, dextraprop=None)[source]

Add a Struct instance to the config

An already existing Struct subclass instance can be added Or it will be created from the (Cls,Name,Poly,Lim) keyword args

add_extraprop(key, val)[source]
calc_solidangle_particle(pts=None, part_traj=None, part_radius=None, approx=None, aniso=None, block=None)[source]

Compute the solid angle subtended by a particle along a trajectory

The particle has radius r, and trajectory (array of points) traj It is observed from pts (array of points) Takes into account blocking of the field of view by structural elements

traj and pts are (3, N) and (3, M) arrays of cartesian coordinates

approx = True => use approximation aniso = True => return also unit vector of emission block = True consider LOS collisions (with Ves, Struct…)

if block:

config used for LOS collisions

Parameters
  • traj (np.ndarray) – Array of (3, N) pts coordinates (X, Y, Z) representing the particle positions

  • pts (np.ndarray) – Array of (3, M) pts coordinates (X, Y, Z) representing points from which the particle is observed

  • rad (float / np.ndarray) –

    Unique of multiple values for the radius of the spherical particle

    if multiple, rad is a np.ndarray of shape (N,)

  • approx (None / bool) – Flag indicating whether to compute the solid angle using a 1st-order series development (in which case the solid angle becomes proportional to the radius of the particle, see Notes_Upgrades/)

  • aniso (None / bool) – Flag indicating whether to consider anisotropic emissivity, meaning the routine must also compute and return the unit vector directing the flux from each pts to each position on the trajectory

  • block (None / bool) – Flag indicating whether to check for vignetting by structural elements provided by config

  • Return

  • -------

  • sang (np.ndarray) – (N, M) Array of floats, solid angles

calc_solidangle_particle_integrated(part_traj=None, part_radius=None, approx=None, block=None, resolution=None, DR=None, DZ=None, DPhi=None, plot=None, vmin=None, vmax=None, scale=None, fs=None, dmargin=None, returnax=None)[source]

Compute the integrated solid angle map subtended by particles

Integrates the solid angle toroidally on a volume sampling of Config

The particle has radius r, and trajectory (array of points) traj It is observed from pts (array of points) Takes into account blocking of the field of view by structural elements

traj and pts are (3, N) and (3, M) arrays of cartesian coordinates

approx = True => use approximation block = True consider LOS collisions (with Ves, Struct…)

if block:

config used for LOS collisions

Parameters
  • traj (np.ndarray) – Array of (3, N) pts coordinates (X, Y, Z) representing the particle positions

  • pts (np.ndarray) – Array of (3, M) pts coordinates (X, Y, Z) representing points from which the particle is observed

  • rad (float / np.ndarray) –

    Unique of multiple values for the radius of the spherical particle

    if multiple, rad is a np.ndarray of shape (N,)

  • approx (None / bool) – Flag indicating whether to compute the solid angle using a 1st-order series development (in which case the solid angle becomes proportional to the radius of the particle, see Notes_Upgrades/)

  • block (None / bool) – Flag indicating whether to check for vignetting by structural elements provided by config

  • Return

  • -------

  • sang (np.ndarray) – (N, M) Array of floats, solid angles

property dStruct
property dextraprop
property dsino
fdistfromwall(r, z, phi)[source]

Return a callable (function) for detecting trajectory collisions with wall

The function is continuous wrt time and space It takes into account all Struct in Config, including non-axisymmetric ones

It is desined for iterative root-finding algorithms and is thus called for a unique position

classmethod from_SOLEDGE3X(pfe=None, Name=None, Exp=None)[source]
classmethod from_svg(pfe, res=None, point_ref1=None, point_ref2=None, length_ref=None, r0=None, z0=None, scale=None, Exp=None, Name=None, shot=None, Type=None, SavePath='/home/lasofivec/tofu/doc/source', verb=None, returnas=None)[source]

Build a config from a svg file (Inkscape)

The svg shall have only:
  • closed polygons (possibly inc. Bezier curves)

  • an optional unique 2-points straight line (non-closed) used for auto-scaling

If Beziers curves are included, they will be discretized according to resolution parameter res (absolute maximum tolerated distance between points)

All closed polygons will be interpreted as:
  • a Ves instance if it has no fill color

  • a PFC instance if it has a fill color

The names are derived from Inkscape objects id

The coordinates are extracted from the svg They can be rescaled either:

  • automatically:

    scaling computed from the unique straight line and from the corresponding 2 points real-life coordinates provided by the user as 2 iterables (list, arrays or tuples) of len() = 2 (point_ref1 and point_ref2) Alternatively a single point (point_ref1) and the length_ref of the line can be provided

  • forcefully:

    the origin (r0, z0) and a common scaling factor (scale) are provided by the user

The result Config instance must have a Name and be associated to an experiment (Exp).

get_color()[source]

Return the array of rgba colors (same order as lStruct)

get_kwdargs_LOS_isVis()[source]
get_reflections(indout, u=None, vperp=None)[source]
get_summary(sep='  ', line='-', just='l', table_sep=None, verb=True, return_=False)[source]

Summary description of the object content

isInside(pts, In='(X,Y,Z)', log='any')[source]

Return a 2D array of bool

Equivalent to applying isInside to each Struct Check self.lStruct[0].isInside? for details

Arg log determines how Struct with multiple Limits are treated
  • ‘all’ : True only if pts belong to all elements

  • ‘any’ : True if pts belong to any element

property lStruct

Return the list of Struct that was used for creation

As tofu objects or SavePath+SaveNames (according to strip status)

property lStructIn

Return the list of StructIn contained in self.lStruct

As tofu objects or SavePath+SaveNames (according to strip status)

property nLim
property nStruct
plot(lax=None, proj=None, element='P', dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, indices=False, Lim=None, Nstep=None, draw=True, fs=None, wintit=None, tit=None, Test=True)[source]
plot_phithetaproj_dist(refpt=None, ntheta=None, nphi=None, theta=None, phi=None, cmap=None, invertx=None, ax=None, fs=None, tit=None, wintit=None, draw=None)[source]
plot_sino(ax=None, dP=None, Ang='theta', AngUnit='rad', Sketch=True, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, draw=True, fs=None, wintit=None, tit=None, Test=True)[source]
remove_Struct(Cls=None, Name=None)[source]
save_to_imas(shot=None, run=None, refshot=None, refrun=None, user=None, database=None, version=None, occ=None, dryrun=False, verb=True, description_2d=None)[source]
set_colors_random(cmap=<matplotlib.colors.ListedColormap object>)[source]
set_dsino(RefPt, nP=50)[source]
strip(strip=0, force=False, verb=True)[source]

Remove non-essential attributes to save memory / disk usage

Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes

See the difference by doing:

> self.get_nbytes() > self.strip(-1) > self.get_nbytes()

Parameters

strip (int) –

Flag indicating how much to strip from the object

0: Make complete (retrieve all attributes) 1: apply strip(1) to objects in self.lStruct 2: apply strip(2) to objects in self.lStruct 3: replace objects in self.lStruct by SavePath + SaveName

-1: Equivalent to strip=3

to_SOLEDGE3X(name=None, path=None, verb=None, type_extraprop=None, matlab_version=None, matlab_platform=None)[source]
class tofu.geom._core.PFC(Poly=None, Type=None, Lim=None, pos=None, extent=None, Id=None, Name=None, Exp=None, shot=None, sino_RefPt=None, sino_nP=50, Clock=False, arrayorder='C', fromdict=None, sep=None, SavePath='/home/lasofivec/tofu/doc/source', SavePath_Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], color=None, nturns=None, superconducting=None, active=None, temperature_nominal=None, mag_field_max=None, current_lim_max=None)[source]

Bases: tofu.geom._core.StructOut

_color = (0.8, 0.8, 0.8, 0.8)
_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (0.8, 0.8, 0.8, 0.8)}, 'dphys': {}, 'dreflect': {'Type': 'specular'}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (0.8, 0.8, 0.8, 0.8), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dP': {'ec': 'k', 'fc': (0.8, 0.8, 0.8, 0.8), 'linewidth': 1}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'ec': 'none', 'fc': (0.8, 0.8, 0.8, 0.8)}}}
_dstrip = {'allowed': [0, 1, 2], 'strip': None}
class tofu.geom._core.PlasmaDomain(Poly=None, Type=None, Lim=None, pos=None, extent=None, Id=None, Name=None, Exp=None, shot=None, sino_RefPt=None, sino_nP=50, Clock=False, arrayorder='C', fromdict=None, sep=None, SavePath='/home/lasofivec/tofu/doc/source', SavePath_Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], color=None, nturns=None, superconducting=None, active=None, temperature_nominal=None, mag_field_max=None, current_lim_max=None)[source]

Bases: tofu.geom._core.StructIn

_color = (0.8, 0.8, 0.8, 1.0)
_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (0.8, 0.8, 0.8, 1.0)}, 'dphys': {}, 'dreflect': {'Type': 'specular'}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (0.8, 0.8, 0.8, 1.0), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dP': {'color': (0.8, 0.8, 0.8, 1.0), 'lw': 2}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'color': (0.8, 0.8, 0.8, 1.0), 'lw': 2}}}
_dstrip = {'allowed': [0, 1, 2], 'strip': None}
class tofu.geom._core.Rays(dgeom=None, lOptics=None, Etendues=None, Surfaces=None, config=None, dchans=None, dX12='geom', Id=None, Name=None, Exp=None, shot=None, Diag=None, sino_RefPt=None, fromdict=None, sep=None, method='optimized', SavePath='/home/lasofivec/tofu/doc/source', color=None)[source]

Bases: tofu.utils.ToFuObject

Parent class of rays (ray-tracing), LOS, CamLOS1D and CamLOS2D

Focused on optimizing the computation time for many rays.

Each ray is defined by a starting point (D) and a unit vector(u). If a vessel (Ves) and structural elements (LStruct) are provided, the intersection points are automatically computed.

Methods for plootting, computing synthetic signal are provided.

Parameters
  • Id (str / ID) – A name string or a ID to identify this instance, if a string is provided, it is fed to ID

  • Du (iterable) –

    Iterable of len=2, containing 2 np.ndarrays represnting, for N rays:
    • Ds: a (3,N) array of the (X,Y,Z) coordinates of starting points

    • us: a (3,N) array of the (X,Y,Z) coordinates of the unit vectors

  • Ves (None / Ves) – A Ves instance to be associated to the rays

  • LStruct (None / Struct / list) – A Struct instance or list of such, for obstructions

  • Sino_RefPt (None / np.ndarray) –

    Iterable of len=2 with the coordinates of the sinogram reference point
    • (R,Z) coordinates if the vessel is of Type ‘Tor’

    • (Y,Z) coordinates if the vessel is of Type ‘Lin’

  • Exp (None / str) –

    Experiment to which the LOS belongs:
    • if both Exp and Ves are provided: Exp==Ves.Id.Exp

    • if Ves is provided but not Exp: Ves.Id.Exp is used

  • Diag (None / str) – Diagnostic to which the LOS belongs

  • shot (None / int) – Shot number from which this LOS is valid

  • SavePath (None / str) – If provided, default saving path of the object

property D
property Etendues
property Surfaces
_calc_signal_postformat(sig, Brightness=True, dataname=None, t=None, E=None, units=None, plot=True, out=<class 'object'>, fs=None, dmargin=None, wintit=None, invert=True, draw=True, connect=True)[source]
_calc_signal_preformat(ind=None, DL=None, t=None, out=<class 'object'>, Brightness=True)[source]
_check_indch(ind, out=<class 'int'>)[source]
static _checkformat_dOptics(lOptics=None)[source]
_checkformat_dX12(dX12=None)[source]
classmethod _checkformat_fromdict_dconfig(dconfig)[source]
classmethod _checkformat_inputs_Id(Id=None, Name=None, Exp=None, shot=None, Diag=None, include=None, **kwdargs)[source]
_checkformat_inputs_dES(val=None)[source]
_checkformat_inputs_dchans(dchans=None)[source]
static _checkformat_inputs_dconfig(config=None)[source]
_checkformat_inputs_dgeom(dgeom=None)[source]
classmethod _checkformat_inputs_dmisc(color=None)[source]
_checkformat_inputs_dsino(RefPt=None)[source]
_complete_dX12(dgeom)[source]
_compute_dgeom_extra1()[source]
_compute_dgeom_extra2D()[source]
_compute_dgeom_kRMin()[source]
_compute_dsino_extra()[source]
_compute_kInOut(largs=None, dkwd=None, indStruct=None)[source]
_dcases = {'A': {'lk': [], 'type': <class 'tuple'>}, 'B': {'lk': ['D', 'u'], 'type': <class 'dict'>}, 'C': {'lk': ['D', 'pinhole'], 'type': <class 'dict'>}, 'D': {'lk': ['pinhole', 'F', 'nIn', 'e1', 'x1', 'e2', 'x2'], 'type': <class 'dict'>}, 'E': {'lk': ['pinhole', 'F', 'nIn', 'e1', 'l1', 'n1', 'e2', 'l2', 'n2'], 'type': <class 'dict'>}, 'F': {'lk': ['pinhole', 'F', 'angles', 'x1', 'x2'], 'type': <class 'dict'>}, 'G': {'lk': ['pinhole', 'F', 'angles', 'l1', 'n1', 'l2', 'n2'], 'type': <class 'dict'>}}
_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': 'k'}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (0.8, 0.8, 0.8, 1.0), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'm': 'x', 'mew': 2, 'ms': 8}, 'dP': {'color': 'k', 'lw': 2}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'color': 'k', 'lw': 2}}}
_dstrip = {'allowed': [0, 1, 2, 3, 4], 'strip': None}
_from_dict(fd)[source]
static _get_keys_dOptics()[source]
static _get_keys_dX12()[source]
static _get_keys_dchans()[source]
static _get_keys_dconfig()[source]
static _get_keys_dgeom()[source]
static _get_keys_dmisc()[source]
static _get_keys_dsino()[source]
static _get_largs_dOptics()[source]
static _get_largs_dX12()[source]
static _get_largs_dchans()[source]
static _get_largs_dconfig()[source]
static _get_largs_dgeom(sino=True)[source]
static _get_largs_dmisc()[source]
static _get_largs_dsino()[source]
_get_plotL(reflections=True, Lplot=None, proj=None, ind=None, return_pts=False, multi=False)[source]

Get the (R,Z) coordinates of the cross-section projections

classmethod _get_x12_fromflat(X12)[source]
_init(dgeom=None, config=None, Etendues=None, Surfaces=None, sino_RefPt=None, dchans=None, method='optimized', **kwargs)[source]

To be overloaded

classmethod _is2D()[source]
classmethod _isLOS()[source]
_kInOut_Isoflux_inputs(lPoly, lVIn=None)[source]
_kInOut_Isoflux_inputs_usr(lPoly, lVIn=None)[source]
_method = 'optimized'
_prepare_inputs_kInOut(D=None, u=None, indStruct=None)[source]
_reset()[source]

To be overloaded

_rotate_DPinholeu(func, **kwdargs)[source]
_set_color(color=None)[source]
classmethod _set_color_ddef(color)[source]
_set_dOptics(lOptics=None)[source]
_set_dgeom(dgeom=None, Etendues=None, Surfaces=None, sino_RefPt=None, extra=True, sino=True)[source]
_set_dmisc(color=None)[source]
_strip(strip=0, verb=True)[source]
_strip_dconfig(strip=0, force=False, verb=True)[source]
_strip_dgeom(strip=0)[source]
_strip_dmisc(lkeep=['color'])[source]
_strip_dsino(strip=0)[source]
classmethod _strip_init()[source]
_to_dict()[source]
_update_dgeom_from_TransRotFoc(val, key='x')[source]
_update_or_copy(D, u, pinhole=None, return_copy=None, name=None, diag=None, dchans=None)[source]
add_reflections(Type=None, nb=None)[source]

Add relfected LOS to the camera

Reflected LOS can be of 3 types:
  • ‘speculiar’: standard mirror-like reflection

  • ‘diffusive’: random reflection

  • ‘ccube’: corner-cube reflection (ray goes back its way)

As opposed to self.get_reflections_as_cam(), the reflected rays are stored in the camera object

calc_kInkOut_Isoflux(lPoly, lVIn=None, Lim=None, kInOut=True)[source]

Calculate the intersection points of each ray with each isoflux

The isofluxes are provided as a list of 2D closed polygons

The intersections are the inward and outward intersections They are retruned as two np.ndarrays: kIn and kOut Each array contains the length parameter along the ray for each isoflux

calc_length_in_isoflux(lPoly, lVIn=None, Lim=None, kInOut=True)[source]

Return the length of each LOS inside each isoflux

Uses self.calc_kInkOut_Isoflux() to compute the linear abscissa (k) of the entry points (kIn) and exit points (kOut) for each LOS

The isofluxes must be provided as a list of polygons

The length is returned as a (nPoly, nLOS) 2d array

calc_min_geom_radius(axis)[source]

Return the minimum geom. radius of each LOS, from an arbitrary axis

The axis mut be provided as a (R,Z) iterable Uses self.set_dsino()

p: np.ndarray

(nLOS,) array of minimal radius (or impact parameter)

theta: np.ndarray

(nLOS,) array of associated theta with respect to axis

pts: np.ndarray

(3,nLOS) array of (X,Y,Z) coordinates of associated points on LOS

calc_min_rho_from_Plasma2D(plasma, t=None, log='min', res=None, resMode='abs', method='sum', quant=None, ref1d=None, ref2d=None, interp_t=None, interp_space=None, fill_value=nan, pts=False, Test=True)[source]

Return the min/max value of scalar field quant for each LOS

Typically used to get the minimal normalized minor radius But can be used for any quantity available in plasma if:

  • it is a 2d profile

  • it is a 1d profile that can be interpolated on a 2d mesh

Currently sample each LOS with desired resolution and returns the absolute min/max interpolated value (and associated point)

See self.get_sample() for details on sampling arguments:
  • res, resMode, method

See Plasma2D.interp_pts2profile() for details on interpolation args:
  • t, quant, q2dref, q1dref, interp_t, interp_space, fill_value

val: np.ndarray

(nt, nLOS) array of min/max values

pts: np.ndarray

(nt, nLOS, 3) array of (X,Y,Z) coordinates of associated points Only returned if pts = True

t: np.ndarray

(nt,) array of time steps at which the interpolations were made

calc_signal(func, t=None, ani=None, fkwdargs={}, Brightness=True, res=None, DL=None, resMode='abs', method='sum', minimize='calls', num_threads=16, reflections=True, coefs=None, coefs_reflect=None, ind=None, returnas=<class 'object'>, plot=True, dataname=None, fs=None, dmargin=None, wintit=None, invert=True, units=None, draw=True, connect=True, newcalc=True)[source]

Return the line-integrated emissivity

Beware, by default, Brightness=True and it is only a line-integral !

Indeed, to get the received power, you need an estimate of the Etendue (previously set using self.set_Etendues()) and use Brightness=False.

Hence, if Brightness=True and if the emissivity is provided in W/m3 (resp. W/m3/sr), => the method returns W/m2 (resp. W/m2/sr) The line is sampled using get_sample(),

Except func, arguments common to get_sample()

Parameters
  • func (callable) –

    The user-provided emissivity function Shall take at least:

    func(pts, t=None, vect=None)

    where:
    • pts : (3,N) np.ndarray, (X,Y,Z) coordinates of points

    • t : None / (nt,) np.ndarray, time vector

    • vect: None / (3,N) np.ndarray, unit direction vectors (X,Y,Z)

    Should return at least:
    • val : (N,) np.ndarray, local emissivity values

  • method (string, the integral can be computed using 3 different methods) –

    • ‘sum’: A numpy.sum() on the local values (x segments) DEFAULT

    • ’simps’: using scipy.integrate.simps()

    • ’romb’: using scipy.integrate.romb()

  • minimize (string, method to minimize for computation optimization) –

    • “calls”: minimal number of calls to func (default)

    • ”memory”: slowest method, to use only if “out of memory” error

    • ”hybrid”: mix of before-mentioned methods.

Returns

  • sig (np.ndarray) – The computed signal, a 1d or 2d array depending on whether a time vector was provided.

  • units (str) – Units of the result

calc_signal_from_Plasma2D(plasma2d, t=None, newcalc=True, quant=None, ref1d=None, ref2d=None, q2dR=None, q2dPhi=None, q2dZ=None, Type=None, Brightness=True, interp_t='nearest', interp_space=None, fill_value=None, res=None, DL=None, resMode='abs', method='sum', minimize='calls', num_threads=16, reflections=True, coefs=None, coefs_reflect=None, ind=None, returnas=<class 'object'>, plot=True, dataname=None, fs=None, dmargin=None, wintit=None, invert=True, units=None, draw=True, connect=True)[source]
check_ff(ff, t=None, ani=None)[source]
compute_dgeom(extra=True, show_debug_plot=True)[source]

Compute dictionnary of geometrical attributes (dgeom)

Parameters

show_debug_plot (bool) – In case some lines of sight have no visibility inside the tokamak, they will be considered invalid. tofu will issue a warning with their indices and if show_debug_plot is True, try to plot a 3d figure to help understand why these los have no visibility

property config
property dchans
property dgeom
property dsino
get_indStruct_computeInOut(unique_In=None)[source]

The indices of structures with compute = True

The indidces refer to self.config.lStruct
  • The first array corresponds to Struct of type In

  • The second array corresponds to Struct of type Out

get_inspector(ff)[source]
get_reflections_as_cam(Type=None, Name=None, nb=None)[source]

Return a camera made of reflected LOS

Reflected LOS can be of 3 types:
  • ‘speculiar’: standard mirror-like reflection

  • ‘diffusive’: random reflection

  • ‘ccube’: corner-cube reflection (ray goes back its way)

As opposed to self.add_reflections(), the reflected rays are return as an independent camera (CamLOS1D)

get_sample(res=None, resMode='abs', DL=None, method='sum', ind=None, pts=False, compact=True, num_threads=10, Test=True)[source]

Return a linear sampling of the LOS

The LOS is sampled into a series a points and segments lengths The resolution (segments length) is <= res The sampling can be done according to different methods It is possible to sample only a subset of the LOS

Parameters
  • res (float) – Desired resolution

  • resMode (str) –

    Flag indicating res should be understood as:
    • ’abs’: an absolute distance in meters

    • ’rel’: a relative distance (fraction of the LOS length)

  • DL (None / iterable) – The fraction [L1;L2] of the LOS that should be sampled, where L1 and L2 are distances from the starting point of the LOS (LOS.D) DL can be an iterable of len()==2 (identical to all los), or a (2,nlos) array

  • method (str) –

    Flag indicating which to use for sampling:
    • ’sum’: the LOS is sampled into N segments of equal length,
      where N is the smallest int such that:
      • segment length <= resolution(res,resMode)

      The points returned are the center of each segment

    • ’simps’: the LOS is sampled into N segments of equal length,
      where N is the smallest int such that:
      • segment length <= resolution(res,resMode)

      • N is even

      The points returned are the egdes of each segment

    • ’romb’: the LOS is sampled into N segments of equal length,
      where N is the smallest int such that:
      • segment length <= resolution(res,resMode)

      • N = 2^k + 1

      The points returned are the egdes of each segment

  • ind (None / iterable of int) – indices of the LOS to be sampled

  • pts (bool) – Flag indicating whether to return only the abscissa parameter k (False) or the 3D pts coordinates (True)

  • compact (bool) – Flag incating whether to retrun the sampled pts of all los in a single concatenated array (True) or splitted into a list of nlos arrays)

Returns

  • k (np.ndarray) –

    if pts == False:
    A (npts,) array of the abscissa parameters

    (i.e.: points distances from the LOS starting points)

    In order to get the 3D cartesian coordinates of pts do:

    if pts == True:

    A (3,npts) array of the sampled points 3D cartesian coordinates

  • reseff (np.ndarray) – A (nlos,) array of the effective resolution (<= res input), as an absolute distance

  • ind (np.ndarray) – A (nlos-1,) array of integere indices (where to split k to separate the points of each los). e.g.: lk = np.split(k,ind)

get_subset(indch=None, Name=None)[source]

Return an instance which is a sub-set of the camera

The subset is the same camera but with only the LOS selected by indch It can be assigned a new Name (str), or the same one (True)

get_touch_colors(ind=None, dElt=None, cbck=(0.8, 0.8, 0.8), rgba=True)[source]

Get array of colors per LOS (color set by the touched Struct)

get_touch_dict(ind=None, out=<class 'bool'>)[source]

Get a dictionnary of Cls_Name struct with indices of Rays touching

Only includes Struct object with compute = True

(as returned by self.lStruct__computeInOut_computeInOut)

Also return the associated colors If in is not None, the indices for each Struct are split between:

  • indok : rays touching Struct and in ind

  • indout: rays touching Struct but not in ind

property isInPoloidalPlane
property isPinhole
property kIn
property kMin
property kOut
property lOptics
move(param)[source]

Set new position to desired param according to default movement

Can only be used if default movement was set before See self.set_move()

property nRays
property pinhole
plot(lax=None, proj='all', reflections=True, Lplot='Tot', element='L', element_config='P', Leg='', dL=None, dPtD={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtI={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtO={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtR={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtP={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, multi=False, ind=None, fs=None, tit=None, wintit=None, draw=True, Test=True)[source]

Plot the Rays / LOS, in the chosen projection(s)

Optionnally also plot associated Ves and Struct The plot can also include:

  • special points

  • the unit directing vector

Parameters
  • lax (list / plt.Axes) – The axes for plotting (list of 2 axes if Proj=’All’) If None a new figure with new axes is created

  • proj (str) –

    Flag specifying the kind of projection:
    • ’Cross’ : cross-section

    • ’Hor’ : horizontal

    • ’All’ : both cross-section and horizontal (on 2 axes)

    • ’3d’ : a (matplotlib) 3d plot

  • projections (bool) – Flag indicating whether to plot also the reflected rays Assuming some reflected rays are present (self.add_reflections())

  • element (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 if Ves.Type=’Tor’)

    • ’P’: Point of used for impact parameter (i.e.: with minimal

      distance to reference point Sino_RefPt)

  • Lplot (str) –

    Flag specifying the length to plot:
    • ’Tot’: total length, from starting point (D) to output point

    • ’In’ : only the in-vessel fraction (from input to output)

  • element_config (str) – Fed to self.config.plot()

  • Leg (str) – Legend, if Leg=’’ the LOS name is used

  • dL (dict / None) – Dictionary of properties for plotting the lines Fed to plt.Axes.plot(), set to default if None

  • dPtD (dict) – Dictionary of properties for plotting point ‘D’

  • dPtI (dict) – Dictionary of properties for plotting point ‘I’

  • dPtO (dict) – Dictionary of properties for plotting point ‘O’

  • dPtR (dict) – Dictionary of properties for plotting point ‘R’

  • dPtP (dict) – Dictionary of properties for plotting point ‘P’

  • dLeg (dict or None) – Dictionary of properties for plotting the legend Fed to plt.legend(), the legend is not plotted if None

  • draw (bool) – Flag indicating whether fig.canvas.draw() shall be called

  • a4 (bool) – Flag indicating whether to plot the figure in a4 dimensions

  • Test (bool) –

  • a4 – Flag indicating whether to plot the figure in a4 dimensions

  • Test

  • a4 – Flag indicating whether to plot the figure in a4 dimensions

  • Test

  • a4 – Flag indicating whether to plot the figure in a4 dimensions

  • Test

  • Test – Flag indicating whether the inputs should be tested for conformity

Returns

La (list / plt.Axes) – Handles of the axes used for plotting (list if Proj=’All’)

plot_sino(ax=None, element='LV', Sketch=True, Ang='theta', AngUnit='rad', Leg=None, dL={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dVes={'edgecolor': (0.8, 0.8, 0.8, 1.0), 'facecolor': (0.8, 0.8, 0.8, 1.0), 'linestyle': 'solid', 'linewidth': 1}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, ind=None, multi=False, fs=None, tit=None, wintit=None, draw=True, Test=True)[source]

Plot the LOS in projection space (sinogram)

Plot the Rays in projection space (cf. sinograms) as points. Can also optionnally plot the associated Ves

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:
    • ’Cross’: a classic sinogram (vessel cross-section)

    • ’3d’: an extended 3D version (‘3d’), with an additional angle

  • ax (None / plt.Axes) – The axes on which to plot, if None a new figure is created

  • Elt (str) –

    Flag indicating which elements to plot (one per capital letter):
    • ’L’: LOS

    • ’V’: Vessel

  • Ang (str) –

    Flag indicating which angle to use for the impact parameter:
    • ’xi’: the angle of the line itself

    • ’theta’: its impact parameter (theta)

  • AngUnit (str) –

    Flag for the angle units to be displayed:
    • ’rad’: for radians

    • ’deg’: for degrees

  • Sketch (bool) – Flag indicating whether to plot a skecth with angles definitions

  • dL (dict) – Dictionary of properties for plotting the Rays points

  • dV (dict) – Dictionary of properties for plotting the vessel envelopp

  • dLeg (None / dict) – Dictionary of properties for plotting the 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 a4

  • Test (bool) – Flag indicating whether the inputs shall be tested for conformity

Returns

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

plot_touch(key=None, quant='lengths', Lplot=None, invert=None, ind=None, Bck=True, fs=None, wintit=None, tit=None, connect=True, draw=True)[source]

Interactive plot of the camera and the structures it touches

The camera LOS are plotted in poloidal and horizontal projections The associated Config is also plotted The plot shows which strutural element is touched by each LOS

In addition, an extra quantity can be mapped to alpha (transparency)

Parameters
  • key (None / str) – Only relevant if self.dchans was defined key is then a key to sekf.dchans

  • quant (None / str) –

    Flag indicating which extra quantity is used to map alpha: - ‘lengths’ (default): the length of each LOS - ‘angles’ : the angle of incidence of each LOS

    (with respect to the normal of the surface touched,

    useful for assessing reflection probabilities)

    • ’indices’: the index of each LOS

      (useful for checking numbering)

    • ’Etendues’: the etendue associated to each LOS (user-provided)

    • ’Surfaces’: the surfaces associated to each LOS (user-provided)

  • Lplot (None / str) –

    Flag indicating whether to plot:
    • ’tot’: the full length of the LOS

    • ’in’: only the part that is inside the vessel

  • invert (None / bool) – Flag indicating whether to plot 2D camera images inverted (pinhole)

  • ind (None / np.ndarray) – Array of bool indices used to select only a subset of the LOS

  • Bck (None / bool) – Flag indicating whether to plot the background LOS

  • fs (None / tuple) – figure size in inches

  • wintit (None / str) – Title for the window

  • tit (None / str) – Title for the figure

  • connect (None / bool) – Flag indicating to connect interactive actuators

  • draw (None / bool) – Flag indicating whether to draw the figure

rotate_around_3daxis(angle=None, axis=None, return_copy=None, diag=None, name=None, dchans=None)[source]

Rotate the instance around the provided 3d axis

rotate_around_torusaxis(angle=None, return_copy=None, diag=None, name=None, dchans=None)[source]

Rotate the instance around the torus axis

rotate_in_cross_section(angle=None, axis_rz=None, phi=None, return_copy=None, diag=None, name=None, dchans=None)[source]

Rotate the instance in the cross-section

select(key=None, val=None, touch=None, log='any', out=<class 'int'>)[source]

Return the indices of the rays matching selection criteria

The criterion can be of two types:
  • a key found in self.dchans, with a matching value

  • a touch tuple (indicating which element in self.config is touched

    by the desired rays)

Parameters
  • key (None / str) – A key to be found in self.dchans

  • val (int / str / float / list of such) – The value to be matched If a list of values is provided, the behaviour depends on log

  • log (str) –

    A flag indicating which behaviour to use when val is a list
    • any : Returns indices of rays matching any value in val

    • all : Returns indices of rays matching all values in val

    • not : Returns indices of rays matching None of the val

  • touch (None / str / int / tuple) –

    Used if key is None Tuple that can be of len()=1, 2 or 3 Tuple indicating you want the rays that are touching some specific elements of self.config:

    • touch[0]str / int or list of such

      str : a ‘Cls_Name’ string indicating the element int : the index of the element in self.config.lStruct

    • touch[1]int / list of int

      Indices of the desired segments on the polygon (i.e.: of the cross-section polygon of the above element)

    • touch[2]int / list of int

      Indices, if relevant, of the toroidal / linear unit Only relevant when the element has noccur>1

    In this case only log=’not’ has an effect

  • out (str) –

    Flag indicating whether to return:
    • bool : a (nRays,) boolean array of indices

    • inta (N,) array of int indices (N=number of matching

      rays)

Returns

ind (np.ndarray) – The array of matching rays

set_Etendues(val)[source]
set_Surfaces(val)[source]
set_dX12(dX12=None)[source]
set_dchans(dchans=None)[source]
set_dconfig(config=None, calcdgeom=True)[source]
set_dsino(RefPt=None, extra=True)[source]
set_move(move=None, param=None, **kwdargs)[source]

Set the default movement parameters

A default movement can be set for the instance, it can be any of the pre-implemented movement (rotations or translations) This default movement is the one that will be called when using self.move()

Specify the type of movement via the name of the method (passed as a str to move)

Specify, for the geometry of the instance at the time of defining this default movement, the current value of the associated movement parameter (angle / distance). This is used to set an arbitrary difference for user who want to use absolute position values The desired incremental movement to be performed when calling self.move will be deduced by substracting the stored param value to the provided param value. Just set the current param value to 0 if you don’t care about a custom absolute reference.

kwdargs must be a parameters relevant to the chosen method (axis, direction…)

e.g.:
self.set_move(move=’rotate_around_3daxis’,

param=0., axis=([0.,0.,0.], [1.,0.,0.]))

self.set_move(move=’translate_3d’,

param=0., direction=[0.,1.,0.])

strip(strip=0, verb=True)[source]

Remove non-essential attributes to save memory / disk usage

Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes

See the difference by doing:

> self.get_nbytes() > self.strip(-1) > self.get_nbytes()

Parameters

strip (int) –

Flag indicating how much to strip from the object

0: Make complete (retrieve all attributes) 1: dgeom w/o pts + config.strip(1) 2: dgeom w/o pts + config.strip(2) + dsino empty 3: dgeom w/o pts + config.strip(3) + dsino empty 4: dgeom w/o pts + config=pathfile + dsino empty

-1: Equivalent to strip=4

translate_3d(distance=None, direction=None, return_copy=None, diag=None, name=None, dchans=None)[source]

Translate the instance in provided direction

translate_in_cross_section(distance=None, direction_rz=None, phi=None, return_copy=None, diag=None, name=None, dchans=None)[source]

Translate the instance in the cross-section

property u
class tofu.geom._core.Ves(Poly=None, Type=None, Lim=None, pos=None, extent=None, Id=None, Name=None, Exp=None, shot=None, sino_RefPt=None, sino_nP=50, Clock=False, arrayorder='C', fromdict=None, sep=None, SavePath='/home/lasofivec/tofu/doc/source', SavePath_Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], color=None, nturns=None, superconducting=None, active=None, temperature_nominal=None, mag_field_max=None, current_lim_max=None)[source]

Bases: tofu.geom._core.StructIn

_color = 'k'
_ddef = {'Id': {'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dgeom': {'Lim': [], 'Type': 'Tor', 'arrayorder': 'C'}, 'dmisc': {'color': (0.0, 0.0, 0.0, 1)}, 'dphys': {}, 'dreflect': {'Type': 'specular'}, 'dsino': {}}
_dplot = {'3d': {'Elt': 'P', 'Lim': None, 'Nstep': 50, 'dP': {'antialiased': False, 'color': (0.0, 0.0, 0.0, 1), 'cstride': 1, 'linewidth': 0.0, 'rstride': 1}}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dP': {'color': (0.0, 0.0, 0.0, 1), 'lw': 2}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'color': (0.0, 0.0, 0.0, 1), 'lw': 2}}}
_dstrip = {'allowed': [0, 1, 2], 'strip': None}

tofu.geom._core_optics module

This module is the geometrical part of the ToFu general package It includes all functions and object classes necessary for tomography on Tokamaks

class tofu.geom._core_optics.CrystalBragg(dgeom=None, dmat=None, dbragg=None, Id=None, Name=None, Exp=None, Diag=None, shot=None, fromdict=None, sep=None, SavePath='/home/lasofivec/tofu/doc/source', SavePath_Include=['Mod', 'Cls', 'Type', 'Exp', 'Deg', 'Diag', 'Name', 'shot'], color=None)[source]

Bases: tofu.utils.ToFuObject

A class defining crystals for Bragg diffraction

A crystal can be of Type flat, cylindrical or spherical It is characterized by its:

  • geometry (Type, dimensions, curvature radii and position/orientation)

  • Material and lattice

  • Bragg parameters (angle vs lambda)

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()

  • dgeom (dict) –

    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

    dspectral: str

    Flag indicating whether the vessel will be a torus (‘Tor’) or a linear device (‘Lin’)

  • SavePath (None / str) – If provided, forces the default saving path of the object to the provided value

property Type

Return the type of structure

_calc_dthetapsiphi_from_lambpts(pts=None, bragg=None, lamb=None, n=None, ndtheta=None, use_non_parallelism=None, grid=None)[source]
_calc_spect1d_from_data2d(data, lamb, phi, nlambfit=None, nphifit=None, nxi=None, nxj=None, spect1d=None, mask=None, vertsum1d=None)[source]
_checkformat_bragglamb(bragg=None, lamb=None, n=None)[source]
_checkformat_det(det=None)[source]
_checkformat_get_Rays_from(phi=None, bragg=None)[source]
classmethod _checkformat_inputs_Id(Id=None, Name=None, Exp=None, Diag=None, shot=None, Type=None, include=None, **kwdargs)[source]
_ddef = {'Id': {'Diag': 'dummy', 'Exp': 'dummy', 'include': ['Mod', 'Cls', 'Exp', 'Diag', 'Name', 'shot', 'version'], 'shot': 0}, 'dbragg': {'braggref': 0.7853981633974483}, 'dgeom': {'Type': 'sph', 'Typeoutline': 'rect'}, 'dmat': {}, 'dmisc': {'color': 'k'}}
_dplot = {'3d': {}, 'cross': {'Elt': 'P', 'dBs': {'color': 'b', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dBv': {'color': 'g', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dI': {'color': 'k', 'ls': '--', 'marker': 'x', 'mew': 2, 'ms': 8}, 'dP': {'color': 'k', 'lw': 2}, 'dVect': {'color': 'r', 'scale': 10}}, 'hor': {'Elt': 'P', 'Nstep': 50, 'dBs': {'color': 'b', 'ls': '--'}, 'dBv': {'color': 'g', 'ls': '--'}, 'dI': {'color': 'k', 'ls': '--'}, 'dP': {'color': 'k', 'lw': 2}}}
_dstrip = {'allowed': [0, 1], 'strip': None}
_from_dict(fd)[source]
static _get_keys_dbragg()[source]
static _get_keys_dgeom()[source]
static _get_keys_dmat()[source]
static _get_keys_dmisc()[source]
static _get_largs_dbragg()[source]
static _get_largs_dgeom(sino=True)[source]
static _get_largs_dmat()[source]
static _get_largs_dmisc()[source]
_get_local_coordinates_of_det(bragg=None, lamb=None, det_ref=None, use_non_parallelism=None)[source]

Computation of translation (ddist, di, dj) and angular (dtheta, dpsi, tilt) properties of an arbitrary detector choosen by the user.

_get_rays_from_cryst(phi=None, bragg=None, lamb=None, n=None, dtheta=None, psi=None, ntheta=None, npsi=None, use_non_parallelism=None, include_summit=None, grid=None)[source]
_init(dgeom=None, dmat=None, dbragg=None, color=None, **kwdargs)[source]

To be overloaded

_rebuild_dbragg(lkeep=None)[source]
_rebuild_dgeom(lkeep=None)[source]
_rebuild_dmat(lkeep=None)[source]
_rebuild_dmisc(lkeep=['color'])[source]
_reset()[source]

To be overloaded

_rotate_or_translate(func, **kwdargs)[source]
_set_color(color=None)[source]
classmethod _set_color_ddef(color)[source]
_set_dmisc(color=None)[source]
_strip(strip=0)[source]
_strip_dbragg(lkeep=None)[source]
_strip_dgeom(lkeep=None)[source]
_strip_dmat(lkeep=None)[source]
_strip_dmisc(lkeep=['color'])[source]
classmethod _strip_init()[source]
_to_dict()[source]
_update_or_copy(dgeom, pinhole=None, return_copy=None, name=None, diag=None, shot=None)[source]
calc_johannerror(xi=None, xj=None, err=None, det=None, n=None, lpsi=None, ldtheta=None, lambda_interval_min=None, lambda_interval_max=None, use_non_parallelism=None, plot=True, fs=None, cmap=None, vmin=None, vmax=None, tit=None, wintit=None)[source]

Plot the johann error

The johann error is the error (scattering) induced by defocalization

due to finite crystal dimensions

There is a johann error on wavelength (lamb => loss of spectral

resolution) and on directionality (phi)

If provided, lpsi and ldtheta are taken as normalized variations with

respect to the crystal summit and to its extenthalf. Typical values are:

  • lpsi = [-1, 1, 1, -1]

  • ldtheta = [-1, -1, 1, 1]

They must have the same len()

First affecting a reference lambda according to:
  • pixel’s position

  • crystal’s summit

Then, computing error on bragg and phi angles on each pixels by computing lambda and phi from the crystal’s outline Provide lambda_interval_min/max to ensure the given wavelength interval is detected over the whole surface area. A True/False boolean is then returned.

calc_meridional_sagital_focus(rcurve=None, bragg=None, alpha=None, use_non_parallelism=None, verb=None)[source]

Compute sagittal and meridional focuses distances. Optionnal result according to non-parallelism, using first the update_non_parallelism method.

Parameters
  • rcurve (float) – in dgeom dict., curvature radius of the crystal.

  • bragg (float) – in dbragg dict., reference bragg angle of the crystal.

  • alpha (float) – in dmat dict., amplitude of the non-parallelism as an a angle defined by user, in radian.

  • use_non_parallelism (str) – Need to be True to use new alpha angle

Returns

  • merid_ref (float) – Distance crystal-meridional focus (m), for a perfect crystal

  • sagit_ref (float) – Distance crystal-sagital focus (m), for a perfect crystal

  • merid_unp (float) – Distance crystal-meridional focus (m), using non_parallelism

  • sagit_unp (float) – Distance crystal-sagital focus (m), using non_parallelism

calc_raytracing_from_lambpts(lamb=None, bragg=None, pts=None, xi_bounds=None, xj_bounds=None, nphi=None, det=None, n=None, ndtheta=None, johann=False, lpsi=None, ldtheta=None, rocking=False, strict=None, plot=None, fs=None, dmargin=None, wintit=None, tit=None, proj=None, legend=None, draw=None, returnas=None)[source]

Visualize the de-focusing by ray-tracing of chosen lamb

If plot, 3 different plots can be produced:
  • det: plots the intersection of rays with detector plane

  • ‘2d’: plots the geometry of the rays in 2d cross and hor

  • ‘3d’: plots the geometry of the rays in 3d

Specify the plotting option by setting plot to any of these (or a list)

calc_xixj_from_braggphi(phi=None, bragg=None, lamb=None, n=None, dtheta=None, psi=None, det=None, use_non_parallelism=None, strict=None, return_strict=None, data=None, plot=True, dax=None)[source]

Assuming crystal’s summit as frame origin

According to [1], this assumes a local frame centered on the crystal

These calculations are independent from the tokamak’s frame:

The origin of the local frame is the crystal’s summit The (O, ez) axis is the crystal’s normal The crystal is tangent to (O, ex, ey)

[1] tofu/Notes_Upgrades/SpectroX2D/SpectroX2D_EllipsesOnPlane.pdf

Z: float

Detector’s plane intersection with (O, ez) axis

n: np.ndarray

(3,) array containing local (x,y,z) coordinates of the plane’s normal vector

property center
property dbragg

Return the polygon defining the structure cross-section

property dgeom
property dmat

Return the polygon defining the structure cross-section

property dmisc
fit1d(data=None, lamb=None, dinput=None, dprepare=None, dlines=None, dconstraints=None, mask=None, domain=None, subset=None, pos=None, same_spectrum=None, same_spectrum_dlamb=None, focus=None, valid_fraction=None, valid_nsigma=None, focus_half_width=None, dx0=None, dscales=None, x0_scale=None, bounds_scale=None, method=None, tr_solver=None, tr_options=None, max_nfev=None, xtol=None, ftol=None, gtol=None, loss=None, verbose=None, chain=None, jac=None, showonly=None, amp=None, coefs=None, ratio=None, Ti=None, width=None, vi=None, shift=None, pts_lamb_total=None, pts_lamb_detail=None, save=None, name=None, path=None, plot=None, fs=None, dmargin=None, tit=None, wintit=None, returnas=None)[source]
static fit1d_dinput(dlines=None, dconstraints=None, dprepare=None, data=None, lamb=None, mask=None, domain=None, pos=None, subset=None, same_spectrum=None, same_spectrum_dlamb=None, focus=None, valid_fraction=None, valid_nsigma=None, focus_half_width=None, valid_return_fract=None)[source]

Return a formatted dict of lines and constraints

To be fed to _fit12d.multigausfit1d_from_dlines() Provides a user-friendly way of defining constraints

static fit1d_extract(dfit1d=None, amp=None, coefs=None, ratio=None, Ti=None, width=None, vi=None, shift=None, pts_lamb_total=None, pts_lamb_detail=None)[source]
fit1d_from2d()[source]

Useful for optimizing detector or crystal position

Given a set of 2d images on a detector Transform the 2d (xi, xj) image into (lamb, phi) Slice nphi 1d spectra Fit them using a dict of reference lines (dlines) Optionally provide constraints for the fitting Return the vertical profiles of the wavelength shitf of each line To be used as input for an cost function and optimization

1d fitting is used instead of 2d because:
  • faster (for optimization)

  • does not require a choice of nbsplines

  • easier to understand and decide for user

fit2d(data=None, xi=None, xj=None, det=None, dtheta=None, psi=None, n=None, dinput=None, dprepare=None, dlines=None, dconstraints=None, mask=None, domain=None, subset=None, pos=None, binning=None, focus=None, valid_fraction=None, valid_nsigma=None, focus_half_width=None, deg=None, knots=None, nbsplines=None, dx0=None, dscales=None, x0_scale=None, bounds_scale=None, method=None, tr_solver=None, tr_options=None, max_nfev=None, xtol=None, ftol=None, gtol=None, loss=None, verbose=None, chain=None, jac=None, showonly=None, predeclare=None, debug=None, amp=None, coefs=None, ratio=None, Ti=None, width=None, vi=None, shift=None, pts_lamb_total=None, pts_lamb_detail=None, save=None, name=None, path=None, plot=None, fs=None, dmargin=None, tit=None, wintit=None, returnas=None)[source]

Perform 2d fitting of a 2d spectrometre image

Fit the spectrum by a sum of gaussians Modulate each gaussian parameters by bsplines in the spatial direction

data must be provided in shape (nt, nxi, nxj), where:
  • nt is the number of time steps

  • nxi is the nb. of pixels in the horizontal / spectral direction

  • nxj is the nb. of pixels in the vertical / spacial direction

fit2d_dinput(dlines=None, dconstraints=None, dprepare=None, data=None, xi=None, xj=None, n=None, det=None, dtheta=None, psi=None, mask=None, domain=None, pos=None, binning=None, subset=None, deg=None, knots=None, nbsplines=None, focus=None, valid_fraction=None, valid_nsigma=None, focus_half_width=None, valid_return_fract=None)[source]

Return a formatted dict of lines and constraints

To be fed to _fit12d.multigausfit1d_from_dlines() Provides a user-friendly way of defining constraints

static fit2d_extract(dfit2d=None, amp=None, Ti=None, vi=None, pts_phi=None, npts_phi=None, pts_lamb_phi_total=None, pts_lamb_phi_detail=None)[source]
fit2d_plot(dfit2d=None, ratio=None, dax=None, plotmode=None, angunits=None, cmap=None, vmin=None, vmax=None, dmargin=None, tit=None, wintit=None, fs=None)[source]
get_bragg_from_lamb(lamb=None, n=None)[source]

Braggs’ law: n*lamb = 2dsin(bragg)

get_color()[source]
get_detector_approx(bragg=None, lamb=None, rcurve=None, n=None, ddist=None, di=None, dj=None, dtheta=None, dpsi=None, tilt=None, lamb0=None, lamb1=None, dist01=None, use_non_parallelism=None, tangent_to_rowland=None, plot=False)[source]

Return approximate ideal detector geometry

Assumes infinitesimal and ideal crystal Returns a dict containing the position and orientation of a detector if

it was placed ideally on the rowland circle, centered on the desired bragg angle (in rad) or wavelength (in m)

The detector can be tangential to the Rowland circle or perpendicular

to the line between the crystal and the detector

Assumes detector center matching lamb (m) / bragg (rad)

The detector can be translated towards / away from the crystal

to make sure the distance between 2 spectral lines

(lamb0 and lamb1) on the detector’s plane matches a desired distance (dist01, in m)

Finally, a desired offset (translation) can be added

via (ddist, di, dj), in m

Similarly, an extra rotation can be added via (dtheta, dpsi, tilt)

Detector is described by center position

and (nout, ei, ej) unit vectors

By convention, nout = np.cross(ei, ej) Vectors (ei, ej) define an orthogonal frame in the detector’s plane All coordinates are 3d (X, Y, Z in the tokamak’s frame)

det: dict
dict of detector geometrical characteristics:
‘cent’: np.ndarray

(3,) array of (x, y, z) coordinates of detector center

‘nout’: np.ndarray

(3,) array of (x, y, z) coordinates of unit vector perpendicular to detector’ surface oriented towards crystal

‘ei’: np.ndarray

(3,) array of (x, y, z) coordinates of unit vector defining first coordinate in detector’s plane

‘ej’: np.ndarray

(3,) array of (x, y, z) coordinates of unit vector defining second coordinate in detector’s plane

‘outline’: np.darray

(2, N) array to build detector’s contour where the last point is identical to the first. (for example for WEST X2D spectrometer: x*np.r_[-1,-1,1,1,-1], y*np.r_[-1,1,1,-1,-1])

get_lamb_avail_from_pts(pts=None, n=None, ndtheta=None, npsi=None, det=None, nlamb=None, klamb=None, use_non_parallelism=None, strict=None, return_xixj=None)[source]

Return the wavelength accessible from plasma points on the crystal

For a given plasma point, only a certain lambda interval can be bragg-diffracted on the crystal (due to bragg’s law and the crystal’s dimensions)

Beware, for a given pts and lamb, there can be up to 2 sets of solutions All non-valid solutions are set to nans, such that most of the time there is only one

For a set of given:
  • pts (3, npts) array, (x, y, z) coordinates

Using:
  • nlamb: sampling of the lamb interval (default: 100)

  • ndtheta: sampling of the lamb interval (default: 20)

  • npsi: sampling of the lamb interval (default: ‘envelop’)

  • det: (optional) a detector dict, for xi and xj

Returns

- lamb – (npts, nlamb) array of sampled valid wavelength interval - phi: (npts, nlamb, ndtheta, npsi, 2) array of phi - dtheta: (npts, nlamb, ndtheta, npsi, 2) array of dtheta - psi: (npts, nlamb, ndtheta, npsi, 2) array of psi

And optionally (return_xixj=True and det provided as dict):
  • xi: (npts, nlamb, ndtheta, npsi, 2) array of xi

  • xj: (npts, nlamb, ndtheta, npsi, 2) array of xj

The result is computed with or w/o taking into account non-parallelism

get_lamb_from_bragg(bragg=None, n=None)[source]

Braggs’ law: n*lamb = 2dsin(bragg)

get_lambbraggphi_from_ptsxixj_dthetapsi(pts=None, xi=None, xj=None, det=None, dtheta=None, psi=None, ntheta=None, npsi=None, n=None, use_non_parallelism=None, grid=None, return_lamb=None)[source]

Return the lamb, bragg and phi for provided pts and dtheta/psi

if grid = True:
compute all pts / dtheta/psi comnbinations

=> return (npts, ndtheta) arrays

else:
each pts is associated to a single dtheta/psi

=> assumes npts == ndtheta == npsi => return (npts,) arrays

get_local_noute1e2(dtheta=None, psi=None, ntheta=None, npsi=None, use_non_parallelism=None, include_summit=None)[source]

Return (nout, e1, e2) associated to pts on the crystal’s surface

All points on the spherical crystal’s surface are identified
by (dtheta, psi) coordinates, where:
  • theta = np.pi/2 + dtheta (dtheta=0 default) for the center

(for the diffracted beam), from frame’s basis vector ez - psi = 0 for the center, positive in direction of e1

They are the spherical coordinates from a sphere centered on the crystal’s center of curvature.

Return the pts themselves and the 3 perpendicular unit vectors

(nout, e1, e2), where nout is towards the outside of the sphere and nout = np.cross(e1, e2)

summit: np.ndarray

(3,) array of (x, y, z) coordinates of the points on the surface

nout: np.ndarray

(3,) array of (x, y, z) coordinates of outward unit vector

e1: np.ndarray

(3,) array of (x, y, z) coordinates of first unit vector

e2: np.ndarray

(3,) array of (x, y, z) coordinates of second unit vector

get_phi_from_magaxis_summit(r, z, lamb=None, bragg=None, n=None)[source]
get_rays_from_cryst(phi=None, bragg=None, lamb=None, n=None, dtheta=None, psi=None, use_non_parallelism=None, ntheta=None, npsi=None, include_summit=None, det=None, config=None, length=None, returnas=None, return_xixj=None, grid=None)[source]
get_rockingcurve_func(lamb=None, n=None)[source]

Return the rocking curve function

Also return the wavelength (lamb) (in meters) for which it was computed

and the associated reference bragg angle (in rad)

get_rowland_dist_from_lambbragg(bragg=None, lamb=None, n=None)[source]

Return the array of dist from cryst summit to pts on rowland

get_summary(sep='  ', line='-', just='l', table_sep=None, verb=True, return_=False)[source]

Summary description of the object content

get_unit_vectors(use_non_parallelism=None)[source]

Return the unit vectors (direct orthonormal basis)

Depending on:

use_non_parallelism: True => return the geometrical basis use_non_parallelism: False => return the mesh basis

property ismobile
move(param)[source]

Set new position to desired param according to default movement

Can only be used if default movement was set before See self.set_move()

noise_analysis(data=None, xi=None, xj=None, n=None, det=None, dtheta=None, psi=None, mask=None, valid_fraction=None, nxerrbin=None, margin=None, domain=None, nlamb=None, deg=None, knots=None, nbsplines=None, loss=None, max_nfev=None, xtol=None, ftol=None, gtol=None, method=None, tr_solver=None, tr_options=None, verbose=None, plot=None, ms=None, dcolor=None, dax=None, fs=None, dmargin=None, wintit=None, tit=None, sublab=None, save_fig=None, name_fig=None, path_fig=None, fmt=None, return_dax=None)[source]
static noise_analysis_plot(dnoise=None, margin=None, valid_fraction=None, ms=None, dcolor=None, dax=None, fs=None, dmargin=None, wintit=None, tit=None, sublab=None, save=None, name=None, path=None, fmt=None)[source]
noise_analysis_scannbs(data=None, xi=None, xj=None, n=None, det=None, dtheta=None, psi=None, mask=None, nxerrbin=None, domain=None, nlamb=None, deg=None, knots=None, nbsplines=None, lnbsplines=None, loss=None, max_nfev=None, xtol=None, ftol=None, gtol=None, method=None, tr_solver=None, tr_options=None, verbose=None, plot=None, ms=None, dax=None, fs=None, dmargin=None, wintit=None, tit=None, sublab=None, save_fig=None, name_fig=None, path_fig=None, fmt=None, return_dax=None)[source]
static noise_analysis_scannbs_plot(dnoise_scan=None, ms=None, dax=None, fs=None, dmargin=None, wintit=None, tit=None, sublab=None, save=None, name=None, path=None, fmt=None)[source]
plot(dcryst=None, phi=None, bragg=None, lamb=None, pts=None, n=None, config=None, det=None, length=None, dtheta=None, psi=None, ntheta=None, npsi=None, include_summit=None, dax=None, proj=None, res=None, element=None, color=None, ddet=None, dleg=None, draw=True, dmargin=None, use_non_parallelism=None, grid=None, rays_npts=None, rays_color=None, fs=None, wintit=None, tit=None)[source]

Plot the crystal in desired projeection

The projection is 3d, cross-section or horizontal Optionaly add rays reflected on cryst at:

  • lamb / phi: desired wavelength and incidence angle

and either:
  • psi, dtheta : desired pts on the crystal surface

  • pts: emitted from desired pts (e.g.: in the plasma)
    (need to be refresh with get_rays_from_cryst method

    if new pts are wanted)

Parameters
  • dax (None / dict) –

    dict of axes to be used, with keys:
    • ’cross’: axe where to plot cross-section view

    • ’hor’: axe where to plot horizontal (from top) view

    • ’3d’: axe where to plot 3d view

    if None, a new figure and axes are created

  • proj (None / str) –

    key indicating which plot to make:
    • ’cross’: cross-section projection

    • ’hor’: horizontal projection

    • ’all’: cross-section + horizontal view

    • ’3d’: 3d view

  • element (None / str) –

    char string where each letter indicates an element to plot
    • ’o’: outline (edges of crystal)

    • ’s’: summit (geometrical center of the crystal)

    • ’c’: center (of the sphere of curvature)

    • ’r’: rowland circle (plotted in e1 direction)

    • ’v’: local unit vectors e1, e2, nout

    If None, default to ‘oscvr’

  • res (None / float) – Resolution for the discretization of the outline

  • dcryst (None / dict) –

    dict of dict for plotting the various elements of the crystal:
    • ’outline’: dict of properties fed to plot()

    • ’cent’: dict of properties fed to plot()

    • ’summit’: dict of properties fed to plot()

    • ’rowland’: dict of properties fed to plot()

    • ’vectors’: dict of properties fed to quiver()

  • ddet (None / dict) –

    dict of dict for plotting the various elements of the det:
    • ’outline’: dict of properties fed to plot()

    • ’cent’: dict of properties fed to plot()

    • ’vectors’: dict of properties fed to quiver()

  • color (None / str / tuple) – color to be used for plotting Overwrites all colors in dcryst and ddet

  • det (None / dict) –

    Optionnal associated detector to be plotted, as a dict with keys:
    • ’cent’: 1d array of cartesian coordinates of the center

    • ’nout’: 1d array of cartesian coordinates of unit vector

      oriented towards the crystal

    • ’ei’: 1d array of cartesian coordinates of unit vector

    • ’ej’: 1d array of cartesian coordinates of unit vector

    • ’outline’: 2d array of outline coordinates in (ei, ej)

  • dleg (None / dict) – dict of properties to be passed to plt.legend() if False legend is not plotted

  • use_non_parallelism (None / str) –

    Return the unit vectors (direct orthonormal basis) Depending on:

    • use_non_parallelism: True => return the geometrical basis

    • use_non_parallelism: False => return the mesh basis

plot_data_vs_lambphi(xi=None, xj=None, data=None, mask=None, det=None, dtheta=None, psi=None, n=None, nlambfit=None, nphifit=None, magaxis=None, npaxis=None, dlines=None, spect1d='mean', lambmin=None, lambmax=None, xjcut=None, dxj=None, plot=True, fs=None, tit=None, wintit=None, cmap=None, vmin=None, vmax=None, returnas=None)[source]
plot_focal_error_summed(dist_min=None, dist_max=None, di_min=None, di_max=None, ndist=None, ndi=None, lamb=None, bragg=None, xi=None, xj=None, err=None, use_non_parallelism=None, tangent_to_rowland=None, n=None, plot=None, pts=None, det_ref=None, plot_dets=None, nsort=None, dcryst=None, lambda_interval_min=None, lambda_interval_max=None, contour=None, fs=None, ax=None, cmap=None, vmin=None, vmax=None, return_ax=None)[source]

Using the calc_johannerror method, computing the sum of the focalization error over the whole detector for different positions characterized by the translations ddist and di in the equatorial plane (dist_min, dist_max, ndist) (di_min, di_max, ndi).

  • lamb/braggfloat

    Automatically set to crystal’s references

  • xi, xjnp.ndarray

    pixelization of the detector (from “inputs_temp/XICS_allshots_C34.py” l.649)

  • alpha, betafloat

    Values of Non Parallelism references angles

  • use_non_parallelism : str

  • tangent_to_rowland : str

  • plot_detsstr

    Possibility to plot the nsort- detectors with the lowest summed focalization error, next to the Best Approximate Real detector dict(np.load(‘det37_CTVD_incC4_New.npz’, allow_pickle=True))

  • nsortfloat

    Number of best detector’s position to plot

  • lambda_interv_min/maxfloat

    To ensure the given wavelength interval is detected over the whole surface area. A True/False boolean is then returned.

plot_line_on_det_tracing(lamb=None, n=None, nphi=None, det=None, johann=None, use_non_parallelism=None, lpsi=None, ldtheta=None, strict=None, ax=None, dleg=None, rocking=None, fs=None, dmargin=None, wintit=None, tit=None)[source]

Visualize the de-focusing by ray-tracing of chosen lamb Possibility to plot few wavelength’ arcs on the same plot. :param - lamb: array of min size 1, in 1e-10 [m] :param - det: dict :param - xi_bounds: np.min & np.max of _XI :param - xj_bounds: np.min & np.max of _XJ :param (from “inputs_temp/XICS_allshots_C34.py” l.649): :param - johann: True or False

plot_rockingcurve(lamb=None, n=None, sigma=None, npts=None, color=None, ang_units=None, dmargin=None, fs=None, ax=None, legend=None)[source]
property rockingcurve
rotate_around_3daxis(angle=None, axis=None, return_copy=None, diag=None, name=None, shot=None)[source]

Rotate the instance around the provided 3d axis

rotate_around_torusaxis(angle=None, return_copy=None, diag=None, name=None, shot=None)[source]

Rotate the instance around the torus axis

rotate_in_cross_section(angle=None, axis_rz=None, phi=None, return_copy=None, diag=None, name=None, shot=None)[source]

Rotate the instance in the cross-section

sample_outline_plot(use_non_parallelism=None, res=None)[source]
set_color(col)[source]
set_dbragg(dbragg=None)[source]
set_dgeom(dgeom=None)[source]
set_dmat(dmat=None)[source]
set_move(move=None, param=None, **kwdargs)[source]

Set the default movement parameters

A default movement can be set for the instance, it can be any of the pre-implemented movement (rotations or translations) This default movement is the one that will be called when using self.move()

Specify the type of movement via the name of the method (passed as a str to move)

Specify, for the geometry of the instance at the time of defining this default movement, the current value of the associated movement parameter (angle / distance). This is used to set an arbitrary difference for user who want to use absolute position values The desired incremental movement to be performed when calling self.move will be deduced by substracting the stored param value to the provided param value. Just set the current param value to 0 if you don’t care about a custom absolute reference.

kwdargs must be a parameters relevant to the chosen method (axis, direction…)

e.g.:
self.set_move(move=’rotate_around_3daxis’,

param=0., axis=([0.,0.,0.], [1.,0.,0.]))

self.set_move(move=’translate_3d’,

param=0., direction=[0.,1.,0.])

split(direction=None, nb=None)[source]
strip(strip=0)[source]

Remove non-essential attributes to save memory / disk usage

Useful to save a very compressed version of the object The higher strip => the more stripped the object Use strip=0 to recover all atributes

See the difference by doing:

> self.get_nbytes() > self.strip(-1) > self.get_nbytes()

Parameters

strip (int) –

Flag indicating how much to strip from the object

0: Make complete (retrieve all attributes) 1: Remove nothing

-1: Equivalent to strip=1

property summit
translate_3d(distance=None, direction=None, return_copy=None, diag=None, name=None, shot=None)[source]

Translate the instance in provided direction

translate_in_cross_section(distance=None, direction_rz=None, phi=None, return_copy=None, diag=None, name=None, shot=None)[source]

Translate the instance in the cross-section

update_non_parallelism(alpha=None, beta=None)[source]

Compute new values of unit vectors nout, e1 and e2 into dmat basis, due to non parallelism

Update new values into dmat dict

tofu.geom._def module

This module stores all the default setting of ToFu Including in particular computing parameters, dictionnaries and figures

tofu.geom._def.Plot_3D_plt_Tor_DefAxes(dmargin=None, fs=None, wintit='tofu')[source]
tofu.geom._def.Plot_AllCryst(fs=None, dmargin=None, wintit=None)[source]
tofu.geom._def.Plot_CrystIm(fs=None, dmargin=None, wintit=None)[source]
tofu.geom._def.Plot_Impact_DefAxes(Proj, Ang='theta', AngUnit='rad', fs=None, wintit='tofu', Sketch=True)[source]
tofu.geom._def.Plot_LOSProj_DefAxes(Mode, Type='Tor', dmargin=None, fs=None, wintit='tofu')[source]
tofu.geom._def._Config_phithetaproj_default(fs=None, dmargin=None, fontsize=8, labelpad=0, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', ntMax=1)[source]
tofu.geom._def._DET_PLOT_DDICT = {'cent': {'color': 'k', 'ls': 'None', 'marker': 'o', 'ms': 6}, 'outline': {'color': 'k', 'ls': '-', 'lw': 2.0}, 'rowland': {'color': 'k', 'ls': '--', 'lw': 1.0}, 'summit': {'color': 'k', 'ls': 'None', 'marker': '^', 'ms': 6}, 'vectors': {'color': 'k', 'ls': '-', 'lw': 1.0}}

# ————– Figures ————————

def Plot_Lens_Alone_DefAxes(fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (20,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) axPos = [0.05, 0.1, 0.9, 0.85] ax = f.add_axes(axPos,facecolor=axCol) ax.set_xlabel(r”x (m)”) ax.set_ylabel(r”y (m)”) return ax

# ———— Computing settings —————

DetSpanRMinMargin = 0.9 DetSpanNEdge = 5 DetSpanNRad = 5

DetConeNEdge = 8 DetConeNRad = 6

DetPreConedX12 = [0.01, 0.01] DetPreConedX12Mode = ‘abs’ DetPreConeds = 0.01 DetPreConedsMode = ‘abs’ DetPreConeMarginS = 0.002

DetConeDX = 0.002 DetConeDRY = 0.0025 # 0.0025 DetConeDTheta = np.pi/1024. # 512. DetConeDZ = 0.0025 # 0.0025 #DetConeNTheta = 25 # 25 #DetConeNZ = 50 # 50

DetConeRefdMax = 0.02

DetEtendMethod = ‘quad’ DetEtenddX12 = [0.01, 0.01] DetEtenddX12Mode = ‘rel’ DetEtendepsrel = 1.e-3 DetEtendRatio = 0.02 DetCalcEtendColis = False

DetCalcSAngVectColis = True DetCalcSAngVectCone = True

DetSynthEpsrel = 1.e-4 DetSynthdX12 = [0.005, 0.005] DetSynthdX12Mode = ‘abs’ DetSynthds = 0.005 DetSynthdsMode = ‘abs’ DetSynthMarginS = 0.001

# — Plotting dictionaries and parameters ——

ApPd = {‘c’:’k’,’lw’:2,’ls’:’solid’} ApVd = {‘color’:’r’,’lw’:2,’ls’:’solid’} DetPd = {‘c’:’k’,’lw’:2,’ls’:’solid’} DetVd = {‘color’:’r’,’lw’:2,’ls’:’solid’} DetSAngPld = {‘cmap’:plt.cm.YlOrRd,’lw’:0.,’rstride’:1,’cstride’:1, ‘antialiased’:False, ‘edgecolor’:’None’} DetSangPlContd = {‘linewidths’:0.} DetConed = {‘edgecolors’:’k’, ‘facecolors’:(0.8,0.8,0.8,0.2), ‘alpha’:0.2, ‘linewidths’:0., ‘linestyles’:’-’, ‘antialiaseds’:False} DetImpd = {‘ls’:’solid’,’c’:’k’,’lw’:1}

ApLVin = 0.1 DetSAngPlRa = 0.5 DetSAngPldX12 = [0.025,0.025] DetSAngPldX12Mode = ‘rel’ DetSAngPlRatio = 0.01 DetEtendOnLOSNP = 20 DetEtendOnLOSModes = [‘trapz’] DetEtendOnLOSLd = {‘ls’:’solid’,’c’:’k’,’lw’:2}

DetSAngPlot = ‘Int’ DetSAngPlotMode = ‘scatter’ DetSAngPlotd = {‘cmap’:plt.cm.YlOrRd} DetSAngPlotLvl = 20

DetSliceAGdR = 0.005 DetSliceAGdY = 0.005 DetSliceAGdX = 0.01 DetSliceAGdTheta = np.pi/512. DetSliceAGdZ = 0.005 DetSliceNbd = {‘scatter’:{‘cmap’:plt.cm.Greys,’marker’:’s’,’edgecolors’:’None’,’s’:10},

‘contour’:{‘cmap’:plt.cm.Greys}, ‘contourf’:{‘cmap’:plt.cm.Greys}, ‘imshow’:{‘cmap’:plt.cm.Greys}}

DetSliceSAd = {‘scatter’:{‘cmap’:plt.cm.YlOrRd,’marker’:’s’,’edgecolors’:’None’,’s’:10, ‘vmin’:0},

‘contour’:{‘cmap’:plt.cm.YlOrRd, ‘vmin’:0}, ‘contourf’:{‘cmap’:plt.cm.YlOrRd, ‘vmin’:0}, ‘imshow’:{‘cmap’:plt.cm.YlOrRd, ‘vmin’:0}}

DetPolProjNTheta = 50 DetPolProjNZ = 25 DetSAngColis = True

GDetEtendMdA = {‘ls’:’None’,’c’:’k’,’lw’:2,’marker’:’+’} GDetEtendMdR = {‘ls’:’None’,’c’:’b’,’lw’:2,’marker’:’x’} GDetEtendMdS = {‘ls’:’None’,’c’:’g’,’lw’:2,’marker’:’o’} GDetEtendMdP = {‘ls’:’None’,’c’:’r’,’lw’:2,’marker’:’*’}

GDetSigd = {‘ls’:’solid’,’c’:’k’,’lw’:2,’marker’:’+’}

Apertdict = dict(Lax=None, Proj=’All’, Elt=’PV’, EltVes=’’, Leg=’’, LVIn=ApLVin, Pdict=ApPd, Vdict=ApVd, Vesdict=Vesdict, LegDict=TorLegd, draw=True, Test=True) #Detdict =

# ————– Figures ————————

def Plot_SAng_Plane_DefAxes(fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) (fW,fH,fdpi,axCol) = (11.69,8.27,80,’w’) if a4 else (10,8,80,’w’) axPos = [0.05, 0.05, 0.9, 0.9] f = plt.figure(facecolor=”w”,figsize=(fW,fH),dpi=fdpi) ax = f.add_axes(axPos,facecolor=axCol,projection=’3d’) ax.set_xlabel(r”X1 (m)”) ax.set_ylabel(r”X2 (m)”) ax.set_zlabel(r”$Omega$ (sr)”) return ax

def Plot_Etendue_AlongLOS_DefAxes(kMode=’rel’,fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) (fW,fH,fdpi,axCol) = (11.69,8.27,80,’w’) if a4 else (14,8,80,’w’) axPos = [0.06, 0.08, 0.70, 0.86] f = plt.figure(facecolor=”w”,figsize=(fW,fH),dpi=fdpi) ax = f.add_axes(axPos,frameon=True,facecolor=axCol) if kMode.lower()==’rel’:

ax.set_xlabel(r”Rel. length (adim.)”)

else:

ax.set_xlabel(r”Length (m)”)

ax.set_ylabel(r”Etendue ($sr.m^2$)”) return ax

def Plot_CrossSlice_SAngNb_DefAxes(VType=’Tor’, fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) (fW,fH,fdpi,axCol) = (11.69,8.27,80,’w’) if a4 else (15,8,80,’w’) f = plt.figure(facecolor=”w”,figsize=(fW,fH),dpi=fdpi) axSAng = f.add_axes([0.05, 0.06, 0.40, 0.85],frameon=True,facecolor=axCol) axNb = f.add_axes([0.60, 0.06, 0.40, 0.85],frameon=True,facecolor=axCol) if VType==’Tor’:

axSAng.set_xlabel(r”R (m)”), axNb.set_xlabel(r”R (m)”)

elif VType==’Lin’:

axSAng.set_xlabel(r”Y (m)”), axNb.set_xlabel(r”Y (m)”)

axSAng.set_ylabel(r”Z (m)”), axNb.set_ylabel(r”Z (m)”) axSAng.set_aspect(aspect=”equal”, adjustable=’datalim’) axNb.set_aspect(aspect=”equal”, adjustable=’datalim’) return axSAng, axNb

def Plot_HorSlice_SAngNb_DefAxes(fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) (fW,fH,fdpi,axCol) = (11.69,8.27,80,’w’) if a4 else (15,8,80,’w’) f = plt.figure(facecolor=”w”,figsize=(fW,fH),dpi=fdpi) axSAng = f.add_axes([0.07, 0.12, 0.35, 0.8],frameon=True,facecolor=axCol) axNb = f.add_axes([0.55, 0.12, 0.35, 0.8],frameon=True,facecolor=axCol) axSAng.set_xlabel(r”X (m)”), axSAng.set_ylabel(r”Y (m)”) axNb.set_xlabel(r”X (m)”), axNb.set_ylabel(r”Y (m)”) axSAng.set_aspect(aspect=”equal”, adjustable=’datalim’) axNb.set_aspect(aspect=”equal”, adjustable=’datalim’) return axSAng, axNb

def Plot_Etendues_GDetect_DefAxes(fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) (fW,fH,fdpi,axCol) = (11.69,8.27,80,’w’) if a4 else (18,8,80,’w’) f = plt.figure(facecolor=”w”,figsize=(fW,fH),dpi=fdpi) ax = f.add_axes([0.05,0.1,0.85,0.80],frameon=True,facecolor=axCol) ax.set_xlabel(r””) ax.set_ylabel(r”Etendue (sr.m^2)”) return ax

def Plot_Sig_GDetect_DefAxes(fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) (fW,fH,fdpi,axCol) = (11.69,8.27,80,’w’) if a4 else (18,8,80,’w’) f = plt.figure(facecolor=”w”,figsize=(fW,fH),dpi=fdpi) ax = f.add_axes([0.05,0.1,0.85,0.80],frameon=True,facecolor=axCol) ax.set_xlabel(r””) ax.set_ylabel(r”Signal (W)”) return ax

#Ldict_mlab_Def = {‘color’:(0.,0.,0.),’tube_radius’:None} #Mdict_mlab_Def = {‘color’:(0.,0.,0.),’line_width’:1,’mode’:’sphere’} #Dict_3D_mlab_Tor_Def = {‘color’:(0.8,0.8,0.8),’opacity’:0.15,’transparent’:False,’scale_factor’:0.1}

def Plot_GDetect_Resolution_DefAxes(VType=’Tor’, fs=None, wintit=’tofu’):

axCol, fdpi = ‘w’, 80 if fs is None:

fs = (16,8) if Mode.lower()==’all’ else (6,8)

elif type(fs) is str and fs==’a4’:

fs = (11.69,8.27) if Mode.lower()==’all’ else (8.27,11.69)

f = plt.figure(facecolor=”w”, figsize=fs, dpi=fdpi) axCol = “w” (fW,fH) = (11.69,8.27) if a4 else (16,10) f = plt.figure(figsize=(fW,fH),facecolor=axCol) ax1 = f.add_axes([0.05, 0.06, 0.32, 0.80], frameon=True, facecolor=axCol) ax2 = f.add_axes([0.50, 0.55, 0.47, 0.40], frameon=True, facecolor=axCol) ax3 = f.add_axes([0.50, 0.06, 0.47, 0.40], frameon=True, facecolor=axCol) X1 = r”R (m)” if VType==’Tor’ else r”Y (m)” ax1.set_xlabel(X1) ax1.set_ylabel(r”Z (m)”) ax2.set_xlabel(r”size (a.u.)”) ax2.set_ylabel(r”Signal (mW)”) ax3.set_xlabel(r”Channels index (from 0)”) ax3.set_ylabel(r”Signal (mW)”) ax1.set_aspect(aspect=’equal’,adjustable=’datalim’) return ax1, ax2, ax3

tofu.geom._def._labelpad = 0

Defaults settings generic

tofu.geom._def_config module

tofu.geom._distance_tools module

tofu.geom._distance_tools module

tofu.geom._openmp_tools module

tofu.geom._openmp_tools.get_effective_num_threads(n_threads=None)

Based on Scikit-learn: scikit-learn/sklearn/utils/_openmp_helpers.pyx Determine the effective number of threads to be used for OpenMP calls

  • For n_threads = None, - if the OMP_NUM_THREADS environment variable is set, return

    openmp.omp_get_max_threads()

    • otherwise return the minimum between openmp.omp_get_max_threads() and the number of cpus, taking cgroups quotas into account. Cgroups quotas can typically be set by tools such as Docker.

    The result of omp_get_max_threads can be influenced by environment variable OMP_NUM_THREADS or at runtime by omp_set_num_threads.

  • For n_threads > 0, return this as the maximal number of threads for parallel OpenMP calls.

  • For n_threads < 0, return the maximal number of threads minus |n_threads + 1|. In particular n_threads = -1 will use as many threads as there are available cores on the machine.

  • Raise a ValueError for n_threads = 0.

If scikit-learn is built without OpenMP support, always return 1.

tofu.geom._openmp_tools module

tofu.geom._openmp_tools.get_effective_num_threads(n_threads=None)

Based on Scikit-learn: scikit-learn/sklearn/utils/_openmp_helpers.pyx Determine the effective number of threads to be used for OpenMP calls

  • For n_threads = None, - if the OMP_NUM_THREADS environment variable is set, return

    openmp.omp_get_max_threads()

    • otherwise return the minimum between openmp.omp_get_max_threads() and the number of cpus, taking cgroups quotas into account. Cgroups quotas can typically be set by tools such as Docker.

    The result of omp_get_max_threads can be influenced by environment variable OMP_NUM_THREADS or at runtime by omp_set_num_threads.

  • For n_threads > 0, return this as the maximal number of threads for parallel OpenMP calls.

  • For n_threads < 0, return the maximal number of threads minus |n_threads + 1|. In particular n_threads = -1 will use as many threads as there are available cores on the machine.

  • Raise a ValueError for n_threads = 0.

If scikit-learn is built without OpenMP support, always return 1.

tofu.geom._plot module

tofu.geom._plot.Config_phithetaproj_dist(config, refpt, dist, indStruct, distonly=False, cmap=None, vmin=None, vmax=None, invertx=None, ax=None, fs=None, cbck=(0.8, 0.8, 0.8, 0.8), tit=None, wintit=None, legend=None, draw=None)[source]
tofu.geom._plot.Config_plot_solidangle_map_particle(config=None, part_traj=None, part_radius=None, ptsRZ=None, sang=None, indices=None, reseff=None, vmin=None, vmax=None, scale=None, fs=None, dmargin=None)[source]
tofu.geom._plot.GLOS_plot_Sino(GLos, Proj='Cross', ax=None, Elt='LV', Sketch=True, Ang='theta', AngUnit='rad', Leg=None, dL={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dVes={'edgecolor': (0.8, 0.8, 0.8, 1.0), 'facecolor': (0.8, 0.8, 0.8, 1.0), 'linestyle': 'solid', 'linewidth': 1}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, ind=None, multi=False, draw=True, fs=None, tit=None, wintit=None, Test=True)[source]
tofu.geom._plot.Get_FieldsFrom_LLOS(L, Fields)[source]
tofu.geom._plot.Plot_Impact_3DPoly(T, Leg='', ax=None, Ang='theta', AngUnit='rad', Pdict={'color': (0.8, 0.8, 0.8, 0.4), 'linestyle': 'solid', 'linewidth': 0}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]

Plotting the toroidal projection of a Ves instance

D. VEZINET, Aug. 2014 Inputs :

T A Ves instance Leg A str (the legend label to be used if T is not a Ves instance) ax A plt.Axes instance (if given) on which to plot the projection space, otherwise (‘None’) a new figure/axes is created Dict A dictionnary specifying the style of the boundary polygon plot dLeg A dictionnary specifying the style of the legend box

Outputs :

ax The plt.Axes instance on which the poloidal plot was performed

tofu.geom._plot.Plot_Impact_PolProjPoly(lS, Leg='', ax=None, Ang='theta', AngUnit='rad', Sketch=True, dP=None, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, draw=True, fs=None, wintit=None, tit=None, Test=True)[source]

Plotting the toroidal projection of a Ves instance

D. VEZINET, Aug. 2014 Inputs :

T A Ves instance Leg A str (the legend label to be used if T is not a Ves instance) ax A plt.Axes instance (if given) on which to plot the projection space, otherwise (‘None’) a new figure/axes is created Dict A dictionnary specifying the style of the boundary polygon plot dLeg A dictionnary specifying the style of the legend box

Outputs :

ax The plt.Axes instance on which the poloidal plot was performed

tofu.geom._plot.Rays_plot(GLos, Lax=None, Proj='all', reflections=True, Lplot='Tot', element='LDIORP', element_config='P', Leg=None, dL=None, dPtD={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtI={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtO={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtR={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtP={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, multi=False, draw=True, fs=None, wintit=None, tit=None, Test=True, ind=None)[source]
tofu.geom._plot.Rays_plot_touch(cam, key=None, ind=None, quant='lengths', cdef='k', invert=None, Bck=True, cbck=(0.8, 0.8, 0.8), Lplot=None, incch=[1, 10], ms=4, cmap='touch', vmin=None, vmax=None, fmt_ch='02.0f', labelpad=0, dmargin=None, nchMax=4, lcch=[(0.8392156862745098, 0.15294117647058825, 0.1568627450980392), (0.5803921568627451, 0.403921568627451, 0.7411764705882353), (0.5490196078431373, 0.33725490196078434, 0.29411764705882354), (1.0, 0.596078431372549, 0.5882352941176471), (0.7725490196078432, 0.6901960784313725, 0.8352941176470589), (0.7686274509803922, 0.611764705882353, 0.5803921568627451)], fs=None, wintit=None, tit=None, fontsize=8, draw=True, connect=True)[source]
tofu.geom._plot.Struct_plot(lS, lax=None, proj=None, element=None, dP=None, dI=None, dBs=None, dBv=None, dVect=None, dIHor=None, dBsHor=None, dBvHor=None, Lim=None, Nstep=None, dLeg=None, indices=False, draw=True, fs=None, wintit=None, tit=None, Test=True)[source]

Plot the projections of a list of Struct subclass instances

D. VEZINET, Aug. 2014 Inputs :

V A Ves instance Nstep An int (the number of points for evaluation of theta by np.linspace) axP A plt.Axes instance (if given) on which to plot the poloidal projection, otherwise (‘None’) a new figure/axes is created axT A plt.Axes instance (if given) on which to plot the toroidal projection, otherwise (‘None’) a new figure/axes is created Tdict A dictionnary specifying the style of the polygon plot dLeg A dictionnary specifying the style of the legend box (if None => no legend)

Outputs :

axP The plt.Axes instance on which the poloidal plot was performed axT The plt.Axes instance on which the toroidal plot was performed

tofu.geom._plot._Cam12D_plot_touch_init(fs=None, dmargin=None, fontsize=8, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', nchMax=4, nD=1)[source]
tofu.geom._plot._Cam12D_plottouch(cam, key=None, ind=None, quant='lengths', nchMax=4, Bck=True, lcch=[(0.8392156862745098, 0.15294117647058825, 0.1568627450980392), (0.5803921568627451, 0.403921568627451, 0.7411764705882353), (0.5490196078431373, 0.33725490196078434, 0.29411764705882354), (1.0, 0.596078431372549, 0.5882352941176471), (0.7725490196078432, 0.6901960784313725, 0.8352941176470589), (0.7686274509803922, 0.611764705882353, 0.5803921568627451)], cbck=(0.8, 0.8, 0.8), Lplot=None, incch=[1, 5], ms=4, plotmethod='imshow', cmap=None, vmin=None, vmax=None, fmt_ch='01.0f', invert=True, Dlab=None, fontsize=8, labelpad=0, fs=None, dmargin=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', tit=None, draw=True, connect=True, nD=1)[source]
tofu.geom._plot._LOS_calc_InOutPolProj_Debug(config, Ds, us, PIns, POuts, L=3, nptstot=None, Lim=None, Nstep=100, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', draw=True)[source]
tofu.geom._plot._Plot_3D_plt_Ves(V, ax=None, Elt='P', Lim=None, Nstep=0.15707963267948966, Pdict={'antialiased': False, 'color': (0.8, 0.8, 0.8, 1.0), 'cstride': 1, 'linewidth': 0, 'rstride': 1}, LegDict={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]
tofu.geom._plot._Plot_CrossProj_Ves(V, ax=None, Elt='PIBsBvV', Pdict={'c': 'k', 'lw': 2}, Idict={'c': 'k', 'ls': 'dashed', 'marker': 'x', 'markersize': 8, 'mew': 2}, Bsdict={'c': 'b', 'ls': 'dashed', 'marker': 'x', 'markersize': 8, 'mew': 2}, Bvdict={'c': 'g', 'ls': 'dashed', 'marker': 'x', 'markersize': 8, 'mew': 2}, Vdict={'color': 'r', 'scale': 10}, LegDict={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, indices=False, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]

Plot the poloidal projection of a Ves instance

Parameters
  • V (tfg.Ves / tfg.Struct) – A Ves instance

  • ax (None / plt.Axes) – A plt.Axes instance (if given) on which to plot, otherwise (‘None’) a new figure/axes is created

  • Pdict (dict) – A dictionnary specifying the style of the polygon plot

  • LegDict (None / dict) – A dictionnary specifying the style of the legend box (if None => no legend)

Returns

ax The plt.Axes instance on which the plot was performed

tofu.geom._plot._Plot_HorProj_Ves(V, ax=None, Elt='PI', Nstep=50, Pdict={'c': 'k', 'lw': 2}, Idict={'c': 'k', 'ls': 'dashed'}, Bsdict={'c': 'b', 'ls': 'dashed'}, Bvdict={'c': 'g', 'ls': 'dashed'}, LegDict={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, indices=False, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]

Plotting the toroidal projection of a Ves instance

Parameters
  • instance (V A Ves) –

  • np.linspace) (Nstep An int (the number of points for evaluation of theta by) –

  • plot (Tdict A dictionnary specifying the style of the polygon) –

  • created (otherwise ('None') a new figure/axes is) –

  • plot

  • legend) (LegDict A dictionnary specifying the style of the legend box (if None => no) –

Returns

ax The plt.Axes instance on which the plot was performed

tofu.geom._plot._Plot_Sinogram_3D(L, ax=None, Leg='', Ang='theta', AngUnit='rad', dL={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, ind=None, multi=False, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', LegDict={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}})[source]
tofu.geom._plot._Plot_Sinogram_CrossProj(L, ax=None, Leg='', Ang='theta', AngUnit='rad', Sketch=True, dL={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, LegDict={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, ind=None, multi=False, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]
tofu.geom._plot._Rays_plot_3D(L, Leg=None, reflections=True, Lplot='Tot', Elt='LDIORr', ax=None, dL={'c': 'k', 'lw': 2}, dPtD={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtI={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtO={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtR={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtP={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, multi=False, ind=None, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]
tofu.geom._plot._Rays_plot_Cross(L, Leg=None, reflections=True, Lplot='Tot', Elt='LDIORP', ax=None, dL={'c': 'k', 'lw': 2}, dPtD={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtI={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtO={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtR={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtP={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, multi=False, ind=None, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]
tofu.geom._plot._Rays_plot_Hor(L, Leg=None, reflections=True, Lplot='Tot', Elt='LDIORP', ax=None, dL={'c': 'k', 'lw': 2}, dPtD={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtI={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtO={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtR={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dPtP={'c': 'k', 'ls': 'None', 'lw': 2, 'marker': 'x', 'markersize': 8, 'mew': 2}, dLeg={'bbox_to_anchor': (1.01, 1), 'borderaxespad': 0.0, 'frameon': False, 'loc': 2, 'ncol': 1, 'prop': {'size': 10}}, multi=False, ind=None, draw=True, fs=None, wintit='tofu-1.5.0-3-g96c1c10c        report issues / requests at https://github.com/ToFuProject/tofu/issues', Test=True)[source]
tofu.geom._plot._Struct_plot_format(ss, proj='all', **kwdargs)[source]
tofu.geom._plot._check_Lax(lax=None, n=2)[source]
tofu.geom._plot._get_LLOS_Leg(GLLOS, Leg=None, ind=None, Val=None, Crit='Name', PreExp=None, PostExp=None, Log='any', InOut='In')[source]

tofu.geom._plot_optics module

tofu.geom._plot_optics.CrystalBragg_plot(cryst=None, dcryst=None, det=None, ddet=None, dax=None, proj=None, res=None, element=None, color=None, pts_summit=None, pts1=None, pts2=None, xi=None, xj=None, rays_color=None, rays_npts=None, dleg=None, draw=True, fs=None, dmargin=None, use_non_parallelism=None, wintit=None, tit=None)[source]
tofu.geom._plot_optics.CrystalBragg_plot_approx_detector_params(Rrow, bragg, d, Z, frame_cent, nn)[source]
tofu.geom._plot_optics.CrystalBragg_plot_braggangle_from_xixj(xi=None, xj=None, bragg=None, angle=None, ax=None, plot=None, braggunits='rad', angunits='rad', leg=None, colorbar=None, fs=None, wintit=None, tit=None, **kwdargs)[source]
tofu.geom._plot_optics.CrystalBragg_plot_focal_error_summed(cryst=None, dcryst=None, lamb=None, bragg=None, error_lambda=None, ddist=None, di=None, ddist0=None, di0=None, dj0=None, dtheta0=None, dpsi0=None, tilt0=None, angle_nout=None, det_ref=None, units=None, plot_dets=None, nsort=None, tangent_to_rowland=None, use_non_parallelism=None, pts=None, test_lamb_interv=None, contour=None, fs=None, cmap=None, vmin=None, vmax=None, ax=None)[source]
tofu.geom._plot_optics.CrystalBragg_plot_johannerror(xi, xj, lamb, phi, err_lamb, err_phi, err_lamb_units=None, err_phi_units=None, cmap=None, vmin=None, vmax=None, fs=None, dmargin=None, wintit=None, tit=None, angunits=None)[source]
tofu.geom._plot_optics.CrystalBragg_plot_line_tracing_on_det(lamb, xi, xj, xi_err, xj_err, det=None, johann=None, rocking=None, ax=None, dleg=None, fs=None, dmargin=None, wintit=None, tit=None)[source]
tofu.geom._plot_optics.CrystalBragg_plot_raytracing_from_lambpts(xi=None, xj=None, lamb=None, xi_bounds=None, xj_bounds=None, pts=None, ptscryst=None, ptsdet=None, det_cent=None, det_nout=None, det_ei=None, det_ej=None, cryst=None, proj=None, fs=None, ax=None, dmargin=None, wintit=None, tit=None, legend=None, draw=None)[source]
tofu.geom._plot_optics.CrystalBragg_plot_rockingcurve(func=None, bragg=None, lamb=None, sigma=None, npts=None, ang_units=None, axtit=None, color=None, legend=None, fs=None, ax=None)[source]
tofu.geom._plot_optics.CrystalBragg_plot_xixj_from_braggangle(bragg=None, xi=None, xj=None, data=None, ax=None)[source]
tofu.geom._plot_optics._CrystalBragg_plot(cryst=None, dcryst=None, det=None, ddet=None, nout=None, nin=None, e1=None, e2=None, outline=None, proj=None, dax=None, element=None, rays=None, rays_color=None, rays_npts=None, xi=None, xj=None, quiver_cmap=None, draw=True, dmargin=None, fs=None, wintit=None)[source]
tofu.geom._plot_optics._CrystalBragg_plot_check(cryst=None, dcryst=None, det=None, ddet=None, res=None, element=None, color=None, pts_summit=None, pts1=None, pts2=None, xi=None, xj=None, rays_color=None, rays_npts=None, dleg=None, draw=True, use_non_parallelism=None, wintit=None, tit=None)[source]
tofu.geom._plot_optics._check_projdax_mpl(dax=None, proj=None, dmargin=None, fs=None, wintit=None)[source]

tofu.geom._raytracing_tools module

tofu.geom._raytracing_tools module

tofu.geom._sampling_tools module

tofu.geom._sampling_tools.get_nb_dmode(dmode)
tofu.geom._sampling_tools.get_nb_imode(imode)

tofu.geom._sampling_tools module

tofu.geom._sampling_tools.get_nb_dmode(dmode)
tofu.geom._sampling_tools.get_nb_imode(imode)

tofu.geom._vignetting_tools module

tofu.geom._vignetting_tools module

tofu.geom.openmp_enabled module

tofu.geom.openmp_enabled.is_openmp_enabled()[source]

Determine whether this package was built with OpenMP support.

tofu.geom.utils module

tofu.geom.utils.compute_RaysCones(Ds, us, angs=0.03490658503988659, nP=40)[source]
tofu.geom.utils.coords_transform(pts, coords_in='11', coords_out='11')[source]
tofu.geom.utils.create_CamLOS1D(case=None, pinhole=None, P=None, focal=None, F=None, sensor_nb=None, N12=None, sensor_size=None, D12=None, orientation=None, angs=None, config=None, Etendues=None, etendues=None, Surfaces=None, surfaces=None, Exp=None, Diag=None, Name=None, nD=None, dchans=None, color=None, method=None, nIn=None, VType='Tor', dcam={'V1': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [1, 1], 'P': [1.5, -3.2, 0.0], 'nIn': [-0.5, 1.0, 0.0]}, 'V10': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [5, 2], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V100': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [20, 5], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V1000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [50, 20], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V10000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [125, 80], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V100000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [500, 200], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V1000000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [1600, 625], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'VA1': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [1, 1], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA10': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [5, 2], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA100': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [20, 5], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA1000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [50, 20], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA10000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [125, 80], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA100000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [500, 200], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA1000000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [1600, 625], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'testV': {'D12': [0.3, 0.1], 'F': 0.4, 'N12': [1600, 625], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}}, defRY=None, Lim=None, returnas=<class 'object'>, SavePath='./')[source]

Create a pinhole CamLOS1D

Typical use case:
>>> import tofu as tf
>>> conf = tf.load_config('WEST')
>>> cam1d = tf.geom.utils.create_CamLOS1D(
    pinhole=[3., 0., 0.],       # pinhole position [X, Y, Z] [m]
    focal=0.1,                  # pinhole-sensors distance [m]
    sensor_nb=100,              # number of sensors on sensor plane
    sensor_size=0.1,            # size of sensor plane [m]
    orientation=[np.pi, 0., 0.],# 3 angles orienting whole camera [rad]
    config=conf,                # configuration (for computing LOS)
    Etendues=None,              # Etendues (optional)
    Surfaces=None,              # Surfaces (optional) [m^2]
    Exp='WEST',                 # Experiment
    Diag='Bolo',                # Diagnostic
    Name='Cam1',                # Name of this particular camera
)
>>> cam2d = tf.geom.utils.create_CamLOS2D(
    pinhole=[3., 0., 0.],       # pinhole position [X, Y, Z] [m]
    focal=0.1,                  # pinhole-sensors distance [m]
    sensor_nb=[100, 100],       # number of sensors on sensor plane
    sensor_size=[0.1, 0.1],     # size of sensor plane [m]
    orientation=[np.pi, 0., 0.],# 3 angles orienting whole camera [rad]
    config=conf,                # configuration (for computing LOS)
    Etendues=None,              # Etendues (optional)
    Surfaces=None,              # Surfaces (optional) [m^2]
    Exp='WEST',                 # Experiment
    Diag='Bolo',                # Diagnostic
    Name='Cam1',                # Name of this particular camera
)

In tofu, a CamLOS is a camera described as a set of Lines of Sight (LOS), as opposed to a Cam, where the Volume of Sight (VOS) of all pixels are computed in 3D. The CamLOS is then a simplified approximation of the Cam. It can be:

  • 1D : like when all LOS are included in a common plane

  • 2D : like a regular everyday camera, producing a 2D image

For a pinhole camera, all LOS pass through a common point (pinhole)

This function provides an easy way to create a pinhole CamLOS1D In tofu, LOS are described as semi-lines using:

  • a starting point (D)

  • a unit vector (u)

All coordinates are 3D cartesian (X,Y,Z)

Here, you simply need to provide, either:
  • the name of a standard test case

  • a set of geometrical parameters:
    • pinhole: throught which the camera axis passes

    • focal: distance between pinhole and sensor plane

    • size: dimensions of the sensor planendicular to the camera axis

    • N12 : number of pixels (LOS)

    • angs: 3 angles defining the orientation of the camera

The computed set of LOS, optionnaly associated to a Config, can then be returned as:

  • a tofu object (i.e.: a CamLOS1D)

  • a set of starting points (D) and unit vectors (u)

  • a set of starting points (D), a pinhole, and and the coordinates of D

in the camera frame

tofu.geom.utils.create_CamLOS2D(case=None, pinhole=None, P=None, focal=None, F=None, sensor_nb=None, N12=None, sensor_size=None, D12=None, orientation=None, angs=None, config=None, Etendues=None, etendues=None, Surfaces=None, surfaces=None, Exp=None, Diag=None, Name=None, nD=None, dchans=None, color=None, method=None, nIn=None, VType='Tor', dcam={'V1': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [1, 1], 'P': [1.5, -3.2, 0.0], 'nIn': [-0.5, 1.0, 0.0]}, 'V10': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [5, 2], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V100': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [20, 5], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V1000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [50, 20], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V10000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [125, 80], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V100000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [500, 200], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'V1000000': {'D12': [0.3, 0.1], 'F': 0.1, 'N12': [1600, 625], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}, 'VA1': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [1, 1], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA10': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [5, 2], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA100': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [20, 5], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA1000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [50, 20], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA10000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [125, 80], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA100000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [500, 200], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'VA1000000': {'D12': [0.4, 0.3], 'F': 0.1, 'N12': [1600, 625], 'P': [4.9, -6.9, 0.0], 'nIn': [-0.75, 1.0, 0.0]}, 'testV': {'D12': [0.3, 0.1], 'F': 0.4, 'N12': [1600, 625], 'P': [1.5, 3.2, 0.0], 'nIn': [-0.5, -1.0, 0.0]}}, defRY=None, Lim=None, returnas=<class 'object'>, SavePath='./')[source]

Create a pinhole CamLOS2D

Typical use case:
>>> import tofu as tf
>>> conf = tf.load_config('WEST')
>>> cam1d = tf.geom.utils.create_CamLOS1D(
    pinhole=[3., 0., 0.],       # pinhole position [X, Y, Z] [m]
    focal=0.1,                  # pinhole-sensors distance [m]
    sensor_nb=100,              # number of sensors on sensor plane
    sensor_size=0.1,            # size of sensor plane [m]
    orientation=[np.pi, 0., 0.],# 3 angles orienting whole camera [rad]
    config=conf,                # configuration (for computing LOS)
    Etendues=None,              # Etendues (optional)
    Surfaces=None,              # Surfaces (optional) [m^2]
    Exp='WEST',                 # Experiment
    Diag='Bolo',                # Diagnostic
    Name='Cam1',                # Name of this particular camera
)
>>> cam2d = tf.geom.utils.create_CamLOS2D(
    pinhole=[3., 0., 0.],       # pinhole position [X, Y, Z] [m]
    focal=0.1,                  # pinhole-sensors distance [m]
    sensor_nb=[100, 100],       # number of sensors on sensor plane
    sensor_size=[0.1, 0.1],     # size of sensor plane [m]
    orientation=[np.pi, 0., 0.],# 3 angles orienting whole camera [rad]
    config=conf,                # configuration (for computing LOS)
    Etendues=None,              # Etendues (optional)
    Surfaces=None,              # Surfaces (optional) [m^2]
    Exp='WEST',                 # Experiment
    Diag='Bolo',                # Diagnostic
    Name='Cam1',                # Name of this particular camera
)

In tofu, a CamLOS is a camera described as a set of Lines of Sight (LOS), as opposed to a Cam, where the Volume of Sight (VOS) of all pixels are computed in 3D. The CamLOS is then a simplified approximation of the Cam. It can be:

  • 1D : like when all LOS are included in a common plane

  • 2D : like a regular everyday camera, producing a 2D image

For a pinhole camera, all LOS pass through a common point (pinhole)

This function provides an easy way to create a pinhole CamLOS2D In tofu, LOS are described as semi-lines using:

  • a starting point (D)

  • a unit vector (u)

All coordinates are 3D cartesian (X,Y,Z)

Here, you simply need to provide, either:
  • the name of a standard test case

  • a set of geometrical parameters:
    • pinhole: throught which the camera axis passes

    • focal: distance between pinhole and sensor plane

    • size: dimensions of the sensor planendicular to the camera axis

    • N12 : number of pixels (LOS)

    • angs: 3 angles defining the orientation of the camera

The computed set of LOS, optionnaly associated to a Config, can then be returned as:

  • a tofu object (i.e.: a CamLOS2D)

  • a set of starting points (D) and unit vectors (u)

  • a set of starting points (D), a pinhole, and and the coordinates of D

in the camera frame

tofu.geom.utils.create_config(case=None, Exp='Dummy', Type='Tor', Lim=None, Bump_posextent=[0.7853981633974483, 0.7853981633974483], R=None, r=None, elong=None, Dshape=None, divlow=None, divup=None, nP=None, returnas=None, strict=None, SavePath='./', path='/home/lasofivec/tofu/tofu/geom/inputs')[source]

Create easily a tofu.geom.Config object

In tofu, a Config (short for geometrical configuration) refers to the 3D geometry of a fusion device. It includes, at least, a simple 2D polygon describing the first wall of the fusion chamber, and can also include other structural elements (tiles, limiters…) that can be non-axisymmetric.

To create a simple Config, provide either the name of a reference test case, of a set of geometrical parameters (major radius, elongation…).

This is just a tool for fast testing, if you want to create a custom config, use directly tofu.geom.Config and provide the parameters you want.

Parameters
  • case (str) – The name of a reference test case, if provided, this arguments is sufficient, the others are ignored

  • Exp (str) – The name of the experiment

  • Type (str) – The type of configuration (toroidal ‘Tor’ or linear ‘Lin’)

  • Lim_Bump (list) – The angular (poloidal) limits, in the cross-section of the extension of the outer bumper

  • R (float) – The major radius of the center of the cross-section

  • r (float) – The minor radius of the cross-section

  • elong (float) – An elongation parameter (in [-1;1])

  • Dshape (float) – A parameter specifying the D-shape of the cross-section (in [-1;1])

  • divlow (bool) – A flag specifying whether to include a lower divertor-like shape

  • divup (bool) – A flag specifying whether to include an upper divertor-like shape

  • nP (int) – Number of points used to describe the cross-section polygon

  • out (str) –

    FLag indicating whether to return:
    • ’dict’ : the polygons as a dictionary of np.ndarrays

    • ’object’: the configuration as a tofu.geom.Config instance

  • returnas (object / dict) –

    Flag indicating whether to return the config as:
    • object: a Config instance

    • dict: a dict of Struct instances

  • strict (bool) –

    Flag indicating whether to raise an error if a Struct cannot be loaded

    Otherwise only raises a warning

  • path (str) – Absolute path where to find the test case data

  • SavePath (str) – The default path used for saving Struct and Config objects returned by the routine.

Returns

conf (tofu.geom.Config / dict) –

Depending on the value of parameter out, either:
  • the tofu.geom.Config object created

  • a dictionary of the polygons and their pos/extent (if any)

tofu.geom.utils.get_X12fromflat(X12, x12u=None, nx12=None)[source]
tofu.geom.utils.get_available_config(dconfig=None, dconfig_shortcuts=None, verb=True, returnas=False)[source]

Print a table showing all pre-defined config

Each pre-defined config in tofu can be called by its unique name or by a series of shortcuts / alterantive names refereing to the same unique name. this feature is useful for retro-compatibility and for making sure a standard name always refers to the latest (most detailed) available version of the geometry.

Can also return the table as str

No input arg needed:
>>> import tofu as tf
>>> tf.geom.utils.get_available_config()
tofu.geom.utils.get_nIne1e2(P, nIn=None, e1=None, e2=None)[source]