Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Develop #39

Merged
merged 74 commits into from
Oct 24, 2022
Merged
Changes from 1 commit
Commits
Show all changes
74 commits
Select commit Hold shift + click to select a range
b2c2687
Added data writing tools
kbspooner Feb 11, 2021
9d0b457
fix ipython
kbspooner Feb 12, 2021
ef3b8bd
enable amset to work with n and p type doping
kbspooner Mar 12, 2021
fda2b33
bug fixes
kbspooner Mar 12, 2021
ba8c067
boltztrap flexbility and bug fixes
kbspooner Mar 17, 2021
a72aa9a
Merge branch 'develop' into get-data
kbspooner Mar 17, 2021
7e839ee
bug fix
kbspooner Mar 17, 2021
b9ec38d
allow multiple data files and directions in add_cumkappa
kbspooner Mar 19, 2021
df1cb33
command-line data extraction of zt and kappa
kbspooner Mar 19, 2021
76376fe
added cumkappa-writing function and script; bug fixes
Mar 23, 2021
e37c181
bug fix
Mar 29, 2021
336cce2
New amset_mesh outputs, bug fixes
Apr 2, 2021
c3d4308
bug fix
Apr 12, 2021
db56e9c
Added data writing tools
kbspooner Feb 11, 2021
964c4d7
fix ipython
kbspooner Feb 12, 2021
b469d3b
bug fix
Apr 12, 2021
fa07360
Merge branch 'init-test' of https://github.com/kbspooner/ThermoPlotte…
Apr 13, 2021
17d8a63
normalise weighted_rates weighting
Apr 21, 2021
719a0da
bug fix
Apr 30, 2021
d8964d4
Robust unit conversions, bug fixes
May 24, 2021
0985e32
Merge branch 'custom-units' into init-test
kbspooner May 24, 2021
ecd4926
Merge branch 'custom-units' into stacked-cumkappa
kbspooner May 24, 2021
0e79836
bug fix
May 24, 2021
2686dc1
Merge pull request #24 from SMTG-UCL/init-test
dandavies99 May 25, 2021
973f2e9
Merge branch 'custom-units' into stacked-cumkappa
kbspooner May 25, 2021
950d797
Merge pull request #25 from SMTG-UCL/stacked-cumkappa
dandavies99 May 25, 2021
49b793e
bug fix
May 25, 2021
4c6aa0f
Merge pull request #26 from SMTG-UCL/custom-units
dandavies99 May 25, 2021
e15e72f
Begin various linting, remove unused imports etc
May 26, 2021
707eb59
fix legend bugs
May 27, 2021
6b79fa8
bug fix
Jun 1, 2021
7f4e147
new vasp setup module
Jun 18, 2021
054ee8d
added cli for kpoint and kpar generators
Jun 24, 2021
c7d2420
gen-kpar now reads automatic mesh KPOINTS files and is more
Jun 24, 2021
1bb9d8b
added more input types for vasp setup
Jun 25, 2021
bce53c2
very wip, not fit for use
Jul 16, 2021
093b6d8
wip but working click interface
Aug 18, 2021
f664cce
completed basic click functionality
kbspooner Aug 19, 2021
de263b9
bug fixes
kbspooner Aug 23, 2021
975ee21
Merge pull request #27 from SMTG-UCL/fix-legend
dandavies99 Sep 23, 2021
0b715e9
wip commit for internal file sharing
kbspooner Nov 22, 2021
7265c10
Expanded cli with graphs and data retrieval, numerous improvements
kbspooner Feb 3, 2022
8dfdb66
Bug fixes
kbspooner Feb 4, 2022
940dfb7
Phonon + DoS, devolved avg-rates and panda-friendly cumkappa
kbspooner Feb 7, 2022
8324827
finished new cli, bug fixes etc.
Feb 14, 2022
1b37838
verbose output, bug fixes etc.
Feb 16, 2022
b516c3f
**BREAKING CHANGES** simpifies axes, bug fixes etc.
Mar 3, 2022
39a61e5
New tutorialised examples, bug fixes
Mar 15, 2022
39fcf64
new functions, bug fixes and performance updates
Mar 18, 2022
999a0a4
Rearranged examples, bug fixes and upgrades
Mar 28, 2022
90556a6
test update
Mar 29, 2022
1aea199
Merge pull request #30 from SMTG-UCL/simplify-axes
kbspooner Mar 29, 2022
a32effd
bug fixes and clarifications
Apr 7, 2022
1d1144f
Merge pull request #31 from SMTG-UCL/bug-fix
kbspooner Apr 7, 2022
3c00888
bug fixes
Apr 8, 2022
a43d2e8
update tests
Apr 12, 2022
c537832
Merge pull request #33 from SMTG-UCL/bug-fix
kbspooner Apr 12, 2022
1b55659
bug fix fix
Apr 14, 2022
5ae2c84
Merge pull request #34 from SMTG-UCL/bug-fix
kbspooner Apr 14, 2022
9cce7b0
Directional average default change, bug fixes
Aug 4, 2022
418fb6c
option to show not save, robustness
Aug 11, 2022
9151c5d
tp get zt --max, bug fixes and test updates
Aug 18, 2022
7cc5bed
Merge pull request #35 from SMTG-UCL/bug-fix
kbspooner Aug 18, 2022
2ec2c1b
Merge branch 'develop' into docstrings-tidy
kbspooner Aug 18, 2022
9a9ce09
Merge pull request #36 from SMTG-UCL/docstrings-tidy
kbspooner Aug 18, 2022
edf8ad4
update tutorialised examples, bug fixes
Aug 22, 2022
04c3f32
Merge pull request #37 from SMTG-UCL/docs
kbspooner Aug 22, 2022
15dc788
Update docs
Sep 12, 2022
07b5958
added dataset merging, qol improvements
Oct 4, 2022
4e8c46f
expanded cli, bugfixes and maintainability
Oct 11, 2022
9e7bd37
**BREAKING CHANGES last update** smeared dos, docs
Oct 20, 2022
eefcfce
Docs and website overhaul
Oct 24, 2022
7ace126
Merge pull request #38 from SMTG-UCL/docs
kbspooner Oct 24, 2022
b05e037
Merge branch 'master' into develop
kbspooner Oct 24, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
completed basic click functionality
also enhanced and streamlined colour parsing with
tp.plot.utilities.parse_colours and bug fixes
kbspooner committed Aug 19, 2021
commit f664cced2f72e2aededbce50659155085786d219
179 changes: 90 additions & 89 deletions tp/cli/cli.py
Original file line number Diff line number Diff line change
@@ -81,7 +81,7 @@ def kpoints(kpoints, mesh, poscar, zero_kpoints, zero_mesh, output):

@tp_cli.group()
def run():
"""Tools for transport properties postprocessing"""
"""Tools for transport properties postprocessing."""
return


@@ -183,7 +183,7 @@ def save():
help='x-axis quantity. [default: frequency]',
default=False,
show_default=False)
@directions_option
@direction_option
@temperature_option
@click.option('-o', '--output',
help='Output filename, sans extension.',
@@ -232,31 +232,32 @@ def save_kappa(filename, direction, output):
return


#@save.command('zt')
#@input_argument
#@click.option('-k', '--kappa',
# help='Phono3py kappa-mxxx.hdf5.',
# type=click.Path(exists=True, file_okay=True, dir_okay=False))
#@doping_type_option
#@direction_option
#@interpolate_options
#@click.option('-o', '--output',
# help='Output filename, sans extension.',
# default='tp-zt',
# show_default=True)
#def save_zt(filename, kappa, dtype, direction, interpolate, kind, output):
# """Extracts ZT from electronic transport data file.
#
# Saves ZT to hdf5 and highlights to yaml, and prints max to stdout.
# Currently accepts AMSET transport json or BoltzTraP hdf5, along with
# Phono3py hdf5 for lattice thermal conductivity.
# """
#
# tp.data.save.zt(filename, kappa, direction=direction, doping=dtype,
# tinterp=interpolate, dinterp=interpolate, kind=kind,
# output=output)
#
# return
@save.command('zt')
@input_argument
@click.option('-k', '--kappa',
help='Phono3py kappa-mxxx.hdf5.',
type=click.Path(exists=True, file_okay=True, dir_okay=False))
@doping_type_option
@direction_option
@interpolate_options
@click.option('-o', '--output',
help='Output filename, sans extension.',
default='tp-zt',
show_default=True)
def save_zt(filename, kappa, dtype, direction, interpolate, kind, output):
"""Extracts ZT from electronic transport data file.

Saves ZT to hdf5 and highlights to yaml, and prints max to stdout.
Currently accepts AMSET transport json or BoltzTraP hdf5, along with
Phono3py hdf5 for lattice thermal conductivity.
"""

tp.data.save.zt(filename, kappa, direction=direction, doping=dtype,
tinterp=interpolate, dinterp=interpolate, kind=kind,
output=output)
click.echo('{0}.yaml and {0}.hdf5 written'.format(output))

return



@@ -808,68 +809,68 @@ def wideband(phonons, kappa, temperature, poscar, colour, smoothing, style,
return


#@plot.command()
#@input_argument
#@click.option('-k', '--kappa',
# help='Phono3py kappa hdf5. Ignored if ZT is in file. If '
# 'otherwise unspecified, set to 1 (W m-1 K-1).',
# type=click.Path(file_okay=True, dir_okay=False))
#
#@direction_option
#@doping_type_option
#@interpolate_options
#
#@click.option('-c', '--colour',
# help='Colourmap name or #rrggbb highlight colour or min '
# 'and max and highlight #rrggbb colours to generate '
# 'a colourmap from.',
# multiple=True,
# default=['viridis'],
# show_default=True)
#
#@xyc_limit_options
#@plot_io_options
#@click.option('-o', '--output',
# help='Output filename, sans extension.',
# default='tp-ztmap',
# show_default=True)
#
#def ztmap(filename, kappa, direction, dtype, interpolate, colour, xmin, xmax,
# ymin, ymax, cmin, cmax, style, large, extension, output):
# """Plots ZT against temperature and carrier concentration."""
#
# axes = tp.axes.one_large if large else tp.axes.one
# if len(colour) == 1:
# colour = colour[0]
#
# try:
# edata = tp.data.load.amset(filename)
# except UnicodeDecodeError:
# try:
# edata = tp.data.load.boltztrap(filename, doping=dtype)
# except Exception:
# data = h5py.File(filename, 'r')
# edata = dict(data)
# for key in edata.keys():
# if isinstance(edata[key], dict) and dtype in edata[key]:
# edata[key] = edata[key][dtype][()]
#
# if kappa is not None:
# kdata = tp.data.load.phono3py(kappa)
# else:
# kdata = None
#
# fig, ax = axes.colourbar(style)
#
# tp.plot.heatmap.add_ztmap(ax, edata, kdata=kdata, direction=direction,
# xinterp=interpolate, yinterp=interpolate,
# kind=kind, colour=colour, xmin=xmin, xmax=xmax,
# ymin=ymin, ymax=ymax, cmin=cmin, cmax=cmax)
#
# for ext in extension:
# plt.savefig('{}.{}'.format(output, ext))
#
# return
@plot.command()
@input_argument
@click.option('-k', '--kappa',
help='Phono3py kappa hdf5. Ignored if ZT is in file. If '
'otherwise unspecified, set to 1 (W m-1 K-1).',
type=click.Path(file_okay=True, dir_okay=False))

@direction_option
@doping_type_option
@interpolate_options

@click.option('-c', '--colour',
help='Colourmap name or #rrggbb highlight colour or min '
'and max and highlight #rrggbb colours to generate '
'a colourmap from.',
multiple=True,
default=['viridis'],
show_default=True)

@xyc_limit_options
@plot_io_options
@click.option('-o', '--output',
help='Output filename, sans extension.',
default='tp-ztmap',
show_default=True)

def ztmap(filename, kappa, direction, dtype, interpolate, kind, colour, xmin,
xmax, ymin, ymax, cmin, cmax, style, large, extension, output):
"""Plots ZT against temperature and carrier concentration."""

axes = tp.axes.one_large if large else tp.axes.one
if len(colour) == 1:
colour = colour[0]

try:
edata = tp.data.load.amset(filename)
except UnicodeDecodeError:
try:
edata = tp.data.load.boltztrap(filename, doping=dtype)
except Exception:
data = h5py.File(filename, 'r')
edata = dict(data)
for key in edata.keys():
if isinstance(edata[key], dict) and dtype in edata[key]:
edata[key] = edata[key][dtype][()]

if kappa is not None:
kdata = tp.data.load.phono3py(kappa)
else:
kdata = None

fig, ax = axes.colourbar(style)

tp.plot.heatmap.add_ztmap(ax, edata, kdata=kdata, direction=direction,
xinterp=interpolate, yinterp=interpolate,
kind=kind, colour=colour, xmin=xmin, xmax=xmax,
ymin=ymin, ymax=ymax, cmin=cmin, cmax=cmax)

for ext in extension:
plt.savefig('{}.{}'.format(output, ext))

return



4 changes: 2 additions & 2 deletions tp/cli/options.py
Original file line number Diff line number Diff line change
@@ -52,7 +52,7 @@ def doping_type_option(f):
default='n',
show_default=True)(f)

return
return f

def input_argument(f):
"""Option for an input file."""
@@ -81,7 +81,7 @@ def interpolate_options(f):
type=click.IntRange(1),
default=200,
show_default=True)(f)
f = click.option('--kind', metavar='kind',
f = click.option('--kind',
help='Interpolation kind.',
default='linear',
show_default=True)(f)
9 changes: 8 additions & 1 deletion tp/data/save.py
Original file line number Diff line number Diff line change
@@ -356,7 +356,14 @@ def hdf5(data, output):
if isinstance(data[key][k], dict):
group2 = group.create_group(k)
for k2 in data[key][k].keys():
group2[k2] = data[key][k][k2]
if isinstance(data[key][k][k2], list) and \
len(data[key][k][k2]) != 0 and \
isinstance(data[key][k][k2][0], str):
ds = group2.create_dataset(k2, (len(data[key][k][k2]),),
dtype=h5py.string_dtype())
ds = data[key][k][k2]
else:
group2[k2] = data[key][k][k2]
else:
group[k] = data[key][k]
else:
70 changes: 18 additions & 52 deletions tp/plot/frequency.py
Original file line number Diff line number Diff line change
@@ -579,10 +579,11 @@ def add_waterfall(ax, data, quantity, xquantity='frequency', temperature=300,
invert : bool, optional
invert x- and y-axes. Default: False.

colour : colourmap or str or array-like, optional
colour : colourmap or str or array-like or dict, optional
colourmap or colourmap name or list of colours (one for
each band or one for each point) or a single colour.
Default: viridis.
each band or one for each point) or two colours for a linear
colourmap or a dictionary with cmin and cmax keys or a
single colour. Default: viridis.

kwargs
keyword arguments passed to matplotlib.pyplot.scatter.
@@ -643,8 +644,9 @@ def add_waterfall(ax, data, quantity, xquantity='frequency', temperature=300,
# colour
# Tries to read as a colourmap name or colourmap object or list of
# colours (of varying formats), one per band, and assigns
# appropriately. Otherwise leaves as is, which is appropriate for
# a single colour or colour per point.
# appropriately, or just two colours generate a linear colourmap, or
# a dictionary with cmin and cmax keys. Otherwise leaves as is,
# which is appropriate for a single colour or colour per point.

s = np.shape(data[xquantity])
try:
@@ -669,6 +671,10 @@ def add_waterfall(ax, data, quantity, xquantity='frequency', temperature=300,
colour = tp.plot.colour.linear(cmin=colour[0], cmax=colour[1])
colours = [colour(i) for i in np.linspace(0, 1, s[1])]
colours = np.tile(colours, (s[0], 1))
elif isinstance(colour, dict):
colour = tp.plot.colour.linear(**colour)
colours = [colour(i) for i in np.linspace(0, 1, s[1])]
colours = np.tile(colours, (s[0], 1))
else:
colours = colour

@@ -733,9 +739,9 @@ def add_projected_waterfall(ax, data, quantity, projected,
invert x- and y-axes. Default: False.

colour : colourmap or str or array-like or dict, optional
colourmap or colourmap name or highlight colour or
colourmap or colourmap name or #rrggbb highlight colour or
highlight, min, max colours in that order, or dictionary
with mid and min and/or max keys. Default: viridis.
with cmid and cmin and/or cmax keys. Default: viridis.
cmin : float, optional
colour scale minimum. Default: display 99 % data.
cmax : float, optional
@@ -809,27 +815,7 @@ def add_projected_waterfall(ax, data, quantity, projected,
y = np.abs(np.ravel(data[quantity]))
c = np.abs(np.ravel(data[projected]))

# colour
# Reads a colourmap or colourmap name.

try:
cmap = copy(mpl.cm.get_cmap(colour))
except ValueError:
if isinstance(colour, mpl.colors.ListedColormap):
cmap = copy(colour)
elif isinstance(colour, str):
colours = tp.plot.colour.uniform(colour)
elif isinstance(colour, list):
colours = tp.plot.colour.uniform(*colour)
elif isinstance(colour, dict):
colours = tp.plot.colour.uniform(**colour)
else:
raise Exception('colour must be a colourmap, colourmap '
'name, single #rrggbb highlight colour or '
'highlight, min, max #rrggbb colours in '
'that order, or a dictionary with mid and '
'min and/or max keys.')

cmap = tp.plot.utilities.parse_colours(colour)
cnorm, extend = tp.plot.utilities.colour_scale(c, projected, cmap, cmin,
cmax, cscale, unoccupied)

@@ -894,9 +880,9 @@ def add_density(ax, data, quantity, xquantity='frequency', temperature=300,
invert x- and y-axes. Default: False.

colour : colourmap or str or array-like or dict, optional
colourmap or colourmap name or highlight colour or
colourmap or colourmap name or #rrggbb highlight colour or
highlight, min, max colours in that order, or dictionary
with mid and min and/or max keys. Default: Blues.
with cmid and cmin and/or cmax keys. Default: Blues.

kwargs
keyword arguments passed to matplotlib.pyplot.scatter.
@@ -950,31 +936,11 @@ def add_density(ax, data, quantity, xquantity='frequency', temperature=300,
idx = z.argsort()
x_dens, y_dens, z_dens = x[idx], y[idx], z[idx]

# colour
# Tries to read as a colourmap or colourmap name, or uses a single
# #rrggbb colour as the highlight colour for a tp.plot.colour.uniform.

try:
colours = mpl.cm.get_cmap(colour)
except ValueError:
if isinstance(colour, mpl.colors.ListedColormap):
colours = colour
elif isinstance(colour, str):
colours = tp.plot.colour.uniform(colour)
elif isinstance(colour, list):
colours = tp.plot.colour.uniform(*colour)
elif isinstance(colour, dict):
colours = tp.plot.colour.uniform(**colour)
else:
raise Exception('colour must be a colourmap, colourmap '
'name, single #rrggbb highlight colour or '
'highlight, min, max #rrggbb colours in '
'that order, or a dictionary with mid and '
'min and/or max keys.')
cmap = tp.plot.utilities.parse_colours(colour)

# plotting

ax.scatter(x_dens, y_dens, c=z_dens, cmap=colour, **kwargs)
ax.scatter(x_dens, y_dens, c=z_dens, cmap=cmap, **kwargs)

# axes formatting

60 changes: 37 additions & 23 deletions tp/plot/phonons.py
Original file line number Diff line number Diff line change
@@ -235,10 +235,13 @@ def add_multi(ax, data, bandmin=None, bandmax=None, main=True, label=None,
label : array-like, optional
legend labels. Default: None
colour : colourmap or str or array-like, optional
colourmap or colourmap name or list of colours. Note [r,g,b]
format colours should be enclosed in and additional [],
i.e. [[[r,g,b]],...]. Default: winter_r.
colour : colourmap or str or array-like or dict, optional
colourmap or colourmap name or list of colours, one for each
dispersion or a min and max colour to generate a linear
colourmap between or a dictionary with cmin and cmax
keys. Note [r,g,b] format colours should be enclosed in
and additional [], i.e. [[[r,g,b]],...].
Default: winter_r.
linestyle : str or array-like, optional
linestyle(s) ('-', '--', '.-', ':'). Default: solid.
marker : str or array-like, optional
@@ -297,6 +300,12 @@ def add_multi(ax, data, bandmin=None, bandmax=None, main=True, label=None,
elif isinstance(colour, str) and colour == 'skelton':
colour = tp.plot.colour.skelton()
colours = [[colour(i)] for i in np.linspace(0, 1, len(data))]
elif isinstance(colour, list) and len(colour) == 2 and len(data) != 2:
colours = tp.plot.colour.linear(*colour)
colours = [[colour(i)] for i in np.linspace(0, 1, len(data))]
elif isintance(colour, dict):
colours = tp.plot.colour.linear(**colour)
colours = [[colour(i)] for i in np.linspace(0, 1, len(data))]
else:
colours = colour

@@ -631,8 +640,10 @@ def add_projected_dispersion(ax, data, pdata, quantity, bandmin=None,
number of points per path (e.g. gamma -> X) per line.
Default: 500.
colour : colormap or str, optional
colourmap or colourmap name. Default: viridis_r.
colour : colourmap or str or array-like or dict, optional
colourmap or colourmap name or #rrggbb highlight colour or
highlight, min, max colours in that order, or dictionary
with cmid and cmin and/or cmax keys. Default: viridis_r.
cmin : float, optional
colour scale minimum. Default: display 99 % data.
cmax : float, optional
@@ -755,10 +766,7 @@ def add_projected_dispersion(ax, data, pdata, quantity, bandmin=None,
kind='cubic', axis=0, fill_value='extrapolate')
c2.append(np.abs(cinterp(xtemp)))

if isinstance(colour, str):
cmap = copy(plt.cm.get_cmap(colour))
else:
cmap = copy(colour)
cmap = tp.plot.utilities.parse_colours(colour)
cnorm, extend = tp.plot.utilities.colour_scale(c2, quantity, cmap, cmin,
cmax, cscale, unoccupied)

@@ -789,7 +797,7 @@ def add_alt_projected_dispersion(ax, data, pdata, quantity, projected,
bandmin=None, bandmax=None, temperature=300,
direction='avg', poscar='POSCAR', main=True,
log=False, interpolate=10000, smoothing=10,
colour='viridis', cmin=None, cmax=None,
colour='viridis_r', cmin=None, cmax=None,
cscale=None, unoccupied='grey', workers=32,
xmarkkwargs={}, **kwargs):
"""Plots a phono3py quantity on a high-symmetry path and projection.
@@ -852,8 +860,10 @@ def add_alt_projected_dispersion(ax, data, pdata, quantity, projected,
smoothing : int, optional
every n points to sample. Default: 10.
colour : colormap or str, optional
colourmap or colourmap name. Default: viridis.
colour : colourmap or str or array-like or dict, optional
colourmap or colourmap name or #rrggbb highlight colour or
highlight, min, max colours in that order, or dictionary
with cmid and cmin and/or cmax keys. Default: viridis_r.
cmin : float, optional
colour scale minimum. Default: display 99 % data.
cmax : float, optional
@@ -985,10 +995,7 @@ def add_alt_projected_dispersion(ax, data, pdata, quantity, projected,

cinterp = interp1d(x, c2, kind='cubic', axis=0)
c2 = np.abs(cinterp(x2))
if isinstance(colour, str):
cmap = copy(plt.cm.get_cmap(colour))
else:
cmap = copy(colour)
cmap = tp.plot.utilities.parse_colours(colour)
cnorm, extend = tp.plot.utilities.colour_scale(c2, projected, cmap, cmin,
cmax, cscale, unoccupied)

@@ -1062,7 +1069,8 @@ def add_wideband(ax, kdata, pdata, temperature=300, poscar='POSCAR', main=True,
colour : colormap or str or list, optional
colourmap or colourmap name or max #RRGGBB colour (fades to
white) or min and max #RRGGBB colours. Default: viridis.
white) or min and max #RRGGBB colours or dictionary with
cmin and cmax keys. Default: viridis.
workers : int, optional
number of workers for paralellised section. Default: 32.
@@ -1178,15 +1186,21 @@ def add_wideband(ax, kdata, pdata, temperature=300, poscar='POSCAR', main=True,
# the min and max values.

try:
colours = mpl.cm.get_cmap(colour)
cmap = mpl.cm.get_cmap(colour)
except ValueError:
if isinstance(colour, mpl.colors.ListedColormap):
colours = colour
elif isinstace(colour, str):
cmap = tp.plot.colour.linear(colour)
elif isinstace(colour, list):
cmap = tp.plot.colour.linear(colour[1], colour[0])
elif isinstace(colour, dict):
cmap = tp.plot.colour.linear(**colour)
else:
try:
colours = tp.plot.colour.linear(colour)
except (ValueError, AttributeError):
colours = tp.plot.colour.linear(colour[1], colour[0])
raise Exception('colour must be a colourmap, colourmap '
'name, single #rrggbb max colour or min '
'and max #rrggbb colours, or a dictionary '
'with cmin and cmax keys.')

# plotting

43 changes: 42 additions & 1 deletion tp/plot/utilities.py
Original file line number Diff line number Diff line change
@@ -4,7 +4,9 @@
---------
colour_scale:
Sorts colour limits and colourbar format.
sorts colour limits and colourbar format.
parse_colours
returns a colour map from a range of input types.
scale_to_axis
scales data to axes limits
set_locators:
@@ -13,6 +15,7 @@

import matplotlib as mpl
import numpy as np
import tp

def colour_scale(c, name, cmap, cmin=None, cmax=None, cscale=None,
unoccupied='grey'):
@@ -117,6 +120,44 @@ def colour_scale(c, name, cmap, cmin=None, cmax=None, cscale=None,

return cnorm, extend

def parse_colours(colour):
"""Parses a range of inputs into a colourmap
Argument
--------
colour : colourmap or str or array-like or dict
colourmap or colourmap name or #rrggbb highlight colour or
highlight, min, max colours in that order, or dictionary
with cmid and cmin and/or cmax keys.
Returns
-------
colourmap
colourmap
"""

try:
cmap = copy(mpl.cm.get_cmap(colour))
except ValueError:
if isinstance(colour, mpl.colors.ListedColormap):
cmap = copy(colour)
elif isinstance(colour, str):
cmap = tp.plot.colour.uniform(colour)
elif isinstance(colour, list):
cmap = tp.plot.colour.uniform(*colour)
elif isinstance(colour, dict):
cmap = tp.plot.colour.uniform(**colour)
else:
raise Exception('colour must be a colourmap, colourmap '
'name, single #rrggbb highlight colour or '
'highlight, min, max #rrggbb colours in '
'that order, or a dictionary with cmid and '
'cmin and/or cmax keys.')

return cmap

def scale_to_axis(ax, data, exclude=[], scale=None, axis='y'):
"""Scale data to fit an axis.