Visualization, tools

visu

visu contains 2D visualization functions.

pyGDM2.visu.structure(struct, projection='auto', color='auto', scale=1, borders=3, marker='s', lw=0.1, EACHN=1, tit='', colors_multimat=None, plot_legend=True, ax=None, absscale=False, show=True, **kwargs)

plot structure in 2d, projected to e.g. the XY plane

plot the structure struct as a scatter projection to a carthesian plane. Either from list of coordinates, or using a simulation definition as input.

kwargs are passed to matplotlib’s scatter

Parameters:
  • struct (list or core.simulation) – either list of 3d coordinate tuples or simulation description object

  • projection (str, default: 'auto') – which 2D projection to plot: “auto”, “XY”, “YZ”, “XZ”

  • color (str or matplotlib color, default: "auto") – Color of scatterplot. Either “auto”, or matplotlib-compatible color. “auto”: automatic color selection (multi-color for multiple materials).

  • scale (float, default: 1) – symbol scaling in units of half the stepsize

  • borders (float, default: 3) – additional space limits around plot in units of stepsize

  • marker (str, default "s" (=squares)) – scatter symbols for plotting meshpoints. Convention of matplotlib’s scatter

  • lw (float, default 0.1) – line width around scatter symbols. Convention of matplotlib’s scatter

  • EACHN (int, default: 1 (=all)) – show each EACHN points only

  • tit (str, default: "") – title for plot (optional)

  • colors_multimat (list, default: None) – optional list of colors (matplotlib compatible) to use for different materials

  • plot_legend (bool, default: True) – whether to add a legend if multi-material structure (requires auto-color enabled)

  • ax (matplotlib axes, default: None (=create new)) – axes object (matplotlib) to plot into

  • absscale (bool, default: False) – absolute or relative scaling. If True, override internal scaling calculation

  • show (bool, default: True) – directly show plot

Return type:

result returned by matplotlib’s scatter

pyGDM2.visu.structure_contour(struct, projection='auto', color='k', N_points=4, borders=3, lw=1, s=5, style='lines', input_mesh='auto', tit='', ax=None, add_first_point=True, show=True, **kwargs)

Contour around structure

further kwargs are passed to matplotlib’s scatter or plot

Parameters:
  • struct (list or core.simulation) – either list of 3d coordinate tuples or simulation description object

  • projection (str, default: 'auto') – which 2D projection to plot: “auto”, “XY”, “YZ”, “XZ”

  • color (str or matplotlib color, default: "b") – matplotlib-compatible color for scatter

  • N_points (int, default: 4) – number of additional points to calculate at each meshpoint-side (basically meant for style “dots”, default: 4)

  • borders (float, default: 3) – additional space limits around plot in units of stepsize

  • lw (float, default: 1) – linewidth as used by pyplot.plot (style=’lines’ only)

  • s (float, default: 5) – symbol scaling for scatterplot as used by pyplot.scatter (style=’dots’ only)

  • stlye (str, default: 'lines') – Style of plot. One of [“dots”, “lines”]

  • input_mesh (str, default: 'auto') – mesh type, default: “auto” (try to infer meshtype from geometry). one of [“auto”, “cube”, “hex”, “hex2”, “hex_onelayer1”, “hex_onelayer2”]

  • tit (str, default: "") – title for plot (optional)

  • ax (matplotlib axes, default: None (=create new)) – axes object (matplotlib) to plot into

  • add_first_point (bool, default: True) – If True, adds first point twice in order to close the contour. Might cause some strange lines if a single edge meshpoint is first in the geometry.

  • show (bool, default: True) – directly show plot

Returns:

contour plot object

Return type:

matplotlib’s scatter or line return value

vector fields

pyGDM2.visu.vectorfield(NF, struct=None, projection='auto', complex_part='real', tit='', slice_level=None, scale=10.0, vecwidth=1.0, cmap=<matplotlib.colors.LinearSegmentedColormap object>, cmin=0.3, ax=None, adjust_axis=True, show=True, borders=3, EACHN=1, sortL=True, overrideMaxL=False, **kwargs)

plot 2D Vector field as quiver plot

plot nearfield list as 2D vector plot, using matplotlib’s quiver. kwargs are passed to pyplot.quiver

Parameters:
  • NF (list of 3- or 6-tuples) – Nearfield definition. np.array, containing 6-tuples: (X,Y,Z, Ex,Ey,Ez), the field components being complex (use e.g. tools.get_field_as_list()). Optionally can also take a list of 3-tuples (Ex, Ey, Ez), in which case the structure must be provided via the struct kwarg.

  • struct (list or core.simulation, optional) – optional structure definition (necessary if field is supplied in 3-tuple form without coordinates). Either simulation description object, or list of (x,y,z) coordinate tuples

  • projection (str, default: 'auto') – Which 2D projection to plot: “auto”, “XY”, “YZ”, “XZ”

  • complex_part (str, default: 'real') – Which part of complex field to plot. Either ‘real’ or ‘imag’.

  • tit (str, default: "") – title for plot (optional)

  • slice_level (float, default: None) –

    optional value of depth where to slice. eg if projection==’XY’, slice_level=10 will take only values where Z==10.

    • slice_level = None, plot all vectors one above another without slicing.

    • slice_level = -9999 : take minimum value in field-list.

    • slice_level = 9999 : take maximum value in field-list.

  • scale (float, default: 10.0) – optional vector length scaling parameter

  • vecwidth (float, default: 1.0) – optional vector width scaling parameter

  • cmap (matplotlib colormap, default: cm.Blues) – matplotlib colormap to use for arrows (color scaling by vector length)

  • cmin (float, default: 0.3) – minimal color to use from cmap to avoid pure white

  • ax (matplotlib axes, default: None (=create new)) – optinal axes object (mpl) to plot into

  • adjust_axis (bool, default: True) – apply adjustments to axis (equal aspect, axis labels, plot-range)

  • show (bool, default: True) – whether or not to call pyplot.show

  • borders (float, default: 3) – additional space limits around plot in units of stepsize

  • EACHN (int, default: 1 [=all]) – show each N points only

  • sortL (bool, default: True) – sort vectors by length to avoid clipping (True: Plot longest vectors on top)

  • overrideMaxL (bool, default: False) – if True, use ‘scale’ as absolute scaling. Otherwise, normalize to field-vector amplitude.

Return type:

return value of matplotlib’s quiver

pyGDM2.visu.vectorfield_by_fieldindex(sim, field_index, which_field='E', **kwargs)

Wrapper to vectorfield(), using simulation object and fieldindex as input

All other keyword arguments are passed to vectorfield().

Parameters:
  • sim (simulation) – instance of core.simulation

  • field_index (int) – index of evaluated self-consistent field to use for calculation. Can be obtained for specific parameter-set using tools.get_closest_field_index()

  • which_field (str, default: "E") – “E” or “H”, for electric or magnetic field

pyGDM2.visu.vectorfield_fieldlines(NF, struct=None, projection='auto', tit='', complex_part='real', borders=0, NX=-1, NY=-1, show=True, **kwargs)

2d plot of fieldlines of field ‘NF’

other optional arguments passed to matplotlib’s pyplot.streamplot

Parameters:
  • NF (list of 3- or 6-tuples) – Nearfield definition. np.array, containing 6-tuples: (X,Y,Z, Ex,Ey,Ez), the field components being complex (use e.g. tools.get_field_as_list()). Optionally can also take a list of 3-tuples (Ex, Ey, Ez), in which case the structure must be provided via the struct kwarg.

  • struct (list or core.simulation, optional) – optional structure definition (necessary if field is supplied in 3-tuple form without coordinates). Either simulation description object, or list of (x,y,z) coordinate tuples

  • projection (str, default: 'XY') – Which projection to plot: “XY”, “YZ”, “XZ”

  • complex_part (str, default: 'real') – Which part of complex field to plot. Either ‘real’ or ‘imag’.

  • tit (str, default: "") – title for plot (optional)

  • borders (float, default: 0) – additional space limits around plot in units of stepsize

  • NX (int, int, defaults: -1, -1) – optional interpolation steps for nearfield. by default take number of independent positions in NF (if NX or NY == -1)

  • NY (int, int, defaults: -1, -1) – optional interpolation steps for nearfield. by default take number of independent positions in NF (if NX or NY == -1)

  • show (bool, default: True) – whether or not to call pyplot.show

Returns:

return matplotlib streamplot object

Return type:

if show == False

scalar fields

pyGDM2.visu.vectorfield_color(NF, struct=None, projection='auto', complex_part='real', tit='', ax=None, slice_level=-9999, NX=None, NY=None, fieldComp='I', borders=0, clim=None, grid_interpolation='linear', show=True, return_map_array=False, **kwargs)

plot of 2D field data as colorplot

other kwargs are passed to matplotlib’s imshow

Parameters:
  • NF (list of 3- or 6-tuples) – Nearfield definition. np.array, containing 6-tuples: (X,Y,Z, Ex,Ey,Ez), the field components being complex (use e.g. tools.get_field_as_list()). Optionally can also take a list of 3-tuples (Ex, Ey, Ez), in which case the structure must be provided via the struct kwarg.

  • struct (list or core.simulation, optional) – optional structure definition (necessary if field is supplied in 3-tuple form without coordinates). Either simulation description object, or list of (x,y,z) coordinate tuples

  • projection (str, default: 'auto') – which 2D projection to plot: “auto”, “XY”, “YZ”, “XZ”

  • complex_part (str, default: 'real') – Which part of complex field to plot. Either ‘real’ or ‘imag’.

  • tit (str, default: "") – title for plot (optional)

  • ax (matplotlib axes, default: None (=create new)) – optinal axes object (mpl) to plot into

  • slice_level (float, default: None) –

    optional value of depth where to slice. eg if projection==’XY’, slice_level=10 will take only values where Z==10.

    • slice_level = None, plot all vectors one above another without slicing.

    • slice_level = -9999 : take minimum value in field-list.

    • slice_level = 9999 : take maximum value in field-list.

  • NX (int, int, defaults: None, None) – optional interpolation steps for nearfield. by default take number of independent positions in NF (if NX or NY == None)

  • NY (int, int, defaults: None, None) – optional interpolation steps for nearfield. by default take number of independent positions in NF (if NX or NY == None)

  • fieldComp (str, default: 'I') – Which component to use. One of [“I”, “abs”, “Ex”, “Ey”, “Ez”]. If one of “I” or “abs” is used, complex_part argument has no effect.

  • borders (float, default: 0) – additional space in nm to plotting borders

  • cmap (matplotlib colormap, default: "seismic") – matplotlib colormap to use for colorplot

  • clim (float, default: None) – optional colormap limits to pass to plt.clim()

  • grid_interpolation (str, default: 'linear') – interpolation method for scipy grid_data. Can be ‘linear’ or ‘nearest’. See scipy.interpolate.griddata for details

  • return_map_array (bool, default: False) – if true, returns tuyple (im, arr). im is matplotlib object, arr the data-array generated for plt.imshow

  • show (bool, default: True) – whether or not to call pyplot.show

Return type:

result of matplotlib’s imshow and optionally the 2D ploted data as numpy array

pyGDM2.visu.vectorfield_color_by_fieldindex(sim, field_index, which_field='E', grid_interpolation='nearest', **kwargs)

Wrapper to vectorfield_color(), using simulation object and fieldindex as input

All other keyword arguments are passed to vectorfield_color().

Parameters:
  • sim (simulation) – instance of core.simulation

  • field_index (int) – index of evaluated self-consistent field to use for calculation. Can be obtained for specific parameter-set using tools.get_closest_field_index()

  • grid_interpolation (str, default: 'nearest') – interpolation method for scipy grid_data. Can be ‘linear’ or ‘nearest’. See scipy.interpolate.griddata for details

  • which_field (str, default: "E") – “E” or “H”, for electric or magnetic field

pyGDM2.visu.scalarfield(NF, **kwargs)

Wrapper to vectorfield_color(), using scalar data tuples (x,y,z,S) as input

All other keyword arguments are passed to vectorfield_color().

Parameters:

NF (list of 4-tuples) – list of tuples (x,y,z,S). Alternatively, the scalar-field can be passed as list of 2 lists containing the x/y positions and scalar values, respectively. ([xy-values, S], with xy-values: list of 2-tuples [x,y]; S: list of scalars). This format is returned e.g. by tools.calculate_rasterscan().

pyGDM2.visu.farfield_pattern_2D(theta, phi, I, degrees=True, show=True, ax=None, **kwargs)

Plot BFP-like 2D far-field radiation pattern

Plot a “back-focal plane”-like radiation pattern. All arrays are of shape (Nteta, Nphi)

kwargs are passed to matplotlib’s pyplot.pcolormesh.

Parameters:
  • tetalist (2D-numpy.ndarray, float) – teta angles

  • philist (2D-numpy.ndarray, float) – phi angles

  • Iff (2D-numpy.ndarray, float) – Intensities at (teta, phi) positions

  • degrees (bool, default: True) – Transform polar angle to degrees for plotting (False: radians)

  • ax (matplotlib axes, default: None (=create new)) – optinal axes object (mpl) to plot into

  • show (bool, default: True) – whether to call pyplot.show()

Return type:

result of matplotlib’s pyplot.pcolormesh

animate_vectorfield

pyGDM2.visu.animate_vectorfield(NF, struct=None, Nframes=50, projection='auto', doQuiver=True, doColor=False, alphaColor=1.0, scale=5.0, clim=None, kwargs={'cmin': 0.3}, kwargsColor={'fieldComp': 'Ex'}, ax=None, t_start=0, frame_list=None, show=True)

Create animation of oszillating complex nearfield (2D-Projection)

Parameters:
  • NF (list of 3- or 6-tuples) – Nearfield definition. np.array, containing 6-tuples: (X,Y,Z, Ex,Ey,Ez), the field components being complex (use e.g. tools.get_field_as_list()). Optionally can also take a list of 3-tuples (Ex, Ey, Ez), in which case the structure must be provided via the struct kwarg.

  • struct (list or core.simulation, optional) – optional structure definition (necessary if field is supplied in 3-tuple form without coordinates). Either simulation description object, or list of (x,y,z) coordinate tuples

  • Nframes (int, default: 50) – number of frames per oscillation cycle

  • projection (str, default: 'auto') – which 2D projection to plot: “auto”, “XY”, “YZ”, “XZ”

  • doQuiver (bool, default: True) – plot field as quiverplot.

  • doColor (bool, default: True) – plot field as colorplot (real part)

  • alphaColor (float, default: 0.5) – alpha value of colormap

  • kwargs (dict, default: {}) – are passed to vectorfield() (if doQuiver)

  • kwargsColor (dict, default: {}) – are passed to vectorfield_color() (if doColor)

  • ax (optional matplotlib axes, default: None) – optional axes object (mpl) to plot into

  • t_start (int, default: 0) – time-step to start animation at (=frame number)

  • frame_list (list, default: None) – optional list of frame indices to use for animation. Can be used to animate only a part of the time-harmonic cycle.

  • show (bool, default: True) – directly show animation

Returns:

im_ani

Return type:

Animation as matplotlib “ArtistAnimation” object

Notes

You can save the animation as video-file using: im_ani.save(‘video.mp4’, writer=”ffmpeg”, codec=’h264’, bitrate=1500). See also matplotlib’s documentation of the animation module for more info.

visu3d

visu3d contains 3D visualization functions based on mayavi.mlab. The API is mostly sytnax-compatible to the visu module.

pyGDM2.visu3d.structure(struct, scale=0.75, abs_scale=False, tit='', color='auto', colorlist=None, mode='cube', draw_substrate=True, substrate_size=2.0, substrate_color=(0.8, 0.8, 0.9), substrate_opacity=0.5, axis_labels=True, material_labels=False, show=True, **kwargs)

plot structure in 3d

plot the structure “struct” using 3d points. Either from list of coordinates, or using a simulation definition dict as input.

Parameters:
  • struct (-) –

  • scale (-) –

  • abs_scale (-) –

  • color (-) –

  • colorlist (-) –

  • mode (-) –

  • draw_substrate (-) –

  • substrate_size (-) –

  • substrate_color (-) –

  • substrate_opacity (-) –

  • axis_labels (-) –

  • material_labels (-) –

  • show (-) –

  • kwargs (-) –

vector fields

pyGDM2.visu3d.vectorfield(NF, struct=None, scale=1.5, abs_scale=False, tit='', complex_part='real', clim=[0.0, 1.0], axis_labels=True, show=True, **kwargs)

3d quiverplot of nearfield

Parameters:
  • NF (-) – (X,Y,Z, Ex,Ey,Ez), the field components being complex.

  • struct (-) – form without coordinates). Either simulation object, or list of coordinate (x,y,z) tuples

  • scale (-) –

  • abs_scale (-) –

  • complex_part (-) – Either ‘real’ or ‘imag’. (default: ‘real’)

  • axis_labels (-) –

  • show (-) –

All other keyword arguments are passed to mlab’s quiver3d.

pyGDM2.visu3d.vectorfield_by_fieldindex(sim, field_index, which_field='E', **kwargs)

Wrapper to vectorfield(), using simulation object and fieldindex as input

Parameters:
  • sim (simulation) – instance of core.simulation

  • field_index (int) – index of evaluated self-consistent field to use for calculation. Can be obtained for specific parameter-set using tools.get_closest_field_index()

  • which_field (str, default: "E") – “E” or “H”, for electric or magnetic field

:param All other keyword arguments are passed to vectorfield().:

scalar fields

pyGDM2.visu3d.vectorfield_color(NF, complex_part='real', fieldComp='I', scale=0.5, abs_scale=False, mode='sphere', tit='', axis_labels=True, show=True, **kwargs)

plot of scalar electric field data as 3D colorplot

vectorfield_color is using mlab.quiver3d to plot colored data-points in order to be able to fix the size of the points while varying the color-code

Parameters:
  • NF (-) – (X,Y,Z, Ex,Ey,Ez), the field components being complex.

  • complex_part (-) – (default ‘real’)

  • fieldComp (-) – if “I”or “abs” is used, complex_part argument has no effect.

  • scale (-) –

  • abs_scale (-) –

  • mode (-) –

  • tit (-) –

  • axis_labels (-) –

  • show (-) –

other kwargs are passed to mlabs’s quiver3d

pyGDM2.visu3d.vectorfield_color_by_fieldindex(sim, field_index, which_field='E', **kwargs)

Wrapper to vectorfield_color(), using simulation object and fieldindex as input

Parameters:
  • sim (simulation) – instance of core.simulation

  • field_index (int) – index of evaluated self-consistent field to use for calculation. Can be obtained for specific parameter-set using tools.get_closest_field_index()

  • which_field (str, default: "E") – “E” or “H”, for electric or magnetic field

:param All other keyword arguments are passed to vectorfield_color().:

pyGDM2.visu3d.scalarfield(NF, **kwargs)

Wrapper to vectorfield_color(), using scalar data tuples (x,y,z,S) as input

Parameters:

NF (list of 4-tuples) – list of tuples (x,y,z,S). Alternatively, the scalar-field can be passed as list of 2 lists containing the x/y positions and scalar values, respectively. ([xy-values, S], with xy-values: list of 2-tuples [x,y]; S: list of scalars). This format is returned e.g. by tools.calculate_rasterscan().

:param All other keyword arguments are passed to vectorfield_color().:

animate_vectorfield

pyGDM2.visu3d.animate_vectorfield(NF, Nframes=50, show=True, scale=1.5, abs_scale=False, draw_struct=False, draw_substrate=True, substrate_size=2.0, clim=[0.0, 1.0], figsize=(600, 400), save_anim=False, fig=None, view=[45, 45], rotate_azimuth=0, rotate_elevation=0, ffmpeg_args='', mov_file='pygdm_animated_field.mp4', tmp_file_prefix='_img_pygdmanim_tmp', delete_pngs=True, save_cycles=1, t_start=0, frame_list=None, **kwargs)

animate vector-field in 3d

animate the time-harmonic vectors of an electromagnetic field

Parameters:
  • NF (list of 4-tuples) – list of tuples (x,y,z,S). Alternatively, the scalar-field can be passed as list of 2 lists containing the x/y positions and scalar values, respectively. ([xy-values, S], with xy-values: list of 2-tuples [x,y]; S: list of scalars). This format is returned e.g. by tools.calculate_rasterscan().

  • Nframes

scalefloat, default: 1.5

vector scaling in units of stepsize

abs_scalebool, default: False

enable absolute scaling, override internal scale calculation

draw_structbool, default: False

whether to draw the structure, assuming that every point in ‘NF’ is a geometry meshpoint

draw_substratebool, default: True

whether to draw a sketch of a substrate

substrate_sizefloat, default: 2.0

size of substrate, if drawn. Factor relative to structure extension

clim2 element list, default: [0.0, 1.0]

range to use from colormap

figsize2-tuple, default: (600, 400)

plot size in pixels (X,Y)

save_animbool, default: False

whether to save a video-file of animation (requires the program ‘ffmpeg’)

fig(optional) mlab figure, default: None

optional mayavi2 “mlab” figure, which can already contain other plotted elements

viewtuple, default (45, 45)

view perspective, passed to mlab.view(): (azimuth, elevation, distance, [r_x,r_y,r_z])

rotate_azimuth, rotate_elevationint, int, default: 0, 0

optional total rotation angle of camera during animation. Camera will rotate from initial angle alpha_0 to alpha_0 + rotate_angle. Should be used together with save_cycles>1.

ffmpeg_argsstr, default: “-b:v 1.5M -c:v libx264”

string of command line arguments passed to ‘ffmpeg’ (if save_anim == True)

mov_filestr, default: “pygdm_animated_field.mp4”

movie file to save animation (if save_anim == True)

tmp_file_prefixstr, default: ‘_img_pygdmanim_tmp’

tmp-file prefix for movie-saving. Will be deleted after encoding of the movie.

delete_pngsbool, default: True

If True, delete temporary pngs after movie creation

save_cyclesint, default: 1

number of harmonic field cycles to do for animation until restart. Useful if camera is slowly rotated during animation.

t_startint, default: 0

time-step to start animation at (=frame number)

frame_listlist, default: None

optional list of frame indices to use for animation. Can be used to animate only a part of the time-harmonic cycle.

**kwargs :

other keyword arguments are passed to mlab.quiver3d()

Return type:

None

tools

tools contains data-processing tools and helper functions

Save / Load / Print info

pyGDM2.tools.save_simulation(sim, fname, mode='h5', tables_filter_kwargs={'complevel': 5, 'complib': 'blosc'}, pickle_protocol=None)

Save simulation object to file using pickle and hdf5 via tables

The electric fields are stored using hdf5 (via tables), the rest via pickle. If not tables module available, everything will be stored via pickle. This behavior can be forced with the mode parameter.

Parameters:
  • sim (simulation) – simulation description

  • fname (str) – filename to save sim to

  • mode (str, default: "hdf5") – which method to use to store data. Either “pickle” or “hd5f” (“h5”==”hd5f”)

  • tables_filter_kwargs (dict, default: {'complib':'blosc', 'complevel':5}) – filter kwargs, passed to tables.Filters if using the “hdf5” mode

  • pickle_protocol (int, default: None) – override default pickle protocol level. “2” is compatible with python2 and 3.

pyGDM2.tools.load_simulation(fname, pickle_encoding=None)

Load simulation from file using pickle

Try loading hdf5 first, if no hdf5 file or no tables module available, fallback to pickle.

Parameters:
  • fname (str) – filename to load sim from

  • pickle_encoding (str, default: None) – for python 2/3 intercompatibility. Use “latin1” to load data saved in python2 from python3

Return type:

instance of core.simulation

pyGDM2.tools.print_sim_info(sim, prnt=True, verbose=False)

print simulation info from simdict

Parameters:
  • sim (simulation) – simulation description

  • prnt (bool, default: True) – If True, print to sdtout. If False, return string

  • verbose (bool, default: False) – if True, print more details like exhaustive incident field parameter list

Notes

print_sim_info() is implemented as its __repr__ attribute in core.simulation. This means

>>> print sim

and

>>> print_sim_info(sim)

will result in identical output

Field-index searching

pyGDM2.tools.get_field_indices(sim)

List all field-configurations including wavelength sorted by field-index

Parameters:

sim (simulation) – simulation description

Returns:

list of kwargs-dict containing field-config parameters. list in the order of the “field_index” convention.

Return type:

list of dict

pyGDM2.tools.get_closest_field_index(sim, search_kwargs)

Find closest calculated scattered field matching to search parameters

Parameters:
  • sim (simulation) – simulation description

  • search_kwargs (dict) – searched kwargs for incident field

Returns:

index – index of field which matches closest search incident field parameters

Return type:

int

Structure geometry tools

pyGDM2.tools.test_geometry(struct, step=None, delete_duplicates_first=True, plotting='fail', return_index=False, verbose=1)

return coordinate lists X,Y,Z either from list of tuples or simulation object

requires scipy

Parameters:
  • struct (list of tuple or core.simulation or structures.struct) – list of coordinate tuples or instance of core.simulation or instance of structures.struct

  • step (float, default: None) – Test if structure is consistent with the given step-size. If None, determine step from geomerty. However, step should normally be given by the user. The test is likely to be false positive if step is set None.

  • delete_duplicates_first (bool, default: True) – delete duplicates, then

  • plotting (bool or str, default: 'fail') – plot consistent and inconsistent parts of structure. Either True, False or “fail”. If “fail” (default), plot only in case of insconsistent structure.

  • return_index (bool, default: False) – if True, returns also ist of indices that compose the “correct” geometry

  • verbose (int, default: 1) – verbose level for info printing. verbose = 2 prints additional info

Returns:

geo_correct, geo_wrong

Return type:

two numpy arrays of (x,y,z) tuples

pyGDM2.tools.get_geometry(struct, return_type='lists')

return coordinate lists X,Y,Z either from list of tuples or simulation object

Parameters:
  • struct (list of tuple or core.simulation or structures.struct) – list of coordinate tuples or instance of core.simulation or instance of structures.struct

  • projection (str, default: "XY") – 2D plane for projection. One of [‘XY’, ‘XZ’, ‘YZ’]

  • return_type (str, default: 'lists') –

    either ‘lists’ or ‘tuples’
    • ’tuples’ : return list of (X,Y,Z)-tuples

    • ’lists’ : return 3 lists with X, Y and Z values

Returns:

  • if return_type == ‘lists’ – np.array containing 3 np.arrays with the X, Y and Z coordinates

  • if return_type == ‘tuples’ – list of 3-tuples : (x,y,z) coordinates of geometry

pyGDM2.tools.get_step_from_geometry(struct, max_meshpoints=1000)

Calculate step from coordinate list defining a nano-object

Will return closest distance occuring between two meshpoints. Uses scipy.spatial.distance.

Parameters:
  • struct (list of tuples or core.simulation) –

  • max_meshpoints (int, default: 1000) – maximum number of meshpoints to consider for step-calculation if using scipy.spatial.distance. (for computational speed at large structures)

Returns:

step – stepsize between mesh-points

Return type:

float

pyGDM2.tools.get_mesh_from_geometry(geo, N_try=20, warn=True, verbose=0)

Try to identify the mesh type from the dipole positions

If meshpoint determination fails, falling back to cube

Parameters:
  • geo (list of tuples or core.simulation) – list of meshpoints to determine grid-type

  • N_try (int, default: 20) – maximum number of random evaluation point tries in order to find a “bulk” meshpoint.

  • warn (bool, default: True) – show warnings if detection fails

  • verbose (int, default: 0) – if 1, print runtime info

Returns:

mesh – mesh type (‘cube’ or ‘hex’)

Return type:

str

pyGDM2.tools.get_geometry_2d_projection(struct, projection='XY')

return the geometry projection onto a 2D-plane

Parameters:
  • struct (list of tuples or core.simulation) –

  • projection (str, default: "XY") – 2D plane for projection. One of [‘XY’, ‘XZ’, ‘YZ’]

Returns:

list of 3-tuples

Return type:

(x,y,z) coordinates of 2D-projection (third coordinate set to zero)

pyGDM2.tools.get_geometric_cross_section(struct, projection='XY', step=None)

return the geometrical cross-section (=’footprint’) of struct in nm

Parameters:
  • struct (list of tuples or core.simulation) –

  • projection (str, default: "XY") – 2D plane for projection. One of [‘XY’, ‘XZ’, ‘YZ’]

  • step (float, default: None) – optional pass step-size. If None, calculate it from geometry (may be slower)

Returns:

float

Return type:

geometric cross section of structure projection in nm^2

pyGDM2.tools.get_surface_meshpoints(struct, NN_bulk=6, max_bound=1.2, NN_surface=-1, max_bound_sf=5.0, return_sfvec_all_points=False)

get surface elements and normal surface vectors of structure

Calculate normal vectors using next-neighbor counting.

To use outmost surface layer only, parameters are:
  • 2D: NN_bulk=4, max_bound=1.1

  • 3D: NN_bulk=6, max_bound=1.1

Parameters:
  • struct (-) – list of tuples or instance of core.simulation

  • NN_bulk (-) – Number of Next neighbors of a bulk lattice point

  • max_bound (-) – Max. distance in step-units to search for next neighbors

  • NN_surface (-) – different number of neighbours to consider for normal surfacevectors

  • max_bound_sf (-) – different calculation range for normal surfacevectors. By default, use search radius of up to 5 steps. If a large number of neighbours should be considered for vector calculation, it might be necessary to increased this limit, which might however slow down the KD-tree queries.

  • return_sfvec_all_points (-) – if True, return vector list for all meshpoints, with zero length if bulk

Returns:

  • - SF (list of surface meshpoint coordinates)

  • - SF_vec (list of normal surface vectors)

Spectra tools

pyGDM2.tools.get_possible_field_params_spectra(sim)

Return all possible field-parameter permutations for spectra

Parameters:

sim (simulation) – simulation description

Returns:

params – list of all possible parameter-permutation at each wavelength

Return type:

list of dict

pyGDM2.tools.calculate_spectrum(sim, field_kwargs, func, verbose=False, callback=None, N_cpu=1, **kwargs)

calculate spectra using function func

Parameters:
  • sim (simulation) – simulation description

  • field_kwargs (dict or int) – dict of field-configuration to use from simulation. If an int is given, it is used as field-index (use e.g. get_closest_field_index())

  • func (function) – evaluation function, which will be called as: func(sim, field_index, **kwargs)

  • callback (func, default: None) – only has effect in sequential mode (`N_cpu=1`) optional callback function, which is called after each wavelength. Passes a dict to callback containing current wavelength, so far calculated spectrum and timing info.

  • N_cpu (int, default: 1) – optional number of parallel tasks to use for function evaluation. ‘-1’: use number of available CPUs

  • **kwargs – all other keyword args are passed to func

Returns:

  • np.array (wavelengths)

  • np.array (results of func for each wavelength)

Raster-scan tools

pyGDM2.tools.get_possible_field_params_rasterscan(sim, key_x_pos='xSpot', key_y_pos='ySpot')

Return all possible field-parameter permutations for raster-scan simulations

Parameters:
  • sim (simulation) – simulation description

  • key_x_pos (str, default: ‘xSpot’) – parameter-name defining the rasterscan beam/illumination x-position

  • key_y_pos (str, default: ‘ySpot’) – parameter-name defining the rasterscan beam/illumination y-position

Returns:

paramslist of dict for all possible parameter-permutation, defining rasterscan map

Return type:

list of dict

pyGDM2.tools.get_rasterscan_fields(sim, search_kwargs, key_x_pos='xSpot', key_y_pos='ySpot')

Return list of all field-parameter sets for a raster-scan

Parameters:
  • sim (simulation) – simulation description

  • search_kwargs (dict) – searched kwargs for incident field

  • key_x_pos (str, default: 'xSpot') – parameter-name defining the rasterscan beam/illumination x-position

  • key_y_pos (str, default: 'ySpot') – parameter-name defining the rasterscan beam/illumination y-position

Returns:

NF_rasterscan – Each element corresponds to the simulated E-field inside the particle at a scan position: [field_param_dict, NF] - field_param_dict is the dict with the field-generator parameters - NF is the nearfield, as list of complex 3-tuples (Ex_i, Ey_i, Ez_i)

Return type:

list of lists

pyGDM2.tools.get_rasterscan_field_indices(sim, search_kwargs, key_x_pos='xSpot', key_y_pos='ySpot')

Return list of all field-parameter-indices corresponding to a raster-scan

Parameters:
  • sim (simulation) – simulation description

  • search_kwargs (dict) – searched kwargs for incident field

  • key_x_pos (str, default: 'xSpot') – parameter-name defining the rasterscan beam/illumination x-position

  • key_y_pos (str, default: 'ySpot') – parameter-name defining the rasterscan beam/illumination y-position

Returns:

NF_rasterscan_indices – index of field which matches closest search incident field parameters

Return type:

list of int

pyGDM2.tools.calculate_rasterscan(sim, field_kwargs, func, key_x_pos='xSpot', key_y_pos='ySpot', verbose=False, callback=None, **kwargs)

calculate rasterscan using function func

Parameters:
  • sim (simulation) – simulation description

  • field_kwargs (dict or int) – dict of field-configuration to use from simulation. If an int is given, it is used as index on results of get_possible_field_params_rasterscan()

  • func (function) – evaluation function, which will be called as: func(sim, field_index, **kwargs)

  • key_x_pos (str, default: 'xSpot') – parameter-name defining the rasterscan beam/illumination x-position

  • key_y_pos (str, default: 'ySpot') – parameter-name defining the rasterscan beam/illumination y-position

  • verbose (bool, default: False) – print some runtime info

  • callback (func, default: None) – optional callback function, which is called after each wavelength. Passes a dict to callback containing current wavelength, so far calculated data and timing info.

  • **kwargs – all other keyword args are passed to func

Returns:

  • list of tuples (x,y) – positions of raster-scan evaluation

  • list of float or tuple (S) – S is the scalar (or tuple) returned by func

Coordinate-list transformations

pyGDM2.tools.list_to_grid(arr, S=None, NX=None, NY=None, interpolation='nearest', fill_value=nan, **kwargs)

List of X/Y/Z tuples to 2D x/y Grid with z as intensity value

Parameters:
  • arr (np.array) – array of either (X,Y) or (X,Y,Z) tuples

  • S (np.array (optional, default: None)) – if arr is list of (x,y)-tuples, S is a list containing the scalar Z-values corresponding to each (x,y)-coordinate.

  • NX (int, optional) –

    number of points in X/Y direction for interpolation
    default: Number of unique occuring x/y elements

    (using np.unique)

  • NY (int, optional) –

    number of points in X/Y direction for interpolation
    default: Number of unique occuring x/y elements

    (using np.unique)

  • interpolation (str, default: 'nearest') – interpolation method for grid, passed to scipy.griddata

  • scipy.interpolate.griddata (**kwargs are passed to) –

Returns:

  • Z (np.array, dim=2) – Z on X/Y plane (linear X/Y ranges)

  • extent (tuple) – X/Y extent of array Z: (Xmin,Xmax, Ymin,Ymax)

pyGDM2.tools.grid_to_list(arr2d, extent=None, add_z=False)

create list of X/Y/S tuples from 2D map data

Parameters:
  • arr2d (2D np.array) – 2D data array of shape (Nx, Ny)

  • extent (4-tuple, default: None) – X / Y limits of array as tuple (x0, x1, y0, y1). If None, uses integer steps between 0 and Nx, Ny.

  • add_z (bool, default: False) – if true, returns (x,y,z,S) tuples, with z=0

Returns:

scalarfield – list of (x,y,S) values, where S are the values of the original 2D map arr2d

Return type:

np.array

pyGDM2.tools.get_field_as_list_by_fieldindex(sim, field_index, which_field='E', full_volume=False, fill_value='nan')

return internal fields in structure as list of (x,y,z,Ex,Ey,Ez) tuples

Parameters:
  • sim (simulation) – simulation description

  • field_index (int) – field-index corresponding to the incident field configuration

  • which_field (str, default: "E") – “E” or “H”, for electric or magnetic field

  • full_volume (bool, default: False) – if True, returns the field in the entire cuboidal volume which contains the structure, but the field is set to zero outside the structure.

  • fill_value (str, default: 'nan') – if full_volume, value to fill outside of structure. Either “zero” or “nan”

Returns:

fieldlist – geometry and field in one list: [(x,y,z, Ex,Ey,Ez), (…), …]

Return type:

list of 6-tuples

pyGDM2.tools.get_field_as_3D_array(sim, field_index, which_field='e', minX=0, minY=0, minZ=0, fill_surrounding=False, fill_field_outside='zero', wl=None, verbose=False)

convert coordinate-lists (geometry and fields) to 3D representations

Note: Geometry x and y coordinates must be on a cubic grid of even multiples of “step”

Parameters:
  • sim (simulation) – simulation description

  • field_index (int) – field-index corresponding to the incident field configuration

  • which_field (str, default: "E") – “E” or “H”, for electric or magnetic field

  • minX (int, default: 0) – minimum extension of 3d array in x/y/z direction

  • minY (int, default: 0) – minimum extension of 3d array in x/y/z direction

  • minZ (int, default: 0) – minimum extension of 3d array in x/y/z direction

  • fill_field_outside (str, default: 'zero') – either “zero” or “none” / “nan”

  • wl (float, default: None) – as alternative to ‘field_index’, wavelength to evaluate material dispersion of structure. field_index must be set None if wl is used.

  • verbose (bool, default: False) – print runtime info

Returns:

  • voxels: 3D binary np-array. 1=structure, 2=no structure

  • voxels_eps: 3D complex np-array with permittivity at each geometry-position. =0 at all other positions.

  • voxels_field: 3D complex np-array. Ex, Ey, Ez at each position

Return type:

voxels, voxels_eps, voxels_field

pyGDM2.tools.adapt_map_to_structure_mesh(mapping, structure, projection=None, min_dist=1.1, occupy_all_geo_positions=False, verbose=False)

changes the positions of mapping coordinates close to structure meshpoints

All coordinates closer than a minimum (e.g. the stepsize) to a meshpoint of the nanostructure are replaced by the position of the closest meshpoint. Optionally all meshpoint positions can be added to the mapping.

Parameters:
  • mapping (list of 3-tuples) – list containing the mapping coordinates.

  • structure (list of coordinate 3-tuples or core.simulation) – instance of object containing the mapping information. Accepts list of coordinate tuples or instance of core.simulation

  • projection (str, default: None) – consider some geometric projection. possible values: [‘XY’, ‘XZ’, ‘YZ’, None] if None: use closest meshpoint no matter which direction in space. If one of the strings, only consider meshpoints in the same plane as the mapping coordinates.

  • min_dist (float, default: 1.5) – minimum distance to meshpoints in units of stepsize

  • occupy_all_geo_positions (bool, default: False) – if true and a planar mapping or a specific projection is chosen, all positions in the geometry-mesh plane closest to the scan-height will be added to the new mapping as well.

  • verbose (bool, default: False) – print timing info

Returns:

coords – mapping with positions close to / inside the structure replaced by the nearest mesh-point coordinates

Return type:

list of 3-tuples

pyGDM2.tools.get_intensity_from_fieldlist(NF_list)

calculate intensity values from complex fields in field-vector-list

Parameters:
  • NF (list of 6-tuples, complex) – field as returned e.g. from linear.nearfield()

  • struct (list of tuples, float) – geometry of nano-object, as returned by structure generated in module structures

Returns:

fieldlist – list of tuples containing coordinates and field-intensity: [(x,y,z, I), (…), …]

Return type:

list of 4-tuples

pyGDM2.tools.get_field_as_list(NF, struct)

convert field NF and geometry struct to a list of coordinate/field tuples

Note, that usually it is easier to use get_field_as_list_by_fieldindex() instead.

Parameters:
  • NF (list of 3-tuples, complex) – field as returned e.g. from core.scatter()

  • struct (list of tuples, float) – geometry of nano-object, as returned by structure generated in module structures

Returns:

fieldlist – geometry and field in one list: [(x,y,z, Ex,Ey,Ez), (…), …]

Return type:

list of 6-tuples

pyGDM2.tools.unique_rows(a)

delete all duplicates with same x/y coordinates

Parameters:

a (list of tuples) – list of (x,y) or (x,y,z) coordinates with partially redunant (x,y) values.

Returns:

  • list of tuples in which all multiple tuples with equal first and second value

  • (x,y coordinates) are removed.

  • If 3-D data (Z-coordinate (3rd column) is replaced by 0.)

pyGDM2.tools.unique_rows_3D(a)

delete all duplicates with same x/y/z coordinates

Parameters:

a (list of tuples) – list of (x,y,z) coordinates with partially redunant (x,y) values.

Returns:

  • list of tuples in which all multiple tuples with equal (x,y,z) coordinates

  • are removed.

2D-mapping coordinate generators

pyGDM2.tools.generate_NF_map(X0, X1, NX, Y0, Y1, NY, Z0=0, projection='XY', dtype='f')

Generate coordinate list with equidistant positions on a rectangular map

e.g. for nearfield calcuation on this map

Parameters:
  • X0 (-) – X-Limits for Map

  • X1 (float, float) – X-Limits for Map

  • NX (-) – Nr of discretization pts in first projection direction

  • Y0 (-) – Y-Limits for Map

  • Y1 (float, float) – Y-Limits for Map

  • NY (-) – Nr of discretization pts in second projection direction

  • Z0 (-) – Z-Height of map

  • projection (-) – projection of map. must be one of [‘XY’,’XZ’,’YZ’], default: ‘XY’

  • dtype (-) – dtype of coordinates. passed to np.asfortranarray. e.g. “f” (single) or “d” (double). default: “f”

Returns:

list of 3 lists of X, Y, Z coordinates, to use e.g. in linear.nearfield()

Return type:

list of lists

pyGDM2.tools.generate_NF_map_XY(X0, X1, NX, Y0, Y1, NY, Z0=0, dtype=None)

Generate coordinate list with equidistant positions on a rectangular map in XY plane

see generate_NF_map() for doc.

pyGDM2.tools.generate_NF_map_XZ(X0, X1, NX, Z0, Z1, NZ, Y0=0, dtype=None)

Generate coordinate list with equidistant positions on a rectangular map in XZ plane

see generate_NF_map() for doc.

pyGDM2.tools.generate_NF_map_YZ(Y0, Y1, NY, Z0, Z1, NZ, X0=0, dtype=None)

Generate coordinate list with equidistant positions on a rectangular map in XZ plane

see generate_NF_map() for doc.

Other

pyGDM2.tools.get_intensity_from_fieldlist(NF_list)

calculate intensity values from complex fields in field-vector-list

Parameters:
  • NF (list of 6-tuples, complex) – field as returned e.g. from linear.nearfield()

  • struct (list of tuples, float) – geometry of nano-object, as returned by structure generated in module structures

Returns:

fieldlist – list of tuples containing coordinates and field-intensity: [(x,y,z, I), (…), …]

Return type:

list of 4-tuples

pyGDM2.tools.split_simulation(sim, geo_split, verbose=0)

split structure in simulation and return two sim with the sub-geometries

Can be used to isolate part of a complex / composed nanostructure after the simulation, in order to study optical interaction effects

Parameters:
  • sim (simulation) – instance of simulation, efield may be pre-calculated, in which case they will be also split and returned in the splitted simulations

  • geo_split (list of 3-tuples or simulation) – list of coordinates to be split off the simulation geometry or simulation in which case its geometry will be extracted and used.

  • verbose (bool, default: False) – print some info

Returns:

new simulation with splitted geometries and other same parameters as well as pre-calculated fields first sim is split part, second sim is remaining part of original geometry

Return type:

list of 2 simulation instances

pyGDM2.tools.combine_simulations(sim_list)

Combine several simulations

Can be used to artificially disable optical interactions between several structures

Parameters:

sim_list (list of sim) – list of simulation instances, efield and environment configuration must be identical for the different simulations

Returns:

sim – new simulation with combined geometry

Return type:

simulation