示例#1
0
def basic_example():
    print('Family =', pywt.families())
    for family in pywt.families():
        print('\t%s family: ' % family + ', '.join(pywt.wavelist(family)))

    # Discrete wavelet object:
    #	haar family:
    #		'haar'.
    #	db family:
    #		'db1', 'db2', 'db3', 'db4', 'db5', 'db6', 'db7', 'db8', 'db9', 'db10', 'db11', 'db12', 'db13', 'db14', 'db15', 'db16', 'db17', 'db18', 'db19', 'db20', 'db21', 'db22', 'db23', 'db24', 'db25', 'db26', 'db27', 'db28', 'db29', 'db30', 'db31', 'db32', 'db33', 'db34', 'db35', 'db36', 'db37', 'db38'.
    #	sym family:
    #		'sym2', 'sym3', 'sym4', 'sym5', 'sym6', 'sym7', 'sym8', 'sym9', 'sym10', 'sym11', 'sym12', 'sym13', 'sym14', 'sym15', 'sym16', 'sym17', 'sym18', 'sym19', 'sym20'.
    #	coif family:
    #		'coif1', 'coif2', 'coif3', 'coif4', 'coif5', 'coif6', 'coif7', 'coif8', 'coif9', 'coif10', 'coif11', 'coif12', 'coif13', 'coif14', 'coif15', 'coif16', 'coif17'.
    #	bior family:
    #		'bior1.1', 'bior1.3', 'bior1.5', 'bior2.2', 'bior2.4', 'bior2.6', 'bior2.8', 'bior3.1', 'bior3.3', 'bior3.5', 'bior3.7', 'bior3.9', 'bior4.4', 'bior5.5', 'bior6.8'.
    #	rbio family:
    #		'rbio1.1', 'rbio1.3', 'rbio1.5', 'rbio2.2', 'rbio2.4', 'rbio2.6', 'rbio2.8', 'rbio3.1', 'rbio3.3', 'rbio3.5', 'rbio3.7', 'rbio3.9', 'rbio4.4', 'rbio5.5', 'rbio6.8'.
    #	dmey family:
    #		'dmey'.
    # Continuous wavelet object:
    #	gaus family:
    #		'gaus1', 'gaus2', 'gaus3', 'gaus4', 'gaus5', 'gaus6', 'gaus7', 'gaus8'.
    #	mexh family:
    #		'mexh'.
    #	morl family:
    #		'morl'.
    #	cgau family:
    #		'cgau1', 'cgau2', 'cgau3', 'cgau4', 'cgau5', 'cgau6', 'cgau7', 'cgau8'.
    # Discrete continuous wavelet object:
    #	shan family:
    #		'shan'.
    #	fbsp family:
    #		'fbsp'.
    #	cmor family:
    #		'cmor'.

    #--------------------
    w = pywt.Wavelet('db3')

    print('Summary =', w)
    print('Name = {}, short family name = {}, family name = {}.'.format(
        w.name, w.short_family_name, w.family_name))

    # Decomposition (dec_len) and reconstruction (rec_len) filter lengths.
    print('dec_len = {}, rec_len = {}.'.format(int(w.dec_len), int(w.rec_len)))
    # Orthogonality and biorthogonality.
    print('Orthogonal = {}, biorthogonal = {}.'.format(w.orthogonal,
                                                       w.biorthogonal))
    # Symmetry.
    print('Symmetry = {}.'.format(w.symmetry))
    # Number of vanishing moments for the scaling function phi (vanishing_moments_phi) and the wavelet function psi (vanishing_moments_psi) associated with the filters.
    print('vanishing_moments_phi = {}, vanishing_moments_psi = {}.'.format(
        w.vanishing_moments_phi, w.vanishing_moments_psi))

    # Lowpass and highpass decomposition filters and lowpass and highpass reconstruction filters.
    print('Filter bank? =',
          w.filter_bank == (w.dec_lo, w.dec_hi, w.rec_lo, w.rec_hi))
示例#2
0
    def setupContent(self, content_widget: QWidget):
        self.ui = Ui_Wavelet()
        self.ui.setupUi(content_widget)

        self.ui.level_spin.setMinimum(1)
        families = pywt.families(False)
        self.ui.wavelet_family_combo.addItems(families)
        self.ui.wavelet_combo.addItems(pywt.wavelist(pywt.families()[self.ui.wavelet_family_combo.currentIndex()]))
        self.ui.wavelet_family_combo.currentIndexChanged.connect(self._onFamilyChanged)
示例#3
0
 def dwt_library(cls, img_arr):
     '''Display all the availbale DWT (single level) for the input array  
     '''
     t1 = time.time()
     count = 0
     for fam in pywt.families():
         for mothwv in pywt.wavelist(fam):
             for mod in pywt.Modes.modes:
                 print '\tWavelet: {0} / Mode: {1}'.format(mothwv, mod)
                 (c_A, (c_H, c_V, c_D)) = pywt.dwt2(img_arr,
                                                    pywt.Wavelet(mothwv),
                                                    mod)
                 count += 1
                 fig = plt.figure(figsize=(6, 11))
                 ax1 = fig.add_subplot(221)
                 ax2 = fig.add_subplot(222)
                 ax3 = fig.add_subplot(223)
                 ax4 = fig.add_subplot(224)
                 ax1.imshow(c_A, cmap='seismic')  #'flag'
                 ax2.imshow(c_V, cmap='seismic')
                 ax3.imshow(c_H, cmap='seismic')
                 ax4.imshow(c_D, cmap='seismic')
                 plt.title('Wavelet: {0} / Mode: {1}'.format(mothwv, mod))
                 plt.subplots_adjust(left=.06,
                                     bottom=0.05,
                                     right=0.99,
                                     top=0.99,
                                     wspace=0.,
                                     hspace=0.)
                 plt.show()
     t2 = time.time()
     print(
         '\nTotal time in all {1} modes+mother wavelets: {0:.2f}\''.format(
             (t2 - t1) / 60., count))
示例#4
0
文件: wttest.py 项目: Saberin312/CNNS
def test_pywt():
    import numpy as np
    import matplotlib.pyplot as plt
    import pywt
    import pywt.data

    # Load image
    original = pywt.data.camera()

    # Wavelet transform of image, and plot approximation and details
    titles = [
        'Approximation', ' Horizontal detail', 'Vertical detail',
        'Diagonal detail'
    ]
    coeffs2 = pywt.dwt2(original, 'bior1.3')
    LL, (LH, HL, HH) = coeffs2
    plt.imshow(original)
    plt.colorbar(shrink=0.8)
    fig = plt.figure(figsize=(12, 3))
    for i, a in enumerate([LL, LH, HL, HH]):
        ax = fig.add_subplot(1, 4, i + 1)
        ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
        ax.set_title(titles[i], fontsize=10)
        ax.set_xticks([])
        ax.set_yticks([])

    fig.tight_layout()
    plt.show()
    print(pywt.families())
示例#5
0
文件: wavelets.py 项目: Xifax/muscale
def _plot_wavelet_families(all=False):
    '''Plotting waveletes approximations'''
    lvl = 4 # because!
    for name in pywt.families():
        if not all:
            _plot_wavelet(pywt.wavelist(name)[0], lvl)
        else:
            for wv in pywt.wavelist(name):
                _plot_wavelet(wv, lvl, True)
示例#6
0
        def wrapper(*args, **kwargs):
            wavelet = args[2]
            families = pywt.families()
            wavelets = list()
            [wavelets.extend(pywt.wavelist(family)) for family in families]
            if not wavelet in wavelets:

                raise TypeError("{} is not a valid wavelet".format(wavelet))

            return func(*args, **kwargs)
示例#7
0
文件: wt.py 项目: jpcoles/jcode
def startup():
    global w, N, L0, mode, level

    print pywt.families()
    print pywt.wavelist('db')

    w = pywt.Wavelet('db6')
    mode = pywt.MODES.per

    print w
    print "vanishing_moments_psi:", w.vanishing_moments_psi
    print "vanishing_moments_phi:", w.vanishing_moments_phi

    N = 2**9
    print "max level = ", pywt.dwt_max_level(N, w.dec_len)
    L0 = numpy.zeros((N,N), 'double')
    if True:
        for i in xrange(0,N):
            L0[i][i-1], L0[i][i], L0[i-1][i] = (1., -2., 1.)
    else:
        for i in xrange(1,N):
            L0[i][i-1], L0[i][i], L0[i-1][i] = (1., -2., 1.)
        L0[0][0] = -2.

#L0[0][N-1], L0[0][0], L0[N-1][0] = (1, -2, 1)

#L0 = numpy.eye(N)

#for i in xrange(0,N):
        #L0[i] = [1,2,3,4,5,6,7,8]

    numpy.core.arrayprint.set_printoptions(threshold=N*N+1, linewidth=100000)

#print L0

#coeffs = pywt.wavedec2(L0, w) #, level=pywt.dwt_max_level(N, w.dec_len))
#print coeffs
#print pywt.waverec2(coeffs, w)
#
#coeffs = pywt.wavedec2(L0, w) #, level=pywt.dwt_max_level(N, w.dec_len))
#print coeffs

    print "max level = ", pywt.dwt_max_level(N, w.dec_len)
示例#8
0
    def __init__(self, wavelet="db8"):

        # create list of supported wavelets
        supported = []
        for family in pywt.families():
            supported += pywt.wavelist(family)

        # check if wavelet is supported
        if wavelet not in supported:
            raise ValueError("DWT supports only " + str(supported) +
                             " as input wavelet")

        self.m_wavelet = wavelet
def wavelet_descomposition_experiment():
    dataset = '../datasets/grabado como el libro super bien'
    experiment_rsult = './descomposition experiment con entonema 6'
    if not os.path.exists(experiment_rsult):
        os.mkdir(experiment_rsult)

    name = os.path.basename(dataset)
    for family in pywt.families():
        wavelet = pywt.wavelist(family=family, kind='discrete')[0]
        if wavelet in pywt.wavelist(kind='discrete'):    
            directory = '{}/{}'.format(experiment_rsult, wavelet)
            if not os.path.exists(directory):
                os.mkdir(directory)
            for wav in os.listdir('{}/6'.format(dataset)):
                plot_descomposition(dataset, 6, wav, wavelet, directory)
    print('Finish')
示例#10
0
文件: wavelets.py 项目: Xifax/muscale
def select_wavelet(data, r, method='median'):
    comparison = {}
    level = 5
    r.initial = data
    for family in pywt.families():
        for wv in pywt.wavelist(family):
            values = pywt.Wavelet(wv).wavefun(level=level)
            r('coef <- ccf(initial, %s)$acf' % Str4R(values[-2]))   #psi
            if method == 'mean':
                r('med <- mean(coef)')
            elif method == 'sum':
                r('med <- sum(coef)')
            elif method == 'median':
                r('med <- coef[length(coef)/2]')
            else:
                r('med <- coef[length(coef)/2]')
            comparison[r.med] = (family, wv)    #it's okay to rewrite keys

    return comparison
示例#11
0
def main():
   # verify input
   wtype = pick_option(sys.argv, 't', 'db7')
   if len(sys.argv) > 4:
      image  = piio.read(sys.argv[1])
      prefix = sys.argv[2]
      levels = int(sys.argv[3])
      suffix = sys.argv[4]
   else:
      print("Incorrect syntax, use:")
      print("  > " + sys.argv[0] + " input prefix levels suffix [-t type]")
      print("        multiscale decomposition using wavelets")
      print("        available types:")
      for family in pywt.families():
         print "%s family:" % family, ', '.join(pywt.wavelist(family))
      sys.exit(1)

   if pywt.Wavelet(wtype).orthogonal == False:
      print "Warning \'%s\' is not orthogonal"%wtype

   decompose(image, prefix, levels, suffix, wtype)
示例#12
0
def main():

    levels = [4]
    img_type = ['ad', 'da', 'dd']
    families = []
    for family in pywt.families():
        families = families + pywt.wavelist(family)

    pathToDataset = "E://clg/Graduation project/Data set/DS"
    pathToFolder = "E://clg/Dr waleed work/testing"
    images, states = Read_data(pathToDataset)
    counter = 0
    for level in levels:
        for mode in families:
            for img in img_type:
                Wavelet_Features(images, states, mode, level, img,
                                 pathToFolder)
                counter = counter + 1
                print(counter)

    pass
示例#13
0
文件: decompose.py 项目: tehret/vbm3d
def main():
    # verify input
    wtype = pick_option(sys.argv, 't', 'db7')
    if len(sys.argv) > 4:
        image = piio.read(sys.argv[1])
        prefix = sys.argv[2]
        levels = int(sys.argv[3])
        suffix = sys.argv[4]
    else:
        print("Incorrect syntax, use:")
        print("  > " + sys.argv[0] + " input prefix levels suffix [-t type]")
        print("        multiscale decomposition using wavelets")
        print("        available types:")
        for family in pywt.families():
            print "%s family:" % family, ', '.join(pywt.wavelist(family))
        sys.exit(1)

    if pywt.Wavelet(wtype).orthogonal == False:
        print "Warning \'%s\' is not orthogonal" % wtype

    decompose(image, prefix, levels, suffix, wtype)
示例#14
0
def main():
   # verify input
   wtype = pick_option(sys.argv, 't', 'db7')
   if len(sys.argv) > 3:
      image  = piio.read(sys.argv[1])
      coarse = piio.read(sys.argv[2])
      oname  = sys.argv[3]
   else:
      print("Incorrect syntax, use:")
      print("  > " + sys.argv[0] + " image coarse result [-t type]")
      print("        2 scale recomposition using wavelets")
      print("        available types:")
      for family in pywt.families():
         print "%s family:" % family, ', '.join(pywt.wavelist(family))
      sys.exit(1)

   if pywt.Wavelet(wtype).orthogonal == False:
      print "Warning \'%s\' is not orthogonal"%wtype

   res = recompose(image, coarse, wtype)

   piio.write(oname, res);
示例#15
0
def main():
   # verify input
   wtype = pick_option(sys.argv, 't', 'db7')
   if len(sys.argv) > 3:
      image  = piio.read(sys.argv[1])
      coarse = piio.read(sys.argv[2])
      oname  = sys.argv[3]
   else:
      print("Incorrect syntax, use:")
      print("  > " + sys.argv[0] + " image coarse result [-t type]")
      print("        2 scale recomposition using wavelets")
      print("        available types:")
      for family in pywt.families():
         print "%s family:" % family, ', '.join(pywt.wavelist(family))
      sys.exit(1)

   if pywt.Wavelet(wtype).orthogonal == False:
      print "Warning \'%s\' is not orthogonal"%wtype

   res = recompose(image, coarse, wtype)

   piio.write(oname, res);
示例#16
0
    def __init__(self, wavelet: str = 'db8') -> None:
        """
        Parameters
        ----------
        wavelet : str
            Wavelet.

        Returns
        -------
        NoneType
            None
        """

        # create list of supported wavelets
        supported = []
        for item in pywt.families():
            supported += pywt.wavelist(item)

        # check if wavelet is supported
        if wavelet not in supported:
            raise ValueError(
                f'DWT supports only {supported} as input wavelet.')

        self.m_wavelet = wavelet
示例#17
0
    def __init__(self, wavelet="db8"):
        """
        Parameters
        ----------
        wavelet : str
            Wavelet.

        Returns
        -------
        NoneType
            None
        """

        # create list of supported wavelets
        supported = []
        for family in pywt.families():
            supported += pywt.wavelist(family)

        # check if wavelet is supported
        if wavelet not in supported:
            raise ValueError("DWT supports only " + str(supported) +
                             " as input wavelet.")

        self.m_wavelet = wavelet
import pywt
import pandas as pd
from os.path import join
from os import listdir
from os.path import isfile, join
import os


def get_folders(path):
    return [join(path, f) for f in listdir(path) if not isfile(join(path, f))]


print '{\\bf \\#} & {\\bf Raw}',
for family in pywt.families():
    for wavelet_name in pywt.wavelist(family)[-1:]:
        print '& {\\bf', wavelet_name, '}',
print '\\\\'
print '\\midrule'

rows = []
i = 0
for folder in get_folders('NewlyAddedDatasets/'):
    print i + 1,
    print '&',
    row = {"dataset": i + 1}

    try:
        df = pd.DataFrame.from_csv(join(folder, 'fastdtw_prediction_db1.csv'), index_col=False)
        raw = 100.0 * df[df['label'] == df['original_data']].shape[0] / df.shape[0]
        print "{0:.1f}".format(raw),
    except:
示例#19
0
    def init_window(self):
        self.master.title("Thermal Fusion GUI")

        menu = Menu(self)
        self.master.config(menu=menu)

        filemenu = Menu(menu)

        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Open RGB Image",
                             command=lambda: self.loadFile(True))
        filemenu.add_command(label="Open IR Image",
                             command=lambda: self.loadFile(False))
        filemenu.add_command(label="Open Example Images",
                             command=self.loadDefault)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.client_exit)

        self.pack(fill=BOTH, expand=1)

        canvasRGB = Canvas(self, width=382, height=288, bg='white')
        canvasRGB.grid(column=0, row=0)

        RGB_id = canvasRGB.create_text(191, 142, fill="blue", tag="RGB")
        canvasRGB.insert(RGB_id, 12, "RGB")

        self.canvasRGB = canvasRGB

        canvasIR = Canvas(self, width=382, height=288, bg='white')
        canvasIR.grid(column=1, row=0)

        IR_id = canvasIR.create_text(191, 142, fill="blue", tag="IR")
        canvasIR.insert(IR_id, 12, "IR")

        self.canvasIR = canvasIR

        button = Button(self,
                        text="Load example images",
                        command=self.loadDefault)
        button.grid(column=2, row=0)
        self.button = button

        buttonRGB = Button(self,
                           text="Select RGB Image",
                           command=lambda: self.loadFile(True))
        buttonRGB.grid(column=0, row=1)
        self.buttonRGB = buttonRGB

        buttonIR = Button(self,
                          text="Select IR Image",
                          command=lambda: self.loadFile(False))
        buttonIR.grid(column=1, row=1)
        self.buttonIR = buttonIR

        fusion = Button(self,
                        text="Start fusion process",
                        command=self.startFusion)
        fusion.grid(column=0, row=2)
        self.fusion = fusion

        text = Text(self, width=70, height=15)
        text.grid(column=0, row=3)
        self.text = text

        self.progressbar = Progressbar(self,
                                       orient=HORIZONTAL,
                                       mode='indeterminate',
                                       length=100)
        self.progressbar.grid(column=1, row=3)

        options = [
            "All", "Min", "Max", "Mean", "Entropy", "MACD", "Edge", "Deviation"
        ]

        self.variable = StringVar(self)
        self.variable.set(options[0])

        self.dropdown = OptionMenu(self, self.variable, options[0], *options)
        self.dropdown.grid(column=3, row=1)

        # Only the first wavelets are functionnal
        wavelets = families(short=False)[:7]
        shortWavelets = families()[:7]

        self.dictWavelets = dict(zip(wavelets, shortWavelets))

        self.waveletVar = StringVar(self)
        self.waveletVar.set(wavelets[1])

        self.waveletDropdown = OptionMenu(self, self.waveletVar, wavelets[1],
                                          *wavelets)
        self.waveletDropdown.grid(column=4, row=1)

        self.queue = Queue()

        self.rgb_path = ""
        self.ir_path = ""
示例#20
0
def printDetails():
    print("Family of wavelets available:")
    print(pywt.families())
    print("\n{0}".format(pywt.Wavelet('haar')))
示例#21
0
		frequency = np.arange(n / 2) / (n * interval) 
		nfft = abs(ft[range(int(n / 2))] / n ) 
		plt.plot(frequency, nfft, 'maroon')
		#plt.scatter(frequency[0],nfft[0],marker='o',c='maroon',edgecolors='red',linewidths=2)
		plt.xlabel('Freq'), plt.ylabel('RH') 
		plt.show()


	def fft(a):
		yy=np.fft.fft(y)#快速傅里叶变换
		return yy
	#show(y,yy)
	#plt.show()

	#小波变换
	print pywt.families()
	print pywt.wavelist(kind='discrete')#选择离散还是连续
	print pywt.ContinuousWavelet('morl')#连续小波morl的系列
	mode = pywt.Modes.smooth
	#离散小波变换

	def plot_signal_decomp(data, w, title,order):
		"""Decompose and plot a signal S.
		S = An + Dn + Dn-1 + ... + D1
		"""
		w = pywt.Wavelet(w)#选取小波函数
		a = data
		ca = []#近似分量/低频
		cd = []#细节分量/高频
		for i in range(order):
			(a, d) = pywt.dwt(a, w, mode)#进行order阶离散小波变换
示例#22
0
 def populateWindow(self):
     self.cbbWaveletFamily.addItems(pywt.families())
     self.cbbWavelet.addItems(pywt.wavelist('haar'))
示例#23
0
import sys, os
import numpy
import matplotlib.pyplot
from PIL import Image
import pywt


def rgb2gray(rgb):
    return numpy.dot(rgb[..., :3], [0.299, 0.587, 0.114])


image_path = sys.argv[1]
dwt_method = sys.argv[2]  # dwt/dwt2

print pywt.families(short=False)

#######################################################################3
# read img from file
print '#######################################################################'
img_file = Image.open(image_path)
img = numpy.array(img_file)
print 'rgb matrix'
print img

# turn rbg to gray
gray = rgb2gray(img)
print 'gray matrix', gray.shape
print gray

# create a figure
figure, ax = matplotlib.pyplot.subplots(5, 2)
示例#24
0
def all_wavelets():
    for family in pywt.families():
        for n in pywt.wavelist(family):
            if n == 'db1':  # Same as Haar
                continue
            yield n
示例#25
0
文件: wvgrp.py 项目: jpcoles/jcode
    Pw = []
    for i,n in enumerate(xrange(0,log(N,2))):
        pylab.figure()
        Pw.append(deepcopy(P))
        print len(Pw)
        level = n
        print "n=",n
        Pw[i] = xfrm2d(Pw[i]).T
        Pw[i] = xfrm2d(Pw[i]).T
        #Pw[Pw==0.0] = 255
        pylab.matshow(Pw[i])

def two():
    global P
    eps = 1
    Pw = deepcopy(P)
    for i,n in enumerate(xrange(1,4)):
        X = pywt.wavedec2(Pw, 'sym5', level=n)
        Pw = X[1][0]
        #Pw[abs(Pw) < eps] = 0
        #Pw[abs(Pw) >= eps] = 1
        pylab.matshow(Pw)

print pywt.families()

pylab.gray()
P = load_image()
two()

pylab.show()
示例#26
0
文件: muWizard.py 项目: Xifax/muscale
 def initComponents(self):
    self.setWindowFlags(Qt.Tool)
    self.setWindowTitle('Custom settings')
    self.waveletFamily.addItems(pywt.families())
    self.signalEx.addItems(pywt.MODES.modes)
    self.periodic.clicked.connect(self.showFrequency)
    self.options['enable'] = False
    
    self.setStyleSheet('QPushButton {\
                color: #333;\
                border: 1px solid #555;\
                border-radius: 11px;\
                padding: 2px;\
                background: qradialgradient(cx: 0.3, cy: -0.4,\
                fx: 0.3, fy: -0.4,\
                radius: 1.35, stop: 0 #fff, stop: 1 #888);\
                min-width: 80px;}\
            QPushButton:hover {\
                color: #fff;\
                background: qradialgradient(cx: 0.3, cy: -0.4,\
                fx: 0.3, fy: -0.4,\
                radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}\
            QPushButton:pressed {\
                background: qradialgradient(cx: 0.4, cy: -0.1,\
                fx: 0.4, fy: -0.1,\
                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}\
            QPushButton:checked {\
                background: qradialgradient(cx: 0.4, cy: -0.1,\
                fx: 0.4, fy: -0.1,\
                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}\
            QComboBox {\
                color: #333;\
                border: 1px solid #555;\
                border-radius: 11px;\
                padding: 1px 18px 1px 3px;\
                background: qradialgradient(cx: 0.3, cy: -0.4,\
                fx: 0.3, fy: -0.4,\
                radius: 1.35, stop: 0 #fff, stop: 1 #888);\
                min-width: 20px;}\
            QComboBox:hover {\
                color: #fff;\
                background: qradialgradient(cx: 0.3, cy: -0.4,\
                fx: 0.3, fy: -0.4,\
                radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}\
            QComboBox::down-arrow {\
                 image: url(' + RES + ICONS + ARROW_DOWN + ');}\
            QComboBox::down-arrow:on {\
                 top: 1px;\
                 left: 1px;}\
            QComboBox::drop-down {\
                 subcontrol-origin: padding;\
                 subcontrol-position: top right;\
                 width: 15px;\
                 border-left-width: 1px;\
                 border-left-color: darkgray;\
                 border-left-style: solid;\
                 border-top-right-radius: 3px;\
                 border-bottom-right-radius: 3px;}\
            QToolButton {\
                color: #333;\
                border: 1px solid #555;\
                border-radius: 11px;\
                padding: 2px;\
                background: qradialgradient(cx: 0.3, cy: -0.4,\
                fx: 0.3, fy: -0.4,\
                radius: 1.35, stop: 0 #fff, stop: 1 #888);\
                min-width: 20px;}\
            QToolButton:hover {\
                color: #fff;\
                background: qradialgradient(cx: 0.3, cy: -0.4,\
                fx: 0.3, fy: -0.4,\
                radius: 1.35, stop: 0 #fff, stop: 1 #bbb);}\
            QToolButton:pressed {\
                background: qradialgradient(cx: 0.4, cy: -0.1,\
                fx: 0.4, fy: -0.1,\
                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}\
            QToolButton:checked {\
                background: qradialgradient(cx: 0.4, cy: -0.1,\
                fx: 0.4, fy: -0.1,\
                radius: 1.35, stop: 0 #fff, stop: 1 #ddd);}')
示例#27
0
 def _onFamilyChanged(self, index):
     self.ui.wavelet_combo.clear()
     self.ui.wavelet_combo.addItems(pywt.wavelist(pywt.families()[index]))
示例#28
0
import pywt
from matplotlib import pyplot
import numpy
from PIL import Image
import urllib.request
import io
import torch
from torch.autograd import Variable

URL = 'https://upload.wikimedia.org/wikipedia/commons/thumb/b/bc/Zuse-Z4-Totale_deutsches-museum.jpg/315px-Zuse-Z4-Totale_deutsches-museum.jpg'


print(pywt.families())

w=pywt.Wavelet('bior2.2')
pyplot.plot(w.dec_hi[::-1], label="dec hi")
pyplot.plot(w.dec_lo[::-1], label="dec lo")
pyplot.plot(w.rec_hi, label="rec hi")
pyplot.plot(w.rec_lo, label="rec lo")
pyplot.title("Bior 2.2 Wavelets")
pyplot.legend()
dec_hi = torch.Tensor(w.dec_hi[::-1]) 
dec_lo = torch.Tensor(w.dec_lo[::-1])
rec_hi = torch.Tensor(w.rec_hi)
rec_lo = torch.Tensor(w.rec_lo)


imgraw = Image.open(io.BytesIO(urllib.request.urlopen(URL).read())).resize((256,256))
img = numpy.array(imgraw).mean(2)/255
img = torch.from_numpy(img).float()
pyplot.figure()
示例#29
0
import numpy as np
import matplotlib.pyplot as plt
import os
import pywt
import datetime

elliot_waves = []
wavelets = pywt.families()


def showPlot(date, data, file_name):
    fig, ax = plt.subplots()
    ax.plot(date, data)
    fig.savefig(file_name)
    plt.close(fig)


# def generate_elliot_waves(folder):

common_folder = 'static/results/'
folder_name = 'elliot/'


def trend(data):
    return 0 * np.arange(len(data))


def print_wave(data, file_name):
    date = np.arange(len(data))
    return showPlot(date, data, file_name)
示例#30
0
import pywt
import pandas as pd
import matplotlib.pyplot as plt

print(pywt.families())  # 打印出小波族
# ['haar', 'db', 'sym', 'coif', 'bior', 'rbio', 'dmey', 'gaus', 'mexh', 'morl', 'cgau', 'shan', 'fbsp', 'cmor']

for family in pywt.families():  # 打印出每个小波族的每个小波函数
    print('%s family: ' % (family) + ','.join(pywt.wavelist(family)))
# haar family: haar
# db family: db1,db2,db3,db4,db5,db6,db7,db8,db9,db10,db11,db12,db13,db14,db15,db16,db17,db18,db19,db20,db21,db22,db23,db24,db25,db26,db27,db28,db29,db30,db31,db32,db33,db34,db35,db36,db37,db38
# sym family: sym2,sym3,sym4,sym5,sym6,sym7,sym8,sym9,sym10,sym11,sym12,sym13,sym14,sym15,sym16,sym17,sym18,sym19,sym20
# coif family: coif1,coif2,coif3,coif4,coif5,coif6,coif7,coif8,coif9,coif10,coif11,coif12,coif13,coif14,coif15,coif16,coif17
# bior family: bior1.1,bior1.3,bior1.5,bior2.2,bior2.4,bior2.6,bior2.8,bior3.1,bior3.3,bior3.5,bior3.7,bior3.9,bior4.4,bior5.5,bior6.8
# rbio family: rbio1.1,rbio1.3,rbio1.5,rbio2.2,rbio2.4,rbio2.6,rbio2.8,rbio3.1,rbio3.3,rbio3.5,rbio3.7,rbio3.9,rbio4.4,rbio5.5,rbio6.8
# dmey family: dmey
# gaus family: gaus1,gaus2,gaus3,gaus4,gaus5,gaus6,gaus7,gaus8
# mexh family: mexh
# morl family: morl
# cgau family: cgau1,cgau2,cgau3,cgau4,cgau5,cgau6,cgau7,cgau8
# shan family: shan
# fbsp family: fbsp
# cmor family: cmor

db3 = pywt.Wavelet('db3')  # 创建一个小波对象
print(db3)

# Filters length: 6        #滤波器长度
# Orthogonal:     True    #正交
# Biorthogonal:   True    #双正交
# Symmetry:       asymmetric    #对称性,不对称
    * Haar (``haar``)
    * Daubechies (``db``)
    * Symlets (``sym``)
    * Coiflets (``coif``)
    * Biorthogonal (``bior``)
    * Reverse biorthogonal (``rbio``)
    * `"Discrete"` FIR approximation of Meyer wavelet (``dmey``)
    * Gaussian wavelets (``gaus``)
    * Mexican hat wavelet (``mexh``)
    * Morlet wavelet (``morl``)
    * Complex Gaussian wavelets (``cgau``)
    * Shannon wavelets (``shan``)
    * Frequency B-Spline wavelets (``fbsp``)
    * Complex Morlet wavelets (``cmor``)
"""

# 得到支持的小波
wavelet_list = pywt.families()
wavelet_list_long = pywt.families(short=False)

print(wavelet_list)
print(wavelet_list_long)

# 得到所有可利用的小波
wave_haar = pywt.wavelist(family="haar")
print(wave_haar)
wave_coif = pywt.wavelist(family="coif")
print(wave_coif)
wave_continuous = pywt.wavelist(kind="continuous")
print(wave_continuous)
示例#32
0
文件: cycle.py 项目: Xifax/muscale
def __modelling_cycle():

    initial_data = test_data

    fig_init = plt.figure()
    fig_init.canvas.manager.set_window_title('Initial data')
    plt.plot(initial_data, color='g')
#--------------- wavelet decomposition -------------------#
    decomposition_level = 2
    wavelet_families = pywt.families()
    wavelet_family = wavelet_families[0]
    selected_wavelet = pywt.wavelist(wavelet_family)[0]

    wavelet = pywt.Wavelet(selected_wavelet)  #NB: taking first variant of wavelet (e.g. haar1)
    # discrete (non stationary) multilevel decomposition
    wCoefficients_Discrete = pywt.wavedec(initial_data, wavelet, level=decomposition_level) #NB: output length also depends on wavelet type
    # stationary (Algorithme à trous ~ does not decimate coefficients at every transformation level) multilevel decomposition
    wCoefficients_Stationary = pywt.swt(initial_data, wavelet, level=decomposition_level)

    fig_discrete = plt.figure(); n_coeff = 1
    fig_discrete.canvas.manager.set_window_title('Discrete decomposition [ ' + str(decomposition_level) + ' level(s) ]') 
    for coeff in wCoefficients_Discrete:
#        print coeff
        fig_discrete.add_subplot(len(wCoefficients_Discrete), 1, n_coeff); n_coeff += 1
        plt.plot(coeff)

    fig_stationary = plt.figure(); n_coeff = 1; rows = 0
    fig_stationary.canvas.manager.set_window_title('Stationary decomposition [ ' + str(decomposition_level) + ' level(s) ]')
    for item in wCoefficients_Stationary: rows += len(item)
    i = 0; j = 0    # tree coeffs
    for coeff in wCoefficients_Stationary:
        for subcoeff in coeff:
            print i, j
#            print subcoeff
            fig_stationary.add_subplot(rows, 1, n_coeff); n_coeff += 1
            plt.plot(subcoeff)
            j += 1
        i += 1

    plt.show()

    fig_stat_sum = plt.figure(); n_coeff = 1
    fig_stat_sum.canvas.manager.set_window_title('SWT sum by levels [ ' + str(decomposition_level) + ' level(s) ]')
    for coeff in wCoefficients_Stationary:
        sum = coeff[0] + coeff[1]
        fig_stat_sum.add_subplot(len(wCoefficients_Discrete), 1, n_coeff); n_coeff += 1
        plt.plot(sum)
        
#    plt.show()

#------------------ modelling by level -------------------#

    r = R()
    r.i_data = initial_data     # or r['i_data'] = initial_data

    ### Holt-Winters ###
    # non-seasonal Holt-Winters
    print r('hw <- HoltWinters( i_data, gamma = FALSE )')

    # seasonal Holt-Winters
    r.freq = 4  #series sampling (month, days, years, etc)
#    print r( 'hw <- HoltWinters( ts ( %s, frequency = %s ) )' % ( Str4R(r.i_data), Str4R(r.freq) ) )
#    print r( 'hw <- HoltWinters( ts ( %s, frequency = %s, start = c(1,1) ) )' % ( Str4R(r.i_data), Str4R(r.freq) ) )

    # resulting Square Estimation Sum
    print r.hw['SSE']

    # bruteforce frequency search
#    print 'test ahead:'
#    sse_dict = {}
#    for i in xrange(2, 50):
#        r.freq = i
##        r( 'hw <- HoltWinters( ts ( %s, frequency = %s, start = c(1,1) ) )' % ( Str4R(r.i_data), Str4R(r.freq) ) )
#        r( 'hw <- HoltWinters( ts ( %s, frequency = %s ) )' % ( Str4R(r.i_data), Str4R(r.freq) ) )
#        print r.hw['SSE']
#        sse_dict[r.hw['SSE']] = i; i += 1
#    print 'Resulting:'
#    m = min(sse_dict.keys())
#    print sse_dict[m], m

    fig = plt.figure()
    fig.canvas.manager.set_window_title('Holt-winters model')
    ax = fig.add_subplot(111)
#    ax.plot(r.hw['fitted'][:,0])   # the colums are: xhat, level, trend
#    plt.show()

    # forecast length
    r.steps_ahead = 50
#    print r('pred <- predict(%s, %s, prediction.interval = TRUE)' % ( Str4R(r.hw), Str4R(r.steps_ahead)) )
#    print r( 'pred <- predict(hw, %s, prediction.interval = TRUE)', Str4R(r.steps_ahead) )
    print r( 'pred <- predict(hw, 50, prediction.interval = TRUE)')
#    plt.plot(r.pred)
    ax.plot(initial_data)
    ax.plot(append(r.hw['fitted'][:,0], r.pred[:,0]))   # concatenating reconstructed model and resulting forecast

#    plt.show()

#------------------ reconstruction -------------------#
    # multilevel idwt
    reconstructed_Discrete = pywt.waverec(wCoefficients_Discrete, selected_wavelet)
    fig_dis_r = plt.figure()
    fig_dis_r.canvas.manager.set_window_title('DWT reconstruction')
    plt.plot(reconstructed_Discrete)
#    plt.show()

    # multilevel stationary
    reconstructed_Stationary = iswt(wCoefficients_Stationary, selected_wavelet)

    fig_sta_r = plt.figure()
    fig_sta_r.canvas.manager.set_window_title('SWT reconstruction')
    plt.plot(reconstructed_Stationary)
    plt.show()
    print 'end'
示例#33
0
def denoise(st, wavelet="coif4", MODE="zero", remove_bg=True,
                threshold='soft', zero_coarse_levels=1, zero_fine_levels=1,
                preevent_window=10.0, preevent_threshold_reduction=2.0,
                store_orig=False, store_noise=False):
    """Remove noise from waveforms using wavelets in a two-step
    process. In the first step, noise is identified via a Kurtosis
    analysis of the wavelet coefficients. In the second step, the
    noise level in a pre-event window is determined for each wavelet
    level and then removed from the waveform using a soft threshold.

    :type wavelet: str
    :param wavelet: Name of wavelet to use in denoising.
    :type remove_bg: bool
    :param remove_bg: If True, perform the first step in the denoising process.
    :type preevent_window: float
    :param preevent_window: Size of pre-event window to use in second step. Skip second step if <= 0.
    :type preevent_threshold_reduction: float
    :param preevent_threshold_reduction: Factor to reduce threshold of noise level in second step.
    :type store_orig: bool
    :param store_orig: Return a copy of the original waveforms.
    :type store_noise: bool
    :param store_noise: Return the noise waveforms removed.
    :returns: Dictionary containing the denoised waveforms and, if
    requested, original waveforms and noise waveforms.

    """
    # Use of "__name__" is to grab the module's name in this python package namespace
    logger = logging.getLogger(__name__)

    try:
        import pywt
    except ImportError:
        raise ImportError("dwt_denoise() requires PyWavelets (pywt) Python module.")

    # Incorporate use of other wavelets, check that they are valid
    try:
        wt_fams = pywt.families()
        wt_fams_lists = []
        for i, fam in enumerate(wt_fams):
            wt_fams_lists.append(pywt.wavelist(fam))

        if ~(wavelet in wt_fams_lists):
            logger.info("")
    except LookupError:
        logger.info("The wavelet selected by the user is not supported by PyWavelets")

    # Incorporate other options for padding, while default is still zero
        # Do at some point

    # Keep a copy of the input data
    dataOut = {}
    if store_orig:
        dataOut["orig"] = st.copy()

    # Prep in case user wants to also keep noise
    tracesNoise = []
    for tr in st:
        channelLabel = "%s.%s.%s" % (tr.stats.network,
                                     tr.stats.station,
                                     tr.stats.channel)
        coefsNoise = []

        coefs = pywt.wavedec(tr.data, wavelet, mode=MODE)

        # Do kurtosis analysis to determine noise
        if remove_bg:
            coefsNoise = utils.kurtosis(channelLabel, coefs, logger)

        # Identify pre-event noise at all wavelet levels and remove
        coefs, coefsNoise = utils.remove_pre_event_noise(tr,coefs, preevent_window, preevent_threshold_reduction)
        for ilevel in range(1+zero_coarse_levels):
            coefsNoise[ilevel] += coefs[ilevel].copy()
            coefs[ilevel] *= 0.0
        for ilevel in range(zero_fine_levels):
            index = -(1+ilevel)
            coefsNoise[index] += coefs[index].copy()
            coefs[index] *= 0.0

        # Reconstruct a reduced noise signal from processed wavelet coefficients
        tr.data = pywt.waverec(coefs, wavelet, mode=MODE)

        if store_noise:
            trNoise = tr.copy()
            trNoise.data = pywt.waverec(coefsNoise, wavelet, mode=MODE)
            tracesNoise.append(trNoise)

        #Signal to noise ratio
        if threshold == 'soft':
            tr = utils.soft_threshold(tr, channelLabel, coefs, coefsNoise, logger)
        elif threshold == 'hard':
            tr = utils.soft_threshold(tr, channelLabel, coefs, coefsNoise, logger)
        elif threshold == 'block':
            logger.info("Block thresholding currenlty under development")
        else:
            logger.info("Unsupported thresholding option")

    dataOut["data"] = st
    if store_noise:
        import obspy.core
        dataOut["noise"] = obspy.core.Stream(traces=tracesNoise)

    return dataOut
示例#34
0
 def show(self):
     print("Available wavelets:")
     for family in pywt.families():
         print("* %s family: " % family + ', '.join(pywt.wavelist(family)))
示例#35
0
文件: cycle.py 项目: Xifax/muscale
def modelling_cycle():

#--------------- initialization -------------------#
#    initial_data = test_data
    initial_data = test_data_one

#    fig_init = plt.figure()
#    fig_init.canvas.manager.set_window_title('Initial data')
#    plt.plot(initial_data, color='g')

    wavelet_families = pywt.families()
    print 'Wavelet families:', ', '.join(wavelet_families)
    wavelet_family = wavelet_families[4]
    selected_wavelet = pywt.wavelist(wavelet_family)[0]
    wavelet = pywt.Wavelet(selected_wavelet)
    print 'Selected wavelet:', selected_wavelet

    max_level = pywt.swt_max_level(len(initial_data))
#    decomposition_level = max_level / 2
    decomposition_level = 3
    print 'Max level:', max_level, '\t Decomposition level:', decomposition_level

#--------------- decomposition -------------------#
    w_initial_coefficients = pywt.swt(initial_data, wavelet, level=decomposition_level)
    w_selected_coefficiets = select_levels_from_swt(w_initial_coefficients)
    w_node_coefficients = select_node_levels_from_swt(w_initial_coefficients)      #something terribly wrong here, yet the rest works!

#------------------ threshold --------------------#

    threshold = measure_threshold(w_initial_coefficients)

    w_threshold_coeff = w_initial_coefficients[:]
    apply_threshold(w_threshold_coeff)
    plot_initial_updated(w_initial_coefficients, w_threshold_coeff)

#    plt.figure()
#    for coeff in w_selected_coefficiets:
#        plt.plot(coeff)
#    plt.figure()
#    for coeff in w_node_coefficients:
#        plt.plot(coeff)
#    plt.show()

#--------------- modification -------------------#
    r = R()

    w_new_coefficients = [0] * len(w_selected_coefficiets)
    for index in range(0, len(w_selected_coefficiets)):
        r.i_data = w_selected_coefficiets[index]

        r('hw <- HoltWinters( ts(i_data, frequency = 12), gamma = TRUE )')
        r('pred <- predict(hw, 50, prediction.interval = TRUE)')

        w_new_coefficients[index] = append(w_selected_coefficiets[index], r.pred[:,0])
        index += 1

    w_new_node_coefficients = [0] * len(w_node_coefficients)
    for index in range(0, len(w_node_coefficients)):
        r.i_data = w_node_coefficients[index]

        r('hw <- HoltWinters( ts(i_data, frequency = 12), gamma = TRUE )')
        r('pred <- predict(hw, 50, prediction.interval = TRUE)')

        w_new_node_coefficients[index] = append(w_node_coefficients[index], r.pred[:,0])
        index += 1
#----

#    plt.figure()
#    for coeff in w_new_coefficients:
#        plt.plot(coeff)
#    plt.figure()
#    for coeff in w_new_node_coefficients:
#        plt.plot(coeff)
#    plt.show()

#--------------- reconstruction  -------------------#
#    wInitialwithUpdated_Nodes = update_node_levels_swt(w_initial_coefficients, w_new_node_coefficients)

#    plot_initial_updated(w_initial_coefficients, w_new_node_coefficients, True)
#    plot_initial_updated(w_initial_coefficients, wInitialwithUpdated_Nodes) (!)

#    plt.figure()
#    for dyad in wInitialwithUpdated_Nodes:
#        plt.plot(dyad[0])
#        plt.plot(dyad[1])
#
#    plt.figure()
#    for dyad in w_initial_coefficients:
#        plt.plot(dyad[0])
#        plt.plot(dyad[1])
#
#    plt.show()

#    w_updated_coefficients = update_selected_levels_swt(w_initial_coefficients, w_selected_coefficiets)
#    w_updated_coefficients = update_selected_levels_swt(w_initial_coefficients, w_new_coefficients)


#----
#    w_updated_coefficients = update_swt(w_initial_coefficients, w_selected_coefficiets, w_node_coefficients)

    w_updated_coefficients_nodes = update_swt(w_initial_coefficients, w_new_coefficients, w_new_node_coefficients)
    w_updated_coefficients = update_selected_levels_swt(w_initial_coefficients, w_new_coefficients)

    plot_initial_updated(w_initial_coefficients, w_updated_coefficients_nodes)
    plot_initial_updated(w_initial_coefficients, w_updated_coefficients)

    reconstructed_Stationary_nodes = iswt(w_updated_coefficients_nodes, selected_wavelet)
    reconstructed_Stationary = iswt(w_updated_coefficients, selected_wavelet)

    fig_sta_r = plt.figure()
    fig_sta_r.canvas.manager.set_window_title('SWT reconstruction')
    plt.plot(reconstructed_Stationary)

    fig_sta_r_n = plt.figure()
    fig_sta_r_n.canvas.manager.set_window_title('SWT reconstruction (nodes)')
    plt.plot(reconstructed_Stationary_nodes)

    plt.show()
coeffs2 = pywt.dwt2(original, 'bior1.3')
LL, (LH, HL, HH) = coeffs2
fig = plt.figure(figsize=(12, 3))
for i, a in enumerate([LL, LH, HL, HH]):
    ax = fig.add_subplot(1, 4, i + 1)
    ax.imshow(a, interpolation="nearest", cmap=plt.cm.gray)
    ax.set_title(titles[i], fontsize=10)
    ax.set_xticks([])
    ax.set_yticks([])

fig.tight_layout()
plt.show()

# In[5]:

pywt.families()

# In[6]:

pywt.families(short=False)

# In[7]:

pywt.wavelist(family='coif', kind='discrete')

# In[8]:

pywt.wavelist(family='haar', kind='continuous')

# In[9]:
示例#37
0
import numpy as np
import matplotlib.pyplot as plt
import os
import pywt
import datetime

elliot_waves = []
wavelets = pywt.families()


def showPlot(date, data, file_name):
    fig, ax = plt.subplots()
    ax.plot(date, data)
    fig.savefig(file_name)
    plt.close(fig)


# def generate_elliot_waves(folder):

common_folder = 'static/results/'
folder_name = 'elliot/'


def trend(data):
    return 0 * np.arange(len(data))


def print_wave(data, file_name):
    date = np.arange(len(data))
    return showPlot(date, data, file_name)
示例#38
0
#PLOT FFT COEFFICIENTS
fig, axarr = plt.subplots(nrows=2, figsize=(12, 8))
axarr[0].title.set_text('FFT of Periodic Signal')
axarr[0].plot(f_values1, fft_values1)
axarr[1].title.set_text('FFT of Chirp Signal')
axarr[1].plot(f_values2, fft_values2)
for ax in axarr.flat:
    ax.set(xlabel='Frequency [Hz]', ylabel='Amplitude')
    ax.set_xlim([0, 100])
plt.subplots_adjust(top=1, hspace=0.3)
plt.show()

#%% PRINT MOTHER WAVELETS & WAVELET FAMILY INFO

wavelet_families = pywt.families(short=False)
discrete_mother_wavelets = pywt.wavelist(kind='discrete')
continuous_mother_wavelets = pywt.wavelist(kind='continuous')

print("PyWavelets contains the following families: ")
print(wavelet_families)
print()
print("PyWavelets contains the following Continuous families: ")
print(continuous_mother_wavelets)
print()
print("PyWavelets contains the following Discrete families: ")
print(discrete_mother_wavelets)
print()
for family in pywt.families():
    print("    * The {} family contains: {}".format(family,
                                                    pywt.wavelist(family)))
def wavelist():
    for w in pywt.families():
        print pywt.wavelist(w)
def wavelist():
    for w in pywt.families():
        print pywt.wavelist(w)    
def createCompressions(hist, cumHist, buckets, plot, log, coord, plotBreakFraction, plotBreakMaxVal):
	solutions = queue.PriorityQueue()

	classify = classifyHist(cumHist, plotBreakMaxVal)
	if classify > plotBreakFraction:
		return classify

	# Now, let's create all built-in wavelet compressions
	# Sort them by quality of compression and space usage.
	for family in pywt.families():
		for wave in pywt.wavelist(family):
			for compression in range(0, 8):	
				restoredCoeffs, recCumHist, stored, traildel, coeffs = generateCompression(cumHist, wave, compression)
		
				if stored > 40:
					continue
		
				# restore approximate histogram from cumulative
				recHist = np.diff(recCumHist)
					
				# calculate quality as sum of cumulative differences
				# note: lower is better for quality
				diff = np.absolute(np.subtract(cumHist, recCumHist))
				quality = calculateQuality(diff)
			
				# push the solution to the solutions-queue
				thisSol = Comp(hist, recHist, diff, quality, "wave ("+wave+")", "compression ("+str(compression)+"), traildel ("+str(traildel)+")", "size: "+str(stored)+", max 10: {:.2%}".format(classifyHist(cumHist, 10)), coord)
				solutions.put((quality, thisSol)) 
	
				if log:
					classify = classifyHist(cumHist, 10)
					print "Region "+coord+" Classify (max 10): "+str(classify)+" Quality: "+str(quality)
				
		
	# Also create a compression just based on reducing the number of buckets (if flag set)
	if buckets:
		res = 4
		bucCumHist = np.zeros(len(cumHist)/res)
		bucCumHist[0] = cumHist[0]
		for i in range(1, len(bucCumHist)):
			bucCumHist[i] = cumHist[i*res]

		recBucCumHist = np.zeros(len(cumHist))
		for i in range(0, len(recBucCumHist)):
			ind = math.floor(i/res)
			recBucCumHist[i] = bucCumHist[ind]
			# Add linear approximation ..
			if ind < len(bucCumHist)-1:
				recBucCumHist[i] += (i % res) * ((bucCumHist[ind+1] - bucCumHist[ind])/res)

		recHist = np.diff(recBucCumHist)

		diff = np.absolute(np.subtract(cumHist, recBucCumHist))
		quality = calculateQuality(diff)

		# plot the bucket solution
		bucketSol = Comp(hist, recHist, diff, quality, "buckets", "equal-spaced, under-approximation", "size: "+str(stored)+", max 10: "+classifyHist(len(bucCumHist), 10), coord)
		bucketSol.plot(plt)

	# plot the best solution seen
	solutions.get()[1].plot(plt)

	# return classification
	return classify