def test_plot(): # create test cells test_cell1 = Cell() test_cell1.add_surface(Circle(0, 0, 2), False) # inside a circle (r = 2) test_cell1.add_surface(Rectangle(0, 0, 0.5, 0.5), True) # outside a square (l = 1) test_cell2 = Cell() test_cell2.add_surface(Circle(1, 1, 2), True) # outside a circle test_cell2.add_surface(Circle(0, 0, 4), False) # inside a larger circle test_cell3 = Cell() test_cell3.add_surface(Rectangle(0, 0, 2, 2), False) # inside a rectangle test_cell3.add_surface(Circle(0, 0, 1), True) # outside a circle test_cell4 = Cell() test_cell4.add_surface(Rectangle(0, 0, 5, 5), False) test_cell4.add_surface(Rectangle(0, 0, 3, 3), True) # call simple_plot or plot simple_plot(test_cell1, 0) simple_plot(test_cell2, 0) simple_plot(test_cell3, 0) simple_plot(test_cell4, 0) plot(test_cell1, 0, -5, 10, -5, 5, 0.1)
def test_plot(): # create test cells test_cell1 = Cell() test_cell1.add_surface(Circle(0,0,2), False) # inside a circle (r = 2) test_cell1.add_surface(Rectangle(0, 0, 0.5, 0.5), True) # outside a square (l = 1) test_cell2 = Cell() test_cell2.add_surface(Circle(1,1,2), True) # outside a circle test_cell2.add_surface(Circle(0,0,4), False) # inside a larger circle test_cell3 = Cell() test_cell3.add_surface(Rectangle(0,0,2,2), False) # inside a rectangle test_cell3.add_surface(Circle(0,0,1), True) # outside a circle test_cell4 = Cell() test_cell4.add_surface(Rectangle(0,0,5,5),False) test_cell4.add_surface(Rectangle(0,0,3,3), True) # call simple_plot or plot simple_plot(test_cell1, 0) simple_plot(test_cell2, 0) simple_plot(test_cell3, 0) simple_plot(test_cell4, 0) plot(test_cell1, 0, -5, 10, -5, 5, 0.1)
def train_weights(matrix, weights, nb_epoch=10, l_rate=1.00, stop_early=True, verbose=False, do_plot=False): for epoch in range(nb_epoch): #epoch for i in range(len(matrix)): prediction = predict(matrix[i][:-1], weights) # get predicted classificaion error = matrix[i][ -1] - prediction # get error from real classification if verbose: sys.stdout.write("Training on data at index %d...\n" % (i)) for j in range(len(weights)): # calculate new weight for each node if verbose: sys.stdout.write("\tWeight[%d]: %0.5f --> " % (j, weights[j])) weights[j] = weights[j] + (l_rate * error * matrix[i][j]) if verbose: sys.stdout.write("%0.5f\n" % (weights[j])) cur_acc = accuracy(matrix, weights) print("\nEpoch %d \nWeights: " % epoch, weights) print("Accuracy: ", cur_acc) if do_plot: plot(matrix=matrix, weights=weights, title="Epoch %d" % epoch) if cur_acc == 1.0 and stop_early: break return weights
def train_model_unsupervised(self, x, y, num_epochs): print("Unsupervised Training") logging.info("Unsupervised Training") for epoch in range(num_epochs): x, y = shuffle(x=x, y=y) for i in range(int(len(x) / self.args.batch_size)): x_l, y_l, _ = sample_minibatch_deterministically(x, y, batch_i=i, batch_size=self.args.batch_size) labels_onehot = torch.zeros([y_l.size(0), self.num_classes]) labels_onehot.scatter_(1, y_l.unsqueeze(1).long(), 1) out = x_l # Forward + Backward + Optimize for (optimizer, forward) in zip(self.net.optimizers, self.net.forwards): if self.conditioned: out = self.optimizer_module(optimizer, forward, out, labels_onehot) else: out = self.optimizer_module(optimizer, forward, out) if (epoch+1) % 1 == 0: perf = self.test_model(epoch+1) if perf > self.best_perf: torch.save(self.net.state_dict(), self.model_name+'_model_best.pkl') self.net.train() # Save the Model ans Stats pkl.dump(self.stats, open(self.model_name+'_stats.pkl', 'wb')) torch.save(self.net.state_dict(), self.model_name+'_model.pkl') if self.plot: plot(self.stats, name=self.model_name)
def voxelRand(times, speed): speed = speed / 5 voxels = [] #plot random points to fill the cube for t in range(times): vX = randint(0, 3) vY = randint(0, 3) vZ = randint(0, 3) plot(vX, vY, vZ, 1) sleep(speed) fullcube() sleep(speed * 2) #plot random points to empty the cube for t in range(times): vX = randint(0, 3) vY = randint(0, 3) vZ = randint(0, 3) plot(vX, vY, vZ, 0) sleep(speed) #smoothly erase any remaining points plotFill(0, 3, 0, 3, 3, 3, 0) sleep(speed * 2) plotFill(0, 2, 0, 3, 2, 3, 0) sleep(speed * 2) plotFill(0, 1, 0, 3, 1, 3, 0) sleep(speed * 2) fullcube(0) sleep(speed)
def exec(point_x, point_y, t_param): sigma = [0.01 * i for i in range(100)] kcr = [KCR([point_x, point_y], t_param, sigmai) for sigmai in sigma] lsm_B_list = [] lsm_D_list = [] mle_B_list = [] mle_D_list = [] for si in sigma: # print(len(x)) #円フィッティング n = 500 params_lsm = [] params_mle = [] for i in range(n): x, y = setErrND([point_x, point_y], si) p = np.random.normal(size=param.shape) p = p / np.linalg.norm(p) params_lsm.append(LSM([x, y])) params_mle.append(MLE([x, y], p, ep=1.0e-6)) # print(params_lsm) lsm_B, lsm_D = BE(params_lsm, t_param, n) mle_B, mle_D = BE(params_mle, t_param, n) lsm_B_list.append(lsm_B) lsm_D_list.append(lsm_D) mle_B_list.append(mle_B) mle_D_list.append(mle_D) # viewErrGraph(kcr, [lsm_B_list, mle_B_list], [lsm_D_list, mle_D_list], sigma) plot(sigma, lsm_D_list, mle_D_list, kcr, lsm_B_list, mle_B_list)
def train_model_supervised(self, x, y, num_epochs): print("Supervised Training") logging.info("Supervised Training") for epoch in range(num_epochs): x, y = shuffle(x=x, y=y) # for i, (images, labels) in enumerate(self.train_loader): for i in range(int(len(x) / self.args.batch_size)): # Convert torch tensor to Variable x_l, y_l, _ = sample_minibatch_deterministically(x, y, batch_i=i, batch_size=self.args.batch_size) labels_onehot = torch.zeros([y_l.size(0), self.num_classes]) labels_onehot.scatter_(1, y_l.long().unsqueeze(1), 1) # Forward + Backward + Optimize loss, grad_loss = self.optimize_grad_and_net(x_l, y_l.long(), labels_onehot, self.net.grad_optimizer, self.net.optimizer, self.net) if (i+1) % 10 == 0: print ('Epoch [%d/%d], Step [%d/%d], Loss: %.6f, Grad Loss: %.8f' %(epoch+1, self.num_epochs, i+1, len(x)//self.batch_size, loss.item(), grad_loss.item())) logging.info('Epoch [%d/%d], Step [%d/%d], Loss: %.6f, Grad Loss: %.8f' %(epoch+1, self.num_epochs, i+1, len(x)//self.batch_size, loss.item(), grad_loss.item())) if (epoch + 1) % 10 == 0: perf = self.test_model(epoch + 1) if perf > self.best_perf: torch.save(self.net.state_dict(), self.model_name + '_model_best.pkl') self.net.train() # Save the Model ans Stats pkl.dump(self.stats, open(self.model_name + '_stats.pkl', 'wb')) torch.save(self.net.state_dict(), self.model_name + '_model.pkl') if self.plot: plot(self.stats, name=self.model_name)
def wireframe(time, size, xF=0, yF=0, zF=0): fullcube(0) if size == 4: #if the cube is size 4, it fills the whole LED cube and thus can ignore # the start point (xF, yF, zF) #fill cube, then cut out inner sections fullcube() plotFill(1, 0, 1, 2, 3, 2, 0) plotFill(1, 1, 0, 2, 2, 3, 0) plotFill(0, 1, 1, 3, 2, 2, 0) elif size == 3: #if the cube is smaller than size 4, plot cube relative to (xF, yF, zF) plotFill(xF, yF, zF, xF + 2, yF + 2, zF + 2) plotFill(xF + 1, yF, zF + 1, xF + 1, yF + 2, zF + 1, 0) plotFill(xF + 1, yF + 1, zF, xF + 1, yF + 1, zF + 2, 0) plotFill(xF, yF + 1, zF + 1, xF + 2, yF + 1, zF + 1, 0) elif size == 2: plotFill(xF, yF, zF, xF + 1, yF + 1, zF + 1) elif size == 1: plot(xF, yF, zF) sleep(time)
def testSurface(): S1 = Surface(0, 0, 0, 3, 0, -3) # XPlane(1) S2 = Surface(0, 0, 0, 0, 2, 1) # YPlane(-0.5) S3 = Surface(0, 0, 0, 1, 1, 0) # angled plane S4 = Surface(1, 2, 0, 0, 0, -3) # ellipse!! cell = Cell() cell.add_surface(S4, True) simple_plot(cell, 0) plot(cell, 0, -2, 2, -2, 2, 0.1)
def doCluster1(r): L = 100 #r = rand(L,L) p = 0.4 z = r < p #print(r) figure(figsize=(16, 5)) subplot(1, 3, 1) a = imshow(z, origin='lower', interpolation='nearest') colorbar() title("Matrix") # Show image of labeled clusters (shuffled) lw, num = measurements.label(z) subplot(1, 3, 2) b = arange(lw.max() + 1) # create an array of values from 0 to lw.max() + 1 shuffle(b) # shuffle this array shuffledLw = b[lw] # replace all values with values from b b = imshow(shuffledLw, origin='lower', interpolation='nearest' ) # show image clusters as labeled by a shuffled lw colorbar() title("Labeled clusters") # Calculate areas subplot(1, 3, 3) area = measurements.sum(z, lw, index=arange(lw.max() + 1)) areaImg = area[lw] im3 = imshow(areaImg, origin='lower', interpolation='nearest') colorbar() title("Clusters by area") # Bounding box sliced = measurements.find_objects(areaImg == areaImg.max()) if (len(sliced) > 0): sliceX = sliced[0][1] sliceY = sliced[0][0] plotxlim = im3.axes.get_xlim() plotylim = im3.axes.get_ylim() plot([ sliceX.start, sliceX.start, sliceX.stop, sliceX.stop, sliceX.start ], [ sliceY.start, sliceY.stop, sliceY.stop, sliceY.start, sliceY.start ], color="red") xlim(plotxlim) ylim(plotylim) show() plt.savefig(a) plt.savefig(b) plt.savefig(im3)
def main_functions(): inputData = input() m1 = inputData.get('m1') m2 = inputData.get('m2') L1 = inputData.get('L1') L2 = inputData.get('L2') theta1 = inputData.get('theta1') theta2 = inputData.get('theta2') g = inputData.get('g') t = inputData.get('t') temp = ODE(theta1, theta2, m1, m2, L1, L2, g, t) output(temp[0], temp[1], temp[2]) plot(temp[0], temp[1], temp[2])
def voxelSend(times, speed): #fill the top and bottom layers plotFill(0, 0, 0, 3, 0, 3) plotFill(0, 3, 0, 3, 3, 3) sleep(speed) for t in range(times): #select a new point vX = randint(0, 3) vY = randint(0, 1) * 3 vZ = randint(0, 3) #send it up or down the cube, depending on its starting y-position for n in range(0, 4): if vY == 0: if n > 0: plot(vX, n - 1, vZ, 0) plot(vX, n, vZ) elif vY == 3: if n > 0: plot(vX, (3 - n) + 1, vZ, 0) plot(vX, (3 - n), vZ) sleep(speed)
def split(X, Y, x_to_classify, name, call_plot, key): # Iterations if iteration: perform_iteration(X, Y, 100, x_to_classify, name) return # 70/30 split for training and testing data, X_train, X_test, Y_train, Y_test = train_test_split(X, Y, random_state=42, test_size=0.3, stratify=Y) # Visualise the Training Data On all features, not on some features if call_plot: plot(X_train, Y_train, name, key) models(X_train, X_test, Y_train, Y_test, x_to_classify, name, key)
def train_model(self): for epoch in range(self.num_epochs): for i, (images, labels) in enumerate(self.train_loader): # Convert torch tensor to Variable labels_onehot = torch.zeros([labels.size(0), self.num_classes]) labels_onehot.scatter_(1, labels.unsqueeze(1), 1) # TODO: gpu based # images = Variable(images).cuda() # labels = Variable(labels).cuda() # labels_onehot = Variable(labels_onehot).cuda() images = Variable(images) labels = Variable(labels) labels_onehot = Variable(labels_onehot) out = images # Forward + Backward + Optimize for (optimizer, forward) in zip(self.net.optimizers, self.net.forwards): if self.conditioned: out = self.optimizer_module(optimizer, forward, out, labels_onehot) else: out = self.optimizer_module(optimizer, forward, out) # synthetic model # Forward + Backward + Optimize loss, grad_loss = self.optimizer_dni_module( images, labels, labels_onehot, self.net.grad_optimizer, self.net.optimizer, self.net) # show training loss if (i + 1) % 10 == 0: print( 'Epoch [%d/%d], Step [%d/%d], Loss: %.4f, Grad Loss: %.4f' % (epoch + 1, self.num_epochs, i + 1, self.num_train // self.batch_size, loss.data[0], grad_loss.data[0])) # save test result if (epoch + 1) % 10 == 0: perf = self.test_model(epoch + 1) if perf > self.best_perf: torch.save(self.net.state_dict(), self.model_name + '_model_best.pkl') self.net.train() # Save the Model ans Stats pkl.dump(self.stats, open(self.model_name + '_stats.pkl', 'wb')) torch.save(self.net.state_dict(), self.model_name + '_model.pkl') if self.plot: plot(self.stats, name=self.model_name)
def train_model_supervised(self, x, y, num_epochs): for epoch in range(num_epochs): x, y = shuffle(x=x, y=y) for i in range(int(len(x) / self.args.batch_size)): x_l, y_l, _ = sample_minibatch_deterministically( x, y, batch_i=i, batch_size=self.args.batch_size) labels_onehot = torch.zeros([y_l.size(0), self.num_classes]) labels_onehot.scatter_(1, y_l.long().unsqueeze(1), 1) out = x_l for (optimizer, forward) in zip(self.net.optimizers, self.net.forwards): if self.conditioned: out = self.optimizer_module(optimizer, forward, out, labels_onehot) else: out = self.optimizer_module(optimizer, forward, out) # synthetic model # Forward + Backward + Optimize loss, grad_loss = self.optimizer_dni_module( x_l, y_l.long(), labels_onehot, self.net.grad_optimizer, self.net.optimizer, self.net) if (i + 1) % 10 == 0: print( 'Epoch [%d/%d], Step [%d/%d], Loss: %.6f, Grad Loss: %.8f' % (epoch + 1, self.num_epochs, i + 1, len(x) // self.batch_size, loss.item(), grad_loss.item())) logging.info( 'Epoch [%d/%d], Step [%d/%d], Loss: %.6f, Grad Loss: %.8f' % (epoch + 1, self.num_epochs, i + 1, len(x) // self.batch_size, loss.item(), grad_loss.item())) if (epoch + 1) % 10 == 0: perf = self.test_model(epoch + 1) if perf > self.best_perf: torch.save(self.net.state_dict(), self.model_name + '_model_best.pkl') self.net.train() # Save the Model ans Stats pkl.dump(self.stats, open(self.model_name + '_stats.pkl', 'wb')) torch.save(self.net.state_dict(), self.model_name + '_model.pkl') if self.plot: plot(self.stats, name=self.model_name)
def plot_input(year,feature,country): a=1 size=len(feature) feature_plot_list=[] for item in range(size): feature_df= pd.read_csv('./data/alldata/'+feature[item]+'.csv').drop('Unnamed: 0',axis=1) #read in all the user-required features csv files and convert them to dataframe feature_df = feature_df.set_index(feature_df['Year']).drop(['Year'],axis=1) feature_plot_list.append(plot(feature_df,country,year)) #use plot class for all the dataframes and combine all the plot objects into a list try: while(a==1): print('you could choose plot types below:') print('1,time_series_plot 2,barplot\n3,scatter_plot 4,histogram\n5,boxplot_year 6,boxplot_country\n7,heatmap 8,choropleth\n9,pie_plot\nEnter Q to quit and Enter R to return to previous menu') plot_type = input('Please select a plot type') if plot_type.isdigit(): option=int(plot_type) elif plot_type=='Q': sys.exit(1) elif plot_type=='R': a=0 break else: raise InputError #choose different plots if option==1: for dplot in feature_plot_list: dplot.time_series_plot() if option==2: for dplot in feature_plot_list: dplot.bar_plot() if option==3: for dplot in feature_plot_list: dplot.scatter_plot() if option==4: for dplot in feature_plot_list: dplot.histogram() if option==5: for dplot in feature_plot_list: dplot.boxplot_year() if option==6: for dplot in feature_plot_list: dplot.boxplot_country() if option==7: for dplot in feature_plot_list: dplot.heatmap() if option==8: for dplot in feature_plot_list: dplot.choropleth() if option==9: for dplot in feature_plot_list: dplot.pie_chart() #for different option, the system return different type of plot except InputError: print('Invalid input option') except KeyboardInterrupt: sys.exit(1) except EOFError: sys.exit(1) return a
def enduranceMapMesh(): result = run() """result = sphere(500,10) result = list(result) result.sort() xyz = reduce(fold_tuple_helper,result, [[],[],[]])""" x = map(mapping, result) y = map(mapping2, result) z = zip(x,y) filt = filter(lambda x: x[1]<3650, z) filt = filter(lambda x: x[1]>3610,filt) filt = map(list,zip(*filt)) x = filt[0] y = filt[1] #plot_cool(result[0],result[1],[0]*len(x)) plot(x,y,[0]*len(x))
def generatePlotForVirusValueHistogram(last_term, interval): n = last_term / interval for i in range(n): out((i + 1) * interval) plot((i + 1) * interval) fhtml = open('VirusDataBase/' + 'index.html', 'w') outputLine( fhtml, '<html><link rel="stylesheet" href="%s">' % CSS_DIR + '<body><font color=gray><code>') outputHeader(fhtml, '<font color=black># RESULT</font>', 1) # Image Section for i in range(n): setImage(fhtml, 400, '%d_vvd.png' % ((i + 1) * interval)) # End outputLine(fhtml, '</code></body></html>')
def on_enter(self): try: grouplist = [] #TODO get cyclelength from user cyclelength = 1 for x in xrange(0, len(self.manager.groupList)): grouplist.append(self.manager.groupList[x].name) print( "this is the number of slots " + str( len(self.manager.edit_timeline_screen.ids.glayout3. children))) self.test_send(x + 1) plot(cyclelength, len(self.manager.edit_timeline_screen.ids.glayout3.children), grouplist) except IndexError: print('No slots created!')
def rain(snow=False, times=1, speed=0.075): speed = speed / 2 drops = [] for t in range(times): #create a new drop rX = randint(0, 3) rZ = randint(0, 3) drops.append([rX, 3, rZ]) #for each raindrop for d in drops: #move the drop down one voxel, and erase its old position if d[1] < 3: plot(d[0], d[1] + 1, d[2], 0) plot(d[0], d[1], d[2]) sleep(speed) #if it hits the ground, stop updating it if d[1] == 0: if not snow == True and not snow == "snow": plot(d[0], d[1], d[2], 0) drops.remove(d) d[1] -= 1 sleep(speed)
def main(argv=None): # Lectura de archivo f = open('../../data/iris.data', 'r') lines = f.readlines() f.close() dataset = read_data() choice = '' while choice != 4: choice = input('1. Plot data\n2. PCA analysis\n3. Fisher\n4. Exit\n') if choice == 1: plot(dataset) elif choice == 2: pca(dataset) elif choice == 3: fischer(dataset) elif choice == 4: return else: print('Invalid input. Try again.')
def onPressInt(self): self.InputLower = float(self.InputLowerRaw.get()) self.InputUpper = float(self.InputUpperRaw.get()) self.InputFunc = str(self.InputFuncRaw.get()) if len(self.InputFunc) == 0: messagebox.showwarning( "Fejl", "Det indtastede tal, skal være enten et tal eller decimaltal (brug punktum ikke komma)" ) else: self.objectInt = integralregning(self.InputFunc, self.InputLower, self.InputUpper, 1000) self.objectInt.integral() plotObjectInt = plot(self.objectInt, self.InputLower, self.InputUpper) plotObjectInt.plotIntegral()
def onPressDiff(self): self.InputLower = float(self.InputLowerRaw.get()) self.InputUpper = float(self.InputUpperRaw.get()) self.InputFunc = str(self.InputFuncRaw.get()) if len(self.InputFunc) == 0: messagebox.showwarning( "Fejl", "Det indtastede tal, skal være enten et tal eller decimaltal (brug punktum ikke komma)" ) else: self.objectDiff = Diff(self.InputFunc, self.InputLower, self.InputUpper) # Vælg en af de to til test underneden. Så COMMENT den du ikke bruger. self.objectDiff.Differentialudregner() # self.objectDiff.slopeFunction() plotObjectDiff = plot(self.objectDiff, self.InputLower, self.InputUpper) plotObjectDiff.plotDifferential()
# Best, random ans worst case of each algorithm. if (j == 0): dimensions = [i for i in range(0, 1000)] if (j == 1): dimensions = [rnd.randint(0, 1000) for i in range(1000)] if (j == 2): dimensions = [i for i in range(1000, 0, -1)] printer_1(dimensions, j) # Sort the list dimensions. for i in range(2, len(dimensions) + 1): if (ans == 1): algorithm = Heapsort(dimensions[:i]) sort = algorithm.heapsort() if (ans == 2): algorithm = Cocktail(dimensions[:i], 0, len(dimensions[:i]) - 1) sort = algorithm.cocktail() if (ans == 3): algorithm = Shell(dimensions[:i]) sort = algorithm.shellsort() if (j == 0): gb.parameters_1.append((len(dimensions[:i]), gb.time)) if (j == 1): gb.parameters_2.append((len(dimensions[:i]), gb.time)) if (j == 2): gb.parameters_3.append((len(dimensions[:i]), gb.time)) gb.time = 0 j = j + 1 printer_2(sort) plot(ans)
def plot(self, tg, varargin): return plot(self, tg, varargin)
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging from plot import * from cluster import * def plot(data, density_threshold, distance_threshold, auto_select_dc=False): logging.basicConfig(format="%(asctime)s : %(levelname)s : %(message)s", level=logging.INFO) dpcluster = DensityPeakCluster() rho, delta, nneigh = dpcluster.cluster( load_paperdata, data, density_threshold, distance_threshold, auto_select_dc=auto_select_dc ) logger.info(str(len(dpcluster.ccenter)) + " center as below") for idx, center in dpcluster.ccenter.items(): logger.info("%d %f %f" % (idx, rho[center], delta[center])) plot_rho_delta(rho, delta) # plot to choose the threthold plot_rhodelta_rho(rho, delta) plot_cluster(dpcluster) if __name__ == "__main__": plot("./data/data_in_paper/example_distances.dat", 20, 0.1, False) # plot('./data/data_others/spiral_distance.dat',8,5,False) # plot('./data/data_others/aggregation_distance.dat',15,4.5,False) # plot('./data/data_others/flame_distance.dat',4,7,False) # plot('./data/data_others/jain_distance.dat',12,10,False)
def plot(data, density_threshold, distance_threshold, auto_select_dc=False): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) dpcluster = DensityPeakCluster() rho, delta, nneigh = dpcluster.cluster(load_paperdata, data, density_threshold, distance_threshold, auto_select_dc=auto_select_dc) logger.info(str(len(dpcluster.ccenter)) + ' center as below') for idx, center in dpcluster.ccenter.items(): logger.info('%d %f %f' % (idx, rho[center], delta[center])) plot_rho_delta(rho, delta) # plot to choose the threthold # plot_rhodelta_rho(rho,delta) plot_cluster(dpcluster) print(dpcluster.ccenter) if __name__ == '__main__': # plot('./data/data_in_paper/example_distances.dat', 20, 0.1,False) plot('./data/data_others/spiral_distance.dat', 8, 5, False) # plot('./data/data_others/aggregation_distance.dat',15,4.5,False) #plot('./data/data_others/flame_distance.dat',4,4,False) #plot('./data/data_others/jain_distance.dat', 2, 6, False) #plot('./data/data_others/iris.forcluster',45, 0.95,True) #plot('./data/data_in_paper/example_distances.dat', 20, 0.2) #plot('./data/data_iris_flower/iris.forcluster',47, 0.9, auto_select_dc=False)
from cluster import * def plot(data, auto_select_dc=False): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) dpcluster = DensityPeakCluster() distances, max_dis, min_dis, max_id, rho, rc = dpcluster.local_density( load_paperdata, data, auto_select_dc=auto_select_dc) delta, nneigh = min_distance(max_id, max_dis, distances, rho) plot_rho_delta(rho, delta) # plot to choose the threthold if __name__ == '__main__': # plot('./data/data_in_paper/example_distances.dat') # plot('./data/data_others/spiral_distance.dat') # plot('./data/data_others/aggregation_distance.dat') # plot('./data/data_others/flame_distance.dat') # plot('./data/data_others/jain_distance.dat') # plot('./data/data_others/test_distance.dat') # plot('./data/data_others/feature/features_distance.dat') # plot('./data/data_others/feature/features_consine_distance.dat') # plot('./data/data_others/feature/features_pearson_distance.dat') # plot('./data/data_others/normal_distance.dat') # plot('./data/data_others/sexy_distance.dat') # plot('./data/data_others/pulp_distance.dat') plot('./data/data_others/sexy_1000_distance.dat')
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging from plot import * from cluster import * def plot(data): logging.basicConfig(format="%(asctime)s : %(levelname)s : %(message)s", level=logging.INFO) dpcluster = DensityPeakCluster() distances, max_dis, min_dis, max_id, rho = dpcluster.local_density(load_paperdata, data) delta, nneigh = min_distance(max_id, max_dis, distances, rho) plot_rho_delta(rho, delta) # plot to choose the threthold if __name__ == "__main__": plot("./data/data_in_paper/example_distances.dat")
def plot_single(ddir, species, roc_dir, format = "pdf"): of = tempfile.NamedTemporaryFile() plotfn = "%s/%s/%s" % (ddir, roc_dir, species) fn1 = "%s/%s/%s.full" % (ddir, roc_dir, species) fn2 = "%s/%s/%s.naive" % (ddir, roc_dir, species) fn3 = "%s/%s/%s.blast" % (ddir, roc_dir, species) fn4 = "%s/%s/%s.gtg" % (ddir, roc_dir, species) fn5 = "%s/%s/%s.blasttree" % (ddir, roc_dir, species) fn6 = "%s/%s/%s.gtgtree" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn, format)) of.write(""" full = read.table("%s") naive = read.table("%s") blast = read.table("%s") gtg = read.table("%s") btree = read.table("%s") gtree = read.table("%s") plot(full[,2], full[,3], type="l", xlab="False positive rate", ylab="True positive rate") lines(naive[,2], naive[,3], type="l", pch=22, lty=1, col="red") lines(blast[,2], blast[,3], type="l", pch=22, lty=2, col="blue") lines(gtg[,2], gtg[,3], type="l", pch=22, lty=2, col="green") lines(btree[,2], btree[,3], type="l", pch=22, lty=1, col="purple") lines(gtree[,2], gtree[,3], type="l", pch=22, lty=1, col="orange") lines(c(0,1), c(0,1)) legend("bottomright", c("Full","Naive","BLAST","GTG", "BlastTree", "GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,2,2,1,1), inset=0.01) dev.off() """ % (fn1, fn2, fn3, fn4, fn5, fn6)) plotfn2 = "%s/%s/%s-F1" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn2, format)) of.write(""" plot(full[3:nrow(full)-1,1], full[3:nrow(full)-1,4], type="l", ylim=c(0,1), xlab="Normalized score", ylab="") lines(naive[3:nrow(naive)-1,1], naive[3:nrow(naive)-1,4], col="red", lty=1) lines(blast[3:nrow(blast)-1,1] / max(blast[,1]), blast[3:nrow(blast)-1,4], col="blue", lty=2) lines(gtg[3:nrow(gtg)-1,1], gtg[3:nrow(gtg)-1,4], col="green", lty=2) lines(btree[3:nrow(btree)-1,1], btree[3:nrow(btree)-1,4], col="purple", lty=1) lines(gtree[3:nrow(gtree)-1,1], gtree[3:nrow(gtree)-1,4], col="orange", lty=1) legend("bottomleft", c("Full","Naive","BLAST","GTG","BlastTree","GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,2,2,1,1), inset=0.01) dev.off() """) #par(mfrow=c(2,2), oma=c(2, 0, 3, 0), omi=c(0, 0, 0.8, 0)) # plot(naive[3:nrow(naive)-1,1], naive[3:nrow(naive)-1,4], ylim=c(0,1), type="l", xlab="Posterior probability, naive model", ylab="F1 score") # plot(blast[3:nrow(blast)-1,1] / max(blast[,1]), blast[3:nrow(blast)-1,4], ylim=c(0,1), type="l", xlab="BLAST score", ylab="F1 score") # plot(gtg[3:nrow(gtg)-1,1], gtg[3:nrow(gtg)-1,4], ylim=c(0,1), type="l", xlab="GTG score", ylab="F1 score") plotfn3 = "%s/%s/%s-sens" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn3, format)) of.write(""" plot(full[1:nrow(full),1], full[1:nrow(full),3], type="l", ylim=c(0,1), xlab="Normalized score", ylab="Sensitivity") lines(naive[1:nrow(naive),1], naive[1:nrow(naive),3], col="red", lty=1) lines(blast[1:nrow(blast),1] / max(blast[,1]), blast[1:nrow(blast),3], col="blue", lty=2) lines(gtg[1:nrow(gtg),1], gtg[1:nrow(gtg),3], col="green", lty=2) lines(btree[1:nrow(btree),1], btree[1:nrow(btree),3], col="purple", lty=1) lines(gtree[1:nrow(gtree),1], gtree[1:nrow(gtree),3], col="orange", lty=1) legend("bottomleft", c("Full","Naive","BLAST","GTG","BlastTree","GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,2,2,1,1), inset=0.01) dev.off() """) plotfn4 = "%s/%s/%s-spec" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn4, format)) of.write(""" plot(full[1:nrow(full),1], full[1:nrow(full),5], type="l", ylim=c(0,1), lty=2, xlab="Normalized score", ylab="Specificity") lines(naive[1:nrow(naive),1], naive[1:nrow(naive),5], col="red", lty=2) lines(blast[1:nrow(blast),1] / max(blast[,1]), blast[1:nrow(blast),5], col="blue", lty=2) lines(gtg[1:nrow(gtg),1], gtg[1:nrow(gtg),5], col="green", lty=2) lines(btree[1:nrow(btree),1], btree[1:nrow(btree),5], col="purple", lty=2) lines(gtree[1:nrow(gtree),1], gtree[1:nrow(gtree),5], col="orange", lty=2) legend("bottomleft", c("Full","Naive","BLAST","GTG","BlastTree","GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,1,1,1,1), inset=0.01) dev.off() """) of.flush() subprocess.call("R CMD BATCH %s" % (of.name), shell = True)
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging from plot import * from cluster import * def plot(data, density_threshold, distance_threshold, auto_select_dc = False): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) dpcluster = DensityPeakCluster() rho, delta, nneigh = dpcluster.cluster(load_paperdata, data, density_threshold, distance_threshold, auto_select_dc = auto_select_dc) logger.info(str(len(dpcluster.ccenter)) + ' center as below') for idx, center in dpcluster.ccenter.items(): logger.info('%d %f %f' %(idx, rho[center], delta[center])) #plot_rho_delta(rho, delta) #plot to choose the threthold plot_cluster(dpcluster) if __name__ == '__main__': #plot('./data/data_in_paper/example_distances.dat', 20, 0.1) plot('./data/data_iris_flower/iris.forcluster', 40.7, 0.9, auto_select_dc = True)
def plot_single(ddir, species, roc_dir, format="pdf"): of = tempfile.NamedTemporaryFile() plotfn = "%s/%s/%s" % (ddir, roc_dir, species) fn1 = "%s/%s/%s.full" % (ddir, roc_dir, species) fn2 = "%s/%s/%s.naive" % (ddir, roc_dir, species) fn3 = "%s/%s/%s.blast" % (ddir, roc_dir, species) fn4 = "%s/%s/%s.gtg" % (ddir, roc_dir, species) fn5 = "%s/%s/%s.blasttree" % (ddir, roc_dir, species) fn6 = "%s/%s/%s.gtgtree" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn, format)) of.write(""" full = read.table("%s") naive = read.table("%s") blast = read.table("%s") gtg = read.table("%s") btree = read.table("%s") gtree = read.table("%s") plot(full[,2], full[,3], type="l", xlab="False positive rate", ylab="True positive rate") lines(naive[,2], naive[,3], type="l", pch=22, lty=1, col="red") lines(blast[,2], blast[,3], type="l", pch=22, lty=2, col="blue") lines(gtg[,2], gtg[,3], type="l", pch=22, lty=2, col="green") lines(btree[,2], btree[,3], type="l", pch=22, lty=1, col="purple") lines(gtree[,2], gtree[,3], type="l", pch=22, lty=1, col="orange") lines(c(0,1), c(0,1)) legend("bottomright", c("Full","Naive","BLAST","GTG", "BlastTree", "GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,2,2,1,1), inset=0.01) dev.off() """ % (fn1, fn2, fn3, fn4, fn5, fn6)) plotfn2 = "%s/%s/%s-F1" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn2, format)) of.write(""" plot(full[3:nrow(full)-1,1], full[3:nrow(full)-1,4], type="l", ylim=c(0,1), xlab="Normalized score", ylab="") lines(naive[3:nrow(naive)-1,1], naive[3:nrow(naive)-1,4], col="red", lty=1) lines(blast[3:nrow(blast)-1,1] / max(blast[,1]), blast[3:nrow(blast)-1,4], col="blue", lty=2) lines(gtg[3:nrow(gtg)-1,1], gtg[3:nrow(gtg)-1,4], col="green", lty=2) lines(btree[3:nrow(btree)-1,1], btree[3:nrow(btree)-1,4], col="purple", lty=1) lines(gtree[3:nrow(gtree)-1,1], gtree[3:nrow(gtree)-1,4], col="orange", lty=1) legend("bottomleft", c("Full","Naive","BLAST","GTG","BlastTree","GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,2,2,1,1), inset=0.01) dev.off() """) #par(mfrow=c(2,2), oma=c(2, 0, 3, 0), omi=c(0, 0, 0.8, 0)) # plot(naive[3:nrow(naive)-1,1], naive[3:nrow(naive)-1,4], ylim=c(0,1), type="l", xlab="Posterior probability, naive model", ylab="F1 score") # plot(blast[3:nrow(blast)-1,1] / max(blast[,1]), blast[3:nrow(blast)-1,4], ylim=c(0,1), type="l", xlab="BLAST score", ylab="F1 score") # plot(gtg[3:nrow(gtg)-1,1], gtg[3:nrow(gtg)-1,4], ylim=c(0,1), type="l", xlab="GTG score", ylab="F1 score") plotfn3 = "%s/%s/%s-sens" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn3, format)) of.write(""" plot(full[1:nrow(full),1], full[1:nrow(full),3], type="l", ylim=c(0,1), xlab="Normalized score", ylab="Sensitivity") lines(naive[1:nrow(naive),1], naive[1:nrow(naive),3], col="red", lty=1) lines(blast[1:nrow(blast),1] / max(blast[,1]), blast[1:nrow(blast),3], col="blue", lty=2) lines(gtg[1:nrow(gtg),1], gtg[1:nrow(gtg),3], col="green", lty=2) lines(btree[1:nrow(btree),1], btree[1:nrow(btree),3], col="purple", lty=1) lines(gtree[1:nrow(gtree),1], gtree[1:nrow(gtree),3], col="orange", lty=1) legend("bottomleft", c("Full","Naive","BLAST","GTG","BlastTree","GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,2,2,1,1), inset=0.01) dev.off() """) plotfn4 = "%s/%s/%s-spec" % (ddir, roc_dir, species) of.write(plot.plot_format(plotfn4, format)) of.write(""" plot(full[1:nrow(full),1], full[1:nrow(full),5], type="l", ylim=c(0,1), lty=2, xlab="Normalized score", ylab="Specificity") lines(naive[1:nrow(naive),1], naive[1:nrow(naive),5], col="red", lty=2) lines(blast[1:nrow(blast),1] / max(blast[,1]), blast[1:nrow(blast),5], col="blue", lty=2) lines(gtg[1:nrow(gtg),1], gtg[1:nrow(gtg),5], col="green", lty=2) lines(btree[1:nrow(btree),1], btree[1:nrow(btree),5], col="purple", lty=2) lines(gtree[1:nrow(gtree),1], gtree[1:nrow(gtree),5], col="orange", lty=2) legend("bottomleft", c("Full","Naive","BLAST","GTG","BlastTree","GTGTree"), cex=0.8, col=c("black","red","blue","green","purple","orange"), pch=c(21,21,21,21,21,21), lty=c(1,1,1,1,1,1), inset=0.01) dev.off() """) of.flush() subprocess.call("R CMD BATCH %s" % (of.name), shell=True)
#Checking the solution: >>> soln=solve((exprq,expr2),dict=True) >>> soln=soln[0] >>> exprq.subs({x:soln[x],y:soln[y]}) 0 >>> expr2.subs({x:soln[x],y:soln[y]}) 0 #Plotting using sympy >>> from sympy.plotting import plot >>> from sympy import Symbol >>> x=Symbol('x') >>> plot(2*x+3) #If we dont want x from -10 to 10 as is standard but from -5 to 5 we do this >>> from sympy.plotting import plot >>> from sympy import Symbol >>> x=Symbol('x') >>> plot((2*x+3),(x,-5,5)) #We can further decorate the plot >>> from sympy.plotting import plot >>> from sympy import Symbol >>> x=Symbol('x') >>> plot((2*x+3),(x,-5,5),title='A line',xlabel='x',ylabel='2x+3')
def spiral(times, speed): #this function naturally runs slower than most, so speed is divided by 2 # to normalize speed speed = speed / 2 fullcube(0) for t in range(times): #alternate between plotting 1 and 0 for val in range(2): v = 1 - val #draw the spiraling point, then move up a layer for n in range(4): plotFill(1, n, 0, 2, n, 0, v) sleep(speed) plot(1, n, 0, v) plot(0, n, 1, v) sleep(speed) plotFill(0, n, 1, 0, n, 2, v) sleep(speed) plot(0, n, 2, v) plot(1, n, 3, v) sleep(speed) plotFill(1, n, 3, 2, n, 3, v) sleep(speed) plot(2, n, 3, v) plot(3, n, 2, v) sleep(speed) plotFill(3, n, 1, 3, n, 2, v) sleep(speed) plot(3, n, 1, v) if n < 3: plot(2, n + 1, 0, v) sleep(speed)
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging from plot import * from cluster import * def plot(data, auto_select_dc = False): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) dpcluster = DensityPeakCluster() distances, max_dis, min_dis, max_id, rho, rc = dpcluster.local_density(load_paperdata, data, auto_select_dc = auto_select_dc) delta, nneigh = min_distance(max_id, max_dis, distances, rho) plot_rho_delta(rho, delta) #plot to choose the threthold if __name__ == '__main__': #plot('./data/data_in_paper/example_distances.dat') #plot('./data/data_others/spiral_distance.dat') #plot('./data/data_others/aggregation_distance.dat') #plot('./data/data_others/flame_distance.dat') plot('./data/data_others/jain_distance.dat')
]) assert len(res.atoms) == N_atoms return res if __name__ == "__main__": if False: from plot import * N = 6 E = linspace(-8.5,8.5,200)*eV SDOS = array([ SDOS_armchair_analytic(e/(2.66*eV),N)/(2.66*eV*N) for e in E ]) def integral(x,y): return .5*sum((x[1:]-x[:-1])*(y[1:]+y[:-1])) print "integral: %g"%integral(E,SDOS) plot(E,SDOS) show() else: # param.setdefaults() zigzag(10).write_xyz_file('cnt-test-zigzag.xyz') armchair(10).write_xyz_file('cnt-test-armchair.xyz') chiral(5,4).write_xyz_file('cnt-test-chiral.xyz')
DistributionPlot.histogram_plot('data/plots/file_hist/commits_dist.png', num_commits, bins=100) DistributionPlot.histogram_plot('data/plots/file_hist/authors_dist.png', num_authors, bins=100) def test(): test_files = ['actionpack/lib/action_dispatch/http/mime_type.rb', 'actionmailer/lib/action_mailer/mail_helper.rb', 'actionmailer/test/fixtures/auto_layout_mailer/hello.html.erb', 'actionpack/lib/action_view/helpers/asset_tag_helper.rb', 'actionpack/lib/action_view/template/resolver.rb', 'actionpack/test/controller/controller_fixtures/app/controllers/user_controller.rb', 'actionpack/test/controller/new_base/render_layout_test.rb', 'actionpack/test/fixtures/public/javascripts/application.js', 'activesupport/lib/active_support/core_ext/file.rb', 'activesupport/lib/active_support/core_ext/object/inclusion.rb'] git = MGit.MGit('../rails') for test in test_files: print '---' print test player = git.history(test) os.chdir('../ghnet') if player is not None: graph = MGraph.draw_lineage(player.lineage, test) os.chdir('../rails') # player = git.history('actionmailer/test/fixtures/attachments/foo.jpg') # Will fail for sure #test() # walk() # walk_and_prepare() plot()
#itchat.run() rounds = 4 while True: if rounds == 4: print '********refit the model*************' pullfuturekline() pullspotkline() merge_spot() merge_future() classification() rounds = 0 print '*********long term***********' print '********apply the model *************' test = model(15) print '********plot*************' plot(15, True) print '************send to itchat*********' itchat.send_image('data/figure.png', toUserName='******') print '*********short term***********' print '********apply the model *************' test = model(2) print '********plot*************' plot(2) print '************send to itchat*********' itchat.send_image('data/figure.png', toUserName='******') itchat.send( 'long '+str(test.iloc[-1]['longposition'])+'\t'+str(test.iloc[-1]['longamount'])+'\n'+ 'short '+str(test.iloc[-1]['shortposition'])+'\t'+str(test.iloc[-1]['shortamount'])+'\n'+ 'liq '+str(test.iloc[-1]['liqbtc'])+'\n' 'hold '+str(test.iloc[-1]['holdbtc'])+'\n'+
import os #os.chdir("/Users/charleslui/Documents/BCMind/bcmind_py") import numpy as np import Data reload(Data) import technical.SMA reload(technical.SMA) import plot d = Data(1467294196, 100) d.plot() technical.SMA.SMA(d,20) reload(plot) plot(d)
from numpy import * from plot import * from util import * from gradientDescent import * from predict import * from scipy.optimize import * import numpy as np data = loadtxt('data1.txt', delimiter=',') X = data[:,0:2] y = data[:,2] plot(X,y) theta = np.zeros(X.shape[1] + 1) dummy = ones(X.shape[0]) processX = column_stack([dummy, X]) alpha = 1 thetaResult = fmin_bfgs(computeCost, theta, args=(processX, y, alpha), fprime=costGradient) print thetaResult print predict(thetaResult, processX, y)
load_paperdata, data,load_mainPathLen,normalized_path_len, local_den_weight=1.0, path_len_weight=0.0\ ,auto_select_dc=auto_select_dc) delta, nneigh = min_distance(max_id, max_dis, distances, rho) for index, (r_tmp, d_tmp) in enumerate(zip(rho, delta)): if r_tmp > rho_threshold and d_tmp > delta_threshold: print index, path_len_list[index], r_tmp, d_tmp pu.writeGraph2pajekNetFile(subgraph_list[index], 'subgraph_' + str(index) + '.net') if __name__ == '__main__': # plot('./data/data_in_paper/example_distances.dat') #plot('./data/data_iris_flower/iris.forcluster', auto_select_dc=True) plot('./data/data_main_path/main_path_topic_T0_S1_cosine.forcluster',\ './data/data_main_path/normalized_node_num_of_path_array.npy',\ auto_select_dc=False) ''' printChosenCenter('./data/data_main_path/main_path_topic_T0_S1_cosine.forcluster',\ './data/data_main_path/node_num_of_path_list.data', \ './data/data_main_path/normalized_node_num_of_path_list.data',\ 30,0.4, auto_select_dc=False); ''' ''' outputChosenCenter_indicated_mainPath('./data/data_main_path/main_path_topic_T0_S1_cosine.forcluster',\ './data/data_main_path/node_num_of_path_list.data', \ './data/data_main_path/normalized_node_num_of_path_list.data', \ './data/data_main_path/subgraph_list.data', \ 30,0.4, auto_select_dc=False);
""" A simple example script """ import numpy as np import qt from plot import * print locals() d = qt.Data() d.add_coordinate('X') d.add_value('Y') d.create_file() p = plot(d) # Inform wrapper that a measurement has started qt.mstart() for x in np.arange(0, 40, 0.1): y = np.sin(x) + np.random.rand()/10 d.add_data_point(x, y) # Sleep for 100msec and allow UI interaction qt.msleep(0.1) # Inform wrapper that the measurement has ended qt.mend() d.close_file()
#addInstrumentToSong() GenerateNote(instrumentC, [[32, [note("rest")]], [32, [note("C4")]], [32, [note("C5")]]]) #GenerateNote(randomInstrument(20),randomNotes(16,16)) export() ####Execution time#### print "My program took", time.time( ) - start_time, "seconds to run (Excluding plotting time)" from evaluate import song print "Computation time for song length", (len(song) / 44100) / ( time.time() - start_time), "%" ####Execution time#### plot() print "" ''' When you try to divide a list by a real number, python says "you are crazy! You can't do that." The array is like a vector. If you divide it by a real number, each "thing" in there is divided by that number. This can be super useful. ''' ''' t = arange(0,3,0.01) - this makes an array of values. The values start at 0, end at 3 and increment by 0.01. x = cos(pi*t*F) - here is the cool part. Remember that t is an array. This means that x is also an array. I don't have to do any loops or anything like that. Boom, just does it. ''' ''' Do Fourier transform on piano later ''' ''' How it should be like in the beta version (Optimisation such as how many bars to generate each time is not done yet):
from pylab import * from plot import * v_rectangle_area = np.vectorize(rectangle_area) v_rectangle_perimeter = np.vectorize(rectangle_perimeter) S = np.linspace(0,10) # our side lengths A = v_rectangle_area(S) # the areas P = v_rectangle_perimeter(S) # the perimeters plot(S, A, '-r', label="Area") plot(S, P, ':b', label="Perimeter") xlabel('side length') ylabel('geo values') title('rectangle Geo Properties') legend(loc='upper right') show()
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging from plot import * from cluster import * def plot(data, auto_select_dc=False): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) dpcluster = DensityPeakCluster() distances, max_dis, min_dis, max_id, rho, rc = dpcluster.local_density( load_paperdata, data, auto_select_dc=auto_select_dc) delta, nneigh = min_distance(max_id, max_dis, distances, rho) plot_rho_delta(rho, delta) #plot to choose the threthold if __name__ == '__main__': #plot('./data/data_in_paper/example_distances.dat') #plot('./data/data_others/spiral_distance.dat') #plot('./data/data_others/aggregation_distance.dat') #plot('./data/data_others/flame_distance.dat') plot('./data/data_others/jain_distance.dat')
#!/usr/bin/env python # -*- coding: UTF-8 -*- import logging from plot import * from cluster import * def plot(data, density_threshold, distance_threshold): logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO) dpcluster = DensityPeakCluster() rho, delta, nneigh = dpcluster.cluster(load_paperdata, data, density_threshold, distance_threshold) logger.info(str(len(dpcluster.ccenter)) + ' center as below') for idx, center in dpcluster.ccenter.items(): logger.info('%d %f %f' %(idx, rho[center], delta[center])) #plot_rho_delta(rho, delta) #plot to choose the threthold plot_cluster(dpcluster) if __name__ == '__main__': plot('./data/data_in_paper/example_distances.dat', 20, 0.1)