def histogramLSH(self, data):
        if type(data) is np.ndarray:
            return self.histogramLSH(self.generateHashSignature(data))
        assert len(data) == self.m_L
        hist = Histogram()
        for index in range(0, self.m_L):
            if self.m_Tables[index][data[index]]:
                hist.add(self.m_Tables[index][data[index]])

        return hist.thresholdSet(self.m_nn_sizeLimit)
Exemplo n.º 2
0
    def change_text(self, index):
        '''Rewrites the labels & textboxes to hold information about searched team'''

        

        #Clear labels and data
        for mech in robot.mechs:
            self.mechs_list[robot.mechs.index(mech)].pack_forget()
            self.text_list[robot.mechs.index(mech)].pack_forget()
        self.teleGearGraph.pack_forget()
        self.presHist.pack_forget()
        self.teams_found_Label['text'] = ""

        #Change robot class values
        robot.name = inf[index]['Name']
        robot.team = inf[index]['Team']
        robot.drive = inf[index]['Drive']
        robot.chassis = inf[index]['Chassis']
        robot.mechs = inf[index]['Mechs']
        robot.mechD = inf[index]['MechD']
        robot.image = robot.makeSize(inf[index]['Image'])
        robot.image = robot.makeSize(inf[index]['Image'])

        #Create new robot info
        self.create_robot_info()
        self.teleGearGraph = Histogram(self.rightFrame.interior, values=inf[index]['tGearHist'], title="Tele Gears Histogram")
        self.presHist = Histogram(self.rightFrame.interior, title='Pressure Histogram', values=inf[index]['presHist'][0], buckets=inf[index]['presHist'][1])
        self.teleGearGraph.pack(anchor=tk.W)
        self.presHist.pack(anchor=tk.W)
        self.image_label['image'] = robot.image
        self.logo = robot.makeSize(inf[index]['Logo'], logo=True)
        self.logo_label['image'] = self.logo
        self.robotName_label['text'] = robot.name
        self.robotTeam_label['text'] = robot.team
        self.drive_label['text'] = robot.drive
        self.chassis_label['text'] = robot.chassis
        self.teams_found_Label['text'] = robot.teams_found
        self.teams_found_Label.grid(sticky=tk.W, row=1, column=2, columnspan=10)
def Plot(data, title="", DistributionFunction=None, **kwargs):
    """ Plots data and compares them with theoretic distributionFunction, if specified """
    x, histogram = Histogram(data, **kwargs)

    plt.tight_layout()
    plt.plot(x, histogram, label="Histogram")
    plt.title(title)
    plt.xlabel(r"$x$")
    plt.ylabel(r"$\rho$")
    plt.ylim(0)

    if DistributionFunction is not None:
        plt.plot(x, DistributionFunction(x), label="Hustota pravděpodobnosti")
        plt.legend()

    plt.show()
Exemplo n.º 4
0
def compute_stats(histogram):
    """
    Get various stats on the histogram.
    :param histogram <dict>
    :return diameter <int> - the largest distance between two MPRs
    :return mean <float> - the average pairwise distance
    :return std <float> - the standard deviation of the distribution of distances
    """
    # Diameter of MPR-space
    # Average distance between MPRs and standard deviation
    diameter = max(list(histogram.keys()))
    # Re-convert to a Histogram to calculate stats
    h = Histogram.Histogram(histogram)
    mean = h.mean()
    std = h.standard_deviation()
    return diameter, mean, std
Exemplo n.º 5
0
    def computeHistograms(self):
        self.computeFrequences()
        numberOfHistograms = self.prehistogram.size()
        newNames = []
        while ( not self.prehistogram.empty()):
            cpreh = self.prehistogram.back()

            self.histograms.append(Histogram(cpreh, self.numberOfWords, self.frequences, numberOfHistograms)
            newNames.append(self.names.back())
            self.prehistogram.pop_back()
            self.names.pop_back()
            
        self.names = newNames

if __name__ == "__main__":
    print "Self Test - HistogramHelper"
Exemplo n.º 6
0
    def __init__(self, wd, words = {}, filename=""):
        if(len(filename) > 0):
            file = open(filename, "r")
            Line = ""
            Name = ""
            l = 0
            numberOfHistograms = 0
            for Line in file.readline():
                l = l + 1
                if(l == 1):
                    Numbers = Line.split(Line.whitespace)
                    self.numberOfWords = Numbers[0]
                    self.lenghOfWords = Numbers[1]
                    numberOfHistograms = Numbers[2]
                    self.frequences = Numbers[2]
                elif (l - 1 <= self.numberOfWords):
                    j = 0
                    currentWord = {}
                    for conv in Line.split(Line.whitespace):
                        x = float(conv)
                        if (not x)
                            continue
                        if (j == 0):
                            self.frequences[l-2] = x
                        else:
                            currentWord[j-1] = x
                        j += 1
                    self.words.append(currentWord)
                elif (l - 1 - self.numberOfWords < numberOfHistograms):
                    j = 0
                    currentHistogram = np.zeros(self.numberOfWords, dtype='float')
                    for each in Line.split(Line.whitespace):
                        if (j == 0):
                            self.name.append(each)
                        else:
                            conv = each
                            x = float(conv)
                            currentHistogram[j-1] = x
                        j += 1
                    self.histograms.append(Histogram(currentHistogram, self.numberOfWords))
            file.close()
            return

        self.words = words
        self.lengthOfWords = wd
        self.numberOfWords = self.word.size()
        self.frequences = np.zeros(self.numberOfWords, dtype='int32')
Exemplo n.º 7
0
    def getOriginalHistogram(self, parent_id):
        '''
        @summary: 获得NGramSet真实支持度计数

        @param parent_id: node对应parent id
        
        @return: Histogram(bins)
        @rtype: Histogram

        '''
        parent_gram = self.idToGram(parent_id)
        bins = np.zeros(self.size)
        # Fetching real counts from NGramSet
        for i in range(self.size):
            str = strToSeq(reversed(parent_gram)) + unichr(i)
            bins[i] = self.ngram_set[str]

        return Histogram(bins)
def Poisson(numBins=100000, numValues=1000000):
    data = generator.random(numValues)
    histogram = Histogram(data, numBins=numBins)[1]

    minValue = 0
    maxValue = max(histogram)

    l = numValues / numBins

    def DistributionFunction(x):
        return l**x / gamma(x + 1) * np.exp(-l)

    Plot(histogram,
         "Poissonovo rozdělení",
         DistributionFunction,
         normalize=True,
         minValue=minValue,
         maxValue=maxValue,
         numBins=int(maxValue + 1))
Exemplo n.º 9
0
    def setDataUnits(self, dataunits):
        """
		Set the dataunits to be resampled
		"""
        self.dataUnits = dataunits
        unitclass = self.taskPanels["Merging"][2].getDataUnit()
        self.mergeUnit = unitclass("Preview for scaling intensity")

        for dataUnit in dataunits:
            #print "Creating histogram for ",dataUnit
            self.mergeUnit.addSourceDataUnit(dataUnit)
            x, y, z = dataUnit.getDimensions()

            ds = dataUnit.getDataSource()
            minval, maxval = ds.getOriginalScalarRange()
            #print "Original scalar range = ",minval,maxval
            self.resampleDims.append(ds.getResampleDimensions())

            scale = maxval / 255.0
            print "Scale for histograms = ", scale
            #"Using scale",scale
            histogram = Histogram.Histogram(self,
                                            scale=scale,
                                            lowerThreshold=minval,
                                            upperThreshold=maxval)
            self.histogramSizer.Add(histogram)
            self.histograms.append(histogram)
            histogram.setThresholdMode(1)
            histogram.setDataUnit(dataUnit, noupdate=1)
            lib.messenger.connect(histogram, "threshold_changed",
                                  self.onSetThreshold)
            x, y, z = dataUnit.getDimensions()
            self.zslider.SetRange(1, z)

        moduletype = self.taskPanels["Merging"][0]
        module = moduletype()
        self.mergeUnit.setModule(module)
        self.preview.setDataUnit(self.mergeUnit)
        self.preview.zoomToFit()
        self.preview.updatePreview()
        self.sizer.Fit(self)
        self.Layout()
Exemplo n.º 10
0
    def getRoot(self):
        '''
        @summary: create the Root Node

        @return: self.nodes[0]
        @rtype: Node

        '''
        if not 0 in self.nodes:
            bins = np.zeros(self.size)

            # termination is always 0
            for i in range(self.size - 1):
                # default all 1-grams count
                bins[i] = self.ngram_set[unichr(i)]

            self.nodes[0] = Node(0, self.size, -1, Histogram(bins), 1)
            self.start_id += self.size

        return self.nodes[0]
Exemplo n.º 11
0
def process_file(filename, skip_header):
    """Makes a histogram that contains the words from a file.

    filename: string
    skip_header: boolean, whether to skip the Gutenberg header

    returns: Histogram object - map from each word to the number of times it appears.
    """
    word_list = []
    fp = open(filename)

    if skip_header:
        skip_gutenberg_header(fp)

    for line in fp:
        if line.startswith('*** END OF THIS'):
            break
        word_list = process_line(line, word_list)

    # TODO: Create Histogram object from word_list
    hist = hg.Histogram(word_list)

    return hist
Exemplo n.º 12
0
    def createThresholdSelection(self, n, items, currentFilter):
        """
		create a histogram GUI element that can be used to select a lower and upper threshold
		"""
        item = items[n]
        itemName = item[0]
        background = wx.Window(self, -1)
        level = currentFilter.getParameterLevel(itemName)
        if level:
            #background.SetBackgroundColour(level)
            background.SetForegroundColour(level)

        histogram = Histogram.Histogram(background)

        self.histograms.append(histogram)
        func = lambda event, its=item, f=currentFilter: self.onSetThreshold(
            event, its, f)
        histogram.Bind(Histogram.EVT_SET_THRESHOLD, func)

        histogram.setThresholdMode(1)
        dataUnit = self.filter.getDataUnit().getSourceDataUnits()[0]
        flo = lambda obj, event, arg, histogram = histogram, i = item[0], s = self: \
           s.onSetHistogramValues(histogram, i, arg, valuetype = "Lower")
        lib.messenger.connect(currentFilter, "set_%s" % item[0], flo)
        fhi = lambda obj, event, arg, histogram = histogram, i = item[1], s = self: \
           s.onSetHistogramValues(histogram, i, arg, valuetype = "Upper")
        lib.messenger.connect(currentFilter, "set_%s" % item[1], fhi)

        setDataunitFunc = lambda obj, event, dataunit, h=histogram: h.setDataUnit(
            dataunit)

        lib.messenger.connect(currentFilter, "set_%s_dataunit" % item[0],
                              setDataunitFunc)
        lib.messenger.connect(currentFilter, "set_%s_dataunit" % item[1],
                              setDataunitFunc)

        print "Setting dataUnit"
        histogram.setDataUnit(dataUnit, noupdate=1)
        print "done"
        self.itemSizer.Add(background, (0, 0), flag=wx.EXPAND)

        bgsizer = wx.GridBagSizer()
        bgsizer.Add(histogram, (0, 0), span=(1, 2))

        lowerLbl = wx.StaticText(background, -1, "Lower threshold:")
        upperLbl = wx.StaticText(background, -1, "Upper threshold:")

        lower = self.createNumberInput(background, currentFilter, item[0],
                                       types.IntType, 0, "",
                                       self.updateThresholdHistogram)
        upper = self.createNumberInput(background, currentFilter, item[1],
                                       types.IntType, 255, "",
                                       self.updateThresholdHistogram)

        bgsizer.Add(lowerLbl, (1, 0))
        bgsizer.Add(lower, (1, 1))
        bgsizer.Add(upperLbl, (2, 0))
        bgsizer.Add(upper, (2, 1))
        background.SetSizer(bgsizer)
        background.SetAutoLayout(1)
        background.Layout()
        self.items[itemName] = background

        return 0
Exemplo n.º 13
0
def main(filename, n_folds, useWord, sampleSize, reducedDim, opt, n_class,
         kernel, vecName, gridsearch):
    if vecName == "new":
        iter_flag = True
        # trainingData & trainingLabels 作成
        print "opt :", opt
        if opt == "equal":
            while iter_flag:
                training_data, training_labels = createTrainingVec_Equal(
                    filename, useWord, sampleSize, n_class)
                if len(training_labels) > 1:
                    iter_flag = False
        elif opt == "hist":
            while iter_flag:
                try:
                    training_data, training_labels, vplace_lists = createTrainingVec_Equal_Hist(
                        filename, useWord, sampleSize, n_class, opt)
                except:
                    continue
                if len(training_labels) > 1:
                    iter_flag = False
        elif opt == "hist_all":
            while iter_flag:
                try:
                    training_data, training_labels, vplace_lists = createTrainingVec_Equal_Hist(
                        filename, useWord, sampleSize, n_class, opt)
                except:
                    continue
                if len(training_labels) > 1:
                    iter_flag = False
        else:
            training_data, training_labels = createTrainingVec(
                filename, useWord, sampleSize)
        print "sample size :", len(training_labels)

        # for x in training_labels:
        #     print x
        # return True

        # PCAを用いた次元削減
        training_data = DimensionReduction(filename, training_data, reducedDim)

        np.savetxt("data/v20000rd100nc100_data.csv",
                   training_data,
                   delimiter=",")
        np.savetxt("data/v20000rd100nc100_labels.csv",
                   training_labels,
                   delimiter=",")

    elif vecName == "v20000rd100nc100":
        training_data = np.loadtxt("data/v20000rd100nc100_data.csv",
                                   delimiter=",")
        training_labels = np.loadtxt("data/v20000rd100nc100_labels.csv",
                                     delimiter=",")

    if gridsearch:
        print "GridSearch starts"
        GridSearch.Gridsearch(training_data, training_labels)

    else:
        # K-分割交差検証
        kfold = cross_validation.KFold(len(training_data), n_folds=n_folds)
        results = np.array([])
        confirmation = []
        counter = 0
        for training, test in kfold:
            counter += 1
            print counter, "folds    ",
            # 教師データで SVM を学習する
            clf = svm.SVC(kernel=kernel)
            clf.fit(training_data[training], training_labels[training])

            # テストデータを使った検証
            answers = clf.predict(training_data[test])
            # ラベルデータと一致しているか調べる
            are_correct = answers == training_labels[test]
            results = np.r_[results, are_correct]

            pre = np.c_[answers, training_labels[test]]
            confirmation.append(pre)

        print ""
        print('カーネル: {kernel}'.format(kernel=kernel))
        correct = np.sum(results)
        N = len(training_data)
        percent = (float(correct) / N) * 100
        print('正答率: {percent:.2f}% ({correct}/{all})'.format(
            correct=correct,
            all=len(training_data),
            percent=percent,
        ))

    if "hist" in opt:

        for i, x in enumerate(vplace_lists):
            vplace_lists[i] = int(
                float(useWord) * 100 / float(vplace_lists[i]))
        vplace_lists_corr = np.zeros(len(vplace_lists))
        for i, x in enumerate(results):
            if x == 1:
                vplace_lists_corr[i] = vplace_lists[i]
        vplace_lists_corr.sort()
        while True:
            vplace_lists_corr = np.delete(vplace_lists_corr, 0)
            if vplace_lists_corr[0] > 0:
                break
        Histogram.Histogram(filename, vplace_lists, vplace_lists_corr)

    # print results
    # print "prediction, correct"
    # for x in confirmation:
    #      for y in x:
    #          print y[0], "\t", y[1]

    joblib.dump(
        clf, 'data/SVM/SVM_' + filename + '_' + str(n_folds) + 'folds' +
        '_clf_' + kernel + '_rd' + str(reducedDim) + '_nClass' + str(n_class))
Exemplo n.º 14
0
def test(filename, useWord, sampleSize, reducedDim, opt, n_class, kernel):
    #verb_Fixedを使う

    test_size = 1000
    iter_flag = True
    if opt == "equal":
        while iter_flag:
            training_data, training_labels, test_data, test_labels = createTrainingVec_Equal_verbFixed(
                filename, useWord, sampleSize, n_class, test_size)
            if len(training_labels) > 1:
                iter_flag = False

    elif opt == "hist":
        while iter_flag:
            training_data, training_labels, test_data, test_labels, vplace_lists, verb_list = createTrainingVec_Equal_Hist_verbFixed(
                filename, useWord, sampleSize, n_class, test_size)
            if len(training_labels) > 1:
                iter_flag = False
    else:
        print "What is opt?"

    forPCA = np.r_[training_data, test_data]
    forPCA = DimensionReduction(filename, forPCA, reducedDim)
    training_data = forPCA[:len(training_data)]
    test_data = forPCA[len(training_data):]
    print "size", len(training_data), len(test_data)

    np.savetxt("data/v20000rd100nc100_data.csv", training_data, delimiter=",")
    np.savetxt("data/v20000rd100nc100_labels.csv",
               training_labels,
               delimiter=",")

    results = np.array([])
    confirmation = []

    # 教師データで SVM を学習する
    clf = svm.SVC(kernel=kernel)
    clf.fit(training_data, training_labels)

    # テストデータを使った検証
    answers = clf.predict(test_data)
    # ラベルデータと一致しているか調べる
    results = answers == test_labels

    pre = np.c_[answers, test_labels]
    confirmation.append(pre)

    print ""
    print('カーネル: {kernel}'.format(kernel=kernel))

    correct = np.sum(results)
    N = len(test_data)
    percent = (float(correct) / N) * 100
    print('正答率: {percent:.2f}% ({correct}/{all})'.format(
        correct=correct,
        all=N,
        percent=percent,
    ))

    print results
    print "prediction, correct"
    for x in confirmation:
        for y in x:
            print y[0], "\t", y[1]

    joblib.dump(
        clf, 'data/SVM/SVM_' + filename + '_verbFixed' + '_clf_' + kernel +
        '_rd' + str(reducedDim) + '_nClass' + str(n_class))

    if opt == "hist":
        a = 0
        b = test_size
        for verb in verb_list:
            print verb
            vplace_lists_p = vplace_lists[a:b]
            results_p = results[a:b]
            for i, x in enumerate(vplace_lists_p):
                vplace_lists_p[i] = int(
                    float(useWord) * 100 / float(vplace_lists_p[i]))
            vplace_lists_corr = np.zeros(len(vplace_lists_p))
            for i, x in enumerate(results_p):
                if x == 1:
                    vplace_lists_corr[i] = vplace_lists_p[i]
            vplace_lists_corr.sort()
            while True:
                vplace_lists_corr = np.delete(vplace_lists_corr, 0)
                if vplace_lists_corr[0] > 0:
                    break
            Histogram.Histogram(filename, vplace_lists_p, vplace_lists_corr)
            a += test_size
            b += test_size
Exemplo n.º 15
0
    def create_widgets(self):
        #Creating frame for top
        self.topFrame = tk.Frame(self, height=30, bg='gray')
        self.topFrame.pack(fill='x')
        
        #Creating widgets in top frame
        self.top_left_Label= tk.Label(self.topFrame, text="Search ",
                                 font=("courier", "13", "bold"),
                                 fg="#EEE3B9", bg= "gray")
        self.top_left_Label.grid(sticky=tk.W, row=0, column=0)

        self.key_button = tk.Button(self.topFrame, text="Team",
                                    command=lambda: self.key_change())
        self.key_button.grid(sticky=tk.W, row=0, column=1)

        self.top_right_Label = tk.Label(self.topFrame, text=": ",
                                        font=("courier", "13", "bold"),
                                        fg="#EEE3B9", bg= "gray")
        self.top_right_Label.grid(sticky=tk.W, row=0, column=3)

        self.search_entry = tk.Entry(self.topFrame, width=10)
        self.search_entry.grid(sticky=tk.W, row=0, column=4)

        self.search_button = tk.Button(self.topFrame, text="Search",
                                       command=lambda: self.search(self.key_button['text'],
                                                                   self.search_entry.get()))
        self.search_button.grid(sticky=tk.W, row=0, column=5)
        
        self.left_button = tk.Button(self.topFrame, text="<-",
                                      command=lambda: self.profile_change(-1))
        self.left_button.grid(sticky=tk.W, row=0, column=6)
        
        self.right_button = tk.Button(self.topFrame, text="->",
                                      command=lambda: self.profile_change(1))
        self.right_button.grid(sticky=tk.W, row=0, column=7)
        
        self.team_before_Label = tk.Label(self.topFrame, text="Teams found:",
                                          font=("courier", "13", "bold"),
                                          fg="#EEE3B9", bg= "gray")
        self.team_before_Label.grid(sticky=tk.W, row=1, column=0, columnspan=2)
        self.teams_found_Label = tk.Label(self.topFrame, text="Nothing",
                                          font=("courier", "13", "bold"),
                                          fg="#EEE3B9", bg= "gray")

        self.change_button = tk.Button(self.topFrame, text="change",
                                       command=lambda: self.controller.show_frame("CompareTwo"))
        self.change_button.grid(row=0, column=10)
        

        
        #Creating frame for left side
        self.leftFrame = tk.Frame(self, bg='#957156', width=250, height=300)
        self.leftFrame.pack(side='left', anchor=tk.NW)

        #Creating widgets in left side frame
        self.image = robot.makeSize(default_image)
        self.image_label = tk.Label(self.leftFrame, image = self.image, width=250, height=250)
        self.image_label.pack()
        
        #name & team -Need to fix problem with label growing frame becaues of more text
        self.name_label = tk.Label(self.leftFrame, text=("Robot:"),
                                   font=("courier", "15", "bold"),
                                   relief=tk.GROOVE, fg="#EEE3B9", bg="#7D4735")
        self.name_label.pack(pady=(10, 0))
        
        self.robotName_label = tk.Label(self.leftFrame, text=(robot.name),
                                    font=("courier", "15", "bold"),
                                    relief=tk.GROOVE, fg="#EEE3B9", bg="#7D4735")
        self.robotName_label.pack()

        self.t = tk.Frame(self.leftFrame, bg='#957156')
        self.t.pack(side='left', padx=(25, 0))
        self.team_label = tk.Label(self.t, text=("Team:"),
                                   font=("courier", "15", "bold"),
                                   relief=tk.GROOVE, fg="#EEE3B9", bg="#7D4735")
        self.team_label.pack()
        
        self.robotTeam_label = tk.Label(self.t, text=(robot.team),
                                    font=("courier", "15", "bold"),
                                    relief=tk.GROOVE, fg="#EEE3B9", bg="#7D4735")
        self.robotTeam_label.pack(padx=10)
        
        self.image_frame = tk.Frame(self.leftFrame)
        self.image_frame.pack(anchor=tk.E, padx=(10, 25), pady=10)
        self.logo_image = robot.makeSize(robot.logo, True)
        self.logo_label = tk.Label(self.image_frame, image=self.logo_image)
        self.logo_label.pack()
        

        #Magical things happend in VerticalScrolledFrame - bless the coding gods
        self.rightFrame = VerticalScrolledFrame(self)
        self.rightFrame.pack(expand=True, fill=tk.BOTH, anchor=tk.E)
        self.right_img = ImageTk.PhotoImage(robot.right_img)
        self.right_bg = tk.Label(self.rightFrame.interior, image=self.right_img)
        self.right_bg.place(x=0, y=0, relwidth=1, relheight=1)

        #Creating widgets in right side frame - create first instance of info to describe Robodex
        self.dFrame = tk.Frame(self.rightFrame.interior)
        self.dFrame.pack(pady=(10,10), anchor=tk.W)
        self.template_drive_label = tk.Label(self.dFrame, text=("Drive Train Type:"),
                                   font=("courier", "15"), bg='#7D4735', fg='#EEE3B9',
                                        relief=tk.RAISED)
        self.template_drive_label.pack(side="left")
        self.drive_label = tk.Label(self.dFrame, text=(robot.drive),
                                    font=("courier", "15"), bg='#7D4735', fg='#EEE3B9',
                                    relief=tk.RAISED)
        self.drive_label.pack(side="left")
        self.cFrame = tk.Frame(self.rightFrame.interior)
        self.cFrame.pack(pady=(10,10), anchor=tk.W)
        self.template_chassis_label = tk.Label(self.cFrame, text=("Chassis Type:"),
                                     font=("courier", "15"), bg= '#7D4735', fg='#EEE3B9',
                                     relief=tk.RAISED)
        self.template_chassis_label.pack(side="left")
        self.chassis_label = tk.Label(self.cFrame, text=(robot.chassis),
                                     font=("courier", "15"), bg= '#7D4735', fg='#EEE3B9',
                                     relief=tk.RAISED)
        self.chassis_label.pack(side="left")
        self.mechan_label = tk.Label(self.rightFrame.interior, text="Mechanisms",
                                   font=("courier", "15"), bg= '#7D4735', fg='#EEE3B9',
                                     relief=tk.RAISED)
        self.mechan_label.pack()

        #Initializing Lists For Robot Data
        self.mechs_list = []
        self.text_list = []
        self.keys = []
        self.profile = []
        self.teams_found = []
        self.compare = ['=', '<', '>']

        self.indexed = 0
        self.key_index = 0
        self.compare_index = 0
        self.key = ""
        self.isNum = False

        self.numCompare = tk.Button(self.topFrame, text="=",
                                    command=lambda: self.compare_change())
        
        for key, value in inf[0].items():
                self.keys.append(key)
                
        for p in range(len(inf)):
            self.profile.append(p)
            
        self.create_robot_info()
        self.teleGearGraph = Histogram(self.rightFrame.interior, title="Tele Gear Histogram")
        self.presHist = Histogram(self.rightFrame.interior, title="Pressure Histogram")
        self.teleGearGraph.pack(anchor=tk.W)
        self.presHist.pack(anchor=tk.W)
Exemplo n.º 16
0
def Analyse(acquire_new, result_path, source_path, obj_mag, material, ftr,
            presentation):
    steps = [
        '', '', '1_Image_Acquisition', 'Global_Histogram', '2_Segmentation',
        '3_ROIs', '4_Local_Histogram'
    ]
    full_path = []
    for step in steps:
        full_path.append(os.path.join(result_path, step))
    #print (full_path)
    if not acquire_new:
        full_path[2] = source_path
    list_of_samples = os.listdir(full_path[2])

    stats_file = open(os.path.join(result_path, 'ListOfFlakes.csv'), "a+")
    stat = "LithoCoord,Contrast,EstLayers,BoundingBoxArea(um^2)\n"
    stats_file.write(stat)
    stats_file.close()

    for sample in list_of_samples:
        #sample_path = os.path.join(full_path[2], str(sample))
        print(sample)
        ContourObj = Contour.Contour(str(sample), full_path[2], result_path,
                                     obj_mag, material, ftr)
        if material == 'Sb':
            ContourObj.edges_gluey(obj_mag=obj_mag,
                                   ftr=0,
                                   glue_remover=True,
                                   presentation=presentation)
        else:
            ContourObj.edges_gluey(obj_mag,
                                   ftr,
                                   glue_remover=False,
                                   presentation=presentation)
        #self.ContourObj.segmentation(ftr=self.filter)
        ROIObj = Rectangle.Rectangle((full_path[4] + '\\Contours'), sample,
                                     full_path[2], result_path, obj_mag,
                                     material, ftr)
        X_Y_FS = ROIObj.markROIs(True, presentation)

        list_of_chunks = os.listdir((full_path[5] + '\\' + sample[:-4]))
        list_of_chunk_numbers = []
        if material == 'C':
            for chunk, ant in zip(list_of_chunks, X_Y_FS):
                stat = str(sample)[:-4] + '_'
                HistogramObj = Histogram.Histogram(
                    str(chunk), (full_path[5] + '\\' + sample[:-4]),
                    (full_path[6]), result_path, obj_mag)
                #self.HistogramObj = Histogram.Histogram(str(chunk), (full_path[5]+'\\'+sample), (full_path[6]+'\\'+sample), self.result_path,obj_mag=self.obj_mag) #deeper directory
                contrast, layers = HistogramObj.saveLocalHistogram(
                    ftr, material, presentation)
                if not contrast is None and len(contrast) > 3:
                    chunk_number = int(chunk[-6:-4])
                    stat += str(chunk_number).zfill(2) + ',' + contrast
                    stat += ',' + layers
                    list_of_chunk_numbers.append(chunk_number)
                if ant[3] in list_of_chunk_numbers:
                    #TB = 'T' if (ant[1]<256) else ('B')
                    #LR = 'L' if (ant[0]<256) else ('R')
                    stat += "," + str(ant[2]) + "\n"
                    stats_file = open(
                        os.path.join(result_path, 'ListOfFlakes.csv'), "a+")
                    stats_file.write(stat)
                    stats_file.close()

        cv2.destroyAllWindows()
Exemplo n.º 17
0
def getHistogram(field, tablename, databasename, id):
    h = histogram.Histogram(field, tablename, databasename, id)
    thread1 = threading.Thread(target=h.getHistogram)
    thread1.start()
Exemplo n.º 18
0
from ColumnChart import *
from PieChart import *


def getdata():
    global GraphNo
    GraphNo = int(
        input(
            'Enter the Series No. of the graph which you want to use for visualization of your Data : \n 1. Histogram \n 2. Column Chart \n 3. Box Plot Chart \n 4. Pie Chart \n 5. Scatter Plot\n :-'
        ))


while (True):
    getdata()
    if GraphNo == 1:
        Histogram()
        break
    elif GraphNo == 2:
        ColumnChart()
        break
    elif GraphNo == 3:
        BoxPlotGraph()
        break
    elif GraphNo == 4:
        PieChart()
        break
    elif GraphNo == 5:
        ScatterPlot()
        break
    else:
        print("Invalid Input")
The window in your Blackjack program has room for 6 cards for each player. Is this
enough space? What is the probability of a player needing more than 6 cards?

One way to figure this out is by running a Monte Carlo simulation.
"""

import sys
from Deck import *
from Histogram import *
from Blackjack import *

# Initialize 10 bins, from 1 to 10 
# A bin represents how many cards we need to deal before the total is 22 or higher
num_cards_bin = [i for i in range(1, 11)]
histogram = Histogram(num_cards_bin)


def update_bin():
    """
    For each hand, update the bin that corresponds to the number of cards dealt
    before the total is 22 or higher. Ex. If a hand reaches 25 on the 3rd card 
    add one to the count in bin 3.
    """
    deck = Deck(BlackjackCard)
    deck.shuffle()

    hand = [ ] 
    result = 0

    while result < 22:
Exemplo n.º 20
0
def LaplaceMechanism(hist, scale_p):
    #print "\n>>>>>>"
    #print map(lambda x: x, hist.bins)
    #print ">>>>>>\n"

    return Histogram(map(lambda x: x + Utils.laplace(scale_p), hist.bins))
Exemplo n.º 21
0
def generate_histogram(records, field):
    h = Histogram()
    val_list = [getattr(x, field) for x in records]
    h.generate_histogram(val_list)
    return h
Exemplo n.º 22
0
 def get_hist(self):
     self.hist = Histogram(self.image)
     self.hist.create_histogram()
     self.hist.draw_histogram()