API for pyicon#

Warning! This automatically generated documentation
is still under development!

Some semi-automatically generate documentation about the pyicon API.

Top-level package for pyicon.

pyicon.pyicon_accessor#

class pyicon.pyicon_accessor.pyiconDataArray(xarray_obj, path_grid='auto')#
property gname#
interp(fpath_ckdtree='auto', lon_reg=None, lat_reg=None, coordinates='clat clon', radius_of_influence=1000000.0, compute=True, mask_out_of_range=True, mask_out_of_range_before=False, mask_to_zero=False, antialias=1)#
plot(Plot=None, ax=None, cax=None, asp=None, fig_size_fac=2.0, mask_data=True, logplot=False, lon_reg=None, lat_reg=None, central_longitude='auto', clim='auto', cmap='auto', conts=None, contfs=None, clevs=None, use_pcol_or_contf=True, contcolor='k', cincr=-1.0, clabel=False, cbticks='auto', xlabel='', ylabel='', xticks='auto', yticks='auto', template='none', cbar_str='auto', cbar_pos='bottom', title_right='auto', title_left='auto', title_center='auto', projection='pc', coastlines_color='k', land_facecolor='0.7', axes_facecolor='0.7', noland=False, do_plot_settings=True, do_xyticks=True, do_gridlines=False, gname='auto', fpath_tgrid='auto', plot_method='nn', grid_type='auto', res=0.3, fpath_ckdtree='auto', coordinates='clat clon', antialias=1, mask_to_zero=False, lonlat_for_mask=False)#

plot map of data

Parameters:
  • data (xr.DataArray) – data to be

  • Plot (pyicon.Plot, optional) – plotting canvas to draw on, by default None

  • ax (matplotlib.axes, optional) – axis to plot on to , by default None

  • cax (matplotlib.axes, optional) – axis to plot colorbar on, by default None

  • asp (float, optional) – aspect ratio, by default None

  • fig_size_fac (float, optional) – _description_, by default 2.0

  • mask_data (bool, optional) – mask data where data = 0 (NaN value in ICON), by default True

  • logplot (bool, optional) – logarithmic colormap, by default False

  • lon_reg (_type_, optional) – longitude range to plot, by default None

  • lat_reg (_type_, optional) – latitudes range to plot, by default None

  • central_longitude (str or float, optional) – central longitude of plot, by default ‘auto’

  • clim (str or (float, float), optional) – colorbar limits, by default ‘auto’

  • cmap (str or colormap, optional) – colormap to use, by default ‘auto’

  • conts (_type_, optional) – _description_, by default None

  • contfs (_type_, optional) – _description_, by default None

  • clevs (_type_, optional) – _description_, by default None

  • use_pcol_or_contf (bool, optional) – _description_, by default True

  • contcolor (str, optional) – colour of contours, by default ‘k’

  • cincr (float, optional) – _description_, by default -1.0

  • clabel (bool, optional) – whether to label contours, by default False

  • cbticks (str or list, optional) – ticks for colorbar, by default ‘auto’

  • xlabel (str, optional) – label for x-axis, by default ‘’

  • ylabel (str, optional) – label fo y-axis, by default ‘’

  • xticks (str or list, optional) – tick labels for x-axis, by default ‘auto’

  • yticks (str or list, optional) – tick labels for y-axis, by default ‘auto’

  • template (str, optional) – _description_, by default ‘none’

  • cbar_str (str, optional) – label for colorbar, by default ‘auto’

  • cbar_pos (str, optional) – position of colorbar, by default ‘bottom’

  • title_right (str, optional) – title for rhs of plot, by default ‘auto’

  • title_left (str, optional) – title for lhs of plot, by default ‘auto’

  • title_center (str, optional) – title for centre of plot, by default ‘auto’

  • projection (str, optional) – projection for map, by default ‘pc’

  • coastlines_color (str, optional) – colour of coastlines, by default ‘k’

  • land_facecolor (str, optional) – colour of land, by default ‘0.7’

  • axes_facecolor (str, optional) – colour of background axes, by default ‘0.7’

  • noland (bool, optional) – whether to not plot land, by default False

  • do_plot_settings (bool, optional) – whether to apply defauly plot settings, by default True

  • do_xyticks (bool, optional) – _description_, by default True

  • do_gridlines (bool, optional) – whether to plot gridlindes, by default False

  • gname (str, optional) – name of the grid the data is on, by default ‘auto’. Typically the name of a subdirectory of pyicon.params[“path_grid”].

  • fpath_tgrid (str, optional) – path to the triangulation grid, by default ‘auto’.

  • plot_method ("nn" or "tgrid", optional) – whether to use perform nearest neighbour (nn) interpolation or plot on the native triangular grid (tgrid), by default ‘nn’

  • res (float, optional) – resolution for healpix grids, by default 0.3

  • fpath_ckdtree (str, optional) – path to the ckdtree, by default ‘auto’

  • coordinates (str, optional) – the coordinates of the variable to plotted, by default ‘clat clon’. Typically set to “xlon xlat” where x is either “c”, “e” or “v” for cell, edge or vertex points.

  • lonlat_for_mask (bool, optional) – _description_, by default False

Returns:

  • ax (matplotlib.axes) – axes that have been plotted to

  • hm (_type_) – _description_

plot_sec(Plot=None, ax=None, cax=None, asp=0.5, mask_data=True, logplot=False, lon_reg=None, lat_reg=None, clim='auto', cmap='auto', conts=None, contfs=None, clevs=None, use_pcol_or_contf=True, cincr=-1.0, clabel=False, xlabel='auto', ylabel='auto', cbar_str='auto', cbar_pos='bottom', title_right='auto', title_left='auto', title_center='auto', gname='auto', fpath_tgrid='auto', plot_method='nn', grid_type='auto', res=1.0, fpath_ckdtree='auto', coordinates='clat clon', section='gzave', xlim=None, ylim=None, facecolor='0.7', invert_yaxis=True, fpath_fx='auto', npoints=200, weights=None)#

pyicon.pyicon_calc_xr#

pyicon.pyicon_calc_xr._print_verbose(verbose=1, message='', verbose_stage=1)#

Prints message depending on verbosity

pyicon.pyicon_calc_xr.convert_tgrid_data(ds_tg_in, check_previous_conversion=True, set_dim_order=None, old_dim_behaviour=None)#

Convert xarray grid file to grid file compatible with pyicon function.

Parameters:
  • ds_tg_in (xr.Dataset) – raw, unprocessed tgrid

  • check_previous_conversion (bool) – check whether the dataset has already been converted and raise an error if so

  • set_dim_order (bool or list) – Transpose the dataset so dimensions appear in the standard pyicon order, or the order listed

  • old_dim_behaviour (bool or None) – If True labels “nc”, “ne” and “nv” will not be corrected. If False they will be corrected and the DeprecationWarning will be silenced. If None a DeprecationWarning is triggered. Note that setting old_dim_behaviour will render the returned ds_IcD incompatible with other pyicon functions.

Returns:

ds_IcD – A tgrid dataset compatible with pyicon functions

Return type:

xr.Dataset

Notes

Open classical ICON grid file by: ds_tg = xr.open_dataset(fpath_tg, chunks=dict())

Then convert by: ds_IcD = pyic.convert_tgrid_data(ds_tg)

pyicon.pyicon_calc_xr.xr_calc_2dlocal_from_3d(ds_IcD, p_vn_c)#

Transform vector from cartesian to spherical basis at a cell center

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • p_vn_c (xr.Dataset) – dataset containing cartesian representation of vector. Should have the dimension ‘cart’

Returns:

  • uo (xr.DataArray) – zonal component of vector

  • vo (xr.DataArray) – meridional component of vector

Notes

The 3D vector passed is not (u, v, w) where w is the local vertical.

pyicon.pyicon_calc_xr.xr_calc_3d_from_2dlocal(ds_IcD, uo, vo)#

Transform vector from spherical to cartesian basis at a cell center

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • uo (xr.DataArray) – zonal component

  • vo (xr.DataArray) – meridional component

Returns:

p_vn_c – representation of the horizontal vector in a cartesian basis.

Return type:

xr.DataArray

Notes

The components of the returned vector are not zonal, meridional and vertical. This function transforms a locally horizontal vector from a spherical representation to a cartesian representation.

pyicon.pyicon_calc_xr.xr_calc_curl(ds_IcD, vector, rot_coeff=None)#

Calculates the vertical component of the curl

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • vector (xr.DataArray) – Dataarray containing vector variable on cell edges.

  • rot_coeff (xr.DataArray or None) – Array containing dims (“vertex”, “ne_v”)

Returns:

curl_vec – vertical component of the curl of the vector defined on vertex points

Return type:

xr.DataArray

Notes

We calculate the curl through the use of Stokes’/Green’s theorem. A similar procedure can be used to calculate the horizontal components of the curl (oriented along cell edges and defined at intermediate Z levels.) This will be implemented in a future release.

If you’re using this function on large datasets, performance gains may be made if you play around with the dimension order.

pyicon.pyicon_calc_xr.xr_calc_div(ds_IcD, vector, div_coeff=None)#

Calculates coefficients for calculating divergence

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • vector (xr.DataArray) – vector at cell edges

  • div_coeff (xr.DataArray) – coefficients for calculating divergence

Returns:

div_of_vector – divergence of vector at cell centers

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_div_coeff(ds_IcD)#

Calculates coefficients for calculating divergence

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

Returns:

div_coeff – coefficients for calculating divergence

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_edge2cell_coeff_cc(ds_IcD)#

Calculates the edge to cell coefficients

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

Returns:

edge2cell_coeff_cc – coefficients used in mapping edges to cells

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_edge2cell_coeff_cc_t(ds_IcD)#

Calculates the cell to edge coefficients

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

Returns:

edge2cell_coeff_cc_t – coefficients used in mapping cells to edges

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_edge2edge_viacell_coeff(ds_IcD)#

Calculate coefficients for mapping edge vectors to edge vectors

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

pyicon.pyicon_calc_xr.xr_calc_fixed_volume_norm(ds_IcD)#

Calculates the fixed volume

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

Returns:

fixed_vol_norm – volume of grid cell

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_grad(ds_IcD, scalar, grad_coeff=None)#

Calculates coefficients for calculating gradient

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • scalar (xr.DataArray) – scalar at cell center

  • grad_coeff (xr.DataArray) – coefficients for calculating gradient

Returns:

grad_of_scalar – horizontal gradient of scalar at edges

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_grad_coeff(ds_IcD)#

Calculates coefficients for calculating gradient

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

Returns:

grad_coeff – coefficients for calculating gradient

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_calc_rot_coeff(ds_IcD)#

Calculates coefficients used in calculating the curl

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

Returns:

curl_coeffs – coefficients for calculating curls

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_cell2edges(ds_IcD, p_vn_c, edge2cell_coeff_cc_t=None)#

Remaps vector from cell center to edges

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • p_vn_c (xr.DataArray) – locally horizontal vector on cell center in cartesian representation.

  • edge2cell_coeff_cc_t (xr.DataArray or None) – coefficients used in mapping cells to edges

Returns:

ptp_vn – vector p_vn_c remapped to edges

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_crop_tgrid(ds_tg, ireg_c, verbose=1)#

Crop a grid file.

Parameters:
  • ds_tg (xr.Dataset) – dataset containing the grid file

  • ireg_c (np.array) – list of cell indices which should by in cropped domain

Returns:

ds_tg_cut

Return type:

xarray Dataset, which contains (most of) the cropped grid variables.

Examples

>>> ds_tg = xr.open_mfdataset(fpath_tgrid)
>>> clon = ds_tg.clon.compute().data * 180./np.pi
>>> clat = ds_tg.clat.compute().data * 180./np.pi
>>>
>>> lon_reg_3 = [6, 10]
>>> lat_reg_3 = [-32, -30]
>>> ireg_c = np.where(
...    (clon>lon_reg[0]) & (clon<=lon_reg[1]) & (clat>lat_reg[0]) & (clat<=lat_reg[1])
... )[0]
>>>
>>> ds_tg_cut = pyic.xr_crop_tgrid(ds_tg, ireg_c)
pyicon.pyicon_calc_xr.xr_edges2cell(ds_IcD, ve, dze, dzc, edge2cell_coeff_cc=None, fixed_vol_norm=None)#

Remaps vector from edges to cell

Parameters:

ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

vexr.DataArray

vector on edges

dxexr.DataArray

edge length

dzcxr.DataArray

vertical grid spacing at cell centre

edge2cell_coeff_ccxr.DataArray or None

coefficients used in mapping edges to cells

fixed_vol_normxr.DataArray or None

volume of grid cell

Returns:

p_vn_c – cartesian representation of vector ve on cell centres

Return type:

xr.DataArray

pyicon.pyicon_calc_xr.xr_edges2edges_via_cell(ds_IcD, vn_e, dze='const')#

Maps edges to edges via a cell

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • vn_e (xr.DataArray) – vector at edge

  • dze (xr.DataArray or 'const') –

pyicon.pyicon_calc_xr.xr_edges2edges_via_cell_scalar(ds_IcD, vn_e, scalar, dze='const')#

Calculates flux of scalar at edges

Parameters:
  • ds_IcD (xr.Dataset) – pyicon dataset containing coordinate info

  • vn_e (xr.DataArray) – vector at edge

  • scalar (xr.DataArray) – scalar at cell centre

  • dze (xr.DataArray or 'const') –

pyicon.pyicon_calc#

pyicon.pyicon_calc.calc_2dlocal_from_3d(IcD, p_vn_c)#

! these should be calclulated once and stored in the coefficients structure sinLon = SIN(position_local(this_index,blockNo)%lon) cosLon = COS(position_local(this_index,blockNo)%lon) sinLat = SIN(position_local(this_index,blockNo)%lat) cosLat = COS(position_local(this_index,blockNo)%lat)

DO level = 1, levels(this_index,blockNo)

cartesian_x = vector(this_index,level,blockNo)%x(1) cartesian_y = vector(this_index,level,blockNo)%x(2) cartesian_z = vector(this_index,level,blockNo)%x(3)

x(this_index,level,blockNo) = cosLon * cartesian_y - sinLon * cartesian_x y_help = cosLon * cartesian_x + sinLon * cartesian_y y_help = sinLat * y_help y(this_index,level,blockNo) = cosLat * cartesian_z - y_help

pyicon.pyicon_calc.calc_3d_from_2dlocal(IcD, uo, vo)#
pyicon.pyicon_calc.calc_bstr_rgrid(IcD, mass_flux_vint, lon_rg, lat_rg, dtype='float64')#

Calculates barotropic streamfunction in Sv from mass_flux_vint on regular grid.

pyicon.pyicon_calc.calc_bstr_vgrid(IcD, mass_flux_vint, lon_start=0.0, lat_start=90.0, verbose=False, old_version=True)#

Calculates barotropic streamfunction in Sv from mass_flux_vint on vertex-grid.

This function determines neighbouring vertices starting from lon_start, lat_start vertex. It determines source and target vertices and the corresponding edges. Then the bstr value for each target vertex is that of the source vertex plus the transport through the edge between source and target.

Algorithm is taken from mo_postprocess.f90 (Leonidas Linardakis, MPI-M).

pyicon.pyicon_calc.calc_curl(IcD, ve)#
pyicon.pyicon_calc.calc_edge2cell_coeff_cc(IcD)#

From math/mo_scalar_product.f90 map_edges2cell_3d (interface to map_edges2cell_no_height_3d -> map_edges2cell_no_height_3d_onTriangles): and from math/mo_operator_ocean_coeff_3d.f90 init_operator_coeffs_cell:

edge_1_index = patch_2d%cells%edge_idx(cell_index,blockNo,1) edge_1_block = patch_2d%cells%edge_blk(cell_index,blockNo,1) edge_2_index = patch_2d%cells%edge_idx(cell_index,blockNo,2) edge_2_block = patch_2d%cells%edge_blk(cell_index,blockNo,2) edge_3_index = patch_2d%cells%edge_idx(cell_index,blockNo,3) edge_3_block = patch_2d%cells%edge_blk(cell_index,blockNo,3)

DO level = startLevel, MIN(patch_3D%p_patch_1D(1)%dolic_c(cell_index,blockNo), endLevel)
p_vn_c(cell_index,level,blockNo)%x = &

& ( operators_coefficients%edge2cell_coeff_cc(cell_index,level,blockNo,1)%x & & * vn_e(edge_1_index,level,edge_1_block) & &*patch_3d%p_patch_1d(1)%prism_thick_e(edge_1_index,level,edge_1_block) & & + operators_coefficients%edge2cell_coeff_cc(cell_index,level,blockNo,2)%x & & * vn_e(edge_2_index,level,edge_2_block) & &*patch_3d%p_patch_1d(1)%prism_thick_e(edge_2_index,level,edge_2_block) & & + operators_coefficients%edge2cell_coeff_cc(cell_index,level,blockNo,3)%x & & * vn_e(edge_3_index,level,edge_3_block) & &*patch_3d%p_patch_1d(1)%prism_thick_e(edge_3_index,level,edge_3_block)) & & / (operators_coefficients%fixed_vol_norm(cell_index,level,blockNo) & & * patch_3d%p_patch_1d(1)%prism_thick_c(cell_index,level,blockNo))

END DO

edge_index = patch_2D%cells%edge_idx(cell_index, cell_block, neigbor) edge_block = patch_2D%cells%edge_blk(cell_index, cell_block, neigbor)

IF (edge_block > 0 ) THEN

! we have an edge dist_vector = distance_vector( &

& patch_2D%edges%cartesian_center(edge_index,edge_block), & & cell_center, & & patch_2D%geometry_info)

! compute edge2cell_coeff_cc edge2cell_coeff_cc(cell_index,cell_block,neigbor)%x = &

& dist_vector%x * & & prime_edge_length(edge_index,edge_block) * & & patch_2D%cells%edge_orientation(cell_index,cell_block,neigbor)

pyicon.pyicon_calc.calc_edge2cell_coeff_cc_t(IcD)#
pyicon.pyicon_calc.calc_edge2edge_viacell_coeff(IcD)#
pyicon.pyicon_calc.calc_fixed_volume_norm(IcD)#
pyicon.pyicon_calc.calc_moc(clat, wTransp, basin='global', fpath_fx='', res=1.0, dtype='float32')#
pyicon.pyicon_calc.calc_wvel(IcD, mass_flux)#
pyicon.pyicon_calc.cell2edges(IcD, p_vn_c)#

math/mo_scalar_product.f90: map_cell2edges_3d_mlevels

pyicon.pyicon_calc.edges2cell(IcD, ve)#
pyicon.pyicon_calc.edges2edges_via_cell(IcD, vn_e, dze='const')#

Transfer from edge to 3D cell and back to edge. Supposed to mimic the M operator (K2017).

Used e.g. to calculate the mass flux and therewith vert. velocity.

pyicon.pyicon_calc.edges2edges_via_cell_scalar(IcD, vn_e, scalar, dze='const')#

Same as edges2edges_via_cell but with scalar mutiplied at cell centers. Supposed to mimic M[v,phi] (K2017).

Used e.g. to calculate advective tracer fluxes (before flux limiter are applied).

pyicon.pyicon_calc.planar_triangle_area(p1, p2, p3)#

p1: cartesian vector with 2nd dim (x,y,z) dim(npoints, 3) p2: same as p1 p3: same as p1

pyicon.pyicon_calc.scalar_product(v1, v2, dim=1, numpy_sum=False)#
pyicon.pyicon_calc.vector_product(v1, v2)#

pyicon.pyicon_IconData#

class pyicon.pyicon_IconData.IconData(fname='', path_data='', path_grid='', gname='', lev='', fpath_tgrid='auto', fpath_fx='auto', path_ckdtree='auto', rgrid_name='', section_name='', run='auto', lon_reg=[], lat_reg=[], do_triangulation=True, omit_last_file=False, load_vertical_grid=True, load_vgrid_depth='auto', load_vgrid_dz='auto', load_vgrid_mask='auto', load_triangular_grid=True, load_rectangular_grid=True, load_variable_info=True, load_grid_from_data_file=False, load_xarray_dset=False, xr_chunks=None, calc_coeff=True, calc_coeff_mappings=False, do_only_timesteps=False, time_mode='num2date', model_type='oce', do_conf_dwd=False, output_freq='auto', time_at_end_of_interval=True, verbose=False, dtype='float32')#

Used by Jupyter

crop_tgrid(lon_reg, lat_reg)#

Crop all cell related variables (data, clon, clat, vertex_of_cell, edge_of_cell to regin defined by lon_reg and lat_reg.

load_grid_from_file()#

Load lon and lat from first netcdf file of list (e.g. if nc file was created by cdo)

load_rgrid(lon_reg='all', lat_reg='all')#

Load lon and lat from the ckdtree rectangular grid file self.rgrid_fpath.

load_tgrid(do_conf_dwd=False)#

Load certain variables related to the triangular grid from the grid file self.fpath_tgrid.

load_vgrid(lon_reg='all', lat_reg='all', load_vgrid_depth=True, load_vgrid_dz=True, load_vgrid_mask=True)#

Load certain variables from self.fpath_fx which are typically related to a specification of the vertical grid.

pyicon.pyicon_params#

pyicon.pyicon_plotting#

pyicon.pyicon_plotting.arrange_axes_old(nx, ny, asy=3.5, sasp=0.5, plot_cb=False, sharex=False, sharey=False, xlabel='', ylabel='', oxl=0.1, oxr=0.0, oyb=0.0, oyt=0.0, axfac_x=1.0, axfac_y=1.0, axlab_kw={}, fig_size='auto', fig_asp='auto', fig_size_fac=2.0, fig_title=None, projection=None)#

last change: 2015-07-22

pyicon.pyicon_plotting.axlab(hca, figstr=[], posx=[-0.0], posy=[1.05], fontdict=None)#

input:#

hca: list with axes handles figstr: list with strings that label the subplots posx: list with length 1 or len(hca) that gives the x-coordinate in ax-space posy: list with length 1 or len(hca) that gives the y-coordinate in ax-space

last change: 2015-07-21

pyicon.pyicon_plotting.hplot_base(IcD, IaV, clim='auto', cmap='viridis', cincr=-1.0, clevs=None, contfs=None, conts=None, contcolor='k', contthick=0.0, contlw=1.0, ax='auto', cax=0, title='auto', xlabel='', ylabel='', xlim='auto', ylim='auto', adjust_axlims=True, projection='none', use_tgrid='auto', logplot=False, asp=0.5, fig_size_fac=2.0, crs_features=True, do_plot_settings=True, land_facecolor='0.7', do_write_data_range=False, save_data=False, fpath_nc='')#
IaV variable needs the following attributes
  • name

  • long_name

  • units

  • data

  • Tri – if use_tgrid==True

  • lon, lat – else

Returns:

  • ax

  • cax

  • hm

pyicon.pyicon_plotting.plot(data, Plot=None, ax=None, cax=None, asp=None, fig_size_fac=2.0, mask_data=True, logplot=False, lon_reg=None, lat_reg=None, central_longitude='auto', clim='auto', cmap='auto', conts=None, contfs=None, clevs=None, use_pcol_or_contf=True, contcolor='k', cincr=-1.0, clabel=False, cbticks='auto', xlabel='', ylabel='', xticks='auto', yticks='auto', template='none', cbar_str='auto', cbar_pos='bottom', title_right='auto', title_left='auto', title_center='auto', projection='pc', coastlines_color='k', land_facecolor='0.7', axes_facecolor='0.7', noland=False, do_plot_settings=True, do_xyticks=True, do_gridlines=False, gname='auto', fpath_tgrid='auto', plot_method='nn', grid_type='auto', res=0.3, fpath_ckdtree='auto', coordinates='clat clon', antialias=1, mask_to_zero=False, lonlat_for_mask=False)#

plot map of data

Parameters:
  • data (xr.DataArray) – data to be

  • Plot (pyicon.Plot, optional) – plotting canvas to draw on, by default None

  • ax (matplotlib.axes, optional) – axis to plot on to , by default None

  • cax (matplotlib.axes, optional) – axis to plot colorbar on, by default None

  • asp (float, optional) – aspect ratio, by default None

  • fig_size_fac (float, optional) – _description_, by default 2.0

  • mask_data (bool, optional) – mask data where data = 0 (NaN value in ICON), by default True

  • logplot (bool, optional) – logarithmic colormap, by default False

  • lon_reg (_type_, optional) – longitude range to plot, by default None

  • lat_reg (_type_, optional) – latitudes range to plot, by default None

  • central_longitude (str or float, optional) – central longitude of plot, by default ‘auto’

  • clim (str or (float, float), optional) – colorbar limits, by default ‘auto’

  • cmap (str or colormap, optional) – colormap to use, by default ‘auto’

  • conts (_type_, optional) – _description_, by default None

  • contfs (_type_, optional) – _description_, by default None

  • clevs (_type_, optional) – _description_, by default None

  • use_pcol_or_contf (bool, optional) – _description_, by default True

  • contcolor (str, optional) – colour of contours, by default ‘k’

  • cincr (float, optional) – _description_, by default -1.0

  • clabel (bool, optional) – whether to label contours, by default False

  • cbticks (str or list, optional) – ticks for colorbar, by default ‘auto’

  • xlabel (str, optional) – label for x-axis, by default ‘’

  • ylabel (str, optional) – label fo y-axis, by default ‘’

  • xticks (str or list, optional) – tick labels for x-axis, by default ‘auto’

  • yticks (str or list, optional) – tick labels for y-axis, by default ‘auto’

  • template (str, optional) – _description_, by default ‘none’

  • cbar_str (str, optional) – label for colorbar, by default ‘auto’

  • cbar_pos (str, optional) – position of colorbar, by default ‘bottom’

  • title_right (str, optional) – title for rhs of plot, by default ‘auto’

  • title_left (str, optional) – title for lhs of plot, by default ‘auto’

  • title_center (str, optional) – title for centre of plot, by default ‘auto’

  • projection (str, optional) – projection for map, by default ‘pc’

  • coastlines_color (str, optional) – colour of coastlines, by default ‘k’

  • land_facecolor (str, optional) – colour of land, by default ‘0.7’

  • axes_facecolor (str, optional) – colour of background axes, by default ‘0.7’

  • noland (bool, optional) – whether to not plot land, by default False

  • do_plot_settings (bool, optional) – whether to apply defauly plot settings, by default True

  • do_xyticks (bool, optional) – _description_, by default True

  • do_gridlines (bool, optional) – whether to plot gridlindes, by default False

  • gname (str, optional) – name of the grid the data is on, by default ‘auto’. Typically the name of a subdirectory of pyicon.params[“path_grid”].

  • fpath_tgrid (str, optional) – path to the triangulation grid, by default ‘auto’.

  • plot_method ("nn" or "tgrid", optional) – whether to use perform nearest neighbour (nn) interpolation or plot on the native triangular grid (tgrid), by default ‘nn’

  • res (float, optional) – resolution for healpix grids, by default 0.3

  • fpath_ckdtree (str, optional) – path to the ckdtree, by default ‘auto’

  • coordinates (str, optional) – the coordinates of the variable to plotted, by default ‘clat clon’. Typically set to “xlon xlat” where x is either “c”, “e” or “v” for cell, edge or vertex points.

  • lonlat_for_mask (bool, optional) – _description_, by default False

Returns:

  • ax (matplotlib.axes) – axes that have been plotted to

  • hm (_type_) – _description_

pyicon.pyicon_plotting.shade(x='auto', y='auto', datai='auto', ax='auto', cax=0, cmap='auto', cincr=-1.0, norm=None, rasterized=True, clim=[None, None], extend='both', clevs=None, contfs=None, conts=None, nclev='auto', contcolor='k', contthick=0.0, contlw=1.0, use_pcol=True, use_pcol_or_contf=True, cbticks='auto', cbtitle='', cbdrawedges='auto', cborientation='auto', cbkwargs=None, adjust_axlims=True, bmp=None, transform=None, projection=None, logplot=False, edgecolor='none')#

Convenient wrapper around pcolormesh, contourf, contour and their triangular versions.

pyicon.pyicon_plotting.trishade(Tri, data, ax='auto', cax=0, cmap='auto', cincr=-1.0, norm=None, rasterized=True, clim=[None, None], extend='both', edgecolor='none', conts=None, nclev='auto', cint='auto', contcolor='k', contthick=0.0, contfs=None, contlw=1.0, use_pcol=True, adjust_axlims=True, bmp=None, transform=None, logplot=False)#

Makes a nice tripcolor plot.

last change: 2018-03-08

pyicon.pyicon_plotting.vplot_base(IcD, IaV, clim='auto', cmap='viridis', cincr=-1.0, clevs=None, contfs=None, conts=None, contcolor='k', contthick=0.0, contlw=1.0, ax='auto', cax=0, title='auto', xlabel='', ylabel='', xlim='auto', ylim='auto', xvar='lat', log2vax=False, vertaxtype='linear', daxl=1.8, logplot=False, asp=0.5, fig_size_fac=2.0, do_plot_settings=True, do_write_data_range=False, save_data=False, fpath_nc='')#
IaV variable needs the following attributes
  • name

  • long_name

  • units

  • data

  • lon_sec, lat_sec, dist_sec

Returns:

  • ax

  • cax

  • hm

pyicon.pyicon_simulation#

pyic.Simulation is still experimental and was just copied from ~/proj_vmix/simulation_list.ipynb. Therefore, it is not working out of the box yet.

It is tested in ~/proj_vmix/simulation_list.ipynb

class pyicon.pyicon_simulation.Simulation(run, path_data='auto', fpath_fx='auto', fpath_tgrid='auto', fpath_ckdtree='auto', name=None)#
_get_info_str()#
_update_Dinfo()#
get_ckdtree_from_tgrid(path_grid='/work/mh0033/m300602/icon/grids/')#
get_fx_from_path()#
get_tgrid_from_path()#
to_database(path_database='/home/m/m300602/icon_simulation_database/')#
class pyicon.pyicon_simulation.SimulationIterator(simulationList)#
class pyicon.pyicon_simulation.SimulationList(namelist=[], simlist=[])#
add(S)#
addSim(*args, **kwargs)#
from_database(path_database='/home/m/m300602/icon_simulation_database/')#
to_database(path_database='/home/m/m300602/icon_simulation_database/')#
pyicon.pyicon_simulation.get_grid_uuid(fpath_tgrid='/work/mh0033/m300602/icon/grids//*/*_tgrid.nc')#
pyicon.pyicon_simulation.inquire_simulation_details(path_data)#

pyicon.pyicon_tb#

class pyicon.pyicon_tb.IP_hor_sec_rect(IcD, ax='', cax='', var='', clim='auto', nc=1, cmap='viridis', transform=None, lon_reg='auto', lat_reg='auto', title='auto', time_string='auto', depth_string='auto', edgecolor='none')#

To do: * similar to qp_hor_plot, see if we need both * try to use hplot_base

update(data, IcD, title='none', time_string='auto', depth_string='auto')#
pyicon.pyicon_tb.apply_ckdtree(data, fpath_ckdtree, mask=None, coordinates='clat clon', radius_of_influence=1000000.0)#
  • credits function modified from pyfesom (Nikolay Koldunov)

pyicon.pyicon_tb.apply_ckdtree_base(data, inds, distances, radius_of_influence=1000000.0)#
pyicon.pyicon_tb.calc_ckdtree(lon_i, lat_i, lon_o, lat_o, n_nearest_neighbours=1, n_jobs=1, use_npconcatenate=True)#
pyicon.pyicon_tb.calc_grid_area_rectgrid(lon, lat)#
pyicon.pyicon_tb.calc_north_pole_interp_grid_points(lat_south=60.0, res=100000.0)#

Compute grid points optimized for plotting the North Pole area.

Parameters:#

lat_southfloat

Southern latitude of target grid.

resfloat

resolution of target grid

Returns:#

Lon_np, Lat_np: ndarray

Longitude and latitude of target grid as 2d array.

Examples:#

Lon_np, Lat_np = calc_north_pole_interp_grid_points(lat_south=60., res=100e3)

pyicon.pyicon_tb.calc_vertical_interp_weights(zdata, levs, increases_along_axes=True)#

Calculate vertical interpolation weights and indices.

Call example: icall, ind_lev, fac = calc_vertical_interp_weights(zdata, levs)

Afterwards do interpolation like this: datai = data[ind_lev,icall]*fac+data[ind_lev+1,icall]*(1.-fac)

pyicon.pyicon_tb.cartesian_to_spherical(x, y, z)#
pyicon.pyicon_tb.ckdtree_hgrid(lon_reg, lat_reg, res, fname_tgrid='', path_tgrid='', path_ckdtree='', sname='', gname='', tgname='', load_cgrid=True, load_egrid=True, load_vgrid=True, n_nearest_neighbours=1, n_jobs=1, save_as_nc=True)#
pyicon.pyicon_tb.ckdtree_hgrid_rotated(Lon, Lat, rlon, rlat, pol_lon, pol_lat, proj_name, fname_tgrid='', path_tgrid='', path_ckdtree='', sname='', gname='', tgname='', load_cgrid=True, load_egrid=True, load_vgrid=True, n_nearest_neighbours=1, n_jobs=1, save_as_nc=True)#
pyicon.pyicon_tb.ckdtree_points(fpath_tgrid, lon_o, lat_o, load_cgrid=True, load_egrid=True, load_vgrid=True, n_nearest_neighbours=1, n_jobs=1)#
pyicon.pyicon_tb.ckdtree_section(p1, p2, npoints=101, fname_tgrid='', path_tgrid='', path_ckdtree='', sname='auto', gname='', tgname='', n_nearest_neighbours=1, n_jobs=1, load_cgrid=True, load_egrid=True, load_vgrid=True, save_as_nc=True)#
pyicon.pyicon_tb.cons_remap(da, lon=None, lat=None, cell_area=None)#

Conservative remapping to a regular grid.

Parameters:
  • da (xr.DataArray) – Data which should be remapped. It is necessary that da has coordinates clat and clon.

  • lon (numpy 1D array) – Longitude and latitude of the map to which we want to regrid. If lon=None: lon = np.arange(-180,180,1) If lat=None: lat = np.arange(-90.,90,1)

  • lat (numpy 1D array) – Longitude and latitude of the map to which we want to regrid. If lon=None: lon = np.arange(-180,180,1) If lat=None: lat = np.arange(-90.,90,1)

  • cell_area (xr.DataArray) – Area of triangle cell as specified in the grid file. The area is used for the weighted average. If cell_area=None: No area weighting is applied.

Returns:

dai – Remapped field. Coordinates will be lon and lat.

Return type:

xr.DataArray

pyicon.pyicon_tb.conv_gname(gname)#
pyicon.pyicon_tb.crop_regular_grid(lon_reg, lat_reg, Lon, Lat)#
pyicon.pyicon_tb.crop_tripolar_grid(lon_reg, lat_reg, clon, clat, vertex_of_cell, edge_of_cell)#
pyicon.pyicon_tb.datetime64_to_float(dates)#
pyicon.pyicon_tb.degstr_to_degfloat(degstr)#
pyicon.pyicon_tb.derive_section_points(p1, p2, npoints=101)#
pyicon.pyicon_tb.find_section_indices(clon, clat, lon_sec, lat_sec)#
pyicon.pyicon_tb.get_averaging_interval(times, output_freq, end_of_interval=True)#

Determine the length of the averaging time interval in seconds.

times: numpy array containing numpy.datetime64 objects: time points which are associated with averaing interval output_freq: bool: pick either ‘monthly’, ‘yearly’, ‘daily’ or ‘hourly’ end_of_interal: bool: sets whether time points of times are interpreted at the end of the averaging interval (default ICON output) or at the beginning or in the middle (mkexp time shift)

pyicon.pyicon_tb.get_files_of_timeseries(path_data, fname)#
pyicon.pyicon_tb.get_timesteps(flist, time_mode='num2date')#
pyicon.pyicon_tb.get_varnames(fpath, skip_vars=[])#
pyicon.pyicon_tb.haversine_dist(lon_ref, lat_ref, lon_pts, lat_pts, degree=True)#
pyicon.pyicon_tb.hp_add_dims(da)#
pyicon.pyicon_tb.hp_coarsen_grid(data, coarsen_steps=1)#
pyicon.pyicon_tb.hp_from_vector_to_hp(data, zoom=7)#
pyicon.pyicon_tb.hp_grid_from_arr(arr, verbose=False)#
pyicon.pyicon_tb.hp_grid_from_zoom(zoom, verbose=False)#
pyicon.pyicon_tb.hp_to_rectgrid(arr, lon=None, lat=None, lon_reg=[-180, 180], lat_reg=[-90, 90], res=0.3)#
pyicon.pyicon_tb.hp_to_section(arr, name='170W', p1=None, p2=None, npoints=200)#
pyicon.pyicon_tb.hp_zonal_average(arr, zave='gzave', weights=None)#
pyicon.pyicon_tb.identify_depth_name(data)#
pyicon.pyicon_tb.identify_grid(fpath_data, path_grid='none', uuidOfHGrid='none')#

Identifies ICON grid from fpath_data which can be either a path to a file containing a ‘clon’ variable or an xarray dataset or array where the cell dimension name is either ‘ncells’ or ‘cell’.

r2b4: 160km: 15117: OceanOnly_Icos_0158km_etopo40.nc r2b4a: 160km: 20480: /pool/data/ICON/grids/public/mpim/0013/icon_grid_0013_R02B04_G.nc r2b6: 40km: 327680: OCEANINP_pre04_LndnoLak_039km_editSLOHH2017_G.nc r2b8: 10km: 3729001: OceanOnly_Global_IcosSymmetric_0010km_rotatedZ37d_modified_srtm30_1min.nc r2b9: 5km: 14886338: OceanOnly_IcosSymmetric_4932m_rotatedZ37d_modified_srtm30_1min.nc r2b9a: 5km: 20971520: /pool/data/ICON/grids/public/mpim/0015/icon_grid_0015_R02B09_G.nc

pyicon.pyicon_tb.indfind(elements, vector)#

return indices of elements that closest match elements in vector

pyicon.pyicon_tb.info(array)#

Prints some information about an xarray. (not well tested yet).

To do:
  • decide whether numpy, or array

  • decide whether xarray contains dask or numpy array

pyicon.pyicon_tb.interp_to_rectgrid(data, fpath_ckdtree, lon_reg=None, lat_reg=None, indx='all', indy='all', mask_reg=None, coordinates='clat clon')#
pyicon.pyicon_tb.interp_to_rectgrid_xr(arr, fpath_ckdtree='auto', lon_reg=None, lat_reg=None, coordinates='clat clon', radius_of_influence=1000000.0, compute=True, mask_out_of_range=True, mask_out_of_range_before=False, mask_to_zero=False, antialias=1)#
pyicon.pyicon_tb.interp_to_rectgrid_xr_old(arr, fpath_ckdtree='auto', lon_reg=None, lat_reg=None, coordinates='clat clon', radius_of_influence=1000000.0, compute=True, mask_out_of_range=True, mask_out_of_range_before=False)#
pyicon.pyicon_tb.interp_to_section(data, fpath_ckdtree, coordinates='clat clon')#
pyicon.pyicon_tb.load_hsnap(fpath, var, it=0, iz=0, iw=None, fpath_ckdtree='', verbose=True)#
pyicon.pyicon_tb.lonlat2str(lon, lat)#
pyicon.pyicon_tb.mask_big_triangles(vlon, vlat, vertex_of_cell, Tri, only_lon=True)#
pyicon.pyicon_tb.nctime2numpy(ncv)#
pyicon.pyicon_tb.nctime_to_datetime64(ncv_time, time_mode='num2date')#
pyicon.pyicon_tb.patch_plot_derive_bnds(ds_tgrid, lon_reg=[-180, 180], lat_reg=[-90, 90])#
class pyicon.pyicon_tb.pyicon_configure(fpath_config)#
pyicon.pyicon_tb.rename_dimension_names(ds, rename_dict=None, verbose=False)#

Rename dimension names of ICON output files to match name convention in grid files.

ds: Xarray dataset which should be renamed rename_dict: Dictionary. which contains renaming instruction. If left None, default convention is used. verbose: Bool. If set to true rename_dict is printed.

pyicon.pyicon_tb.section_name_to_p1_p2(name)#
pyicon.pyicon_tb.smoothen_data(da_i, antialias=2)#
pyicon.pyicon_tb.spherical_to_cartesian(lon, lat)#
pyicon.pyicon_tb.stats(array)#

Prints some basic information about an array. (not well tested yet).

To do:
  • decide whether numpy, or xarray

  • decide whether xarray contains dask or numpy array

pyicon.pyicon_tb.time_average(IcD, var, t1='none', t2='none', it_ave=[], iz='all', always_use_loop=False, verbose=False, use_xr=False, load_xr_data=False, dimension_from_file='first')#
pyicon.pyicon_tb.timing(ts, string='', verbose=True)#
pyicon.pyicon_tb.triangulation(ds_tgrid, lon_reg=None, lat_reg=None, do_mask_big_triangles=True, only_lon=True, shift_to_zero_dateline=False)#
pyicon.pyicon_tb.write_dataarray_to_nc(fpath, data, coords, name='data', long_name='', units='', long_name_coords=None, units_coords=None, time_bnds=[], verbose=True)#
pyicon.pyicon_tb.zonal_average(fpath_data, var, basin='global', it=0, fpath_fx='', fpath_ckdtree='')#
pyicon.pyicon_tb.zonal_average_3d_data(data3d, basin='global', it=0, coordinates='clat clon', fpath_fx='', fpath_ckdtree='')#

Like zonal_average but here data instead of path to data is given. This can only work if the whole data array fits into memory.

pyicon.pyicon_tb.zonal_average_atmosphere(data3d, ind_lev, fac, fpath_ckdtree='', coordinates='clat clon')#
pyicon.pyicon_tb.zonal_section_3d_data(data3d, fpath_ckdtree, coordinates)#
(

lon_sec, lat_sec, dist_sec, data_sec

) = pyic.zonal_section_3d_data(tbias,

fpath_ckdtree=path_ckdtree+’sections/r2b4_nps100_30W80S_30W80N.npz’)

pyicon.pyicon_thermo#

pyicon.pyicon_thermo._calculate_eos_pressure(da_depth, da_zos=0, da_stretch_c=1)#

calculates hydrostatic pressure for the equation of state

Parameters:
  • da_depth (xr.DataArray) – depth in the water column in metres

  • da_zos (xr.DataArray or 0, optional) – sea surface height in metres

  • da_stretch_c (xr.DataArray or 1, optional) – stretch factor from zstar

Returns:

p – hydrostatic pressure as required by the equation of state in dBar

Return type:

xr.DataArray

Notes

The pressure does not include atmospheric pressure. This is neglected by the equation of state used in ICON.

pyicon.pyicon_thermo._calculate_insitu_temperature(sal, t_pot, p)#

calculates in-situ temperature from model variables and pressure.

Parameters:
  • sal (xr.DataArray) – salinity in PSU

  • t_pot (xr.DataArray) – potential temperature (what ICON outputs) in deg C

  • p (xr.DataArray) – pressure in dBar

Returns:

t_insitu – in-situ temperature in deg C

Return type:

xr.DataArray

pyicon.pyicon_thermo._calculate_mpiom_density(sal, t_insitu, p)#

calculates potential density

Parameters:
  • sal (xr.DataArray) – salinity in PSU

  • t_insitu (xr.DataArray) – in-situ temperature in deg C

  • p (xr.DataArray) – pressure in dBar

Returns:

rho – density in kg / m^3

Return type:

xr.DataArray

pyicon.pyicon_thermo.calculate_density(so, to, zos=0, stretch_c=1, depth=None, eos_type='mpiom')#

calculates density from model variables

Parameters:
  • to (xr.DataArray) – potential temperature in deg C

  • so (xr.DataArray) – salinity in PSU

  • zos (xr.DataArray or 0, optional) – sea surface height in metres, by default 0

  • stretch_c (xr.DataArray or 1, optional) – zos stretch factor, by default 1

  • depth (xr.DataArray, optional) – Array containing depth in metres at prism centres, by default taken from to. Depth should be increasingly positive with distance below the surface.

  • eos_type (str, optional) – which equation of state to use, by default “mpiom”

Returns:

rho – potential density

Return type:

xr.DataArray

Raises:
  • TypeError – raised when depth not provided as a kwarg and also not found as a coordinate on to

  • NotImplementedError – raised when an unrecognised equation of state is requested

Notes

Equations of state are not necessarily linear. When this is the case, the time mean density can not be obtained from the the time mean temperature and salinity. To minimise error you should either calculate the density online at model run time, or use the highest temporal frequency of output available in your calculations.