Exemple #1
0
	def rebin2d(self, bin_size):
		"""
		Rebin 2D plot along x dimension
		"""
		if self.dim != 2:
			raise GE('This rebins 2D histograms only')

		if int(bin_size)<1:
			raise GE('binsize < 1, using 1 instead')
			intbinsize=1
		else:
			intbinsize=int(bin_size)

		excess=len(self.weights[:,0])%intbinsize
		numyslices=self.weights.shape[1]

		if excess != 0:
			currweights=self.weights[0:-excess,:]
			currxaxis=self.x_axis[0:-excess]
		else:
			currweights=self.weights[:,:]
			currxaxis=self.x_axis[:]

		rebinned=[]
		for ii in range(numyslices):
			currslice=currweights[:,ii]
			rebinned.append(currslice.reshape((-1,intbinsize)).sum(axis=1))

		currweights=np.asarray(rebinned)
		currxaxis=currxaxis.reshape((-1,intbinsize)).mean(axis=1)
		currerrors=np.sqrt(abs(currweights))
		currtitle='{}, bin {}'.format(self.title,intbinsize)
		
		currhistogram=Histogram(dim=self.dim,weights=currweights,x_axis=currxaxis,y_axis=self.y_axis,title=currtitle,errors=currerrors)
		return currhistogram
Exemple #2
0
	def rebin1d(self, bin_size=1):
		"""
		Bin 1D histogram, binsize must be larger than 1
		"""
		if self.dim != 1:
			raise GE('This Rebins 1D histograms only.')

		if int(bin_size)<1:
			raise GE('binsize < 1, using 1 instead')
			intbinsize=1
		else:
			intbinsize=int(bin_size)

		excess=len(self.weights)%intbinsize
		if excess != 0:
			currweights=self.weights[0:-excess]
			currxaxis=self.x_axis[0:-excess]
		else:
			currweights=self.weights[:]
			currxaxis=self.x_axis[:]

		currweights=currweights.reshape((-1,intbinsize)).sum(axis=1)
		currxaxis=currxaxis.reshape((-1,intbinsize)).mean(axis=1)
		currerrors=np.sqrt(abs(currweights))
		currtitle='{}, bin {}'.format(self.title,intbinsize)

		currhistogram=Histogram(dim=self.dim,weights=currweights,x_axis=currxaxis,title=currtitle,errors=currerrors)
		return currhistogram
Exemple #3
0
    def __set_rounding(self, rounding):

        if not isinstance(rounding, str):
            raise GE('rounding must be \'low\',\'mid\',\'high\'')
        else:
            if rounding.lower() == 'low':
                self.dx = 0.0
            elif rounding.lower() == 'mid':
                self.dx = 0.5
            elif rounding.lower() == 'high':
                self.dx = 1.0
            else:
                raise GE('unknown rounding ---> {}'.format(rounding))
        self.__rounding = rounding
Exemple #4
0
	def __set_bin_size(self,bin_size):
		if self.histogram.dim!=1:
			raise GE('Currently only 1D histograms can be binned')

		if isinstance(bin_size,int):
			if bin_size > self.bin_size:
				self.__bin_size=bin_size
				self.histogram=self.histogram.rebin1d(bin_size)
			elif bin_size <= self.bin_size:
				pass
			else:
				raise GE('Attempt to set bin size to {}'.format(bin_size))
		else:
			raise GE('Attempt to set bin size to {}'.format(bin_size))
Exemple #5
0
	def __init__(self,size=11,max_2d_bin=1024,font_size=20,legend=True,cmap=color_maps[0]):
		"""
		size:
			0 -------------> None
			1 -------------> 8x6
			11 (default)---> 12x8
			2 -------------> 2 figs of 8x8
			12 ------------> 2 figs of 12x8
		"""
		self.max_2d_bin=max_2d_bin
		self.font_size=font_size
		self.legend=legend
		self.cmap=cmap

		if size==0:
			pass
		elif size==1:
			plt.figure(1,(8,6))
		elif size==11:
			plt.figure(1,(12,8))
		elif size==2:
			plt.figure(1,(8,6))
			plt.figure(2,(8,6))
		elif size==12:
			plt.figure(1,(12,8))
			plt.figure(2,(12,8))
		else:
			raise GE('Unknown size {}, must be 1,2,11,12'.format(size))

		if size != 0:
			plt.tick_params(axis='both',labelsize=self.font_size)
			plt.grid()
			plt.ion()
			plt.show()
Exemple #6
0
    def load_histogram(self, hisid):
        if self.histograms.get(hisid) is None:
            raise GE('Histogram {} not found'.format(hisid))

        offset = self.histograms[hisid]['offset']
        hisname = '{}{}'.format(self.base_name, '.his')

        with open(hisname, 'rb') as hisfile:
            length = 1
            dim = self.histograms[hisid]['dimension']

            if dim > 2:
                raise GE('Histograms with dimensions > 2 not supported')

            for d in range(self.histograms[hisid]['dimension']):
                length *= self.histograms[hisid]['scaled'][d]

            if self.histograms[hisid]['half_words_per_ch'] == 1:
                data = array('h')
            elif self.histograms[hisid]['half_words_per_ch'] == 2:
                data = array('i')
            else:
                msg = 'half-words per channel histograms not supported'
                raise GE(
                    '{} {}'.format(
                        self.histograms[hisid]['half_words_per_ch']), msg)

            hisfile.seek(offset * 2)
            data.fromfile(hisfile, length)

        xaxis=np.arange(self.histograms[hisid]['minc'][0]+self.dx,\
          self.histograms[hisid]['maxc'][0]+self.dx+1.0)

        if self.histograms[hisid]['dimension'] == 2:
            yaxis=np.arange(self.histograms[hisid]['minc'][1]+self.dx,\
              self.histograms[hisid]['maxc'][1]+self.dx+1.0)
            data=np.reshape(data,(self.histograms[hisid]['scaled'][1],\
                    self.histograms[hisid]['scaled'][0]))
            data = np.transpose(data)

        if self.histograms[hisid]['dimension'] == 1:
            return [1, xaxis, None, np.array(data)]
        else:
            return [2, xaxis, yaxis, data]
Exemple #7
0
	def normalize1d(self,norm='area',bin_size=1,xmin=None,xmax=None):
		"""
		Normalize 1D spectra by norm default to area so that it integrates to 1

		n_i=n_i/(norm*binsize)
		"""

		if self.dim != 1:
			raise GE('This Normalizes 1D histograms only.')
		
		if int(bin_size)<1:
			raise GE('binsize < 1, using 1 instead')
			intbinsize=1
		else:
			intbinsize=int(bin_size)

		currhistogram=Histogram(dim=self.dim,x_axis=self.x_axis,weights=self.weights,errors=self.errors)

		if isinstance(norm,str):
			if norm.lower()=='area':
				normalization=currhistogram.weights[xmin:xmax].sum()
				if normalization==0:
					print('Normalization came out to 0, using 1 instead')
					normalization=1
			else:
				raise GE('norm must be int, float, or \'area\'')

		elif isinstance(norm,float) or isinstance(norm,int):
			if norm == 0:
				print('norm set to 0, using 1 instead')
				normalization=1
			else:
				normalization=norm

		currhistogram.title='{},/{:.2e}'.format(self.title,normalization*intbinsize)
		currhistogram.weights=currhistogram.weights/(normalization*intbinsize)
		currhistogram.errors=currhistogram.errors/(normalization*intbinsize)

		return currhistogram
Exemple #8
0
    def __untar(self, tarball):
        sys.stderr.write('{:.<30}'.format('Checking tarball'))
        sys.stderr.flush()
        archive = []
        exstensions = [".drr", ".his", ".list", ".log"]
        for tarinfo in tarball:
            if os.path.splitext(tarinfo.name)[1] not in exstensions:
                raise GE(
                    ' File {} does not belong to tar.gz HISS/DRR histograms'.
                    format(tarinfo.name))
            if os.path.exists(tarinfo.name):
                raise GE('File {} alread exists'.format(tarinfo.name))
            archive.append(tarinfo.name)
        sys.stderr.write('[Done]\n')

        self.tmp_files += archive

        sys.stderr.write('{:.<30}'.format('Extracting tarball'))
        sys.stderr.flush()
        tarball.extractall()
        sys.stderr.write('[Done]\n')

        tarball.close()
Exemple #9
0
	def plot1d(self,plot,xlim=None,ylim=None):
		hist=plot.histogram

		if hist.dim!=1:
			raise GE('1d plotter not {}d'.format(hist.dim))

		if plot.mode=='histogram':
			plt.plot(hist.x_axis,hist.weights,ls='steps-mid',label=hist.title)
		elif plot.mode=='function':
			plt.plot(hist.x_axis,hist.weights,ls='-',label=hist.title)
		elif plot.mode=='errorbar':
			plt.errorbar(hist.x_axis,hist.weights,yerr=hist.errors,\
					marker='o',ls='None',label=hist.title)
		else:
			raise GE('Unknown plot mode {}'.format(plot.mode))

		if xlim is not None:
			plt.xlim(xlim)

		if ylim is not None:
			plt.ylim(ylim)

		if self.legend:
			plt.legend(loc=0,numpoints=1,fontsize='small')
Exemple #10
0
	def __set_norm(self,norm):
		if self.histogram.dim != 1:
			raise GE('Currently only 1D histograms can be normalized')
		self.__norm=norm
		self.histogram=self.histogram.normalize1d(norm,self.bin_size)
Exemple #11
0
	def plot2d(self,plot,xc=None,yc=None,logz=True):
		if plot.histogram.dim!=2:
			raise GE('2d plotter not {}d'.format(plot.histogram.dim))

		x=plot.histogram.x_axis
		y=plot.histogram.y_axis
		w=plot.histogram.weights

		if xc is not None:
			x=x[xc[0]:xc[1]]
			w=w[xc[0]:xc[1],:]

		if yc is not None:
			y=y[yc[0]:yc[1]]
			w=w[:,yc[0]:yc[1]]

		init_nx=len(x)
		init_ny=len(y)
		nx=len(x)
		ny=len(y)

		binx=1
		biny=1

		if nx > self.max_2d_bin:
			binx=math.ceil(nx/self.max_2d_bin)
			missing=binx*self.max_2d_bin-nx
			if missing > 0:
				addx=np.arange(plot.histogram.x_axis[-1]+1,plot.histogram.x_axis[-1]+missing+1)
				x=np.concatenate((x,addx))
				nx=len(x)
				z=np.zeros((missing,ny))
				w=np.concatenate((w,z),axis=0)
			x=np.reshape(x,(-1,binx))
			x=x.mean(axis=1)

		if ny > self.max_2d_bin:
			biny=math.ceil(ny/self.max_2d_bin)
			missing=biny*self.max_2d_bin-ny
			if missing > 0:
				addy=np.arange(plot.histogram.y_axis[-1]+1,plot.histogram.y_axis[-1]+missing+1)
				y=np.concatenate((y,addy))
				ny=len(y)
				z=np.zeros((nx,missing))
				w=np.concatenate((w,z),axis=1)
			y=np.reshape(y,(-1,biny))
			y=y.mean(axis=1)

		nx=len(x)
		ny=len(y)

		if nx!=init_nx or ny!=init_ny:
			w=np.reshape(w,(nx,binx,ny,biny)).mean(3).mean(1)
		w=np.transpose(w)

		title=plot.histogram.title

		if logz:
			w=np.ma.masked_where(w<=0,np.log10(w))
			title+='(log10'

		plt.title(title)
		CS=plt.pcolormesh(x,y,w,cmap=self.cmap)
		plt.xlim(xc)
		plt.ylim(yc)
		plt.colorbar()