def plotcircle(center = np.array([0.,0.]),\ radii = np.arange(0,60,10), \ angles = np.arange(0,350,10),\ color = 'k',linestyle = '--', out = None): """ Plot one or more concentric circles. Args: :center: | np.array([0.,0.]) or ndarray with center coordinates, optional :radii: | np.arange(0,60,10) or ndarray with radii of circle(s), optional :angles: | np.arange(0,350,10) or ndarray with angles (°), optional :color: | 'k', optional | Color for plotting. :linestyle: | '--', optional | Linestyle of circles. :out: | None, optional | If None: plot circles, return (x,y) otherwise. """ xs = np.array([0]) ys = xs.copy() for ri in radii: x = ri*np.cos(angles*np.pi/180) y = ri*np.sin(angles*np.pi/180) xs = np.hstack((xs,x)) ys = np.hstack((ys,y)) if out != 'x,y': plt.plot(x,y,color = color, linestyle = linestyle) if out == 'x,y': return xs,ys
def plot(self, ylabel='Spectrum', *args, **kwargs): """ Make a plot of the spectral data in SPD instance. Returns: :returns: | handle to current axes. """ plt.plot(self.wl, self.value.T, *args, **kwargs) plt.xlabel('Wavelength (nm)') plt.ylabel(ylabel) return plt.gca()
def plot(self, ylabel='Spectrum', wavelength_bar=True, *args, **kwargs): """ Make a plot of the spectral data in SPD instance. Returns: :returns: | handle to current axes. """ plt.plot(self.wl, self.value.T, *args, **kwargs) if wavelength_bar == True: Smax = np.nanmax(self.value) axh = plot_spectrum_colors(spd=None, spdmax=Smax, axh=plt.gca(), wavelength_height=-0.05) plt.xlabel('Wavelength (nm)') plt.ylabel(ylabel) return plt.gca()
_CMF['types'].append(cieobs) _CMF[cieobs] = {'bar': bar} _CMF[cieobs]['K'] = K _CMF[cieobs]['M'] = M #return _CMF if __name__ == '__main__': outcmf = 'lms' out = outcmf + ',trans_lens,trans_macula,sens_photopig,LMSa' LMS, trans_lens, trans_macula, sens_photopig, LMSa = cie2006cmfsEx(out=out) plt.figure() plt.plot(LMS[0], LMS[1], color='r', linestyle='--') plt.plot(LMS[0], LMS[2], color='g', linestyle='--') plt.plot(LMS[0], LMS[3], color='b', linestyle='--') plt.title('cie2006cmfsEx(...)') plt.show() out = outcmf + ',var_age,vAll' LMS_All, var_age, vAll = genMonteCarloObs(n_obs=10, fieldsize=10, list_Age=[32], out=out) plt.figure() plt.plot(LMS_All[0], LMS_All[1], color='r', linestyle='-') plt.plot(LMS_All[0], LMS_All[2], color='g', linestyle='-') plt.plot(LMS_All[0], LMS_All[3], color='b', linestyle='-')
def plot_hue_bins(hbins = 16, start_hue = 0.0, scalef = 100, \ plot_axis_labels = False, bin_labels = '#', plot_edge_lines = True, \ plot_center_lines = False, plot_bin_colors = True, \ axtype = 'polar', ax = None, force_CVG_layout = False): """ Makes basis plot for Color Vector Graphic (CVG). Args: :hbins: | 16 or ndarray with sorted hue bin centers (°), optional :start_hue: | 0.0, optional :scalef: | 100, optional | Scale factor for graphic. :plot_axis_labels: | False, optional | Turns axis ticks on/off (True/False). :bin_labels: | None or list[str] or '#', optional | Plots labels at the bin center hues. | - None: don't plot. | - list[str]: list with str for each bin. | (len(:bin_labels:) = :nhbins:) | - '#': plots number. :plot_edge_lines: | True or False, optional | Plot grey bin edge lines with '--'. :plot_center_lines: | False or True, optional | Plot colored lines at 'center' of hue bin. :plot_bin_colors: | True, optional | Colorize hue bins. :axtype: | 'polar' or 'cart', optional | Make polar or Cartesian plot. :ax: | None or 'new' or 'same', optional | - None or 'new' creates new plot | - 'same': continue plot on same axes. | - axes handle: plot on specified axes. :force_CVG_layout: | False or True, optional | True: Force plot of basis of CVG on first encounter. Returns: :returns: | gcf(), gca(), list with rgb colors for hue bins (for use in other plotting fcns) """ # Setup hbincenters and hsv_hues: if isinstance(hbins, float) | isinstance(hbins, int): nhbins = hbins dhbins = 360 / (nhbins) # hue bin width hbincenters = np.arange(start_hue + dhbins / 2, 360, dhbins) hbincenters = np.sort(hbincenters) else: hbincenters = hbins idx = np.argsort(hbincenters) if isinstance(bin_labels, list) | isinstance(bin_labels, np.ndarray): bin_labels = bin_labels[idx] hbincenters = hbincenters[idx] nhbins = hbincenters.shape[0] hbincenters = hbincenters * np.pi / 180 # Setup hbin labels: if bin_labels is '#': bin_labels = ['#{:1.0f}'.format(i + 1) for i in range(nhbins)] # initializing the figure cmap = None if (ax == None) or (ax == 'new'): fig = plt.figure() newfig = True else: newfig = False rect = [0.1, 0.1, 0.8, 0.8] # setting the axis limits in [left, bottom, width, height] if axtype == 'polar': # the polar axis: if newfig == True: ax = fig.add_axes(rect, polar=True, frameon=False) else: #cartesian axis: if newfig == True: ax = fig.add_axes(rect) if (newfig == True) | (force_CVG_layout == True): # Calculate hue-bin boundaries: r = np.vstack( (np.zeros(hbincenters.shape), scalef * np.ones(hbincenters.shape))) theta = np.vstack((np.zeros(hbincenters.shape), hbincenters)) #t = hbincenters.copy() dU = np.roll(hbincenters.copy(), -1) dL = np.roll(hbincenters.copy(), 1) dtU = dU - hbincenters dtL = hbincenters - dL dtU[dtU < 0] = dtU[dtU < 0] + 2 * np.pi dtL[dtL < 0] = dtL[dtL < 0] + 2 * np.pi dL = hbincenters - dtL / 2 dU = hbincenters + dtU / 2 dt = (dU - dL) dM = dL + dt / 2 # Setup color for plotting hue bins: hsv_hues = hbincenters - 30 * np.pi / 180 hsv_hues = hsv_hues / hsv_hues.max() edges = np.vstack( (np.zeros(hbincenters.shape), dL)) # setup hue bin edges array if axtype == 'cart': if plot_center_lines == True: hx = r * np.cos(theta) hy = r * np.sin(theta) if bin_labels is not None: hxv = np.vstack((np.zeros(hbincenters.shape), 1.3 * scalef * np.cos(hbincenters))) hyv = np.vstack((np.zeros(hbincenters.shape), 1.3 * scalef * np.sin(hbincenters))) if plot_edge_lines == True: hxe = np.vstack( (np.zeros(hbincenters.shape), 1.2 * scalef * np.cos(dL))) hye = np.vstack( (np.zeros(hbincenters.shape), 1.2 * scalef * np.sin(dL))) # Plot hue-bins: for i in range(nhbins): # Create color from hue angle: c = np.abs(np.array(colorsys.hsv_to_rgb(hsv_hues[i], 0.84, 0.9))) #c = [abs(c[0]),abs(c[1]),abs(c[2])] # ensure all positive elements if i == 0: cmap = [c] else: cmap.append(c) if axtype == 'polar': if plot_edge_lines == True: ax.plot(edges[:, i], r[:, i] * 1.2, color='grey', marker='None', linestyle=':', linewidth=3, markersize=2) if plot_center_lines == True: if np.mod(i, 2) == 1: ax.plot(theta[:, i], r[:, i], color=c, marker=None, linestyle='--', linewidth=2) else: ax.plot(theta[:, i], r[:, i], color=c, marker='o', linestyle='-', linewidth=3, markersize=10) if plot_bin_colors == True: bar = ax.bar(dM[i], r[1, i], width=dt[i], color=c, alpha=0.15) if bin_labels is not None: ax.text(hbincenters[i], 1.3 * scalef, bin_labels[i], fontsize=12, horizontalalignment='center', verticalalignment='center', color=np.array([1, 1, 1]) * 0.3) if plot_axis_labels == False: ax.set_xticklabels([]) ax.set_yticklabels([]) else: if plot_edge_lines == True: ax.plot(hxe[:, i], hye[:, i], color='grey', marker='None', linestyle=':', linewidth=3, markersize=2) if plot_center_lines == True: if np.mod(i, 2) == 1: ax.plot(hx[:, i], hy[:, i], color=c, marker=None, linestyle='--', linewidth=2) else: ax.plot(hx[:, i], hy[:, i], color=c, marker='o', linestyle='-', linewidth=3, markersize=10) if bin_labels is not None: ax.text(hxv[1, i], hyv[1, i], bin_labels[i], fontsize=12, horizontalalignment='center', verticalalignment='center', color=np.array([1, 1, 1]) * 0.3) ax.axis(1.1 * np.array( [hxv.min(), hxv.max(), hyv.min(), hyv.max()])) if plot_axis_labels == False: ax.set_xticklabels([]) ax.set_yticklabels([]) else: plt.xlabel("a'") plt.ylabel("b'") plt.plot(0, 0, color='k', marker='o', linestyle=None) return plt.gcf(), plt.gca(), cmap
def plot_chromaticity_diagram_colors(diagram_samples = 256, diagram_opacity = 1.0, diagram_lightness = 0.25,\ cieobs = _CIEOBS, cspace = 'Yxy', cspace_pars = {},\ show = True, axh = None,\ show_grid = True, label_fontname = 'Times New Roman', label_fontsize = 12,\ **kwargs): """ Plot the chromaticity diagram colors. Args: :diagram_samples: | 256, optional | Sampling resolution of color space. :diagram_opacity: | 1.0, optional | Sets opacity of chromaticity diagram :diagram_lightness: | 0.25, optional | Sets lightness of chromaticity diagram :axh: | None or axes handle, optional | Determines axes to plot data in. | None: make new figure. :show: | True or False, optional | Invoke matplotlib.pyplot.show() right after plotting :cieobs: | luxpy._CIEOBS or str, optional | Determines CMF set to calculate spectrum locus or other. :cspace: | luxpy._CSPACE or str, optional | Determines color space / chromaticity diagram to plot data in. | Note that data is expected to be in specified :cspace: :cspace_pars: | {} or dict, optional | Dict with parameters required by color space specified in :cspace: | (for use with luxpy.colortf()) :show_grid: | True, optional | Show grid (True) or not (False) :label_fontname: | 'Times New Roman', optional | Sets font type of axis labels. :label_fontsize: | 12, optional | Sets font size of axis labels. :kwargs: | additional keyword arguments for use with matplotlib.pyplot. Returns: """ offset = _EPS ii, jj = np.meshgrid(np.linspace(offset, 1 + offset, diagram_samples), np.linspace(1+offset, offset, diagram_samples)) ij = np.dstack((ii, jj)) SL = _CMF[cieobs]['bar'][1:4].T SL = np.vstack((SL,SL[0])) SL = 100.0*SL/SL[:,1,None] SL = colortf(SL, tf = cspace, tfa0 = cspace_pars) Y,x,y = asplit(SL) SL = np.vstack((x,y)).T ij2D = ij.reshape((diagram_samples**2,2)) ij2D = np.hstack((diagram_lightness*100*np.ones((ij2D.shape[0],1)), ij2D)) xyz = colortf(ij2D, tf = cspace + '>xyz', tfa0 = cspace_pars) xyz[xyz < 0] = 0 xyz[np.isinf(xyz.sum(axis=1)),:] = np.nan xyz[np.isnan(xyz.sum(axis=1)),:] = offset srgb = xyz_to_srgb(xyz) srgb = srgb/srgb.max() srgb = srgb.reshape((diagram_samples,diagram_samples,3)) if show == True: if axh is None: fig = plt.figure() axh = fig.add_subplot(111) polygon = Polygon(SL, facecolor='none', edgecolor='none') axh.add_patch(polygon) image = axh.imshow( srgb, interpolation='bilinear', extent = (0.0, 1, -0.05, 1), clip_path=None, alpha=diagram_opacity) image.set_clip_path(polygon) plt.plot(x,y, color = 'darkgray') if cspace == 'Yxy': plt.xlim([0,1]) plt.ylim([0,1]) elif cspace == 'Yuv': plt.xlim([0,0.6]) plt.ylim([0,0.6]) if (cspace is not None): xlabel = _CSPACE_AXES[cspace][1] ylabel = _CSPACE_AXES[cspace][2] if (label_fontname is not None) & (label_fontsize is not None): plt.xlabel(xlabel, fontname = label_fontname, fontsize = label_fontsize) plt.ylabel(ylabel, fontname = label_fontname, fontsize = label_fontsize) if show_grid == True: plt.grid() #plt.show() return axh else: return None
def plot_color_data(x,y,z=None, axh=None, show = True, cieobs =_CIEOBS, \ cspace = _CSPACE, formatstr = 'k-', **kwargs): """ Plot color data from x,y [,z]. Args: :x: | float or ndarray with x-coordinate data :y: | float or ndarray with y-coordinate data :z: | None or float or ndarray with Z-coordinate data, optional | If None: make 2d plot. :axh: | None or axes handle, optional | Determines axes to plot data in. | None: make new figure. :show: | True or False, optional | Invoke matplotlib.pyplot.show() right after plotting :cieobs: | luxpy._CIEOBS or str, optional | Determines CMF set to calculate spectrum locus or other. :cspace: | luxpy._CSPACE or str, optional | Determines color space / chromaticity diagram to plot data in. | Note that data is expected to be in specified :cspace: :formatstr: | 'k-' or str, optional | Format str for plotting (see ?matplotlib.pyplot.plot) :kwargs: | additional keyword arguments for use with matplotlib.pyplot. Returns: :returns: | None (:show: == True) | or | handle to current axes (:show: == False) """ x = np.atleast_1d(x) y = np.atleast_1d(y) if 'grid' in kwargs.keys(): plt.grid(kwargs['grid']);kwargs.pop('grid') if z is not None: z = np.atleast_1d(z) if axh is None: fig = plt.figure() axh = plt.axes(projection='3d') axh.plot3D(x,y,z,formatstr, linewidth = 2,**kwargs) plt.zlabel(_CSPACE_AXES[cspace][0], kwargs) else: plt.plot(x,y,formatstr,linewidth = 2,**kwargs) plt.xlabel(_CSPACE_AXES[cspace][1], kwargs) plt.ylabel(_CSPACE_AXES[cspace][2], kwargs) if 'label' in kwargs.keys(): plt.legend() if show == True: plt.show() else: return plt.gca()
def plotellipse(v, cspace_in = 'Yxy', cspace_out = None, nsamples = 100, \ show = True, axh = None, \ line_color = 'darkgray', line_style = ':', line_width = 1, line_marker = '', line_markersize = 4,\ plot_center = False, center_marker = 'o', center_color = 'darkgray', center_markersize = 4,\ show_grid = True, label_fontname = 'Times New Roman', label_fontsize = 12,\ out = None): """ Plot ellipse(s) given in v-format [Rmax,Rmin,xc,yc,theta]. Args: :v: | (Nx5) ndarray | ellipse parameters [Rmax,Rmin,xc,yc,theta] :cspace_in: | 'Yxy', optional | Color space of v. | If None: no color space assumed. Axis labels assumed ('x','y'). :cspace_out: | None, optional | Color space to plot ellipse(s) in. | If None: plot in cspace_in. :nsamples: | 100 or int, optional | Number of points (samples) in ellipse boundary :show: | True or boolean, optional | Plot ellipse(s) (True) or not (False) :axh: | None, optional | Ax-handle to plot ellipse(s) in. | If None: create new figure with axes. :line_color: | 'darkgray', optional | Color to plot ellipse(s) in. :line_style: | ':', optional | Linestyle of ellipse(s). :line_width': | 1, optional | Width of ellipse boundary line. :line_marker: | 'none', optional | Marker for ellipse boundary. :line_markersize: | 4, optional | Size of markers in ellipse boundary. :plot_center: | False, optional | Plot center of ellipse: yes (True) or no (False) :center_color: | 'darkgray', optional | Color to plot ellipse center in. :center_marker: | 'o', optional | Marker for ellipse center. :center_markersize: | 4, optional | Size of marker of ellipse center. :show_grid: | True, optional | Show grid (True) or not (False) :label_fontname: | 'Times New Roman', optional | Sets font type of axis labels. :label_fontsize: | 12, optional | Sets font size of axis labels. :out: | None, optional | Output of function | If None: returns None. Can be used to output axh of newly created | figure axes or to return Yxys an ndarray with coordinates of | ellipse boundaries in cspace_out (shape = (nsamples,3,N)) Returns: :returns: None, or whatever set by :out:. """ Yxys = np.zeros((nsamples,3,v.shape[0])) ellipse_vs = np.zeros((v.shape[0],5)) for i,vi in enumerate(v): # Set sample density of ellipse boundary: t = np.linspace(0, 2*np.pi, nsamples) a = vi[0] # major axis b = vi[1] # minor axis xyc = vi[2:4,None] # center theta = vi[-1] # rotation angle # define rotation matrix: R = np.hstack(( np.vstack((np.cos(theta), np.sin(theta))), np.vstack((-np.sin(theta), np.cos(theta))))) # Calculate ellipses: Yxyc = np.vstack((1, xyc)).T Yxy = np.vstack((np.ones((1,nsamples)), xyc + np.dot(R, np.vstack((a*np.cos(t), b*np.sin(t))) ))).T Yxys[:,:,i] = Yxy # Convert to requested color space: if (cspace_out is not None) & (cspace_in is not None): Yxy = colortf(Yxy, cspace_in + '>' + cspace_out) Yxyc = colortf(Yxyc, cspace_in + '>' + cspace_out) Yxys[:,:,i] = Yxy # get ellipse parameters in requested color space: ellipse_vs[i,:] = math.fit_ellipse(Yxy[:,1:]) #de = np.sqrt((Yxy[:,1]-Yxyc[:,1])**2 + (Yxy[:,2]-Yxyc[:,2])**2) #ellipse_vs[i,:] = np.hstack((de.max(),de.min(),Yxyc[:,1],Yxyc[:,2],np.nan)) # nan because orientation is xy, but request is some other color space. Change later to actual angle when fitellipse() has been implemented # plot ellipses: if show == True: if (axh is None) & (i == 0): fig = plt.figure() axh = fig.add_subplot(111) if (cspace_in is None): xlabel = 'x' ylabel = 'y' else: xlabel = _CSPACE_AXES[cspace_in][1] ylabel = _CSPACE_AXES[cspace_in][2] if (cspace_out is not None): xlabel = _CSPACE_AXES[cspace_out][1] ylabel = _CSPACE_AXES[cspace_out][2] if plot_center == True: plt.plot(Yxyc[:,1],Yxyc[:,2],color = center_color, linestyle = 'none', marker = center_marker, markersize = center_markersize) plt.plot(Yxy[:,1],Yxy[:,2],color = line_color, linestyle = line_style, linewidth = line_width, marker = line_marker, markersize = line_markersize) plt.xlabel(xlabel, fontname = label_fontname, fontsize = label_fontsize) plt.ylabel(ylabel, fontname = label_fontname, fontsize = label_fontsize) if show_grid == True: plt.grid() #plt.show() Yxys = np.transpose(Yxys,axes=(0,2,1)) if out is not None: return eval(out) else: return None
def plotSL(cieobs =_CIEOBS, cspace = _CSPACE, DL = True, BBL = True, D65 = False,\ EEW = False, cctlabels = False, axh = None, show = True,\ cspace_pars = {}, formatstr = 'k-',\ diagram_colors = False, diagram_samples = 100, diagram_opacity = 1.0,\ diagram_lightness = 0.25,\ **kwargs): """ Plot spectrum locus for cieobs in cspace. Args: :DL: | True or False, optional | True plots Daylight Locus as well. :BBL: | True or False, optional | True plots BlackBody Locus as well. :D65: | False or True, optional | True plots D65 chromaticity as well. :EEW: | False or True, optional | True plots Equi-Energy-White chromaticity as well. :cctlabels: | False or True, optional | Add cct text labels at various points along the blackbody locus. :axh: | None or axes handle, optional | Determines axes to plot data in. | None: make new figure. :show: | True or False, optional | Invoke matplotlib.pyplot.show() right after plotting :cieobs: | luxpy._CIEOBS or str, optional | Determines CMF set to calculate spectrum locus or other. :cspace: | luxpy._CSPACE or str, optional | Determines color space / chromaticity diagram to plot data in. | Note that data is expected to be in specified :cspace: :formatstr: | 'k-' or str, optional | Format str for plotting (see ?matplotlib.pyplot.plot) :cspace_pars: | {} or dict, optional | Dict with parameters required by color space specified in :cspace: | (for use with luxpy.colortf()) :diagram_colors: | False, optional | True: plot colored chromaticity diagram. :diagram_samples: | 256, optional | Sampling resolution of color space. :diagram_opacity: | 1.0, optional | Sets opacity of chromaticity diagram :diagram_lightness: | 0.25, optional | Sets lightness of chromaticity diagram :kwargs: | additional keyword arguments for use with matplotlib.pyplot. Returns: :returns: | None (:show: == True) | or | handle to current axes (:show: == False) """ SL = _CMF[cieobs]['bar'][1:4].T SL = np.vstack((SL,SL[0])) SL = 100.0*SL/SL[:,1,None] SL = colortf(SL, tf = cspace, tfa0 = cspace_pars) Y,x,y = asplit(SL) showcopy = show if np.any([DL,BBL,D65,EEW]): show = False if diagram_colors == True: axh_ = plot_chromaticity_diagram_colors(axh = axh, show = diagram_colors, cspace = cspace, cieobs = cieobs,\ cspace_pars = cspace_pars,\ diagram_samples = diagram_samples,\ diagram_opacity = diagram_opacity,\ diagram_lightness = diagram_lightness,\ label_fontname = None, label_fontsize = None) else: axh_ = axh axh_ = plot_color_data(x,y,axh = axh_, cieobs = cieobs, cspace = cspace, show = show, formatstr=formatstr, **kwargs) if DL == True: if 'label' in kwargs.keys(): # avoid label also being used for DL kwargs.pop('label') plotDL(ccts = None, cieobs = cieobs, cspace = cspace, axh = axh_, show = show, cspace_pars = cspace_pars, formatstr = 'k:', **kwargs) if BBL == True: if 'label' in kwargs.keys(): # avoid label also being used for BB kwargs.pop('label') plotBB(ccts = None, cieobs = cieobs, cspace = cspace, axh = axh_, show = show, cspace_pars = cspace_pars, cctlabels = cctlabels, formatstr = 'k-.', **kwargs) if D65 == True: YxyD65 = colortf(spd_to_xyz(_CIE_ILLUMINANTS['D65']), tf = cspace, tfa0 = cspace_pars) plt.plot(YxyD65[...,1],YxyD65[...,2],'bo') if EEW == True: YxyEEW = colortf(spd_to_xyz(_CIE_ILLUMINANTS['E']), tf = cspace, tfa0 = cspace_pars) plt.plot(YxyEEW[...,1],YxyEEW[...,2],'ko') if showcopy == False: return axh_ else: plt.show()
def plotBB(ccts = None, cieobs =_CIEOBS, cspace = _CSPACE, axh = None, cctlabels = True, show = True, cspace_pars = {}, formatstr = 'k-', **kwargs): """ Plot blackbody locus. Args: :ccts: | None or list[float], optional | None defaults to [1000 to 1e19 K]. | Range: | [1000,1500,2000,2500,3000,3500,4000,5000,6000,8000,10000] | + [15000 K to 1e19 K] in 100 steps on a log10 scale :cctlabels: | True or False, optional | Add cct text labels at various points along the blackbody locus. :axh: | None or axes handle, optional | Determines axes to plot data in. | None: make new figure. :show: | True or False, optional | Invoke matplotlib.pyplot.show() right after plotting :cieobs: | luxpy._CIEOBS or str, optional | Determines CMF set to calculate spectrum locus or other. :cspace: | luxpy._CSPACE or str, optional | Determines color space / chromaticity diagram to plot data in. | Note that data is expected to be in specified :cspace: :formatstr: | 'k-' or str, optional | Format str for plotting (see ?matplotlib.pyplot.plot) :cspace_pars: | {} or dict, optional | Dict with parameters required by color space specified in :cspace: (for use with luxpy.colortf()) :kwargs: | additional keyword arguments for use with matplotlib.pyplot. Returns: :returns: | None (:show: == True) | or | handle to current axes (:show: == False) """ if ccts is None: ccts1 = np.array([1000.0,1500.0,2000.0,2500.0,3000.0,3500.0,4000.0,5000.0,6000.0,8000.0,10000.0]) ccts2 = 10**np.linspace(np.log10(15000.0),np.log10(10.0**19.0),100.0) ccts = np.hstack((ccts1,ccts2)) else: ccts1 = None BB = cri_ref(ccts,ref_type='BB') xyz = spd_to_xyz(BB,cieobs = cieobs) Yxy = colortf(xyz, tf = cspace, tfa0 = cspace_pars) Y,x,y = asplit(Yxy) axh = plot_color_data(x,y,axh = axh, cieobs = cieobs, cspace = cspace, show=show, formatstr=formatstr, **kwargs) if (cctlabels == True) & (ccts1 is not None): for i in range(ccts1.shape[0]): if ccts1[i]>= 3000.0: if i%2 == 0.0: plt.plot(x[i],y[i],'k+', color = '0.5') plt.text(x[i]*1.05,y[i]*0.95,'{:1.0f}K'.format(ccts1[i]), color = '0.5') plt.plot(x[-1],y[-1],'k+', color = '0.5') plt.text(x[-1]*1.05,y[-1]*0.95,'{:1.0e}K'.format(ccts[-1]), color = '0.5') if show == False: return axh
v_mac_est = get_macadam_ellipse(xy_test) # Plot results: cspace = 'Yxy' #axh = plot_chromaticity_diagram_colors(cspace = cspace) axh = plotSL(cspace=cspace, cieobs='1931_2', show=False, diagram_colors=True) axh = plotellipse(v_mac, show=True, axh=axh, cspace_out=cspace, plot_center=False, center_color='r', out='axh', line_style=':', line_color='k', line_width=1.5) plotellipse(v_mac_est, show=True, axh=axh, cspace_out=cspace, line_color='k', plot_center=True, center_color='k') if cspace == 'Yuv': axh.set_xlim([0, 0.6]) axh.set_ylim([0, 0.6]) plt.plot(xy_test[:, 0], xy_test[:, 1], 'ro')
def demo_opt(f, args=(), xrange=None, options={}): """ DEMO_OPT: Multi-objective optimization using the DEMO This function uses the Differential Evolution for Multi-objective Optimization (a.k.a. DEMO) to solve a multi-objective problem. The result is a set of nondominated points that are (hopefully) very close to the true Pareto front. Args: :f: | handle to objective function. | The output must be, for each point, a column vector of size m x 1, | with m > 1 the number of objectives. :args: (), optional | Input arguments required for f. :xrange: None, optional | ndarray with lower and upperbounds. | If n is the dimension, it will be a n x 2 matrix, such that the | first column contains the lower bounds, | and the second, the upper bounds. | None defaults to no bounds ( [-Inf, Inf] ndarray). :options: | None, optional | dict with internal parameters of the algorithm. | None initializes default values. | keys: | - 'F': the scale factor to be used in the mutation (default: 0.5); | - 'CR': the crossover factor used in the recombination (def.: 0.3); | - 'mu': the population size (number of individuals) (def.: 100); | - 'kmax': maximum number of iterations (def.: 300); | - 'display': 'on' to display the population while the algorithm is | being executed, and 'off' to not (default: 'off'); | If any of the parameters is not set, the default ones are used | instead. Returns: fopt, xopt :fopt: the m x mu_opt ndarray with the mu_opt best objectives :xopt: the n x mu_opt ndarray with the mu_opt best individuals """ # Initialize the parameters of the algorithm with values contained in dict: options = init_options(options=options) # Initial considerations n = xrange.shape[0] #dimension of the problem P = {'x': np.random.rand(n, options['mu'])} #initial decision variables P['f'] = fobjeval(f, P['x'], args, xrange) #evaluates the initial population m = P['f'].shape[0] #number of objectives k = 0 #iterations counter # Beginning of the main loop Pfirst = P.copy() axh = None while (k <= options['kmax']): # Plot the current population (if desired): if options['display'] == True: if (k == 0) & (m < 4): fig = plt.gcf() fig.show() fig.canvas.draw() if m == 2: # fig = plt.figure() axh = plt.axes() plt.plot(P['f'][0], P['f'][1], 'o') plt.title('Objective values during the execution') plt.xlabel('f_1') plt.ylabel('f_2') fig.canvas.draw() del axh.lines[0] elif m == 3: # fig = plt.figure() axh = plt.axes(projection='3d') # print(P['f']) axh.plot3D(P['f'][0], P['f'][1], P['f'][2], 'o') plt.title('Objective values during the execution') axh.set_xlabel('f_1') axh.set_ylabel('f_2') axh.set_zlabel('f_3') fig.canvas.draw() plt.pause(0.01) del axh.lines[0] # Perform the variation operation (mutation and recombination): O = {'x': mutation(P['x'], options)} #mutation O['x'] = recombination(P['x'].copy(), O['x'], options) #recombination O['x'] = repair( O['x']) #assure the offspring do not cross the search limits O['f'] = fobjeval(f, O['x'], args, xrange) #compute objective functions # Selection and updates P = selection(P, O, options) print('Iteration #{:1.0f} of {:1.0f}'.format(k, options['kmax'])) k += 1 # Return the final population: # First, unnormalize it Xmin = xrange[:, 0][:, None] # * np.ones(options['mu']) #replicate lower bound Xmax = xrange[:, 1][:, None] # * np.ones(options['mu']) #replicate upper limit Xun = (Xmax - Xmin) * P['x'] + Xmin # Then, return the nondominated front: ispar = ndset(P['f']) fopt = P['f'][:, ispar] xopt = Xun[:, ispar] return fopt, xopt