def xCountDistribution( self ): """print distribution of number of units and sequences per family. """ self.PrintStatus() print """# # NUM: number of units/sequences per family # NUNITS: number of families with x units # NSEQ: number of families with x sequences #""" print "num\tnunits\tnseq" sys.stdout.flush() histograms = [] statement = "SELECT nunits, COUNT(*) FROM %s GROUP BY nunits" % self.mTableNameFamilies h1 = self.dbhandle.Execute( statement ).fetchall() histograms.append( h1 ) statement = "SELECT nsequences, COUNT(*) FROM %s GROUP BY nsequences" % self.mTableNameFamilies h2 = self.dbhandle.Execute( statement ).fetchall() histograms.append( h2 ) ch = Histogram.Combine( histograms ) Histogram.Print(ch)
def NumAssignments(self): """Write number of assignments """ if self.mLogLevel >= 1: print "# instance of <" + str( self.__class__) + "> on " + time.asctime( time.localtime(time.time())) print "# source: %s" % (self.mTableNameDomains) print "# hubs between domains" print string.join(("nid", "nassignments", "nclasses"), "\t") sys.stdout.flush() result = self.mTableDomains.GetNumAssignments() for r in result: print string.join(map(str, r), "\t") data = map(lambda x: x[1], result) h = Histogram.Calculate(data) print "# histogram of number of domains per sequence" Histogram.Print(h) data = map(lambda x: x[2], result) h = Histogram.Calculate(data) print "# histogram of number of different domains per sequence" Histogram.Print(h)
class ScholarVR: def __init__(self, root, dd): self.root = root self.dd = dd self.glyphArea = GlyphArea(self) self.yHist = Histogram(self, 'y') self.xHist = Histogram(self, 'x') self.resultList = ResultList(self) self.glyphArea.draw(init=True) self.yHist.draw(init=True) self.xHist.draw(init=True) return
def CountDistribution(self): """print distribution of number of units and sequences per family. """ self.PrintStatus() print """# # NUM: number of units/sequences per family # NUNITS: number of families with x units # NSEQ: number of families with x sequences #""" print "NUM\tNUNITS\tNSEQ" sys.stdout.flush() histograms = [] class_name = self.mTableDomains.GetFieldNameClass() statement = "SELECT COUNT(*) FROM %s GROUP BY %s" % ( self.mTableNameDomains, class_name) data = map(lambda x: x[0], self.dbhandle.Execute(statement).fetchall()) h1 = Histogram.Calculate(data) histograms.append(h1) statement = "SELECT COUNT(DISTINCT nid) FROM %s GROUP BY %s" % ( self.mTableNameDomains, class_name) data = map(lambda x: x[0], self.dbhandle.Execute(statement).fetchall()) h2 = Histogram.Calculate(data) histograms.append(h2) ch = Histogram.Combine(histograms) Histogram.Print(ch)
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)
def printHistogram(values, section, options, min_value=0, increment=1.0): outfile = open(options.output_filename_pattern % section, "w") h = Histogram.Calculate(values, no_empty_bins=True, min_value=0, increment=1.0) outfile.write("bin\t%s\n" % section) for bin, val in h: outfile.write("%5.2f\t%i\n" % (bin, val)) outfile.close()
def featureExtract(dataset, tech=VECTORIZATION, option=dSample.AVG, kernel_size=2, isVectorize=True): if tech == HISTOGRAM: return his.getImgArrHisExtraction(dataset) if tech == VECTORIZATION: return vec.multiImgToVector(dataset) if tech == DOWNSAMPLING: return dSample.Downsample_List_Arr(dataset, option, kernel_size, isVectorize)
def simulaAmostra(entrada): parametros, diagrama, n = entrada relaxacao, mcs, relaxacaoHistograma, mcsHistograma, J1, J2, alpha, tInicio, tFinal, dt, aglomeradoLimit, raio, numeroPontos, numeroAmostras, amostraSimulada, L, concentracao = parametros diagramaAux = [] amostra = [] for ponto in diagrama: p, t0 = ponto J1 = 1 - alpha * p hist = ising.isingbcc(L, relaxacaoHistograma, mcsHistograma, J1, J2, t0, p, aglomeradoLimit) resultado = Histogram.histogram(hist, L, J1, J2, t0, t0 - raio, t0 + raio, numeroPontos, mcsHistograma) VectResultado = np.array(resultado) t_ = VectResultado.transpose()[0] #melhorar isso mag_ = np.nan_to_num(VectResultado.transpose()[1]) mag2_ = np.nan_to_num(VectResultado.transpose()[2]) logmag2_ = np.nan_to_num(VectResultado.transpose()[3]) energia_ = np.nan_to_num(VectResultado.transpose()[4]) calor_ = np.nan_to_num(VectResultado.transpose()[5]) sus_ = np.nan_to_num(VectResultado.transpose()[6]) cumo_ = np.nan_to_num(VectResultado.transpose()[7]) cumuE_ = np.nan_to_num(VectResultado.transpose()[8]) amostra.append((t_, mag_, mag2_, logmag2_, energia_, calor_, sus_, cumo_, cumuE_, p)) tc = t_[sus_.argmax()] resultado2 = Histogram.histogram(hist, L, J1, J2, t0, tc - raio / 200, tc + raio / 200, 2 * numeroPontos, mcsHistograma) VectResultado2 = np.array(resultado2) sus_ = np.nan_to_num(VectResultado.transpose()[6]) tc = t_[sus_.argmax()] resultado3 = Histogram.histogram(hist, L, J1, J2, t0, tc - raio / 20000, tc + raio / 20000, 2 * numeroPontos, mcsHistograma) VectResultado2 = np.array(resultado2) sus_ = np.nan_to_num(VectResultado.transpose()[6]) tc = t_[sus_.argmax()] diagramaAux.append((p, tc)) saida = (amostra, diagramaAux) return saida
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 DomainDistribution( self ): """ distribution of domains per sequence """ self.PrintStatus() if self.mLogLevel >= 1: sys.stdout.flush() print """# # COUNTS: number # NDOMAINS: number of domains per sequence # NDOMAINS/SIN: number of domains without singletons per sequence # NMOBILES: number of mobile modules per sequence #""" print "length\tndomains\tndomains/sin\tnmobiles" sys.stdout.flush() histograms = [] statement = "SELECT COUNT(*) FROM %s GROUP BY nid" % self.mTableNameDomains d1 = map(lambda x: x[0], self.dbhandle.Execute( statement ).fetchall()) histograms.append( Histogram.Calculate( d1 ) ) statement = "SELECT COUNT(*) FROM %s AS d, %s AS f WHERE f.family = d.family AND f.nunits > 1 GROUP BY d.nid" % (self.mTableNameDomains, self.mTableNameFamilies) d2 = map(lambda x: x[0], self.dbhandle.Execute( statement ).fetchall()) histograms.append( Histogram.Calculate( d2 ) ) statement = "SELECT COUNT(*) FROM %s AS d, %s AS f WHERE f.family = d.family GROUP BY d.nid" % (self.mTableNameDomains, self.mTableNameSubset) d3 = map(lambda x: x[0], self.dbhandle.Execute( statement ).fetchall()) histograms.append( Histogram.Calculate( d3 ) ) ch = Histogram.Combine( histograms ) Histogram.Print(ch)
def LengthDistribution( self ): """print distribution of unit length of families """ self.PrintStatus() print """# # LENGTH: number of units/sequences per family # NUNITS: number of domains of that length # NUNITS/SIN: number of domains without singletons # NSIN: number of singletons with that length #""" print "length\tnunits\tnunits/sin\tnsin" sys.stdout.flush() histograms = [] statement = "SELECT CEILING((end-start+1)/10) * 10 AS olength, COUNT(*) FROM %s GROUP BY olength" % self.mTableNameDomains h1 = self.dbhandle.Execute( statement ).fetchall() histograms.append( h1 ) statement = "SELECT CEILING((end-start+1)/10) * 10 AS dlength, COUNT(*) FROM %s AS a, %s AS d " %\ (self.mTableNameDomains, self.mTableNameFamilies) +\ " WHERE d.family = a.family AND d.nunits > 1 GROUP BY dlength" h2 = self.dbhandle.Execute( statement ).fetchall() histograms.append( h2 ) statement = "SELECT CEILING((end-start+1)/10) * 10 AS alength, COUNT(*) FROM %s AS a, %s AS d " %\ (self.mTableNameDomains, self.mTableNameFamilies) +\ " WHERE d.family = a.family AND d.nunits = 1 GROUP BY alength" h3 = self.dbhandle.Execute( statement ).fetchall() histograms.append( h3 ) ch = Histogram.Combine( histograms ) Histogram.Print(ch)
def LengthDistribution(self): """print distribution of unit length of families """ self.PrintStatus() print """# # LENGTH: number of units/sequences per family # NUNITS: number of domains of that length #""" print "LENGTH\tNUNITS" sys.stdout.flush() statement = "SELECT end-start+1 AS length, COUNT(*) FROM %s GROUP BY length" % self.mTableNameDomains h1 = self.dbhandle.Execute(statement).fetchall() Histogram.Print(h1)
def graph(varx, vary): data = jsonReader.getDataCollection(varx, vary) discrete = jsonReader.discrete(varx) if discrete: print("Attempting to graph a boxplot.") # make data into a dictionary dictionary = {} for i in data: if i[0] in dictionary: # update entry i to include i[1] dictionary[i[0]].append(i[1]) else: dictionary[i[0]] = [i[1]] return Histogram.plottingBox(dictionary) else: return Data_Graph_and_Unzip.fin_func(varx, vary)
def BuildHistogram(a, rows, cols): #DP Table #Populate for each column: longest height based on 0's table = [[0 for i in range(cols)] for j in range(rows)] for i in range(cols): for j in range(rows): if a[j][i] == 0: table[j][i] = table[j - 1][i] + 1 #Printtable(table,rows,cols) area = 0 for i in range(rows): #find max area for each row area = max(area, Histogram.maxArea(table[i])) return area
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"
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
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()
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')
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 primeiroDiagrama(parametros): relaxacao, mcs, relaxacaoHistograma, mcsHistograma, J1, J2, alpha, tInicio, tFinal, dt, aglomeradoLimit, raio, numeroPontos, numeroAmostras, amostraSimulada, L, concentracao = parametros def Localizatc(tInicio, tFinal, n, p, L, J1, J2, suv, tv): if n <= 0: return (tInicio + tFinal) / 2 else: dt = (tFinal - tInicio) / 5 t = tInicio while (t <= tFinal): hist = ising.isingbcc(L, relaxacao, mcs, J1, J2, t, p, aglomeradoLimit) h = np.array(hist) sus = h.var(axis=0) suv.append(sus[2]) tv.append(t) t += dt tc = tv[suv.index(max(suv))] return Localizatc(max(tc - dt, 0.02), tc + dt, n - 1, p, L, J1, J2, suv, tv) for p in concentracao: J1 = 1 - alpha * p suv = [] tv = [] tc = Localizatc(tInicio, tFinal, 3, p, L, J1, J2, suv, tv) pontos = zip(tv, suv) pontos.sort(key=lambda x: x[0]) tv, suv = zip(*pontos) diagrama.append((p, tc)) diagramaAux = [] for ponto in diagrama: p, t0 = ponto J1 = 1 - alpha * p hist = ising.isingbcc(L, relaxacaoHistograma, mcsHistograma, J1, J2, t0, p, aglomeradoLimit) resultado = Histogram.histogram(hist, L, J1, J2, t0, t0 - raio, t0 + raio, numeroPontos, mcsHistograma) VectResultado = np.array(resultado) t_ = VectResultado.transpose()[0] sus_ = np.nan_to_num(VectResultado.transpose()[6]) tc = t_[sus_.argmax()] diagramaAux.append((p, tc)) return diagramaAux
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))
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()
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]
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
def generate_histogram(records, field): h = Histogram() val_list = [getattr(x, field) for x in records] h.generate_histogram(val_list) return h
if options.titles: while 1: line = sys.stdin.readline() if not line: break if line[0] == "#": continue data = line[:-1].split("\t") break if options.columns == "all": options.titles = data options.columns = range( len(data) ) else: options.titles = [ data[x] for x in options.columns ] bins = numpy.arange( options.min_value, options.max_value, float(options.bin_size)) hh = Histogram.fillHistograms( sys.stdin, options.columns, [ bins for x in range(len(options.columns) ) ] ) n = len(hh) titles = ['bin'] if options.headers: titles.append( options.headers[x] ) elif options.titles: titles.append( options.titles[x] ) else: for x in options.columns: titles.append( "col%i" % (x+1) ) if len(titles) > 1: options.stdout.write( "\t".join(titles) + "\n" )
vals = [] # retrieve histogram lines = filter(lambda x: x[0] <> "#", sys.stdin.readlines()) for l in lines: data = string.split(l[:-1], "\t") try: val = string.atof(data[param_column]) except IndexError: print "# IndexError in line:", l[:-1] continue if param_upper_limit != None and val > param_upper_limit: val = param_upper_limit if param_lower_limit != None and val < param_lower_limit: val = param_lower_limit vals.append(val) lines = None h = Histogram.Calculate(vals, no_empty_bins=param_empty_bins, increment=param_bin_size) print "# num_values=%i" % len(vals) Histogram.Print(h, nonull=param_nonull)
continue header.append(filename) infile = open(filename, "r") h = [] while 1: line = infile.readline() if not line: break if line[0] == "#": continue if not re.match("(\d+)", line): continue data = map(string.atof, re.split("\s+", line[:-1])) h.append((data[0], tuple(data[1:]))) infile.close() histograms.append(h) print "# bin\t" + string.join(header, "\t\t") ch = Histogram.Combine(histograms) Histogram.Print(ch) ch = Histogram.Normalize(ch) print "# bin\t" + string.join(header, "\t\t") Histogram.Print(ch)
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
image = convolve(image,kernel2,newImage) return image def absoluteSum(im1,im2): [h,w] = im1.shape for x in range(h): for y in range(w): im1[x,y] = math.sqrt(math.pow(abs(im1[x,y]),2)+math.pow(abs(im2[x,y]),2)); im1[x,y]=im1[x,y]/255; return im1 if __name__ == "__main__": filename = sys.argv[1:]; ##filename = 'lena_gray.jpg'; img = cv2.imread(filename,0) histoImage = Histogram.histo(img); cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image',image) [h,w] = img.shape newImage = np.array([[0 for x in range(w)] for y in range(h)]) #####empty image conv1Kernel = np.array([[-1,0,1],[-2,0,2],[-1,0,1]]) conv2Kernel = np.array([[-1,-2,-1], [0,0,0],[1,2,1]]) t1 = time.clock() image1 = convolve(img,conv1Kernel,newImage) image2 = convolve(img,conv2Kernel,newImage) image = absoluteSum(image1,image2) t2 = time.clock()
''' import OHLCRecord import StatModules import Histogram import matplotlib.pyplot as pyplot def load_files(filename, filepath, symbol): try: ohlc_creator = OHLCRecord.OHLCRecordCreator() ohlc_creator.read_file(filename, filepath, symbol) return ohlc_creator except: print 'Error while attempting to open file: ', filename if __name__ == '__main__': print 'Starting Data analysis Sandbox' ohlc_records = load_files('VIX.csv', '../../data', 'VIX') filtered_records = ohlc_records.get_records_inrange('2012-01-01', '2012-06-15') print 'Variance High VIX 2012: ', StatModules.calculate_variance(filtered_records, 'high') print 'Standard Deviation VIX 2012: ', StatModules.calculate_stdev(filtered_records, 'high') h = Histogram.generate_histogram([1,2,3,3,3,5]) vals, freqs = h.render() rectangles = pyplot.bar(vals, freqs) pyplot.show() ''' print 'Average open: ', StatModules.calculate_mean(ohlc_records.records, 'open') print 'Average close: ', StatModules.calculate_mean(ohlc_records.records, 'close') print 'Variance open: ', StatModules.calculate_variance(ohlc_records.records, 'open') '''
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)
line = sys.stdin.readline() if not line: break if line[0] == "#": continue data = line[:-1].split("\t") break if options.columns == "all": options.titles = data options.columns = range(len(data)) else: options.titles = [data[x] for x in options.columns] bins = numpy.arange(options.min_value, options.max_value, float(options.bin_size)) hh = Histogram.fillHistograms( sys.stdin, options.columns, [bins for x in range(len(options.columns))]) n = len(hh) titles = ['bin'] if options.headers: titles.append(options.headers[x]) elif options.titles: titles.append(options.titles[x]) else: for x in options.columns: titles.append("col%i" % (x + 1)) if len(titles) > 1: options.stdout.write("\t".join(titles) + "\n")
import matplotlib.pyplot as plt import plot as Pl plt.figure(figsize=Pl.fig_center ) ptcl = tclLaw(xtcl) plt.plot(xtcl,ptcl, "k--") #import HistogramS as H import Histogram as H import math def sample(): s= sum(GenCLT()) return s/ math.sqrt(nsyn) #H.plot(nhist, -8, 8, 100, sample, lambda x,y:plt.plot(x,y,"b-") ) H.plot(nhist, sample, lambda x,y:plt.plot(x,y,"b-") ) Pl.limitTicks(5,4) plt.xlabel("$z$") plt.ylabel(r"$\Phi(z)$") plt.tight_layout() plt.savefig("Figs/CLT.pdf") plt.savefig("Figs/CLT.svg") r''' % \begin{figure} \centerline{ \includegraphics[width=0.7\columnwidth]{Figs/CLT} } \caption{ \label{fig:clt} Limit law for the centered variable $z=(S-N\mu)/\sqrt{N}$ computed with a Markov integral method. Dashed black line: theoretical distribution; Blue line: empirical histogram computed from $nhist$ realizations of $\vec X$ with $N=nsyn$.} \end{figure}