def Histo(x, mean, sigma_mean, std, stderr, P, orient='horizontal', xlabel='', ylabel=''): ''' Function that plot the histogramm of the distribution given in x imputs: -x is the distrib itself (array) -mean is the mean of the distrib (float) -sigma_mean : the error on the average (float) -std : the standard deviation (RMS) of the distribution (float) -stderr : the errot on the RMS (float) -P is the figure where the histogram will be plotted. -xylabel and y label are the name ofthe axis. ''' numBins = 20 P.hist(x, numBins, color='blue', alpha=0.8, orientation=orient, label='average = ' + str("%.5f" % mean) + '$\pm$' + str("%.5f" % sigma_mean) + '\n' + 'rms =' + str("%.5f" % std) + '$\pm$' + str("%.5f" % stderr)) if xlabel == '': P.set_xlabel('number of SNe') else: P.set_xlabel(xlabel) if ylabel == '': P.set_ylabel('number of SNe') else: P.set_ylabel(ylabel) P.set_title('Residuals') P.legend(bbox_to_anchor=(0.95, 1.0), prop={'size': 10})
def image(sim, qty='rho', width="10 kpc", resolution=500, units=None, log=True, vmin=None, vmax=None, av_z=False, filename=None, z_camera=None, clear=True, cmap=None, title=None, qtytitle=None, show_cbar=True, subplot=False, noplot=False, ret_im=False, fill_nan=True, fill_val=0.0, linthresh=None, **kwargs): """ Make an SPH image of the given simulation. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (10 kpc): The overall width and height of the plot. If ``width`` is a float or an int, then it is assumed to be in units of ``sim['pos']``. It can also be passed in as a string indicating the units, i.e. '10 kpc', in which case it is converted to units of ``sim['pos']``. *resolution* (500): The number of pixels wide and tall *units* (None): The units of the output *av_z* (False): If True, the requested quantity is averaged down the line of sight (default False: image is generated in the thin plane z=0, unless output units imply an integral down the line of sight). If a string, the requested quantity is averaged down the line of sight weighted by the av_z array (e.g. use 'rho' for density-weighted quantity; the default results when av_z=True are volume-weighted). *z_camera* (None): If set, a perspective image is rendered. See :func:`pynbody.sph.image` for more details. *filename* (None): if set, the image will be saved in a file *clear* (True): whether to call clf() on the axes first *cmap* (None): user-supplied colormap instance *title* (None): plot title *qtytitle* (None): colorbar quantity title *show_cbar* (True): whether to plot the colorbar *subplot* (False): the user can supply a AxesSubPlot instance on which the image will be shown *noplot* (False): do not display the image, just return the image array *ret_im* (False): return the image instance returned by imshow *num_threads* (None) : if set, specify the number of threads for the multi-threaded routines; otherwise the pynbody.config default is used *fill_nan* (True): if any of the image values are NaN, replace with fill_val *fill_val* (0.0): the fill value to use when replacing NaNs *linthresh* (None): if the image has negative and positive values and a log scaling is requested, the part between `-linthresh` and `linthresh` is shown on a linear scale to avoid divergence at 0 """ if not noplot: import matplotlib.pylab as plt global config if not noplot: if subplot: p = subplot else: p = plt if isinstance(units, str): units = _units.Unit(units) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) kernel = sph.Kernel() perspective = z_camera is not None if perspective and not av_z: kernel = sph.Kernel2D() if units is not None: try: sim[qty].units.ratio(units, **sim[qty].conversion_context()) # if this fails, perhaps we're requesting a projected image? except _units.UnitsException: # if the following fails, there's no interpretation this routine # can cope with sim[qty].units.ratio( units / (sim['x'].units), **sim[qty].conversion_context()) # if we get to this point, we want a projected image kernel = sph.Kernel2D() if av_z: if isinstance(kernel, sph.Kernel2D): raise _units.UnitsException( "Units already imply projected image; can't also average over line-of-sight!") else: kernel = sph.Kernel2D() if units is not None: aunits = units * sim['z'].units else: aunits = None if isinstance(av_z, str): if units is not None: aunits = units * sim[av_z].units * sim['z'].units sim["__prod"] = sim[av_z] * sim[qty] qty = "__prod" else: av_z = "__one" sim["__one"] = np.ones_like(sim[qty]) sim["__one"].units = "1" im = sph.render_image(sim, qty, width / 2, resolution, out_units=aunits, kernel=kernel, z_camera=z_camera, **kwargs) im2 = sph.render_image(sim, av_z, width / 2, resolution, kernel=kernel, z_camera=z_camera, **kwargs) top = sim.ancestor try: del top["__one"] except KeyError: pass try: del top["__prod"] except KeyError: pass im = im / im2 else: im = sph.render_image(sim, qty, width / 2, resolution, out_units=units, kernel=kernel, z_camera=z_camera, **kwargs) if fill_nan: im[np.isnan(im)] = fill_val if not noplot: # set the log or linear normalizations if log: try: im[np.where(im == 0)] = abs(im[np.where(abs(im != 0))]).min() except ValueError: raise ValueError, "Failed to make a sensible logarithmic image. This probably means there are no particles in the view." # check if there are negative values -- if so, use the symmetric # log normalization if (im < 0).any(): # need to set the linear regime around zero -- set to by # default start at 1/1000 of the log range if linthresh is None: linthresh = np.nanmax(abs(im)) / 1000. norm = matplotlib.colors.SymLogNorm( linthresh, vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) # # do the actual plotting # if clear and not subplot: p.clf() if ret_im: return p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm = norm) ims = p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm = norm) u_st = sim['pos'].units.latex() if not subplot: plt.xlabel("$x/%s$" % u_st) plt.ylabel("$y/%s$" % u_st) else: p.set_xlabel("$x/%s$" % u_st) p.set_ylabel("$y/%s$" % u_st) if units is None: units = im.units if log : units = r"$\log_{10}\,"+units.latex()+"$" else : if units.latex() is "": units="" else: units = "$"+units.latex()+"$" if show_cbar: if log: custom_formatter = FuncFormatter(fmt) ## l_f = LogFormatterExponent() # sometimes tacks 'e' on value...??? l_f = custom_formatter else: l_f = ScalarFormatter() if qtytitle is not None: plt.colorbar(ims,format=l_f).set_label(qtytitle) else: plt.colorbar(ims,format=l_f).set_label(units) # colorbar doesn't work wtih subplot: mappable is NoneType # elif show_cbar: # import matplotlib.pyplot as mpl # if qtytitle: mpl.colorbar().set_label(qtytitle) # else: mpl.colorbar().set_label(units) if title is not None: if not subplot: p.title(title) else: p.set_title(title) if filename is not None: p.savefig(filename) plt.draw() # plt.show() - removed by AP on 30/01/2013 - this should not be here as # for some systems you don't get back to the command prompt return im
def image(sim, qty='rho', width="10 kpc", resolution=500, units=None, log=True, vmin=None, vmax=None, av_z=False, filename=None, z_camera=None, clear=True, cmap=None, title=None, qtytitle=None, show_cbar=True, subplot=False, noplot=False, ret_im=False, fill_nan=True, fill_val=0.0, linthresh=None, **kwargs): """ Make an SPH image of the given simulation. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (10 kpc): The overall width and height of the plot. If ``width`` is a float or an int, then it is assumed to be in units of ``sim['pos']``. It can also be passed in as a string indicating the units, i.e. '10 kpc', in which case it is converted to units of ``sim['pos']``. *resolution* (500): The number of pixels wide and tall *units* (None): The units of the output *av_z* (False): If True, the requested quantity is averaged down the line of sight (default False: image is generated in the thin plane z=0, unless output units imply an integral down the line of sight). If a string, the requested quantity is averaged down the line of sight weighted by the av_z array (e.g. use 'rho' for density-weighted quantity; the default results when av_z=True are volume-weighted). *z_camera* (None): If set, a perspective image is rendered. See :func:`pynbody.sph.image` for more details. *filename* (None): if set, the image will be saved in a file *clear* (True): whether to call clf() on the axes first *cmap* (None): user-supplied colormap instance *title* (None): plot title *qtytitle* (None): colorbar quantity title *show_cbar* (True): whether to plot the colorbar *subplot* (False): the user can supply a AxesSubPlot instance on which the image will be shown *noplot* (False): do not display the image, just return the image array *ret_im* (False): return the image instance returned by imshow *num_threads* (None) : if set, specify the number of threads for the multi-threaded routines; otherwise the pynbody.config default is used *fill_nan* (True): if any of the image values are NaN, replace with fill_val *fill_val* (0.0): the fill value to use when replacing NaNs *linthresh* (None): if the image has negative and positive values and a log scaling is requested, the part between `-linthresh` and `linthresh` is shown on a linear scale to avoid divergence at 0 """ if not noplot: import matplotlib.pylab as plt global config if not noplot: if subplot: p = subplot else: p = plt if isinstance(units, str): units = _units.Unit(units) if isinstance(width, str) or issubclass(width.__class__, _units.UnitBase): if isinstance(width, str): width = _units.Unit(width) width = width.in_units(sim['pos'].units, **sim.conversion_context()) width = float(width) kernel = sph.Kernel() perspective = z_camera is not None if perspective and not av_z: kernel = sph.Kernel2D() if units is not None: try: sim[qty].units.ratio(units, **sim[qty].conversion_context()) # if this fails, perhaps we're requesting a projected image? except _units.UnitsException: # if the following fails, there's no interpretation this routine # can cope with sim[qty].units.ratio(units / (sim['x'].units), **sim[qty].conversion_context()) # if we get to this point, we want a projected image kernel = sph.Kernel2D() if av_z: if isinstance(kernel, sph.Kernel2D): raise _units.UnitsException( "Units already imply projected image; can't also average over line-of-sight!" ) else: kernel = sph.Kernel2D() if units is not None: aunits = units * sim['z'].units else: aunits = None if isinstance(av_z, str): if units is not None: aunits = units * sim[av_z].units * sim['z'].units sim["__prod"] = sim[av_z] * sim[qty] qty = "__prod" else: av_z = "__one" sim["__one"] = np.ones_like(sim[qty]) sim["__one"].units = "1" im = sph.render_image(sim, qty, width / 2, resolution, out_units=aunits, kernel=kernel, z_camera=z_camera, **kwargs) im2 = sph.render_image(sim, av_z, width / 2, resolution, kernel=kernel, z_camera=z_camera, **kwargs) top = sim.ancestor try: del top["__one"] except KeyError: pass try: del top["__prod"] except KeyError: pass im = im / im2 else: im = sph.render_image(sim, qty, width / 2, resolution, out_units=units, kernel=kernel, z_camera=z_camera, **kwargs) if fill_nan: im[np.isnan(im)] = fill_val if not noplot: # set the log or linear normalizations if log: try: im[np.where(im == 0)] = abs(im[np.where(abs(im != 0))]).min() except ValueError: raise ValueError, "Failed to make a sensible logarithmic image. This probably means there are no particles in the view." # check if there are negative values -- if so, use the symmetric # log normalization if (im < 0).any(): # need to set the linear regime around zero -- set to by # default start at 1/1000 of the log range if linthresh is None: linthresh = np.nanmax(abs(im)) / 1000. norm = matplotlib.colors.SymLogNorm(linthresh, vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.LogNorm(vmin=vmin, vmax=vmax) else: norm = matplotlib.colors.Normalize(vmin=vmin, vmax=vmax) # # do the actual plotting # if clear and not subplot: p.clf() if ret_im: return p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) ims = p.imshow(im[::-1, :].view(np.ndarray), extent=(-width / 2, width / 2, -width / 2, width / 2), vmin=vmin, vmax=vmax, cmap=cmap, norm=norm) u_st = sim['pos'].units.latex() if not subplot: plt.xlabel("$x/%s$" % u_st) plt.ylabel("$y/%s$" % u_st) else: p.set_xlabel("$x/%s$" % u_st) p.set_ylabel("$y/%s$" % u_st) if units is None: units = im.units if log: units = r"$\log_{10}\," + units.latex() + "$" else: if units.latex() is "": units = "" else: units = "$" + units.latex() + "$" if show_cbar: if qtytitle is not None: plt.colorbar(ims).set_label(qtytitle) else: plt.colorbar(ims).set_label(units) # colorbar doesn't work wtih subplot: mappable is NoneType # elif show_cbar: # import matplotlib.pyplot as mpl # if qtytitle: mpl.colorbar().set_label(qtytitle) # else: mpl.colorbar().set_label(units) if title is not None: if not subplot: p.title(title) else: p.set_title(title) if filename is not None: p.savefig(filename) plt.draw() # plt.show() - removed by AP on 30/01/2013 - this should not be here as # for some systems you don't get back to the command prompt return im
self.F_D * math.sin(ou_D * self.t[-1])) * self.dt self.omiga.append(omiga_new) sita_new = self.sita[-1] + self.omiga[-1] * self.dt t_new = self.t[-1] + self.dt while sita_new > math.pi: sita_new -= 2 * (math.pi) while sita_new < -math.pi: sita_new += 2 * (math.pi) self.sita.append(sita_new) self.t.append(t_new) F_D2 = [1.35] * 128 sita3 = [] while F_D2[-1] < 1.5: A = pendulum0(F_D2[-1], 0.2) A.calculate() sita2 = [] for i in range(301, 429): A.sita2.append(A.sita[1000 * i]) sita3 = sita3 + A.sita2 F_Dnew = [F_D2[-1] + 0.00005] * 128 F_D2 = F_D2 + F_Dnew py.plot(F_D2[0:-128], sita3, 'g.') py.set_title('$\omega$ versus $\\theta$') py.xlabel('$\\theta$(radians)') py.ylabel('$\omega$(radians/s)') py.show()
def image(sim, qty='rho', width=10, resolution=500, units=None, log=True, vmin=None, vmax=None, av_z = False, filename=None, z_camera=None, clear = True, cmap=None, center=False, title=None, qtytitle=None, show_cbar=True, subplot=False, noplot = False, ret_im=False, fill_nan = True, fill_val=0.0, **kwargs) : """ Make an SPH image of the given simulation. **Keyword arguments:** *qty* (rho): The name of the array to interpolate *width* (10): The overall width and height of the plot in sim['pos'] units *resolution* (500): The number of pixels wide and tall *units* (None): The units of the output *av_z* (False): If True, the requested quantity is averaged down the line of sight (default False: image is generated in the thin plane z=0, unless output units imply an integral down the line of sight). If a string, the requested quantity is averaged down the line of sight weighted by the av_z array (e.g. use 'rho' for density-weighted quantity; the default results when av_z=True are volume-weighted). *z_camera* (None): If set, a perspective image is rendered. See :func:`pynbody.sph.image` for more details. *filename* (None): if set, the image will be saved in a file *clear* (True): whether to call clf() on the axes first *cmap* (None): user-supplied colormap instance *title* (None): plot title *qtytitle* (None): colorbar quantity title *show_cbar* (True): whether to plot the colorbar *subplot* (False): the user can supply a AxesSubPlot instance on which the image will be shown *noplot* (False): do not display the image, just return the image array *ret_im* (False): return the image instance returned by imshow *num_threads* (None) : if set, specify the number of threads for the multi-threaded routines; otherwise the pynbody.config default is used *fill_nan* (True): if any of the image values are NaN, replace with fill_val *fill_val* (0.0): the fill value to use when replacing NaNs """ import matplotlib.pylab as plt global config if subplot: p = subplot else : p = plt if isinstance(units, str) : units = _units.Unit(units) width = float(width) kernel = sph.Kernel() perspective = z_camera is not None if perspective and not av_z: kernel = sph.Kernel2D() if units is not None : try : sim[qty].units.ratio(units, **sim[qty].conversion_context()) # if this fails, perhaps we're requesting a projected image? except _units.UnitsException : # if the following fails, there's no interpretation this routine can cope with sim[qty].units.ratio(units/(sim['x'].units), **sim[qty].conversion_context()) kernel = sph.Kernel2D() # if we get to this point, we want a projected image if av_z : if isinstance(kernel, sph.Kernel2D) : raise _units.UnitsException("Units already imply projected image; can't also average over line-of-sight!") else : kernel = sph.Kernel2D() if units is not None : aunits = units*sim['z'].units else : aunits = None if isinstance(av_z, str) : if units is not None: aunits = units*sim[av_z].units*sim['z'].units sim["__prod"] = sim[av_z]*sim[qty] qty = "__prod" else : av_z = "__one" sim["__one"]=np.ones_like(sim[qty]) sim["__one"].units="1" im = sph.render_image(sim,qty,width/2,resolution,out_units=aunits, kernel = kernel, z_camera=z_camera, **kwargs) im2 = sph.render_image(sim, av_z, width/2, resolution, kernel=kernel, z_camera=z_camera, **kwargs) top = sim.ancestor try: del top["__one"] except KeyError : pass try: del top["__prod"] except KeyError : pass im = im/im2 else : im = sph.render_image(sim,qty,width/2,resolution,out_units=units, kernel = kernel, z_camera = z_camera, **kwargs) if fill_nan : im[np.isnan(im)] = fill_val if log : im[np.where(im==0)] = abs(im[np.where(im!=0)]).min() im = np.log10(im) if clear and not subplot : p.clf() if ret_im: return plt.imshow(im[::-1,:],extent=(-width/2,width/2,-width/2,width/2), vmin=vmin, vmax=vmax, cmap=cmap) ims = p.imshow(im[::-1,:],extent=(-width/2,width/2,-width/2,width/2), vmin=vmin, vmax=vmax, cmap=cmap) u_st = sim['pos'].units.latex() if not subplot: plt.xlabel("$x/%s$"%u_st) plt.ylabel("$y/%s$"%u_st) else : p.set_xlabel("$x/%s$"%u_st) p.set_ylabel("$y/%s$"%u_st) if units is None : units = im.units if log : units = r"$\log_{10}\,"+units.latex()+"$" else : units = "$"+units.latex()+"$" if show_cbar: if qtytitle is not None: plt.colorbar(ims).set_label(qtytitle) else: plt.colorbar(ims).set_label(units) # colorbar doesn't work wtih subplot: mappable is NoneType #elif show_cbar: # import matplotlib.pyplot as mpl # if qtytitle: mpl.colorbar().set_label(qtytitle) # else: mpl.colorbar().set_label(units) if title is not None: p.set_title(title) if filename is not None: p.savefig(filename) plt.draw() plt.show() return im