API Reference#

The top-level coilpy package re-exports the most commonly used classes and helpers for interactive workflows.

This is a python package for plotting and data processing in stellarator optimization.

It contains several python functions on HDF5, Fourier surfaces, FOCUS, cois, magnetic dipoles, STELLOPT, VMEC, BOOZ_XFORM, etc.

The repository is available at USTCstellarators/coilpy.

For full documentation, please check https://ustcstellarators.github.io/coilpy/.

class coilpy.BOOZ_XFORM(*args, **kwargs)[source]#

Bases: SortedDict

static from_vmec(wout, mbooz=0, nbooz=0, surfaces=[])[source]#

Prepare BOOZ_XFORM input file from VMEC wout file

Parameters:
  • wout (str) – VMEC wout filename.

  • mbooz (int, optional) – Maximum poloildal mode number. Defaults to 0 (4*Mpol).

  • nbooz (int, optional) – Maximum toroidal mode number. Defaults to 0 (4*Ntor).

  • surfaces (list, optional) – Flux surfaces list. Defaults to [] (1:NS).

plot(ordering=0, mn=(None, None), ax=None, log=True, normalize=True, logical_not=False, **kwargs)[source]#

Plot \(|B|\) components as a 1D profile.

Parameters:
  • ordering (integer, optional) – Plot the leading Nordering asymmetric modes. Defaults to 0.

  • mn (tuple, optional) – Plot the particular (m,n) mode. Defaults to (None, None).

  • ax (Matplotlib axis, optional) – Matplotlib axis to be plotted on. Defaults to None.

  • log (bool, optional) – Plot in log scale. Defaults to True.

  • normalize (bool, optionl) – Normalize to B_00. Defaults to True.

  • logical_not (bool, optional) – Unselect mn modes. Defaults to False.

  • kwargs (dict) – Keyword arguments for matplotlib.pyplot.plot. Defaults to {}.

Returns:

Matplotlib axis plotted on.

Return type:

ax (Matplotlib axis)

plot2d(ns=-1, npol=128, ntor=128, ax=None, contour=True, **kwargs)[source]#

Plot \(|B|\) contours on the flux surface.

Parameters:
  • ns (int, optional) – Flux surface index in self.jlist. Defaults to -1.

  • npol (int, optional) – Poloidal resolution. Defaults to 128.

  • ntor (int, optional) – Toroidal resolution. Defaults to 128.

  • ax (Matplotlib axis, optional) – Matplotlib axis to be plotted on. Defaults to None.

  • contour (bool, optional) – Whether plotting the contour lines. Defaults to True.

Returns:

Matplotlib axis plotted on.

Return type:

ax (Matplotlib axis)

static plot_helicity(vals, xm, xn, xx, ordering=0, mn=(None, None), ax=None, log=False, normalize=False, logical_not=False, **kwargs)[source]#
to_FOCUS(ns=-1, focus_file='plasma.boundary', tol=1e-08, iota=None)[source]#

Write a FOCUS plasma boundary file in Boozer coordinates

Parameters:
  • ns (int, optional) – Flux surface label to be exported. Defaults to -1.

  • focus_file (str, optional) – FOCUS plasma boundary file name. Defaults to ‘plasma.boundary’.

  • tol (float, optional) – Truncated tolerance. Defaults to 1.0E-8.

  • iota (float, optional) – The target iota to be extracted. Defaults to None.

static write_input(extension, mbooz, nbooz, surfaces)[source]#

Write a BOO_XFORM input file

Parameters:
  • extension (str) – VMEC output extension.

  • mbooz (int) – Maximum poloidal mode.

  • nbooz (int) – Maximum toroidal mode

  • surfaces (list) – List of flux surfaces.

class coilpy.Coil(xx=[], yy=[], zz=[], II=[], names=[], groups=[])[source]#

Bases: object

Python object for a set of coils.

Parameters:
  • xx (list, optional) – Coil data in x-coordinates. Defaults to [[]].

  • yy (list, optional) – Coil data in y-coordinates. Defaults to [[]].

  • zz (list, optional) – Coil data in z-coordinates. Defaults to [[]].

  • II (list, optional) – Coil currents. Defaults to [[]].

  • names (list, optional) – Coil names. Defaults to [[]].

  • groups (list, optional) – Coil groups. Defaults to [[]].

A convenient way for construction is to use self.read_makegrid(filename), like

`` coil = CoilSet.read_makegrid(‘coils.sth’) ``

Each coil is stored in self.data in the format of coilpy.coils.SingleCoil.

You can plot the coilset using self.plot.

The coilset can be saved in the format of MAKEGRID using self.save_makegrid and saved as VTK files using self.toVTK.

bfield(pos, method='hanson_hirshman')[source]#

Compute the magnetic field from a coil set

Parameters:
  • pos (array_like) – Evaluation points, shape is (npoints,3) or (3,).

  • method (str, optional) – Biot-Savart evaluation method. Supported values are "hanson_hirshman", "biot_savart", and "bfield_HH". "biot_savart" expects tangents precomputed with SingleCoil.fourier_tangent or SingleCoil.spline_tangent. Defaults to "hanson_hirshman".

Returns:

The computed magnetic field, shape (npoints,3).

Return type:

array_like

plot(irange=[], engine='pyplot', plot2d=False, ax=None, fig=None, show=True, **kwargs)[source]#

Plot coils in mayavi or matplotlib or plotly.

Parameters:
  • irange (list, optional) – Coil list to be plotted. Defaults to [].

  • engine (string, optional) – Plotting engine. One of {‘pyplot’, ‘mayavi’, ‘plotly’}. Defaults to “pyplot”.

  • plot2d (bool, optional) – If plotting with finite size. Defaults to False.

  • fig (, optional) – figure to be plotted on. Defaults to None.

  • ax (, optional) – axis to be plotted on. Defaults to None.

  • show (bool, optional) – if show the plotly figure immediately. Defaults to True.

  • kwargs (dict, optional) – Keyword dict for plotting settings.

classmethod read_gpec_coils(filename, current=1.0)[source]#

Read coils from GPEC files.

Parameters:
  • filename (str) – File name.

  • current (float, optional) – Coil current. Defaults to 1.0.

Returns:

Coil object.

Return type:

Coil

classmethod read_makegrid(filename)[source]#

Read coils from the MAKEGRID format.

Parameters:

filename (str) – file path and name

Raises:

IOError – Check if file exists

Returns:

the python class Coil

Return type:

Coil class

save_gpec_coils(filename, split=True, nw=1, **kwargs)[source]#

Write the data in standard ascii format for GPEC

Parameters:
  • filename (str) – path (if split==True) or file name to be saved.

  • split (bool, optional) – write each coil into a separate file. Defaults to True

  • nw (integer, optional) – number of windings. Defaults to 1.

save_makegrid(filename, nfp=1, **kwargs)[source]#

Write coils in the MAKEGRID format.

Parameters:
  • filename (str) – File name and path.

  • nfp (int, optional) – Number of toroidal periodicity. Defaults to 1.

toVTK(vtkname, line=True, height=0.1, width=0.1, **kwargs)[source]#

Write entire coil set into a VTK file

Parameters:
  • vtkname (str) – VTK filename.

  • line (bool, optional) – Save coils as polylines or surfaces. Defaults to True.

  • height (float, optional) – Rectangle height when expanded to a finite cross-section. Defaults to 0.1.

  • width (float, optional) – Rectangle width when expanded to a finite cross-section. Defaults to 0.1.

  • kwargs (dict) – Optional kwargs passed to “polyLinesToVTK” or “meshio.Mesh.write”.

class coilpy.Dipole(**kwargs)[source]#

Bases: object

magnetic dipole class

bfield(pos)[source]#
Calculate the magnetic field at an arbitrary position.

No symmetry info considered for now.

Parameters:

pos (array_like) – [x,y,z] Cartesian coordinates in space.

Returns:

The total magnetic field produced by all dipoles

Return type:

numpy.array

change_momentq(newq)[source]#

change the q factor for the normalized density

classmethod from_regcoil(regcoilname, winding, ilambda=-1, symmetry='full', num_pol=128, num_tor=128, m0=None, half_shift=True)[source]#

Initialize from REGCOIL current potential

Parameters:
  • regcoilname (str) – REGCOIL netcdf output file.

  • winding (str, optional) – NESCOIL input format winding surface.

  • ilambda (int, optional) – Lambda index in REGCOIL output. Defaults to -1.

  • symmetry (str, optional) – Stellarator symmetry option. Defaults to ‘full’.

  • num_pol (int, optional) – Number of poloidal dipoles. Defaults to 128.

  • num_tor (int, optional) – Number of toroidal dipoles. Defaults to 128.

  • m0 ([type], optional) – Magnetization limit per thickness. Defaults to None.

  • half_shift (bool, optional) – Logical flag to determine if half-grid shifted. Defaults to True.

Returns:

None

full_period(nfp=1, dim=None)[source]#

map from one period to full periods

inverse()[source]#

get the stellarator symmetric part?

mimic(template, **kwargs)[source]#

Mimic rho, mp, mt following the “template” dipole set

Parameters:

template (Dipole class) – The template Dipole class to be mirrored.

Returns:

None

Return type:

None

classmethod open(filename, verbose=False, **kwargs)[source]#

Read FAMUS dipoles

Parameters:
  • filename (str) – path to open the file.

  • verbose (bool, optional) – Whether to print additional info. Defaults to False.

Returns:

Dipole class

Return type:

Dipole

orientation(unit=True, uniform=False)[source]#
plot(engine='pyplot', start=0, end=None, **kwargs)[source]#
plot_rho_profile(lower=0, upper=1, nrange=10, nofigure=False, **kwargs)[source]#
classmethod read_dipole_old(filename, zeta=0.0, zeta1=6.283185307179586, **kwargs)[source]#

read diploes from FOCUS format (old)

Parameters:
  • filename (str) – path to open the file.

  • zeta (float, optional) – Starting toroidal angle for clipping. Defaults to 0.0.

  • zeta1 (float, optional) – [Ending toroidal angle for clipping]. Defaults to np.pi*2.

Returns:

Dipole class

Return type:

Dipole

round_angle()[source]#

round off the moment orientation to the closest preferred axis

Returns:

return a new dipole class with rounded orientations

Return type:

Dipole class

save(filename, unique=False, tol=0)[source]#

write diploes from FOCUS format

Parameters:
  • filename (str) – FOCUS file name.

  • unique (bool, optional) – Writing dipole every self.nfp term. Defaults to False.

  • tol (float, optional) – tolerance to skip zeros. Defaults to 0.

sp2xyz()[source]#

spherical coordinates to cartesian coordinates

toVTK(vtkname, dim=1, close=False, ntnz=False, toroidal=False, **kwargs)[source]#

write dipole data into a VTK file

Parameters:
  • vtkname (str) – VTK filename, will be appended with .vts or .vtu.

  • dim (tuple, optional) – Dimension information if saved as structured grids. Defaults to (1).

  • close (bool, optional) – Logical flag to manually close the gaps. Defaults to False.

  • ntnz (bool, optional) – Logical flag of theta-zeta order. Defaults to False.

  • toroidal (bool, optional) – Logical flag of filling in the toroidal gap. Defaults to False.

Returns:

None

truncate(cond)[source]#

Truncate dipole set following a condition

Parameters:

cond (array-like, bool) – Slicing conditions

Returns:

Truncated dipole

Return type:

Dipole

volume(magnitization=1100000.0, **kwargs)[source]#
xyz2sp()[source]#

cartesian coordinates to spherical coordinates

class coilpy.FOCUSHDF5(filename, periodic=False, **kwargs)[source]#

Bases: HDF5

FOCUS output hdf5 file

Bmod()[source]#
Bnorm(plottype='2D', source='all', axes=None, flip=False, **kwargs)[source]#

Plot Bn distribution.

Keyword Arguments:
  • '2D' (plottype -- string,)

  • 'all' (source -- string, 'coil', 'plasma', 'sum' or)

  • be (axes -- matplotlib.pyplot or mayavi.mlab axis, axis to) – plotted on (default None)

  • coil, (flip -- logical, determine how to calculate Bn from) – True: coil_Bn = Bn - plas_Bn; False: coil_Bn = Bn + plas_Bn

Returns:

obj – matplotlib.pyplot or mayavi.mlab plotting object

convergence(term='bnorm', iteration=True, axes=None, **kwargs)[source]#
curvature(iteration=True, vlines=True, shift_ind=0, icoil=1, NS=128)[source]#

Curvature ploting for the FOCUS-spline paper [arXiv:2107.02123] by N. Lonigro

Parameters:
  • iteration (bool, optional) – [description]. Defaults to True.

  • vlines (bool, optional) – [description]. Defaults to True.

  • shift_ind (int, optional) – [description]. Defaults to 0.

  • icoil (int, optional) – [description]. Defaults to 1.

  • NS (int, optional) – [description]. Defaults to 128.

Returns:

[description]

Return type:

[type]

iota_plot(axes=None, **kwargs)[source]#

Plot the rotational transform profile

Parameters:
  • axes (matplotlib.pyplot.axis, optional) – axis to be plotted on. Defaults to None.

  • kwargs (optional) – Keyword arguments passed to matplotlib.pyplot.plot, e.g. color=’r’.

Returns:

The updated axis

Return type:

matplotlib.pyplot.axis

plot(engine='plotly', scalars='bn', fig=None, ax=None, show=True, **kwargs)[source]#

Plot 3D field on the plasma from FOCUS ouput

Parameters:
  • engine (str, optional) – 3D plot engine, one of [“mayavi”, “pyplot”, “plotly”]. Defaults to “plotly”.

  • scalars (str, optional) – Scalar function on the surface, one of [“Bn”, “B”, “plas_Bn”] or 2D arrays. Defaults to “bn”.

  • fig (, optional) – Figure to be plotted on. Defaults to None.

  • ax (, optional) – Axis to be plotted on. Defaults to None.

  • show (bool, optional) – If show the plotly figure immediately. Defaults to True.

  • kwargs – optional keyword arguments for plotting.

Raises:

ValueError – Plot engine should be one value of [“mayavi”, “pyplot”, “plotly”].

poincare_plot(color=None, prange='full', **kwargs)[source]#

Poincare plot from FOCUS output. :param color: dot colors. Defaults to None (rainbow). :type color: matplotlib color, or None :param prange: Plot range, one of [“upper”, “lower”, “all”]. Defaults to “full”. :type prange: str, optional :param kwargs: matplotlib scatter keyword arguments

Returns:

None

toVTK(name=None, full=False, **kwargs)[source]#

Save surface and magnetic field data into VTK file :param name – string: None, if None, using self.filename :param VTK file name. default: None, if None, using self.filename :param full – boolean: :param if save the entire torus: :param **kwargs – external data will be saved in VTK file:

Returns:

VTK file name

class coilpy.FourSurf(xm=[], xn=[], rbc=[], zbs=[], rbs=[], zbc=[])[source]#

Bases: object

toroidal surface in Fourier representation R = sum RBC cos(mu-nv) + RBS sin(mu-nv) Z = sum ZBC cos(mu-nv) + ZBS sin(mu-nv)

change_poloidal_angle()[source]#
get_area()[source]#

Get the surface area and saved in self.area More comprehensive options can be found in self._areaVolume()

Parameters:

None

Returns:

area

get_volume()[source]#

Get the surface volume and saved in self.volume More comprehensive options can be found in self._areaVolume()

Parameters:

None

Returns:

volume

grid_box(ntor=64, npol=64)[source]#

Return the max R & Z values of the surface

Parameters:
  • ntor (int, optional) – Toroidal resolution. Defaults to 64.

  • npol (int, optional) – Poloidal resolution. Defaults to 64.

Returns:

the max R & Z values

Return type:

(Rmin, Rmax, Zmin, Zmax)

plot(zeta=0.0, npoints=360, **kwargs)[source]#

plot the cross-section at zeta using matplotlib.pyplot

Parameters:
  • float (zeta --)

  • value (toroidal angle)

  • integer (npoints --) –

  • (default (number of discretization points) –

  • pyplot (kwargs -- optional keyword arguments for)

Returns:

line class in matplotlib.pyplot

plot3d(engine='pyplot', theta0=0.0, theta1=6.283185307179586, zeta0=0.0, zeta1=6.283185307179586, npol=360, ntor=360, normal=False, fig=None, ax=None, show=True, **kwargs)[source]#

plot 3D shape of the surface

Parameters:
  • string (engine --)

  • {'pyplot' (plotting engine)

  • float (zeta1 --) – 0.0)

  • (default (if show the plotly figure immediately) – 0.0)

  • float – 2*np.pi)

  • (default – 2*np.pi)

  • float – 0.0)

  • (default – 0.0)

  • float – 2*np.pi)

  • (default – 2*np.pi)

  • integer (ntor --) –

  • (default

  • integer

  • (default

  • bool (show --) – False)

  • (default – False)

  • -- (ax) – None)

  • (default – None)

  • -- – None)

  • (default – None)

  • bool – True)

  • (default – True)

  • plotting (kwargs -- optional keyword arguments for)

Returns:

xsurf, ysurf, zsurf – arrays of x,y,z coordinates on the surface

classmethod read_focus_input(filename, mpol=9999, ntor=9999)[source]#

initialize surface from the FOCUS format input file ‘plasma.boundary’

Parameters:
  • string (filename --)

  • file (path + name to the FOCUS input boundary)

  • (default (ntor -- maximum truncated toroidal mode number) –

  • (default

Returns:

fourier_surface class

classmethod read_spec_input(filename, tol=1e-08)[source]#

Initialize a surface from a SPEC input file.

Parameters:
  • string (filename --)

  • *.sp (path + name to the SPEC boundary file such as)

  • (default (ntor -- maximum truncated toroidal mode number) –

  • (default

Returns:

fourier_surface class

classmethod read_spec_output(spec_out, ns=-1)[source]#

initialize surface from the ns-th interface SPEC output

Parameters:
  • class (spec_out -- SPEC)

  • results (SPEC hdf5)

  • integer (ns --) – -1)

  • (default (the index of SPEC interface) – -1)

Returns:

fourier_surface class

classmethod read_vmec_input(filename, tol=1e-08)[source]#

initialize surface from the ns-th interface SPEC output

Parameters:
  • string (woutfile --)

  • output (path + name to the wout file from VMEC)

  • integer (ns --) – -1)

  • (default (the index of VMEC nested flux surfaces) – -1)

Returns:

fourier_surface class

classmethod read_vmec_output(woutfile, ns=-1)[source]#

initialize surface from the ns-th interface SPEC output

Parameters:
  • string (woutfile --)

  • output (path + name to the wout file from VMEC)

  • integer (ns --) – -1)

  • (default (the index of VMEC nested flux surfaces) – -1)

Returns:

fourier_surface class

classmethod read_winding_surface(filename, mpol=9999, ntor=9999)[source]#

initialize surface from the NESCOIL format input file ‘nescin.xxx’

Parameters:
  • string (filename --)

  • file (path + name to the NESCOIL input boundary)

  • (default (ntor -- maximum truncated toroidal mode number) –

  • (default

Returns:

fourier_surface class

classmethod read_winding_surfce(filename, mpol=9999, ntor=9999)[source]#
rz(theta, zeta, normal=False)[source]#

get r,z position of list of (theta, zeta)

Parameters:
  • array_like (zeta -- float)

  • angle (poloidal)

  • array_like

  • value (toroidal angle)

  • logical (normal --) – False)

  • (default (calculate the normal vector or not) – False)

Returns:

r, z – float array_like r, z, [rt, zt], [rz, zz] – if normal

toSTL(stlname, **kwargs)[source]#

save surface shape a stl file using meshio

Parameters:
  • string (stlname --)

  • save (the filename you want to)

  • 'stlname.vts' (final name is)

  • self.plot3d. (kwargs -- optional keyword arguments used for)

Returns:

Mesh object in meshio

Return type:

mesh

toVTK(vtkname, npol=360, ntor=360, **kwargs)[source]#

save surface shape a vtk grid file

Parameters:
  • string (vtkname --)

  • save (the filename you want to)

  • 'vtkname.vts' (final name is)

  • integer (ntor --) –

  • (default (number of toroidal discretization points) –

  • integer

  • (default

  • pointdata (kwargs -- optional keyword arguments for saving as)

Returns:

write_focus_input(filename, nfp=1, bn=None)[source]#

Write the Fourier harmonics down in FOCUS format

Parameters:
  • filename ([type]) – Output file name.

  • nfp (int, optional) – Number of toroidal periodicity Defaults to 1.

  • bn (dict, optional) – Bn dict, containing ‘xm’, ‘xn’, ‘bnc’, ‘bns’. Defaults to None.

write_vmec_input(filename, template=None, nfp=1, **kwargs)[source]#
xyz(theta, zeta, normal=False)[source]#

get x,y,z position of list of (theta, zeta)

Parameters:
  • array_like (zeta -- float)

  • angle (poloidal)

  • array_like

  • value (toroidal angle)

  • logical (normal --) – False)

  • (default (calculate the normal vector or not) – False)

Returns:

x, y, z – float array_like x, y, z, [nx, ny, nz] – if normal

class coilpy.HDF5(*args, **kwargs)[source]#

Bases: object

Create a python object for a HDF5 file.

Returns:

python HDF5 object.

Return type:

HDF5 class

Use as s = HDF5(filename), e.g. s=HDF5(“ext.h5”) This class can be iterated or entered. To check all the items, you can use self.inventory().

inventory(prefix='')[source]#

Print a list of items contained in this object

Parameters:

prefix (str, optional) – Header to be printed. Defaults to “”.

class coilpy.Magnet(vertices=[[]], mvec=[0, 0, 1], Br=1.4)[source]#

Bases: object

Cube magnet class used for subdividing magnets

divide()[source]#

Divide the prism into eight dipoles.

Returns:

Dipole objects

Return type:

coilpy.Dipole

sub_cubes()[source]#

Subdivide a prism into 8 cubes.

Returns:

A list of 8 Magnets

Return type:

list

class coilpy.Mgrid(r, z, phi, Br, Bz, Bphi, nfp=1)[source]#

Bases: object

bfield(rzp)[source]#

Return interpolated B-field

Parameters:

rzp (list) – (r,z,phi) values cylindral coodinates

Returns:

[Br, Bz, Bphi] at the evaluation point

Return type:

numpy.array

classmethod compute_mgrid(bfield, rmin, rmax, zmin, zmax, nr=100, nz=100, nphi=100, nfp=1)[source]#

Compute bfield on the grid

Parameters:
  • bfield (func) – callable function to compute B at a sequence of points [N, 3] in cartesian coordinates, e.g. Bxyz = bfield(pos[0:N, 0:3])

  • rmin (float) – minimum r value

  • rmax (float) – maximum r value

  • zmin (float) – minimum z value

  • zmax (float) – maximum z value

  • nr (int, optional) – resolution in r. Defaults to 100.

  • nz (int, optional) – resolution in z. Defaults to 100.

  • nphi (int, optional) – resolution in phi. Defaults to 100.

  • nfp (int, optional) – number of field periods. Defaults to 1.

Returns:

return a Mgrid class with dimensions of [nr, nz, nphi+1]

Return type:

Mgrid

interpolate(**kwargs)[source]#
classmethod read_mgrid_bin(filename, extcur=None)[source]#

Read mgrid file in binary format

Parameters:
  • filename (str) – binary file path and name.

  • extcur (str/list, optional) – current (or file) for each group. Defaults to None.

Returns:

Mgrid class containning all data with B summed together.

Return type:

Mgrid

classmethod read_mgrid_nc(filename, extcur=None)[source]#

Read mgrid file in the netcdf format

Parameters:
  • filename (str) – netcdf file path and name.

  • extcur (str/list, optional) – current (or file) for each group. Defaults to None.

Returns:

Mgrid class containning all data with B summed together.

Return type:

Mgrid

write_mgrid_nc(filename)[source]#

Write a MGRID file in Netcdf format (extcur = 1.0)

Parameters:

filename (str) – file name to be saved

class coilpy.Netcdf(filename, mmap=False, version=1, maskandscale=False)[source]#

Bases: object

Assembly datasets in a netcdf file into python classes. It takes the same arguments as scipy.io.netcdf.netcdf_file. Once parsed, you can access all the data directly via its key as class attributes.

Examples

Read a netcdf file:

data = Netcdf(‘path-to-file.nc’)

Access its attributes:

data.key

List all the keys:

print(list(data))

class coilpy.Regcoil(filename, mmap=False, version=1, maskandscale=False)[source]#

Bases: Netcdf

bfield(pos, fortran=True)[source]#
bfield_cyl(rpz)[source]#
compute_bn()[source]#

Compute B_surface_current cdot n on the plasma surface

Returns:

a 2D array containing Bn information. Dimension: Ntheta x Nzeta

Return type:

numpy.ndarray

get_k(ilambda=0)[source]#

Compute the surface current density on the coil surface Following Eq. A.13 in Landreman Nucl. Fusion 57 (2017) 046003

Parameters:

ilambda (int, optional) – The lambda index in the REGCOIL solution. Defaults to 0.

Returns:

A 3D array containing the current desity information. Dimension: 3 x Ntheta x Nzeta

Return type:

numpy.ndarray

class coilpy.STELLout(*args, **kwargs)[source]#

Bases: SortedDict, OMFITascii

OMFITobject used to interface with stellopt.* file in STELLOPT outputs.

Parameters:

filename – filename passed to OMFITascii class

All additional key word arguments passed to OMFITascii

load()[source]#

Load the file and parse it into a sorted dictionary

plot(ax=None, all=True, **kwargs)[source]#
plot_balloon(it=-1, ax=None, **kwargs)[source]#

Plot Ballooning instability from COBRAVMEC

Parameters:
  • it (int, optional) – Iteration index to be plotted. Defaults to -1.

  • ax (Matplotlib axis, optional) – Matplotlib axis to be plotted on. Defaults to None.

  • kwargs (dict) – Keyword arguments for matplotlib.pyplot.plot. Defaults to {}.

Returns:

Matplotlib axis plotted on.

Return type:

ax (Matplotlib axis)

plot_helicity(it=-1, ordering=0, mn=(None, None), ax=None, log=True, normalize=False, logical_not=False, **kwargs)[source]#

Plot \(|B|\) components in Boozer coordinates from BOOZ_XFORM.

Parameters:
  • it (int, optional) – Iteration index to be plotted. Defaults to -1.

  • ordering (integer, optional) – Plot the leading Nordering asymmetric modes. Defaults to 0.

  • mn (tuple, optional) – Plot the particular (m,n) mode. Defaults to (None, None).

  • ax (Matplotlib axis, optional) – Matplotlib axis to be plotted on. Defaults to None.

  • log (bool, optional) – Plot in log scale. Defaults to True.

  • normalize (bool, optionl) – Normalize to B_00. Defaults to False.

  • logical_not (bool, optional) – Unselect mn modes. Defaults to False.

  • kwargs (dict) – Keyword arguments for matplotlib.pyplot.plot. Defaults to {}.

Returns:

Matplotlib axis plotted on.

Return type:

ax (Matplotlib axis)

plot_neo(it=-1, ax=None, **kwargs)[source]#

Plot effective ripple from NEO

Parameters:
  • it (int, optional) – Iteration index to be plotted. Defaults to -1.

  • ax (Matplotlib axis, optional) – Matplotlib axis to be plotted on. Defaults to None.

  • kwargs (dict) – Keyword arguments for matplotlib.pyplot.plot. Defaults to {}.

Returns:

Matplotlib axis plotted on.

Return type:

ax (Matplotlib axis)

class coilpy.SingleCoil(x=[], y=[], z=[], I=0.0, name='coil1', group=1)[source]#

Bases: object

Python class representing a single coil as discrete points in Cartesian coordinates.

x#
Type:

Data in x-coordinate

Args#

x (list, optional): Data in x-coordinate. Defaults to []. y (list, optional): Data in y-coordinate. Defaults to []. z (list, optional): Data in z-coordinate Defaults to []. I (float, optional): Coil current. Defaults to 0.0. name (str, optional): Coil name. Defaults to “coil1”. group (int, optional): Coil group for labeling. Defaults to 1.

bfield(pos)[source]#

Calculate the magnetic field at an arbitrary point using self.dt.

Parameters:

pos (list) – Evaluation point in Cartesian coordinates.

Returns:

B vector produced by the coil.

Return type:

numpy.ndarray

bfield_HH(pos, **kwargs)[source]#

Calculate B field at an arbitrary point using the Hanson-Hirshman expression

Parameters:

pos (list) – Cartesian coordinates for the evaluation point.

Returns:

B vector produced by the coil.

Return type:

numpy.ndarray

bfield_fd(pos)[source]#

Calculate the magnetic field at an arbitrary point using finite difference.

Parameters:

pos (list) – Evaluation point in Cartesian coordinates.

Returns:

B vector produced by the coil.

Return type:

numpy.ndarray

biot_savart(pos)[source]#
fourier_tangent()[source]#

Approximate the tangent using Fourier representation.

hanson_hirshman(pos)[source]#

Wrapper for the fortran code biotsavart.hanson_hirshman

Parameters:

pos (ndarray, (n,3)) – Evaluation points in space

Returns:

Magnetic field at the evaluation point

Return type:

ndarray, (n,3)

interpolate(num=256, kind='fft', nf=-1)[source]#

Interpolate to get more data points.

Parameters:
  • num (int, optional) – The total number of points after interpolation. Defaults to 256.

  • kind (str, optional) – Specifies the kind of interpolation, could be ‘fft’ or scipy.interp1d.kind. Defaults to ‘fft’.

  • nf (int, optional) – Number of truncated Fourier modes. Defaults to -1.

magnify(ratio)[source]#

Magnify the coil with a ratio.

Parameters:

ratio (float) – The magnifying ratio.

plot(engine='plotly', fig=None, ax=None, show=True, **kwargs)[source]#

Plot the coil in a specified engine.

Parameters:
  • engine (str, optional) – Plot enginer, could be {pyplot, mayavi, plotly}. Defaults to “mayavi”.

  • fig (, optional) – Figure to be plotted on. Defaults to None.

  • ax (matplotlib.axis, optional) – Axis to be plotted on. Defaults to None.

  • show (bool, optional) – If show the plotly figure immediately. Defaults to True.

Raises:

ValueError – Invalid engine option, should be one of {pyplot, mayavi, plotly}.

plot2d(engine='mayavi', fig=None, ax=None, show=True, width=0.1, height=0.1, frame='centroid', **kwargs)[source]#

Plot the coil with finite size.

Parameters:
  • engine (str, optional) – Plot enginer, could be {pyplot, mayavi, plotly}. Defaults to “mayavi”.

  • fig (, optional) – Figure to be plotted on. Defaults to None.

  • ax (matplotlib.axis, optional) – Axis to be plotted on. Defaults to None.

  • show (bool, optional) – If show the plotly figure immediately. Defaults to True.

  • width (float, optional) – Coil width. Defaults to 0.1.

  • height (float, optional) – Coil height. Defaults to 0.1.

  • frame (str, optional) – Finite-build frame, could be one of (“centroid”, “frenet”, “parallel”). Defaults to “centroid”.

rectangle(width=0.1, height=0.1, frame='centroid', **kwargs)[source]#

Expand single coil filament to a finite-build coil.

Parameters:
  • width (float, optional) – Coil width. Defaults to 0.1.

  • height (float, optional) – Coil height. Defaults to 0.1.

  • frame (str, optional) – Finite-build frame, could be one of (“centroid”, “frenet”, “parallel”). Defaults to “centroid”.

Returns:

x-coordiante for plotting as a mesh. numpy.ndarry: y-coordiante for plotting as a mesh. numpy.ndarry: z-coordiante for plotting as a mesh.

Return type:

numpy.ndarry

spline_tangent(order=3, der=1)[source]#

Calculate the tangent of coil using spline interpolation

Parameters:

order (int, optional) – Order of spline interpolation used. Defaults to 3.

toVTK(vtkname, **kwargs)[source]#

Write the coil as a VTK file

Parameters:

vtkname (string) – VTK filename

class coilpy.VMECout(filename, **kwargs)[source]#

Bases: object

Class to parse a VMEC wout file

Parameters:

filename – filename passed to xarray.open_dataset()

The entire dataset is stored in self.wout and you can access to variables via self.wout[‘iotaf’].values. The flux surfaces are all parsed as FourSurf classes and stored in the list of self.surface. Magnetic fields are Fourier transformed to real space (only the stellarator symmetric part, bmnc) and store in self.data[‘b].

self.plot has several options to plot the profiles, etc.

plot(plot_name='none', ax=None, **kwargs)[source]#

Plot various VMEC quantities

Parameters:
  • plot_name (str, optional) – The quantity to be plotted, should be one of iota, q, pressue, <Buco>, <Bvco>, <jcuru>, <jcurv>, <j.B>, LPK, none. Defaults to ‘none’.

  • ax (Matplotlib axis, optional) – The Matplotlib axis to be plotted on. Defaults to None.

coilpy.biot_savart(pos, xyz, current, dxyz=None)[source]#
coilpy.blocks2ficus(block_file, ficus_file, moment_file=None, dipole_file=None, magnitization=1100000.0, clip=None, **kwargs)[source]#

Convert PM4STELL blocks file to FICUS inputs

Parameters:
  • block_file (str) – Path and file name to the blocks file (usually contains _blocks.csv).

  • ficus_file (str) – FICUS input CSV filename.

  • moment_file (str, optional) – Moments file to assign the magnetic moment. Defaults to None.

  • dipole_file (str, optional) – FAMUS dipole file to assign the magnetic moment. Defaults to None.

  • magnitization (float, optional) – The magnetization of the material. Defaults to 1.1e6.

  • clip (float, optional) – The minimum rho value to preserve. Defaults to None.

Returns:

Data in the format of pandas.DataFrame

Return type:

pandas.DataFrame

Note: This requires to load the MUSE package (tmqian/MUSE) to the sys.path.

Example

magnets = blocks2ficus(“magpie_trial104b_blocks.csv”, “trial104b_ficus.csv”, dipole_file=”disc_ftri_wp0_c9a_tr104b.focus”)

coilpy.blocks2tiles(block_file, dipole_file, clip=0, mu=(1.05, 1.05), **kwargs)[source]#

Construct magtense.Tiles from PM4STELL blocks file

Parameters:
  • block_file (str) – Path and file name to the blocks file (usually contains _blocks.csv).

  • dipole_file (str) – FAMUS dipole file to assign the magnetic moment.

  • clip (float, optional) – The minimum rho value to preserve. Defaults to 0.

  • mu (tuple, optional) – Magnetic permeability in the parallel and perpendicular direction. Defaults to (1.05, 1.05).

Returns:

Prisms in the type of magtense.Titles.

Return type:

prism (magtense.Tiles)

coilpy.blocks2vtk(block_file, vtk_file, moment_file=None, dipole_file=None, clip=0, **kwargs)[source]#

Write a VTK file from the blocks file

Parameters:
  • block_file (str) – File name and path to the blocks file.

  • vtk_file (str) – VTK file name to be saved.

  • moment_file (str, optional) – File name and path to the moments file. Defaults to None.

  • dipole_file (str, optional) – File name and path to the FAMUS dipole file (*.focus). Defaults to None.

  • clip (int, optional) – The threshold value to clip magents with rho>=clip. Defaults to 0.

Returns:

The constructed meshio.Mesh object.

Return type:

meshio.Mesh

coilpy.booz2focus(booz_file, ns=-1, focus_file='plasma.boundary', tol=1e-06, Nfp=1)[source]#

convert BOOZ_XFORM output into FOCUS format plasma surface (in Boozer coordinates)

Parameters:
  • booz_file (str) – Netcdf file of BOOZ_XFORM output

  • ns (int, optional) – The specific flux surface you want to convert. Defaults to -1.

  • focus_file (str, optional) – FOCUS plasma boundary filename. Defaults to ‘plasma.boundary’.

  • tol ([type], optional) – Tolerance to truncate. Defaults to 1E-6.

  • Nfp (int, optional) – [description]. Defaults to 1.

coilpy.build_prism(lwh, center, rot, mag_angle, mu, remanence)[source]#

Construct a prism in magtense.Tiles.

Parameters:
  • center (array-like) – The centers of the prisms.

  • rot (array-like) – The rotation angles around x,y,z-axis of the prisms.

  • lwh (array-like) – The dimensions of the prism in length, width, height.

  • mag_angle (array-like) – Magnetization angle in spherical coordinates.

  • mu (array-like) – Permeability in the parallel and perpendicular direction.

  • remanence (float or array-like) – Magnetic remanence.

Returns:

Prisms in the type of magtense.Titles.

Return type:

prism (magtense.Titles)

coilpy.colorbar(mappable, **kwargs)[source]#
coilpy.corner2magnet(corner_file, moment_file, Br=1.4, reset=False)[source]#

Corner file to Magnet objects

Parameters:
  • corner_file (str) – *_corner.csv file.

  • moment_file (str) – *_moments.csv file.

  • Br (float, optional) – Magnetic remanence. Defaults to 1.4.

  • reset (bool, optional) – If reset the magnetic remanence based on Br. Defaults to False.

Returns:

A list of 8 Magnet objects

Return type:

list

coilpy.corner2tiles(corner_file, dipole_file, clip=0, mu=(1.05, 1.05), **kwargs)[source]#

Construct magtense.Tiles from MUSE corner file

Parameters:
  • corner_file (str) – Path and file name to the corner file (usually contains _corner.csv).

  • dipole_file (str) – FAMUS dipole file to assign the magnetic moment.

  • clip (float, optional) – The minimum rho value to preserve. Defaults to 0.

  • mu (tuple, optional) – Magnetic permeability in the parallel and perpendicular direction. Defaults to (1.05, 1.05).

Returns:

Prisms in the type of magtense.Titles.

Return type:

prism (magtense.Tiles)

coilpy.div0(a, b)[source]#
coilpy.fft_deriv(y)[source]#
coilpy.get_center(top, bot)[source]#

Get geometry information from 8 vertices of a prism.

Parameters:
  • top (numpy.ndarray) – Vertices of the top surface, in shape of (4,3).

  • bot (numpy.ndarray) – Vertices of the bottom surface, in shape of (4,3).

Returns:

The center of the prism. rot (numpy.ndarray): The rotation angles around x,y,z-axis of the prism. lwh (numpy.ndarray): The dimension of the prism in length, width, height.

Return type:

center (numpy.ndarray)

coilpy.get_figure(axes=None, **kwargs)[source]#

Check where to plot :param axes: matplotlib.pyplot axis, axis to plot (default: None) :param kwargs: keyword arguments

Returns:

f, ax f : matplotlib.pyplot figure ax : matplotlib.pyplot axis

coilpy.get_rotmat(rot)[source]#

Rotation matrix in the order of x,y,z

Parameters:

rot (list,(3,)) – Rotation angle around x,y,z-axis.

Returns:

The 3X3 rotation matrix.

Return type:

numpy.ndarray

coilpy.kwargs2dict(**kwargs)[source]#
coilpy.magtense2vtk(mags, vtk_file, **kwargs)[source]#

Export magtense.Tiles to VTK

Parameters:
  • mags (magtense.Tiles) – Magnet prisms in magtense.Tiles.

  • vtk_file (str) – VTK file name.

  • kwargs (optional) – keyword arguments passed to meshio.Mesh(), e.g. , cell_data={“m”:[m]}

Returns:

The constructed meshio.Mesh object.

Return type:

meshio.Mesh

coilpy.map_matrix(xx, first=True, second=True)[source]#

Map matrix to be complete (closed) :param xx – 2D numpy array: :param first – boolean: True, if increase the first dimension :param default: True, if increase the first dimension :param second – boolean: True, if increase the second dimension :param default: True, if increase the second dimension

Returns:

new – the new matrix with dimension increased

coilpy.muse2magntense(muse_file, mu=(1.05, 1.05), magnetization=1160000.0, **kwargs)[source]#
coilpy.poincare_plot(data, color=None, **kwargs)[source]#

Making poincare plot

Parameters:
  • data (array_like) – poincare data, shape is [nlines, niterations, 2].

  • color (matplotlib color, optional) – Color code. Defaults to None.

coilpy.print_progress(iteration, total, prefix='Progress', suffix='Complete', decimals=1, bar_length=60)[source]#

Create a terminal progress bar for iterative jobs.

Parameters:
  • iteration (int) – Current iteration index.

  • total (int) – Total number of iterations.

  • prefix (str, optional) – Prefix shown before the bar. Defaults to "Progress".

  • suffix (str, optional) – Suffix shown after the percentage. Defaults to "Complete".

  • decimals (int, optional) – Decimal places for the percentage display. Defaults to 1.

  • bar_length (int, optional) – Character width of the progress bar. Defaults to 60.

coilpy.read_focus_boundary(filename)[source]#

Read FOCUS/FAMUS plasma boundary file

Parameters:

filename (str) – File name and path.

Returns:

Dict contains the parsed data.

nfp : number of toroidal periods nfou : number of Fourier harmonics for describing the boundary nbn : number of Fourier harmonics for Bn surface : Toroidal surface dict, containing ‘xm’, ‘xn’, ‘rbc’, ‘rbs’, ‘zbc’, ‘zbs’ bnormal : Input Bn dict, containing ‘xm’, ‘xn’, ‘bnc’, ‘bns’

Return type:

boundary (dict)

coilpy.real2trig_2d(f, xm, xn, theta, zeta)[source]#

Fourier decomposition in 2D

Parameters:
  • f (numpy.ndarray) – The 2D function to be decomposed. Size: [npol, ntor].

  • xm (numpy.ndarray) – Poloildal mode number. Size: [mn,]

  • xn (numpy.ndarray) – Toroildal mode number. Size: [mn,]

  • theta (numpy.ndarray) – Poloidal angles. Size:[npol,].

  • zeta (numpy.ndarray) – Toroidal angles. Size:[ntor,]

Returns:

Cos harmonics, sin harmonics. Size: [mn,]

Return type:

numpy.ndarray, numpy.ndarray

coilpy.rotation_angle(R, xyz=False)[source]#

Get the rotation angle from a rotation matrix

Parameters:
  • R (3x3 matrix) – The rotation matrix.

  • xyz (bool, optional) – the rotation scenario, RxRyRz vs RzRyRx. Defaults to False.

Returns:

The rotation angle around x,y,z-axis (if xyz=True) or z,y,x-axis.

Return type:

[alpha, beta, gamma]

coilpy.rotation_matrix(alpha=0.0, beta=0.0, gamma=0.0, xyz=False)[source]#

A genera rotation matrix using yaw, pitch, and roll angles

Parameters:
  • alpha (float, optional) – The yaw angle (rotating around the z-axis). Defaults to 0.0.

  • beta (float, optional) – The pitch angle (rotating around the y-axis). Defaults to 0.0.

  • gamma (float, optional) – The roll angle (rotating around the x-axis). Defaults to 0.0.

  • xyz (bool, optional) – The rotation order, True: x->y->z; False: z->y->x. Defaults to False

Returns:

The rotation matrix.

Return type:

R (3x3 matrix)

coilpy.scan_focus(template, key, value, run=False)[source]#

Scan input variable of FOCUS

Parameters:
  • template (str) – A template input file such as *.input.

  • key (str) – the variable name that will be scanned.

  • value (list) – the loop that the scan is going to take.

  • run (bool, optional) – whether you want to run the scan immediately. Defaults to False.

coilpy.set_axes_equal(ax)[source]#

Make axes of 3D plot have equal scale so that spheres appear as spheres, cubes as cubes, etc.. This is one possible solution to Matplotlib’s ax.set_aspect(‘equal’) and ax.axis(‘equal’) not working for 3D.

Input

ax: a matplotlib axis, e.g., as output from plt.gca().

coilpy.toroidal_period(vec, nfp=1)[source]#

vec: [x,y,z] data Nfp: =1, toroidal number of periodicity

coilpy.tracing(bfield, r0, z0, phi0=0.0, niter=100, nfp=1, nstep=1, **kwargs)[source]#

Trace magnetic field line in toroidal geometry

Parameters:
  • bfield (callable) – A callable function. The calling signature is B = bfield(xyz), where xyz is the position in cartesian coordinates and B is the magnetic field at this point (in cartesian coordinates).

  • r0 (list) – Initial radial coordinates.

  • z0 (list) – Initial vertical coordinates.

  • phi0 (float, optional) – The toroidal angle where the poincare plot data saved. Defaults to 0.0.

  • niter (int, optional) – Number of toroidal periods in tracing. Defaults to 100.

  • nfp (int, optional) – Number of field periodicity. Defaults to 1.

  • nstep (int, optional) – Number of intermediate step for one period. Defaults to 1.

Returns:

The stored poincare date, shape is (len(r0), niter+1, 2).

Return type:

array_like

coilpy.trig2real(theta, zeta=None, xm=[], xn=[], fmnc=None, fmns=None)[source]#

Trigonometric coefficients to real space points

Parameters:
  • theta (numpy.ndarray) – Theta values to be evaluated.

  • zeta (numpy.ndarray, optional) – Zeta values to be evaluated if discretizing in 2D. Defaults to None.

  • xm (list, optional) – Poloidal Fourier modes. Defaults to [].

  • xn (list, optional) – Toroidal Fourier modes. Defaults to [].

  • fmnc ([type], optional) – Cosine Fourier coefficients Defaults to None.

  • fmns ([type], optional) – Sin Fourier coefficients. Defaults to None.

Returns:

The discretized values in real space.

Return type:

numpy.ndarray

coilpy.trigfft(y, tr=-1)[source]#

Calculate trigonometric coefficients using FFT.

The signal is assumed to have a periodicity of 2*pi.

Parameters:
  • y (array_like) – One-dimensional array for Fourier transformation.

  • tr (int, optional) – Truncation number. Defaults to -1.

Returns:

Fourier coefficients with the keys n, rcos, rsin, icos, and isin.

Return type:

dict

coilpy.trigfft2(y)[source]#

Calculate two-dimensional trigonometric coefficients using FFT.

The signal is assumed to have a periodicity of 2*pi in both directions.

Parameters:

y (array_like) – Two-dimensional array for Fourier transformation.

Returns:

Fourier coefficients with the keys n, m, rcos, rsin, icos, and isin.

Return type:

dict

coilpy.vmec2focus(vmec_file, focus_file='plasma.boundary', bnorm_file=None, ns=-1, curpol=1.0, flipsign=False)[source]#

Prepare FOCUS input boundary

Parameters:
  • vmec_file (str) – VMEC input or output filename.

  • focus_file (str, optional) – FOCUS boundary filename to be written. Defaults to ‘plasma.boundary’.

  • bnorm_file (str, optional) – BNORM output filename. Defaults to None.

  • ns (int, optional) – VMEC surface index. Defaults to -1.

  • curpol (float, optional) – Normalization factor related to poloidal current. Defaults to 1.0.

  • flipsign (bool, optional) – Bool value to flip the sign of Bn coefficients. Defaults to False.

coilpy.vmecMN(mpol, ntor)[source]#
coilpy.write_focus_boundary(filename, surf, nfp=1, bn=None, **kwargs)[source]#

Write the Fourier harmonics down in FOCUS format

Parameters:
  • filename (str) – File name to be saved.

  • surf (dict) – Plasma surface information, containing ‘xm’, ‘xn’, ‘rbc’, ‘rbs’, ‘zbc’, zbs’.

  • nfp (int, optional) – Number of field periodicity. Defaults to 1.

  • bn (dict, optional) – Nonzero Bn information, containing ‘xm’, ‘xn’, ‘bnc’, ‘bns’. Defaults to None.

coilpy.xy2rp(x, y)[source]#

Convert (x,y) to (R,phi) in polar coordinate

Parameters:
  • x (float) – x coordinate

  • y (float) – y coordinate

Returns:

radius phi (float): angle in rad

Return type:

R (float)