Merge remote-tracking branch 'upstream/devel' into devel

This commit is contained in:
Zhenwen Dai 2016-01-14 09:42:19 +00:00
commit 52c6fe599f
14 changed files with 106 additions and 99 deletions

View file

@ -1 +1 @@
__version__ = "0.9.4" __version__ = "0.9.5"

View file

@ -190,8 +190,8 @@ class VarDTC(LatentFunctionInference):
tmp, _ = dtrtrs(Lm, psi1V, lower=1, trans=0) tmp, _ = dtrtrs(Lm, psi1V, lower=1, trans=0)
tmp, _ = dpotrs(LB, tmp, lower=1) tmp, _ = dpotrs(LB, tmp, lower=1)
woodbury_vector, _ = dtrtrs(Lm, tmp, lower=1, trans=1) woodbury_vector, _ = dtrtrs(Lm, tmp, lower=1, trans=1)
Bi, _ = dpotri(LB, lower=1) #Bi, _ = dpotri(LB, lower=1)
symmetrify(Bi) #symmetrify(Bi)
Bi = -dpotri(LB, lower=1)[0] Bi = -dpotri(LB, lower=1)[0]
diag.add(Bi, 1) diag.add(Bi, 1)

View file

@ -28,4 +28,4 @@ from .src.trunclinear import TruncLinear,TruncLinear_inf
from .src.splitKern import SplitKern,DEtime from .src.splitKern import SplitKern,DEtime
from .src.splitKern import DEtime as DiffGenomeKern from .src.splitKern import DEtime as DiffGenomeKern
from .src.spline import Spline from .src.spline import Spline
from .src.basis_funcs import LinearSlopeBasisFuncKernel, BasisFuncKernel, ChangePointBasisFuncKernel, DomainKernel from .src.basis_funcs import LogisticBasisFuncKernel, LinearSlopeBasisFuncKernel, BasisFuncKernel, ChangePointBasisFuncKernel, DomainKernel

View file

@ -18,7 +18,7 @@ class ODE_UYC(Kern):
self.lengthscale_U = Param('lengthscale_U', lengthscale_U, Logexp()) self.lengthscale_U = Param('lengthscale_U', lengthscale_U, Logexp())
self.ubias = Param('ubias', ubias, Logexp()) self.ubias = Param('ubias', ubias, Logexp())
self.add_parameters(self.variance_Y, self.variance_U, self.lengthscale_Y, self.lengthscale_U, self.ubias) self.link_parameters(self.variance_Y, self.variance_U, self.lengthscale_Y, self.lengthscale_U, self.ubias)
def K(self, X, X2=None): def K(self, X, X2=None):
# model : a * dy/dt + b * y = U # model : a * dy/dt + b * y = U

View file

@ -38,7 +38,7 @@ class ODE_st(Kern):
self.b = Param('b', b, Logexp()) self.b = Param('b', b, Logexp())
self.c = Param('c', c, Logexp()) self.c = Param('c', c, Logexp())
self.add_parameters(self.a, self.b, self.c, self.variance_Yt, self.variance_Yx, self.lengthscale_Yt,self.lengthscale_Yx) self.link_parameters(self.a, self.b, self.c, self.variance_Yt, self.variance_Yx, self.lengthscale_Yt,self.lengthscale_Yx)
def K(self, X, X2=None): def K(self, X, X2=None):

View file

@ -17,7 +17,7 @@ class ODE_t(Kern):
self.a= Param('a', a, Logexp()) self.a= Param('a', a, Logexp())
self.c = Param('c', c, Logexp()) self.c = Param('c', c, Logexp())
self.ubias = Param('ubias', ubias, Logexp()) self.ubias = Param('ubias', ubias, Logexp())
self.add_parameters(self.a, self.c, self.variance_Yt, self.lengthscale_Yt,self.ubias) self.link_parameters(self.a, self.c, self.variance_Yt, self.lengthscale_Yt,self.ubias)
def K(self, X, X2=None): def K(self, X, X2=None):
"""Compute the covariance matrix between X and X2.""" """Compute the covariance matrix between X and X2."""

View file

@ -50,6 +50,17 @@ def _wait_for_updates(view, updates):
# No updateable view: # No updateable view:
pass pass
def _new_canvas(self, projection, kwargs, which_indices):
input_1, input_2, input_3 = sig_dims = self.get_most_significant_input_dimensions(which_indices)
if input_3 is None:
zlabel = None
else:
zlabel = 'latent dimension %i' % input_3
canvas, kwargs = pl().new_canvas(projection=projection, xlabel='latent dimension %i' % input_1,
ylabel='latent dimension %i' % input_2,
zlabel=zlabel, **kwargs)
return canvas, projection, kwargs, sig_dims
def _plot_latent_scatter(canvas, X, visible_dims, labels, marker, num_samples, projection='2d', **kwargs): def _plot_latent_scatter(canvas, X, visible_dims, labels, marker, num_samples, projection='2d', **kwargs):
from .. import Tango from .. import Tango
@ -85,12 +96,8 @@ def plot_latent_scatter(self, labels=None,
:param str marker: markers to use - cycle if more labels then markers are given :param str marker: markers to use - cycle if more labels then markers are given
:param kwargs: the kwargs for the scatter plots :param kwargs: the kwargs for the scatter plots
""" """
input_1, input_2, input_3 = sig_dims = self.get_most_significant_input_dimensions(which_indices) canvas, projection, kwargs, sig_dims = _new_canvas(self, projection, kwargs, which_indices)
canvas, kwargs = pl().new_canvas(projection=projection,
xlabel='latent dimension %i' % input_1,
ylabel='latent dimension %i' % input_2,
zlabel='latent dimension %i' % input_3, **kwargs)
X, _, _ = get_x_y_var(self) X, _, _ = get_x_y_var(self)
if labels is None: if labels is None:
labels = np.ones(self.num_data) labels = np.ones(self.num_data)
@ -101,8 +108,6 @@ def plot_latent_scatter(self, labels=None,
return pl().add_to_canvas(canvas, dict(scatter=scatters), legend=legend) return pl().add_to_canvas(canvas, dict(scatter=scatters), legend=legend)
def plot_latent_inducing(self, def plot_latent_inducing(self,
which_indices=None, which_indices=None,
legend=False, legend=False,
@ -122,17 +127,8 @@ def plot_latent_inducing(self,
:param str marker: markers to use - cycle if more labels then markers are given :param str marker: markers to use - cycle if more labels then markers are given
:param kwargs: the kwargs for the scatter plots :param kwargs: the kwargs for the scatter plots
""" """
input_1, input_2, input_3 = sig_dims = self.get_most_significant_input_dimensions(which_indices) canvas, projection, kwargs, sig_dims = _new_canvas(self, projection, kwargs, which_indices)
if input_3 is None: zlabel=None
else: zlabel = 'latent dimension %i' % input_3
if 'color' not in kwargs:
kwargs['color'] = 'white'
canvas, kwargs = pl().new_canvas(projection=projection,
xlabel='latent dimension %i' % input_1,
ylabel='latent dimension %i' % input_2,
zlabel=zlabel, **kwargs)
Z = self.Z.values Z = self.Z.values
labels = np.array(['inducing'] * Z.shape[0]) labels = np.array(['inducing'] * Z.shape[0])
scatters = _plot_latent_scatter(canvas, Z, sig_dims, labels, marker, num_samples, projection=projection, **kwargs) scatters = _plot_latent_scatter(canvas, Z, sig_dims, labels, marker, num_samples, projection=projection, **kwargs)
@ -231,7 +227,7 @@ def plot_latent(self, labels=None, which_indices=None,
plot_limits=None, plot_limits=None,
updates=False, updates=False,
kern=None, marker='<>^vsd', kern=None, marker='<>^vsd',
num_samples=1000, num_samples=1000, projection='2d',
scatter_kwargs=None, **imshow_kwargs): scatter_kwargs=None, **imshow_kwargs):
""" """
Plot the latent space of the GP on the inputs. This is the Plot the latent space of the GP on the inputs. This is the
@ -251,6 +247,8 @@ def plot_latent(self, labels=None, which_indices=None,
:param imshow_kwargs: the kwargs for the imshow (magnification factor) :param imshow_kwargs: the kwargs for the imshow (magnification factor)
:param scatter_kwargs: the kwargs for the scatter plots :param scatter_kwargs: the kwargs for the scatter plots
""" """
if projection != '2d':
raise ValueError('Cannot plot latent in other then 2 dimensions, consider plot_scatter')
input_1, input_2 = which_indices = self.get_most_significant_input_dimensions(which_indices)[:2] input_1, input_2 = which_indices = self.get_most_significant_input_dimensions(which_indices)[:2]
X = get_x_y_var(self)[0] X = get_x_y_var(self)[0]
_, _, Xgrid, _, _, xmin, xmax, resolution = helper_for_plot_data(self, X, plot_limits, which_indices, None, resolution) _, _, Xgrid, _, _, xmin, xmax, resolution = helper_for_plot_data(self, X, plot_limits, which_indices, None, resolution)

View file

@ -1,21 +1,21 @@
#=============================================================================== #===============================================================================
# Copyright (c) 2015, Max Zwiessele # Copyright (c) 2015, Max Zwiessele
# All rights reserved. # All rights reserved.
# #
# Redistribution and use in source and binary forms, with or without # Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met: # modification, are permitted provided that the following conditions are met:
# #
# * Redistributions of source code must retain the above copyright notice, this # * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer. # list of conditions and the following disclaimer.
# #
# * Redistributions in binary form must reproduce the above copyright notice, # * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation # this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution. # and/or other materials provided with the distribution.
# #
# * Neither the name of GPy.plotting.matplot_dep.plot_definitions nor the names of its # * Neither the name of GPy.plotting.matplot_dep.plot_definitions nor the names of its
# contributors may be used to endorse or promote products derived from # contributors may be used to endorse or promote products derived from
# this software without specific prior written permission. # this software without specific prior written permission.
# #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
@ -41,14 +41,14 @@ class MatplotlibPlots(AbstractPlottingLibrary):
def __init__(self): def __init__(self):
super(MatplotlibPlots, self).__init__() super(MatplotlibPlots, self).__init__()
self._defaults = defaults.__dict__ self._defaults = defaults.__dict__
def figure(self, rows=1, cols=1, **kwargs): def figure(self, rows=1, cols=1, **kwargs):
fig = plt.figure(**kwargs) fig = plt.figure(**kwargs)
fig.rows = rows fig.rows = rows
fig.cols = cols fig.cols = cols
return fig return fig
def new_canvas(self, figure=None, col=1, row=1, projection='2d', xlabel=None, ylabel=None, zlabel=None, title=None, xlim=None, ylim=None, zlim=None, **kwargs): def new_canvas(self, figure=None, row=1, col=1, projection='2d', xlabel=None, ylabel=None, zlabel=None, title=None, xlim=None, ylim=None, zlim=None, **kwargs):
if projection == '3d': if projection == '3d':
from mpl_toolkits.mplot3d import Axes3D from mpl_toolkits.mplot3d import Axes3D
elif projection == '2d': elif projection == '2d':
@ -64,10 +64,10 @@ class MatplotlibPlots(AbstractPlottingLibrary):
fig = self.figure(figsize=kwargs.pop('figsize')) fig = self.figure(figsize=kwargs.pop('figsize'))
else: else:
fig = self.figure() fig = self.figure()
#if hasattr(fig, 'rows') and hasattr(fig, 'cols'): #if hasattr(fig, 'rows') and hasattr(fig, 'cols'):
ax = fig.add_subplot(fig.rows, fig.cols, (col,row), projection=projection) ax = fig.add_subplot(fig.rows, fig.cols, (col,row), projection=projection)
if xlim is not None: ax.set_xlim(xlim) if xlim is not None: ax.set_xlim(xlim)
if ylim is not None: ax.set_ylim(ylim) if ylim is not None: ax.set_ylim(ylim)
if xlabel is not None: ax.set_xlabel(xlabel) if xlabel is not None: ax.set_xlabel(xlabel)
@ -77,7 +77,7 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if zlim is not None: ax.set_zlim(zlim) if zlim is not None: ax.set_zlim(zlim)
if zlabel is not None: ax.set_zlabel(zlabel) if zlabel is not None: ax.set_zlabel(zlabel)
return ax, kwargs return ax, kwargs
def add_to_canvas(self, ax, plots, legend=False, title=None, **kwargs): def add_to_canvas(self, ax, plots, legend=False, title=None, **kwargs):
ax.autoscale_view() ax.autoscale_view()
fontdict=dict(family='sans-serif', weight='light', size=9) fontdict=dict(family='sans-serif', weight='light', size=9)
@ -88,18 +88,18 @@ class MatplotlibPlots(AbstractPlottingLibrary):
legend_ontop(ax, ncol=legend, fontdict=fontdict) legend_ontop(ax, ncol=legend, fontdict=fontdict)
if title is not None: ax.figure.suptitle(title) if title is not None: ax.figure.suptitle(title)
return ax return ax
def show_canvas(self, ax, tight_layout=False, **kwargs): def show_canvas(self, ax, tight_layout=False, **kwargs):
if tight_layout: if tight_layout:
ax.figure.tight_layout() ax.figure.tight_layout()
ax.figure.canvas.draw() ax.figure.canvas.draw()
return ax.figure return ax.figure
def scatter(self, ax, X, Y, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, marker='o', **kwargs): def scatter(self, ax, X, Y, Z=None, color=Tango.colorsHex['mediumBlue'], label=None, marker='o', **kwargs):
if Z is not None: if Z is not None:
return ax.scatter(X, Y, c=color, zs=Z, label=label, marker=marker, **kwargs) return ax.scatter(X, Y, c=color, zs=Z, label=label, marker=marker, **kwargs)
return ax.scatter(X, Y, c=color, label=label, marker=marker, **kwargs) return ax.scatter(X, Y, c=color, label=label, marker=marker, **kwargs)
def plot(self, ax, X, Y, Z=None, color=None, label=None, **kwargs): def plot(self, ax, X, Y, Z=None, color=None, label=None, **kwargs):
if Z is not None: if Z is not None:
return ax.plot(X, Y, color=color, zs=Z, label=label, **kwargs) return ax.plot(X, Y, color=color, zs=Z, label=label, **kwargs)
@ -122,23 +122,23 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if 'align' not in kwargs: if 'align' not in kwargs:
kwargs['align'] = 'center' kwargs['align'] = 'center'
return ax.bar(left=x, height=height, width=width, return ax.bar(left=x, height=height, width=width,
bottom=bottom, label=label, color=color, bottom=bottom, label=label, color=color,
**kwargs) **kwargs)
def xerrorbar(self, ax, X, Y, error, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs): def xerrorbar(self, ax, X, Y, error, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs):
if not('linestyle' in kwargs or 'ls' in kwargs): if not('linestyle' in kwargs or 'ls' in kwargs):
kwargs['ls'] = 'none' kwargs['ls'] = 'none'
#if Z is not None: #if Z is not None:
# return ax.errorbar(X, Y, Z, xerr=error, ecolor=color, label=label, **kwargs) # return ax.errorbar(X, Y, Z, xerr=error, ecolor=color, label=label, **kwargs)
return ax.errorbar(X, Y, xerr=error, ecolor=color, label=label, **kwargs) return ax.errorbar(X, Y, xerr=error, ecolor=color, label=label, **kwargs)
def yerrorbar(self, ax, X, Y, error, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs): def yerrorbar(self, ax, X, Y, error, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs):
if not('linestyle' in kwargs or 'ls' in kwargs): if not('linestyle' in kwargs or 'ls' in kwargs):
kwargs['ls'] = 'none' kwargs['ls'] = 'none'
#if Z is not None: #if Z is not None:
# return ax.errorbar(X, Y, Z, yerr=error, ecolor=color, label=label, **kwargs) # return ax.errorbar(X, Y, Z, yerr=error, ecolor=color, label=label, **kwargs)
return ax.errorbar(X, Y, yerr=error, ecolor=color, label=label, **kwargs) return ax.errorbar(X, Y, yerr=error, ecolor=color, label=label, **kwargs)
def imshow(self, ax, X, extent=None, label=None, vmin=None, vmax=None, **imshow_kwargs): def imshow(self, ax, X, extent=None, label=None, vmin=None, vmax=None, **imshow_kwargs):
if 'origin' not in imshow_kwargs: if 'origin' not in imshow_kwargs:
imshow_kwargs['origin'] = 'lower' imshow_kwargs['origin'] = 'lower'
@ -178,7 +178,7 @@ class MatplotlibPlots(AbstractPlottingLibrary):
if 'origin' not in imshow_kwargs: if 'origin' not in imshow_kwargs:
imshow_kwargs['origin'] = 'lower' imshow_kwargs['origin'] = 'lower'
return ImAnnotateController(ax, plot_function, extent, resolution=resolution, imshow_kwargs=imshow_kwargs or {}, **annotation_kwargs) return ImAnnotateController(ax, plot_function, extent, resolution=resolution, imshow_kwargs=imshow_kwargs or {}, **annotation_kwargs)
def contour(self, ax, X, Y, C, levels=20, label=None, **kwargs): def contour(self, ax, X, Y, C, levels=20, label=None, **kwargs):
return ax.contour(X, Y, C, levels=np.linspace(C.min(), C.max(), levels), label=label, **kwargs) return ax.contour(X, Y, C, levels=np.linspace(C.min(), C.max(), levels), label=label, **kwargs)
@ -191,13 +191,13 @@ class MatplotlibPlots(AbstractPlottingLibrary):
def fill_gradient(self, canvas, X, percentiles, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs): def fill_gradient(self, canvas, X, percentiles, color=Tango.colorsHex['mediumBlue'], label=None, **kwargs):
ax = canvas ax = canvas
plots = [] plots = []
if 'edgecolors' not in kwargs: if 'edgecolors' not in kwargs:
kwargs['edgecolors'] = 'none' kwargs['edgecolors'] = 'none'
if 'facecolors' in kwargs: if 'facecolors' in kwargs:
color = kwargs.pop('facecolors') color = kwargs.pop('facecolors')
if 'array' in kwargs: if 'array' in kwargs:
array = kwargs.pop('array') array = kwargs.pop('array')
else: else:
@ -231,8 +231,8 @@ class MatplotlibPlots(AbstractPlottingLibrary):
# pass # pass
a, b = tee(iterable) a, b = tee(iterable)
next(b, None) next(b, None)
return zip(a, b) return zip(a, b)
polycol = [] polycol = []
for y1, y2 in pairwise(percentiles): for y1, y2 in pairwise(percentiles):
import matplotlib.mlab as mlab import matplotlib.mlab as mlab
@ -244,51 +244,51 @@ class MatplotlibPlots(AbstractPlottingLibrary):
x = ma.masked_invalid(ax.convert_xunits(X)) x = ma.masked_invalid(ax.convert_xunits(X))
y1 = ma.masked_invalid(ax.convert_yunits(y1)) y1 = ma.masked_invalid(ax.convert_yunits(y1))
y2 = ma.masked_invalid(ax.convert_yunits(y2)) y2 = ma.masked_invalid(ax.convert_yunits(y2))
if y1.ndim == 0: if y1.ndim == 0:
y1 = np.ones_like(x) * y1 y1 = np.ones_like(x) * y1
if y2.ndim == 0: if y2.ndim == 0:
y2 = np.ones_like(x) * y2 y2 = np.ones_like(x) * y2
if where is None: if where is None:
where = np.ones(len(x), np.bool) where = np.ones(len(x), np.bool)
else: else:
where = np.asarray(where, np.bool) where = np.asarray(where, np.bool)
if not (x.shape == y1.shape == y2.shape == where.shape): if not (x.shape == y1.shape == y2.shape == where.shape):
raise ValueError("Argument dimensions are incompatible") raise ValueError("Argument dimensions are incompatible")
from functools import reduce from functools import reduce
mask = reduce(ma.mask_or, [ma.getmask(a) for a in (x, y1, y2)]) mask = reduce(ma.mask_or, [ma.getmask(a) for a in (x, y1, y2)])
if mask is not ma.nomask: if mask is not ma.nomask:
where &= ~mask where &= ~mask
polys = [] polys = []
for ind0, ind1 in mlab.contiguous_regions(where): for ind0, ind1 in mlab.contiguous_regions(where):
xslice = x[ind0:ind1] xslice = x[ind0:ind1]
y1slice = y1[ind0:ind1] y1slice = y1[ind0:ind1]
y2slice = y2[ind0:ind1] y2slice = y2[ind0:ind1]
if not len(xslice): if not len(xslice):
continue continue
N = len(xslice) N = len(xslice)
p = np.zeros((2 * N + 2, 2), np.float) p = np.zeros((2 * N + 2, 2), np.float)
# the purpose of the next two lines is for when y2 is a # the purpose of the next two lines is for when y2 is a
# scalar like 0 and we want the fill to go all the way # scalar like 0 and we want the fill to go all the way
# down to 0 even if none of the y1 sample points do # down to 0 even if none of the y1 sample points do
start = xslice[0], y2slice[0] start = xslice[0], y2slice[0]
end = xslice[-1], y2slice[-1] end = xslice[-1], y2slice[-1]
p[0] = start p[0] = start
p[N + 1] = end p[N + 1] = end
p[1:N + 1, 0] = xslice p[1:N + 1, 0] = xslice
p[1:N + 1, 1] = y1slice p[1:N + 1, 1] = y1slice
p[N + 2:, 0] = xslice[::-1] p[N + 2:, 0] = xslice[::-1]
p[N + 2:, 1] = y2slice[::-1] p[N + 2:, 1] = y2slice[::-1]
polys.append(p) polys.append(p)
polycol.extend(polys) polycol.extend(polys)
from matplotlib.collections import PolyCollection from matplotlib.collections import PolyCollection

View file

@ -72,5 +72,5 @@ ard = dict(linewidth=1.2, barmode='stack')
latent = dict(colorscale='Greys', reversescale=True, zsmooth='best') latent = dict(colorscale='Greys', reversescale=True, zsmooth='best')
gradient = dict(colorscale='RdBu', opacity=.7) gradient = dict(colorscale='RdBu', opacity=.7)
magnification = dict(colorscale='Greys', zsmooth='best', reversescale=True) magnification = dict(colorscale='Greys', zsmooth='best', reversescale=True)
latent_scatter = dict(marker_kwargs=dict(size='15', opacity=.7)) latent_scatter = dict(marker_kwargs=dict(size='5', opacity=.7))
# annotation = dict(fontdict=dict(family='sans-serif', weight='light', fontsize=9), zorder=.3, alpha=.7) # annotation = dict(fontdict=dict(family='sans-serif', weight='light', fontsize=9), zorder=.3, alpha=.7)

View file

@ -130,14 +130,15 @@ class PlotlyPlots(AbstractPlottingLibrary):
except: except:
#not matplotlib marker #not matplotlib marker
pass pass
marker_kwargs = marker_kwargs or {}
marker_kwargs.setdefault('symbol', marker) marker_kwargs.setdefault('symbol', marker)
if Z is not None: if Z is not None:
return Scatter3d(x=X, y=Y, z=Z, mode='markers', return Scatter3d(x=X, y=Y, z=Z, mode='markers',
showlegend=label is not None, showlegend=label is not None,
marker=Marker(color=color, colorscale=cmap, **marker_kwargs or {}), marker=Marker(color=color, colorscale=cmap, **marker_kwargs),
name=label, **kwargs) name=label, **kwargs)
return Scatter(x=X, y=Y, mode='markers', showlegend=label is not None, return Scatter(x=X, y=Y, mode='markers', showlegend=label is not None,
marker=Marker(color=color, colorscale=cmap, **marker_kwargs or {}), marker=Marker(color=color, colorscale=cmap, **marker_kwargs or {}),
name=label, **kwargs) name=label, **kwargs)
def plot(self, ax, X, Y, Z=None, color=None, label=None, line_kwargs=None, **kwargs): def plot(self, ax, X, Y, Z=None, color=None, label=None, line_kwargs=None, **kwargs):
@ -169,10 +170,10 @@ class PlotlyPlots(AbstractPlottingLibrary):
elif X.shape[1] == 2: elif X.shape[1] == 2:
marker_kwargs.setdefault('symbol', 'diamond') marker_kwargs.setdefault('symbol', 'diamond')
opacity = kwargs.pop('opacity', .8) opacity = kwargs.pop('opacity', .8)
return Scatter3d(x=X[:, 0], y=X[:, 1], z=np.zeros(X.shape[0]), return Scatter3d(x=X[:, 0], y=X[:, 1], z=np.zeros(X.shape[0]),
mode='markers', mode='markers',
projection=dict(z=dict(show=True, opacity=opacity)), projection=dict(z=dict(show=True, opacity=opacity)),
marker=Marker(color=color, **marker_kwargs or {}), marker=Marker(color=color, **marker_kwargs or {}),
opacity=0, opacity=0,
name=label, name=label,
showlegend=label is not None, **kwargs) showlegend=label is not None, **kwargs)
@ -284,11 +285,11 @@ class PlotlyPlots(AbstractPlottingLibrary):
if color.startswith('#'): if color.startswith('#'):
colarray = Tango.hex2rgb(color) colarray = Tango.hex2rgb(color)
opacity = .9 opacity = .9
else: else:
colarray = map(float(color.strip(')').split('(')[1])) colarray = map(float(color.strip(')').split('(')[1]))
if len(colarray) == 4: if len(colarray) == 4:
colarray, opacity = colarray[:3] ,colarray[3] colarray, opacity = colarray[:3] ,colarray[3]
alpha = opacity*(1.-np.abs(np.linspace(-1,1,len(percentiles)-1))) alpha = opacity*(1.-np.abs(np.linspace(-1,1,len(percentiles)-1)))
def pairwise(iterable): def pairwise(iterable):
@ -302,11 +303,11 @@ class PlotlyPlots(AbstractPlottingLibrary):
for i, y1, a in zip(range(len(percentiles)), percentiles, alpha): for i, y1, a in zip(range(len(percentiles)), percentiles, alpha):
fcolor = 'rgba({}, {}, {}, {alpha})'.format(*colarray, alpha=a) fcolor = 'rgba({}, {}, {}, {alpha})'.format(*colarray, alpha=a)
if i == len(percentiles)/2: if i == len(percentiles)/2:
polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=True, polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=True,
name=label, line=Line(width=0, smoothing=0), mode='none', fill='tonextx', name=label, line=Line(width=0, smoothing=0), mode='none', fill='tonextx',
legendgroup='density', hoverinfo='none', **kwargs)) legendgroup='density', hoverinfo='none', **kwargs))
else: else:
polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=False, polycol.append(Scatter(x=X, y=y1, fillcolor=fcolor, showlegend=False,
name=None, line=Line(width=1, smoothing=0, color=fcolor), mode='none', fill='tonextx', name=None, line=Line(width=1, smoothing=0, color=fcolor), mode='none', fill='tonextx',
legendgroup='density', hoverinfo='none', **kwargs)) legendgroup='density', hoverinfo='none', **kwargs))
return polycol return polycol

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 9 KiB

Before After
Before After

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

After

Width:  |  Height:  |  Size: 9 KiB

Before After
Before After

View file

@ -27,13 +27,21 @@
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#=============================================================================== #===============================================================================
#===============================================================================
# SKIPPING PLOTTING BECAUSE IT BEHAVES DIFFERENTLY ON DIFFERENT
# SYSTEMS, AND WILL MISBEHAVE
from nose import SkipTest
raise SkipTest("Skipping Matplotlib testing")
#===============================================================================
import matplotlib import matplotlib
from unittest.case import TestCase from unittest.case import TestCase
matplotlib.use('agg') matplotlib.use('agg')
import numpy as np import numpy as np
import GPy, os import GPy, os
from nose import SkipTest
from GPy.util.config import config from GPy.util.config import config
from GPy.plotting import change_plotting_library, plotting_library from GPy.plotting import change_plotting_library, plotting_library
@ -41,7 +49,7 @@ from GPy.plotting import change_plotting_library, plotting_library
class ConfigTest(TestCase): class ConfigTest(TestCase):
def tearDown(self): def tearDown(self):
change_plotting_library('matplotlib') change_plotting_library('matplotlib')
def test_change_plotting(self): def test_change_plotting(self):
self.assertRaises(ValueError, change_plotting_library, 'not+in9names') self.assertRaises(ValueError, change_plotting_library, 'not+in9names')
change_plotting_library('none') change_plotting_library('none')
@ -115,12 +123,12 @@ def test_figure():
import warnings import warnings
with warnings.catch_warnings(): with warnings.catch_warnings():
warnings.simplefilter("ignore") warnings.simplefilter("ignore")
ax, _ = pl().new_canvas(num=1) ax, _ = pl().new_canvas(num=1)
def test_func(x): def test_func(x):
return x[:, 0].reshape(3,3) return x[:, 0].reshape(3,3)
pl().imshow_interact(ax, test_func, extent=(-1,1,-1,1), resolution=3) pl().imshow_interact(ax, test_func, extent=(-1,1,-1,1), resolution=3)
ax, _ = pl().new_canvas() ax, _ = pl().new_canvas()
def test_func_2(x): def test_func_2(x):
y = x[:, 0].reshape(3,3) y = x[:, 0].reshape(3,3)
@ -129,21 +137,21 @@ def test_figure():
pl().annotation_heatmap_interact(ax, test_func_2, extent=(-1,1,-1,1), resolution=3) pl().annotation_heatmap_interact(ax, test_func_2, extent=(-1,1,-1,1), resolution=3)
pl().annotation_heatmap_interact(ax, test_func_2, extent=(-1,1,-1,1), resolution=3, imshow_kwargs=dict(interpolation='nearest')) pl().annotation_heatmap_interact(ax, test_func_2, extent=(-1,1,-1,1), resolution=3, imshow_kwargs=dict(interpolation='nearest'))
ax, _ = pl().new_canvas(figsize=(4,3)) ax, _ = pl().new_canvas(figsize=(4,3))
x = np.linspace(0,1,100) x = np.linspace(0,1,100)
y = [0,1,2] y = [0,1,2]
array = np.array([.4,.5]) array = np.array([.4,.5])
cmap = matplotlib.colors.LinearSegmentedColormap.from_list('WhToColor', ('r', 'b'), N=array.size) cmap = matplotlib.colors.LinearSegmentedColormap.from_list('WhToColor', ('r', 'b'), N=array.size)
pl().fill_gradient(ax, x, y, facecolors=['r', 'g'], array=array, cmap=cmap) pl().fill_gradient(ax, x, y, facecolors=['r', 'g'], array=array, cmap=cmap)
ax, _ = pl().new_canvas(num=4, figsize=(4,3), projection='3d', xlabel='x', ylabel='y', zlabel='z', title='awsome title', xlim=(-1,1), ylim=(-1,1), zlim=(-3,3)) ax, _ = pl().new_canvas(num=4, figsize=(4,3), projection='3d', xlabel='x', ylabel='y', zlabel='z', title='awsome title', xlim=(-1,1), ylim=(-1,1), zlim=(-3,3))
z = 2-np.abs(np.linspace(-2,2,(100)))+1 z = 2-np.abs(np.linspace(-2,2,(100)))+1
x, y = z*np.sin(np.linspace(-2*np.pi,2*np.pi,(100))), z*np.cos(np.linspace(-np.pi,np.pi,(100))) x, y = z*np.sin(np.linspace(-2*np.pi,2*np.pi,(100))), z*np.cos(np.linspace(-np.pi,np.pi,(100)))
pl().plot(ax, x, y, z, linewidth=2) pl().plot(ax, x, y, z, linewidth=2)
for do_test in _image_comparison( for do_test in _image_comparison(
baseline_images=['coverage_{}'.format(sub) for sub in ["imshow_interact",'annotation_interact','gradient','3d_plot',]], baseline_images=['coverage_{}'.format(sub) for sub in ["imshow_interact",'annotation_interact','gradient','3d_plot',]],
extensions=extensions): extensions=extensions):
@ -194,9 +202,9 @@ def test_plot():
m.plot_errorbars_trainset() m.plot_errorbars_trainset()
m.plot_samples() m.plot_samples()
m.plot_data_error() m.plot_data_error()
for do_test in _image_comparison(baseline_images=['gp_{}'.format(sub) for sub in ["data", "mean", 'conf', for do_test in _image_comparison(baseline_images=['gp_{}'.format(sub) for sub in ["data", "mean", 'conf',
'density', 'density',
'out_error', 'out_error',
'samples', 'in_error']], extensions=extensions): 'samples', 'in_error']], extensions=extensions):
yield (do_test, ) yield (do_test, )
@ -216,9 +224,9 @@ def test_twod():
m.plot_inducing() m.plot_inducing()
#m.plot_errorbars_trainset() #m.plot_errorbars_trainset()
m.plot_data_error() m.plot_data_error()
for do_test in _image_comparison(baseline_images=['gp_2d_{}'.format(sub) for sub in ["data", "mean", for do_test in _image_comparison(baseline_images=['gp_2d_{}'.format(sub) for sub in ["data", "mean",
'inducing', 'inducing',
#'out_error', #'out_error',
'in_error', 'in_error',
]], extensions=extensions): ]], extensions=extensions):
yield (do_test, ) yield (do_test, )
@ -242,7 +250,7 @@ def test_threed():
m.plot_mean(projection='3d') m.plot_mean(projection='3d')
m.plot_inducing(projection='3d') m.plot_inducing(projection='3d')
#m.plot_errorbars_trainset(projection='3d') #m.plot_errorbars_trainset(projection='3d')
for do_test in _image_comparison(baseline_images=['gp_3d_{}'.format(sub) for sub in ["data", "mean", 'inducing', for do_test in _image_comparison(baseline_images=['gp_3d_{}'.format(sub) for sub in ["data", "mean", 'inducing',
#'error', #'error',
#"samples", "samples_lik" #"samples", "samples_lik"
]], extensions=extensions): ]], extensions=extensions):
@ -316,7 +324,7 @@ def test_gplvm():
matplotlib.rcParams[u'figure.figsize'] = (4,3) matplotlib.rcParams[u'figure.figsize'] = (4,3)
matplotlib.rcParams[u'text.usetex'] = False matplotlib.rcParams[u'text.usetex'] = False
Q = 3 Q = 3
# Define dataset # Define dataset
N = 10 N = 10
k1 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,10,10,0.1,0.1]), ARD=True) k1 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,10,10,0.1,0.1]), ARD=True)
k2 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,0.1,10,0.1,10]), ARD=True) k2 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,0.1,10,0.1,10]), ARD=True)
@ -325,10 +333,10 @@ def test_gplvm():
A = np.random.multivariate_normal(np.zeros(N), k1.K(X), Q).T A = np.random.multivariate_normal(np.zeros(N), k1.K(X), Q).T
B = np.random.multivariate_normal(np.zeros(N), k2.K(X), Q).T B = np.random.multivariate_normal(np.zeros(N), k2.K(X), Q).T
C = np.random.multivariate_normal(np.zeros(N), k3.K(X), Q).T C = np.random.multivariate_normal(np.zeros(N), k3.K(X), Q).T
Y = np.vstack((A,B,C)) Y = np.vstack((A,B,C))
labels = np.hstack((np.zeros(A.shape[0]), np.ones(B.shape[0]), np.ones(C.shape[0])*2)) labels = np.hstack((np.zeros(A.shape[0]), np.ones(B.shape[0]), np.ones(C.shape[0])*2))
k = RBF(Q, ARD=True, lengthscale=2) # + kern.white(Q, _np.exp(-2)) # + kern.bias(Q) k = RBF(Q, ARD=True, lengthscale=2) # + kern.white(Q, _np.exp(-2)) # + kern.bias(Q)
m = GPLVM(Y, Q, init="PCA", kernel=k) m = GPLVM(Y, Q, init="PCA", kernel=k)
m.kern.lengthscale[:] = [1./.3, 1./.1, 1./.7] m.kern.lengthscale[:] = [1./.3, 1./.1, 1./.7]
@ -341,7 +349,7 @@ def test_gplvm():
np.random.seed(111) np.random.seed(111)
m.plot_magnification(labels=labels) m.plot_magnification(labels=labels)
m.plot_steepest_gradient_map(resolution=10, data_labels=labels) m.plot_steepest_gradient_map(resolution=10, data_labels=labels)
for do_test in _image_comparison(baseline_images=['gplvm_{}'.format(sub) for sub in ["latent", "latent_3d", "magnification", 'gradient']], for do_test in _image_comparison(baseline_images=['gplvm_{}'.format(sub) for sub in ["latent", "latent_3d", "magnification", 'gradient']],
extensions=extensions, extensions=extensions,
tol=12): tol=12):
yield (do_test, ) yield (do_test, )
@ -355,7 +363,7 @@ def test_bayesian_gplvm():
matplotlib.rcParams[u'figure.figsize'] = (4,3) matplotlib.rcParams[u'figure.figsize'] = (4,3)
matplotlib.rcParams[u'text.usetex'] = False matplotlib.rcParams[u'text.usetex'] = False
Q = 3 Q = 3
# Define dataset # Define dataset
N = 10 N = 10
k1 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,10,10,0.1,0.1]), ARD=True) k1 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,10,10,0.1,0.1]), ARD=True)
k2 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,0.1,10,0.1,10]), ARD=True) k2 = GPy.kern.RBF(5, variance=1, lengthscale=1./np.random.dirichlet(np.r_[10,0.1,10,0.1,10]), ARD=True)
@ -364,10 +372,10 @@ def test_bayesian_gplvm():
A = np.random.multivariate_normal(np.zeros(N), k1.K(X), Q).T A = np.random.multivariate_normal(np.zeros(N), k1.K(X), Q).T
B = np.random.multivariate_normal(np.zeros(N), k2.K(X), Q).T B = np.random.multivariate_normal(np.zeros(N), k2.K(X), Q).T
C = np.random.multivariate_normal(np.zeros(N), k3.K(X), Q).T C = np.random.multivariate_normal(np.zeros(N), k3.K(X), Q).T
Y = np.vstack((A,B,C)) Y = np.vstack((A,B,C))
labels = np.hstack((np.zeros(A.shape[0]), np.ones(B.shape[0]), np.ones(C.shape[0])*2)) labels = np.hstack((np.zeros(A.shape[0]), np.ones(B.shape[0]), np.ones(C.shape[0])*2))
k = RBF(Q, ARD=True, lengthscale=2) # + kern.white(Q, _np.exp(-2)) # + kern.bias(Q) k = RBF(Q, ARD=True, lengthscale=2) # + kern.white(Q, _np.exp(-2)) # + kern.bias(Q)
m = BayesianGPLVM(Y, Q, init="PCA", kernel=k) m = BayesianGPLVM(Y, Q, init="PCA", kernel=k)
m.kern.lengthscale[:] = [1./.3, 1./.1, 1./.7] m.kern.lengthscale[:] = [1./.3, 1./.1, 1./.7]

View file

@ -1,5 +1,5 @@
[bumpversion] [bumpversion]
current_version = 0.9.4 current_version = 0.9.5
tag = True tag = True
commit = True commit = True