def Spect( self ): #, dimension): # Dimension is unit type as V(olt) W(att), etc Axes3D.plot_surface(self.signalx, self.signaly, self.signalz) if self.signalx.shape == self.signaly.shape == self.signalz.shape: pass elif self.signalx.shape == (len( self.signalx), ) or self.signaly.shape == (len( self.signaly), ): # Check for 1D array both if self.signalx.shape == (len( self.signalx), ) and self.signaly.shape == (len( self.signaly), ): self.signalx, self.signaly = np.meshgrid( self.signalx, self.signaly) nx, mx = np.shape(self.signalx) nz, mz = np.shape(self.signalz) if nx == nz and mx == mz: pass elif nx == mz and mx == nz: self.signalz = np.rot90(self.signalz, 1) # find out if it has to be 1 or 3 elif self.signalx.shape == (len(self.signalx), ): pass elif self.signaly.shape == (len(self.signaly), ): pass if self.signalx.shape == self.signaly.shape != self.signalz.shape: nx, mx = np.shape(self.signalx) nz, mz = np.shape(self.signalz) if nx == nz and mx == mz: pass elif nx == mz and mx == nz: self.signalz = np.rot90(self.signalz, 1) # find out if it has to be 1 or 3 elif self.signalx.shape == self.signalz.shape != self.signaly.shape: nx, mx = np.shape(self.signalx) ny, my = np.shape(self.signalz) if nx == ny and mx == my: pass elif nx == my and mx == ny: self.signaly = np.rot90(self.signaly, 1) # find out if it has to be 1 or 3 elif self.signaly.shape == self.signalz.shape != self.signalx.shape: ny, my = np.shape(self.signaly) nx, mx = np.shape(self.signalx) if ny == nx and my == mx: pass elif ny == mx and my == nx: self.signalz = np.rot90(self.signalz, 1) # find out if it has to be 1 or 3 else: raise MeasError.DataError( "No Valid data found in at least one of the axis") plt.xlabel('time [s]') # Or Sample number plt.ylabel('Frequency [Hz]') # Or Freq Bins number plt.zlabel('voltage [mV]') # auto add unit here plt.title(' ') # set title plt.grid(True) plt.show()
def plot3d(matrix, show=True, savefn=None, plt_type="bar", xlabel=None, ylabel=None, zlabel=None, title=None): """ Plot the input matrix in 3d. Either save, show, or both. Supported types are 'bar', 'tri', and 'surface'. """ fig = plt.figure() fig.set_size_inches(18.5, 10.5) ax = fig.add_subplot(111, projection="3d") x_data, y_data = np.meshgrid(np.arange(matrix.shape[1]), np.arange(matrix.shape[0])) x_data = x_data.flatten() y_data = y_data.flatten() z_data = matrix.flatten() if plt_type == "bar": ax.bar3d(x_data, y_data, np.zeros(len(z_data)), 1, 1, z_data) elif plt_type == "tri": ax.plot_trisurf(x_data, y_data, z_data, cmap=cm.jet, linewidth=0.2) elif plt_type == "surface": pass else: raise RuntimeError("Plot type {} not supported.".format(plt_type)) if xlabel is not None: plt.ylabel(xlabel) if ylabel is not None: plt.xlabel(ylabel) if zlabel is not None: plt.zlabel(zlabel) if title is not None: plt.title(title) if savefn is not None: plt.savefig(savefn, dpi=100) if show: plt.show() return fig
def water(self, *argv): # Dimension is unit type as V(olt) W(att), etc # http://matplotlib.org/examples/mplot3d/polys3d_demo.html Axes3D.plot_surface(self.signalx, self.signaly, self.signalz) # till better funcion plt.xlabel('time [s]') # Or Sample number plt.ylabel('Frequency [Hz]') # Or Freq Bins number plt.zlabel('voltage [mV]') # auto add unit here plt.title(' ') # set title plt.grid(True) plt.show()
def plot_across_companies(tseries, num_features): for j in range(1, num_features + 1): for i in range(1, num_features + 1): if i > j: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for k in tseries.keys(): ax.scatter(tseries[k][:, 0], tseries[k][:, i], tseries[k][:, j]) plt.xlabel("Number of Days Since 1/1/2016") plt.ylabel(features[i - 1]) plt.zlabel(features[j - 1]) plt.show()
def plotAgentVel(self, agent_num): agent = self.dataframe[agent_num]['velocity'] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') Axes3D.scatter(ax, getWithout(agent[:, 0], -1), getWithout(agent[:, 1], -1), zs=np.arange(len(agent))[agent[:, 0] != -1], s=3) plt.title("Example Velocity of Agent") plt.xlabel("x component") plt.ylabel("y component") plt.zlabel("Time") plt.show()
def plotAgentPos(self, agent_num): agent = self.dataframe[agent_num]['coordinates'] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') Axes3D.scatter(ax, getWithout(agent[:, 0], 1), getWithout(agent[:, 1], 1), zs=np.arange(len(agent))[agent[:, 0] != 1], s=3) plt.title("Example Trajectory of Agent") plt.xlabel("x coordinate") plt.ylabel("y coordinate") plt.zlabel("Time") plt.show()
def plotxyz3d(x, y, z, title=""): """ Plot accelerometer readings in 3-D. (If trouble with "projection='3d'", try: ipython --pylab) Parameters ---------- x : list or numpy array of floats y : list or numpy array of floats z : list or numpy array of floats title : string title Examples -------- >>> from mhealthx.xio import read_accel_json >>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/accel_walking_outbound.json.items-6dc4a144-55c3-4e6d-982c-19c7a701ca243282023468470322798.tmp' >>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-5981e0a8-6481-41c8-b589-fa207bfd2ab38771455825726024828.tmp' >>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-a2ab9333-6d63-4676-977a-08591a5d837f5221783798792869048.tmp' >>> start = 150 >>> device_motion = True >>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion) >>> x, y, z = axyz >>> title = 'Test vectors' >>> from mhealthx.utilities import plotxyz3d >>> plotxyz3d(x, y, z, title) """ import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection="3d") # ax.plot(x, y, z) #, marker='o' ax.plot(x[1::], y[1::], z[1::], label="x, y, z") # , marker='o' ax.legend() ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") # ax.set_xlim3d(0, 1) # ax.set_ylim3d(0, 1) # ax.set_zlim3d(0, 1) plt.xlabel("x") plt.ylabel("y") plt.zlabel("z") plt.title(title) plt.show()
def plotxyz3d(x, y, z, title=''): """ Plot accelerometer readings in 3-D. (If trouble with "projection='3d'", try: ipython --pylab) Parameters ---------- x : list or numpy array of floats y : list or numpy array of floats z : list or numpy array of floats title : string title Examples -------- >>> from mhealthx.xio import read_accel_json >>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/accel_walking_outbound.json.items-6dc4a144-55c3-4e6d-982c-19c7a701ca243282023468470322798.tmp' >>> input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-5981e0a8-6481-41c8-b589-fa207bfd2ab38771455825726024828.tmp' >>> #input_file = '/Users/arno/DriveWork/mhealthx/mpower_sample_data/deviceMotion_walking_outbound.json.items-a2ab9333-6d63-4676-977a-08591a5d837f5221783798792869048.tmp' >>> start = 150 >>> device_motion = True >>> t, axyz, gxyz, uxyz, rxyz, sample_rate, duration = read_accel_json(input_file, start, device_motion) >>> x, y, z = axyz >>> title = 'Test vectors' >>> from mhealthx.utilities import plotxyz3d >>> plotxyz3d(x, y, z, title) """ import matplotlib.pyplot as plt fig = plt.figure() ax = fig.gca(projection='3d') #ax.plot(x, y, z) #, marker='o' ax.plot(x[1::], y[1::], z[1::], label='x, y, z') #, marker='o' ax.legend() ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') #ax.set_xlim3d(0, 1) #ax.set_ylim3d(0, 1) #ax.set_zlim3d(0, 1) plt.xlabel('x') plt.ylabel('y') plt.zlabel('z') plt.title(title) plt.show()
def kmeans_cluster_plot(X, y, k=3, cmap=plt.cm.Paired, n_dim=2): kmeans = cluster.KMeans(n_clusters=k).fit(X) klab = kmeans.labels_ fig = plt.figure() if n_dim < 3: plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap) else: ax = Axes3D(fig) ax.scatter3D(X[:, 0], X[:, 1], X[:, 2], c=y, cmap=cmap) plt.title('k-means clusters') plt.xlabel('PC1') plt.ylabel('PC2') if n_dim > 2: plt.zlabel('PC3') return fig
def plot3d(matrix, show=True, savefn=None, plt_type='bar', xlabel=None, ylabel=None, zlabel=None, title=None): """ Plot the input matrix in 3d. Either save, show, or both. Supported types are 'bar', 'tri', and 'surface'. """ fig = plt.figure() fig.set_size_inches(18.5, 10.5) ax = fig.add_subplot(111, projection='3d') x_data, y_data = np.meshgrid(np.arange(matrix.shape[1]), np.arange(matrix.shape[0])) x_data = x_data.flatten() y_data = y_data.flatten() z_data = matrix.flatten() if plt_type == 'bar': ax.bar3d(x_data, y_data, np.zeros(len(z_data)), 1, 1, z_data) elif plt_type == 'tri': ax.plot_trisurf(x_data, y_data, z_data, cmap=cm.jet, linewidth=.2) elif plt_type == 'surface': pass else: raise RuntimeError('Plot type {} not supported.'.format(plt_type)) if xlabel is not None: plt.ylabel(xlabel) if ylabel is not None: plt.xlabel(ylabel) if zlabel is not None: plt.zlabel(zlabel) if title is not None: plt.title(title) if savefn is not None: plt.savefig(savefn, dpi=100) if show: plt.show() return fig
def traj(normalized, positions, dimension, time_scale = 10): lr_asym = np.cos(positions[:, 1] * (np.pi / dimension[1])) bf_asym_spat = np.cos(positions[:, 2] * (np.pi / dimension[2])) bf_asym_temp = np.cos(np.linspace(0, np.pi / 2, time_scale)) traj_sym = np.correlate(normalized.sum(axis = 0), np.ones(time_scale)) traj_lr = np.correlate(np.sum(normalized * lr_asym[:, np.newaxis], axis = 0), np.ones(time_scale)) traj_bf = np.correlate(np.sum(normalized * bf_asym_spat[:, np.newaxis], axis = 0), bf_asym_temp) trajectory = np.c_[traj_bf, traj_lr, traj_sym] fig = plt.figure() ax = fig.add_subplot(111, projection = '3d') ax.plot(trajectory[:, 0], trajectory[:, 1], trajectory[:, 2]) plt.xlabel('forward/backward') plt.ylabel('turning') plt.zlabel('activity') plt.show() return trajectory
def plotresults(filename, type=2, xscale='linear', showiter=False, showtol=True, style=None, limit=False, correct=[], latest=True, label=None): '''Returns: if plot requested: handle otherwise: (par,results,tolret,passes,cputime) filename = text file with simulation results type: 1 = BER 2 = SER (as Hamming distance, default) 3 = FER 4 = GSER (as Levenshtein distance) 5 = 3D profile (not supported) 6 = 2D profile (as multiple graphs) 7 = Burst-error profile 8 = passes 9 = cputime 10 = cputime/pass or a string to match with header xscale: 'linear' (default) or 'log' showiter: plot all iterations / indices in set? (default: false = show last) if true, show all indices if a list, interpret as indices to show NOTE: for profile, indices select positions to show results for showtol: (T1-4,6) plot tolerance limits? (default: true) style: if absent, do not plot results if a string, use this as the line format string if a list, use respectively as color, marker, linestyle limit: limit number of markers? (default: false) if true, limits to 20-40 markers per line if a number 'n', one marker is printed for every 'n' points correct: data set for BSID parameter correction (default: no correction) contains: [Ps, Pd, Pi, Reff] latest: if true (default) load only the latest simulation in file if false, concatenate all simulations in file if a list, concatenate the specified simulations in file label: legend label Note: types 1 & 2 use the same data set (symbol-error), but just change the axis labels this facilitates use with binary codes. ''' # Load data from file, and reorganize as necessary (par,results,tolerance,passes,cputime,header,comments) = loadresults(filename,latest) # extract last system and date from comments system = getafter('Communication System:',comments) date = getafter('Date:',comments) # apply correction to BSID parameter if requested if correct != []: [Ps, Pd, Pi, Reff] = correct par = correct_bsid_to_normerror(par, Ps, Pd, Pi, Reff) # extract results to be plotted if type==1 or type==2 or type==3 or type==4: # extract columns according to type requested tag = { 1: 'BER', 2: 'SER', 3: 'FER', 4:'LD' } #i = [s.startswith(tag[type]) for s in header] (results,dd,hh) = get_columns(results,header,tag[type]) (tolerance,dd,hh) = get_columns(tolerance,header,tag[type]) elif type==7: # compute only P(e_i | e_{i-1}) / P(e_i) results = (results[:,2] / results[:,3]) / (results[:,1] + results[:,2]) elif not (type >= 1 and type <= 10): # extract columns according to type requested (results,dd,hh) = get_columns(results,header,type) (tolerance,dd,hh) = get_columns(tolerance,header,type) ns=1 # determine decimation factor to limit number of markers if limit == True: # limit to 20-40/line if type==6: pts = np.size(results,1) else: ptr = np.size(par,0) ns = max(1, pts/20) elif limit != False: # limit as requested by user ns = limit limit = True # keep results from requested iterations if isinstance(showiter, list): results = results[:,showiter] tolerance = tolerance[:,showiter] elif not showiter: # keep last result in set only results = results[:,-1] tolerance = tolerance[:,-1] # keep tolerance values to return tolret = tolerance # clear tolerances, if requested if not showtol: tolerance = [] # Skip the figure plot if requested if style is None: return (par,results,tolret,passes,cputime) # do the appropriate plot if type==1 or type==2 or type==3 or type==4: ylabel = { 1: 'Bit Error Rate', 2: 'Symbol Error Rate', 3: 'Frame Error Rate', 4: 'Generalized Symbol Error Rate' } h = plotitem(par,results,tolerance,style,xscale,'log',ns,label) plt.xlabel('Channel Parameter') plt.ylabel(ylabel[type]) elif type==5: print "Not supported" sys.exit(1) #plotprofile(par,0:(size(results,2)-1),results,tolerance,xscale,'linear','log') plt.xlabel('Channel Parameter') plt.ylabel('Value/Position') plt.zlabel('Symbol Error Rate') elif type==6: cols = np.size(results,1) # convert to numpy arrays and transpose results = np.array(results).transpose() tolerance = np.array(tolerance).transpose() label = '%s, p=%s' % (label, ','.join([ '%g' % n for n in par ])) h = plotitem(range(cols),results,tolerance,style,'linear','log',ns,label) plt.xlabel('Value/Position') plt.ylabel('Symbol Error Rate') elif type==7: h = plotitem(par,results,[],style,xscale,'log',ns,label) plt.xlabel('Channel Parameter') plt.ylabel(r'Burstiness $Pr[e_i|e_{i-1}] / Pr[e_i]$') elif type==8: # Plot the number of samples h = plotitem(par,passes,[],style,xscale,'log',ns,label) plt.ylabel('Number of Samples (Frames)') elif type==9: # Plot the CPU time used h = plotitem(par,cputime/3600,[],style,xscale,'log',ns,label) plt.ylabel('Compute Time Used (Hours)') elif type==10: # Plot the CPU time used per sample h = plotitem(par,cputime/passes,[],style,xscale,'log',ns,label) plt.ylabel('Compute Time per Sample (Seconds)') else: # catch-all h = plotitem(par,results,tolerance,style,xscale,'log',ns,label) plt.xlabel('Channel Parameter') plt.ylabel('Value') return h
test_y2 = np.linspace(-math.pi, math.pi, 100) xx, yy = np.meshgrid(test_x2, test_y2) test_xy = np.hstack((xx.reshape(xx.shape[0] * xx.shape[1], 1, order='F'), yy.reshape(yy.shape[0] * yy.shape[1], 1, order='F'))) test_z2 = map(lambda t: function_f(t[0], t[1]), test_xy) fig = plt.figure() ax = Axes3D(fig) num_pts = np.shape(test_xy)[0] xs_plot = np.reshape(test_xy[:, 0], [num_pts]) ys_plot = np.reshape(test_xy[:, 1], [num_pts]) zs_plot = np.reshape(test_z2, [num_pts]) ax.plot(xs=xs_plot, ys=ys_plot, zs=xs_plot) plt.xlabel('Samples 1') plt.ylabel('Samples 2') plt.zlabel('Function Value') plt.title('Integration Function Plot') zz = zs_plot.reshape(100, 100) plt.figure() plt.contour(xx, yy, zz) plt.xlabel('Samples 1') plt.ylabel('Samples 2') plt.title('Integration Function Plot - contour') print "MONTE CARLO ------------------------" max_iterations = 50 monte_carlo_estimates = [] for i in range(0, max_iterations):
def nsga_2(input_v,activate_parallel,num_cores): ##import sys import numpy as np from objective_description_function import objective_description_function from initialize_variables import initialize_variables from non_domination_sort_mod import non_domination_sort_mod from tournament_selection import tournament_selection import genetic_operator from replace_chromosome import replace_chromosome import matplotlib.pyplot as plt print('Running Optimization...') input_v['objAll'] = [] input_v['xAll'] = [] import os import timing ##Making sure thet population and generations are integers input_v['population'] = round(input_v['population']) input_v['generations'] = round(input_v['generations']) ##Forming the objective function ##input_v['M'] --- number of objective functions ##input_v['V'] --- number of decision variables ##input_v['min_range'] --- list of corresponding lowerbound of the decision variables ##input_v['max_range'] --- list of corresponding upperbound of the decision variables input_v['M'], input_v['V'], input_v['min_range'], input_v['max_range'] = objective_description_function(input_v) ##Initialize the population ##Population is initialzied with random values which are within the specified range. Each chromosome consist of the ##decision variables. Also the value fo the objective functions, rank and crowding distance information are also added ##to the chromosome vector but only the elements of the vector which has the decision variables are operatedupon to ##perform the genetic operations like crossover and mutation chromosome, input_v = initialize_variables(input_v,activate_parallel,num_cores) ##Sort the initialized population ##Sort the population using non-domination-sort. This returns two columns for each individual which are the rank and the ##crowding distance corresponding to their position in the front they belong. At this stage the rank and the crowding distance ##for each chromosome is added to the chromosome vector for easy of computation. chromosome = non_domination_sort_mod(chromosome, input_v['M'], input_v['V']) ## Start the evolution process # The following are performed in each generation # * Select the parents which are fit for reproduction # * Perfrom crossover and Mutation operator on the selected parents # * Perform Selection from the parents and the offsprings # * Replace the unfit individuals with the fit individuals to maintain a # constant population size. print('Starting search process...') for i in range (0, input_v['generations']): ## Select the parents ## Parents are selected for reproduction to generate offspring. The ## original NSGA-II uses a binary tournament selection based on the ## crowded-comparision operator. The arguments are ## pool - size of the mating pool. It is common to have this to be half the ## population size. ## tour - Tournament size. Original NSGA-II uses a binary tournament ## selection, but to see the effect of tournament size this is kept ## arbitary, to be choosen by the user. pool = int(round(input_v['population']/2)) tour = 2 ## Selection process ## A binary tournament selection is employed in NSGA-II. In a binary ## tournament selection process two individuals are selected at random ## and their fitness is compared. The individual with better fitness is ## selcted as a parent. Tournament selection is carried out until the ## pool size is filled. Basically a pool size is the number of parents ## to be selected. The input arguments to the function ## tournament_selection are chromosome, pool, tour. The function uses ## only the information from last two elements in the chromosome vector. ## The last element has the crowding distance information while the ## penultimate element has the rank information. Selection is based on ## rank and if individuals with same rank are encountered, crowding ## distance is compared. A lower rank and higher crowding distance is ## the selection criteria. parent_chromosome = tournament_selection(chromosome, pool, tour) ## Perfrom crossover and Mutation operator ## The original NSGA-II algorithm uses Simulated Binary Crossover (SBX) and ## Polynomial mutation. Crossover probability pc = 0.9 and mutation ## probability is pm = 1/n, where n is the number of decision variables. ## Both real-coded GA and binary-coded GA are implemented in the original ## algorithm, while in this program only the real-coded GA is considered. ## The distribution indeices for crossover and mutation operators as mu = 20 ## and mum = 20 respectively. mu = 20 mum = 20 offspring_chromosome, input_v = genetic_operator.genetic_operator(parent_chromosome, input_v['M'], input_v['V'], mu, mum, input_v['min_range'], input_v['max_range'], input_v,num_cores,activate_parallel) ##Intermediate population ##Intermediate population is the combined population of parents and offsprings of the current generation. The population ##size is two times the initial population. dim_chromosome = chromosome.shape main_pop = dim_chromosome[0] dim_offspring_chromosome = offspring_chromosome.shape offspring_pop = dim_offspring_chromosome[0] ##Intermediate_chromosome is a concatenation of current population and the offspring population. intermediate_chromosome = np.zeros((main_pop + offspring_pop, input_v['M'] + input_v['V'])) for j in range (0, main_pop): for k in range (0, input_v['M'] + input_v['V']): intermediate_chromosome[j,k] = chromosome[j,k] for j in range (main_pop, main_pop + offspring_pop): for k in range (0, input_v['M'] + input_v['V']): intermediate_chromosome[j,k] = offspring_chromosome[j-main_pop,k] ##Non-domination-sort of intermediate population ##The intermediate population is sorted again based on non-domination sort before the replacement operator is performed ##on the intermediate population. intermediate_chromosome = non_domination_sort_mod(intermediate_chromosome, input_v['M'], input_v['V']) ##np.savetxt('C:\\Optimization_zlc\\solution.csv', intermediate_chromosome, delimiter=',') ##sys.exit() ##Perform Selection ##Once the intermediate population is sorted only the best solution is selected based on it rank and crowding distance. ##Each front is filled in ascending order until the addition of population size is reached. The last front is included ##in the population based on the individuals with least crowding distance chromosome = replace_chromosome(intermediate_chromosome, input_v['M'], input_v['V'], input_v['population']) print('Search ' + 'iteration ' + str(i)) # if not(i%100) and (i !=0): # disp_msg = str(i) + ' generations completed \n' # print(disp_msg) ##Result ##Save the result in csv format xAll = input_v['xAll'] objAll = input_v['objAll'] np.savetxt(os.path.dirname(__file__)+'\\solution\\solution.csv', chromosome, delimiter=',') np.savetxt(os.path.dirname(__file__)+'\\solution\\solutionX.csv', xAll, delimiter=',') np.savetxt(os.path.dirname(__file__)+'\\solution\\solutionObj.csv', objAll, delimiter=',') ##Visualize ##The following is used to visualize the result if objective space dimension can be displayed i.e. 2D, 3D timing.log("NOW") if input_v['M'] == 2: ##Objective functions plt.plot(chromosome[:, input_v['V']], chromosome[:, input_v['V']+1], '*') plt.title('Objective function last population') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.show() ##All populations plt.plot(objAll[:, 0], objAll[:, 1], '*') plt.title('Objective function all populations') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.show() elif input_v['M'] == 3: ##Objective functions plt.plot(chromosome[:, input_v['V']], chromosome[:, input_v['V']+1], chromosome[:, input_v['V']+2], '*') plt.title('Objective function last population') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.zlabel('Objective 3') plt.show() ##All populations plt.plot(objAll[:,0], objAll[:,1], objAll[:,2], '*') plt.title('Objective function all populations') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.zlabel('Objective 3') plt.show() ##Copyright (c) 2009, Aravind Seshadri ##All rights reserved. ##Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following ##conditions are met: ## * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. ## * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer ## in the documentation and/or other materials provided with the distribution ## ##THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT ##NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL ##THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES ##(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ##HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ##ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
plt.show() # 3D graph (Multiple Regression) fig = plt.figure() ax = fig.add_subplot(111, projection="3d") ax.scatter(dataset_merged['distance'], dataset_merged['steps'], dataset_merged['calories'], c='blue', marker='o', s=10) ax.view_init(30, 185) plt.xlabel('Distance') plt.ylabel('Steps') plt.zlabel('Calories') plt.show() # Fitbit import pandas as pd import numpy as np import matplotlib.pyplot as plt fitbit_dataset = pd.read_csv('fitbit_activity_a.csv') fitbit_dataset['Steps'] = fitbit_dataset["Steps"].str.replace(",", "").astype(float) fitbit_dataset['Date'] = fitbit_dataset.Date.astype('datetime64[ns]') fitbit_dataset['Calories'] = fitbit_dataset["Calories"].str.replace( ",", "").astype(float) fitbit_dataset['Distance'] = fitbit_dataset['Distance'] * 1000
x = meters[i].sensors[j].x y = meters[i].sensors[j].y z = meters[i].sensors[j].z if j == 1 or j == 2 or j == 4: lr = left else: lr = right if j == 1 or j == 3: pos = pos1 elif j == 2 or j == 5: pos = pos2 else: pos = pos3 leg.append( ax.quiver(lr, pos, height, np.asarray(x), np.asarray(y), np.asarray(z), length=0.1, color=corder[j])) plt.xlabel("<--West East--> (m)") plt.ylabel("<--South North--> (m)") plt.zlabel('Height (m)') plt.title(input("Title?\n")) for i in range(num_sensors): plt.quiverkey(leg[i], 0.5, 0.9 - (i / 15), 25, "Sensor {}".format(i + 1)) plt.show()
def plot(self, key): assert len((self & key)) == 1 hist = (self & key).fetch1('data') edges = (self & key).fetch1('bin_edges') if len(hist.shape) == 1: plt.figure() plt.plot(edges['0'][0][:-1], hist) sns.despine() plt.xlabel(key['morph_dist_name']) plt.ylabel('P(x)') elif len(hist.shape) == 2: plt.figure() if key['morph_dist_name'] == 'path angle vs branch order': xlabel = 'path angle [deg]' ylabel = 'branch order' elif key['morph_dist_name'] == 'path angle vs path dist': xlabel = 'path angle [deg]' ylabel = 'dist from soma [microns]' elif key['morph_dist_name'] == 'thickness vs path dist': xlabel = 'thickness [microns]' ylabel = 'dist from soma [microns]' elif key['morph_dist_name'] == 'thickness vs branch order': xlabel = 'thickness [microns]' ylabel = 'branch order' elif key['morph_dist_name'] == 'branch angle vs path dist': xlabel = 'branch angle [deg]' ylabel = 'dist from soma [microns]' elif key['morph_dist_name'] == 'branch angle vs branch order': xlabel = 'branch angle [deg]' ylabel = 'branch order' elif key[ 'morph_dist_name'] == 'segment path length vs branch order': xlabel = 'segment path length' ylabel = 'branch order' plt.imshow(hist.T, extent=[0, edges['0'][0][-1], 0, edges['1'][0][-1]]) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.colorbar() elif len(hist.shape) == 3: x, y, z = np.meshgrid(edges['0'][0], edges['1'][0], edges['2'][0], indexing='ij') fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter3D(x, y, z, s=hist.flatten()) plt.xlabel('x') plt.ylabel('y') plt.zlabel('z')
def GeneratePlotResults(full_dataset, methods, output_dir, plots, results, methods_d, fnames_i, title): plot_files = [] for i in range(len(plots)): handles, labels = [], [] fig = plt.figure(i + 1) plt.clf() plot = plots[i] if 'xlim' in plot: plt.xlim(plot['xlim'][0], plot['xlim'][1]) if 'ylim' in plot: plt.ylim(plot['ylim'][0], plot['ylim'][1]) for a in plots[i]['methods']: m = a['name'] if not m in methods_d: continue print str(i) + ' ' + str(m) line_style = a['line_style'] if 'line_style' in a else methods_d[ m]['line_style'] color = a['color'] if 'color' in a else methods_d[m]['color'] if plot['type'] == 'skill': plot = copy.deepcopy(plots[i]) plot['type'] = 'scatter' if len( full_dataset.skill_names) <= 2 else 'scatter3d' if not 'xlabel' in plot: plot['xlabel'] = full_dataset.skill_names[0] if not 'ylabel' in plot: plot['ylabel'] = full_dataset.skill_names[1] if not 'zlabel' in plot and len(full_dataset.skill_names) > 2: plot['zlabel'] = full_dataset.skill_names[2] if not 'x' in a: a['x'] = 'skill0' if not 'y' in a: a['y'] = 'skill1' if not 'z' in a and len(full_dataset.skill_names) > 2: a['z'] = 'skill2' if plot['type'] == 'semilog': print str(len(results[m][a['x']])) + ' ' + str( len(results[m][a['y']])) h = plt.semilogy(results[m][a['x']], results[m][a['y']], line_style, lw=plot["line-width"], color=color) handles.append(h[0]) elif plot['type'] == 'loglog': h = plt.loglog(results[m][a['x']], results[m][a['y']], line_style, lw=plot["line-width"], color=color) handles.append(h[0]) elif plot['type'] == 'plot': h = plt.plot(results[m][a['x']], results[m][a['y']], line_style, lw=plot["line-width"]) handles.append(h[0]) elif plot['type'] == 'hist': if 'y' in a: h = plt.hist(results[m][a['x']], results[m][a['y']], histtype='bar', rwidth=plot["bar-width"], color=plot["bar-color"]) else: h = plt.hist(results[m][a['x']], histtype='bar', rwidth=plot["bar-width"], color=plot["bar-color"]) handles.append(h[0]) elif plot['type'] == 'scatter': h = plt.scatter(results[m][a['x']], results[m][a['y']], c='r', marker='o') handles.append(h) elif plot['type'] == 'scatter3d': ax = fig.add_subplot(111, projection='3d') h = ax.scatter(results[m][a['x']], results[m][a['y']], results[m][a['z']], c='r', marker='o') handles.append(h) labels.append(a['title'] if 'title' in a else m) if plot['type'] == 'scatter3d': if 'xlabel' in plot: ax.set_xlabel(plot['xlabel'], fontsize=plot['axis-font-size']) if 'ylabel' in plot: ax.set_ylabel(plot['ylabel'], fontsize=plot['axis-font-size']) if 'zlabel' in plot: ax.set_zlabel(plot['zlabel'], fontsize=plot['axis-font-size']) else: if 'xlabel' in plot: plt.xlabel(plot['xlabel'], fontsize=plot['axis-font-size']) if 'ylabel' in plot: plt.ylabel(plot['ylabel'], fontsize=plot['axis-font-size']) if 'zlabel' in plot: plt.zlabel(plot['zlabel'], fontsize=plot['axis-font-size']) if 'title' in plot: plt.title(plot['title'], fontsize=plot['title-font-size']) plt.tick_params(axis='both', which='major', labelsize=plot['tick-font-size']) plt.tick_params(axis='both', which='minor', labelsize=plot['tick-font-size']) if 'legend' in plot: plt.legend(handles, labels, prop={'size': plot['legend-font-size']}) plt.savefig(os.path.join('output', output_dir, plot['name'] + '.pdf')) plt.savefig(os.path.join('output', output_dir, plot['name'] + '.png')) plot_files.append(output_dir + '/' + plot['name'] + '.png') with open(os.path.join('output', output_dir, 'galleries.json'), 'w') as f: json.dump({ 'plots': plot_files, 'methods': fnames_i, 'title': title }, f)
def plot_results(mode,sp,x,xT,args): if not args or not args[0]: b_obs = False else: b_obs = True obs = args[0] d, _, nbSPoint = x.shape if mode=='i': if d==2: sp['fig'] = plt.figure(num=0) #,'2D Simulation of the task',figsize=(653 550 560 420) plt.title(r'2D Simulation of the task') sp['axis'] = plt.gca() hold(True) sp['xT'] = plt.plot(xT[0],xT[1],'k*', markersize=10, linewidth=1.5) sp['xT_l'] = plt.plot(xT[0],xT[1],'k--', linewidth=1.5) for j in range(nbSPoint): plot(x[0,0,j],x[1,0,j],'ok',markersize=2,linewidth=7.5) sp['x['str(j)']']= plot(x[0,0,j],x[1,0,j]) plt.xlabel(r'$\xi_1$',interpreter=latex,fontsize=16) plt.ylabel(r'$\xi_2$',interpreter=latex,fontsize=16) plt.show() if b_obs: x_obs, x_obs_sf = obs_draw_ellipsoid(obs,40) for n in range(x_obs.shape[3]): sp['obs'][n] = patch(x_obs[0,:,n],x_obs[1,:,n],0.1*np.ones((1,x_obs.shape[2])),[0.6 1 0.6]) sp['obs_sf'][n] = plot(x_obs_sf[0,:,n],x_obs_sf[1,:,n],'k--',linewidth=0.5) elif d==3: sp['fig'] = plt.figure(num=0) plt.title('3D Simulation of the task') sp['axis'] = plt.gca() ax = sp['fig'].add_subplot(111, projection='3d') sp['xT'] = ax.plot(xT[0],xT[1],xT[2],'k*',markersize=10,linewidth=1.5) sp['xT_l'] = ax.plot(xT[0],xT[1],xT[2],'k--',linewidth=1.5) for j in range(0, nbSPoint-1): ax.plot(x[0,0,j],x[1,0,j],x[2,0,j],markersize=2,linewidth=7.5) sp['x'][j]= ax.plot(x[0,0,j],x[1,0,j],x[2,0,j]) if b_obs: n_theta = 15 n_phi = 10 x_obs = obs_draw_ellipsoid(obs,[n_theta, n_phi]) for n in range(0, np.size(x_obs,2) - 1): sp['obs'][n] = ax.plot_surface(np.reshape(x_obs[0,:,n],n_phi,n_theta), np.reshape(x_obs[1,:,n],n_phi,n_theta), np.reshape(x_obs[2,:,n],n_phi,n_theta)) plt.setp(sp['obs'][n],color=[0.6, 1, 0.6],linewidth=0.1) plt.xlabel(r'$\xi_1$',interpreter=latex,fontsize=16) plt.ylabel(r'$\xi_2$',interpreter=latex,fontsize=16) plt.zlabel(r'$\xi_3$',interpreter=latex,fontsize=16) plt.show() else: sp['fig'] = plt.figure(num=0) plt.title('Simulation of the task') for i in range(1, d-1): sp.['axis'][i-1]=sp['fig'].add_subplot(d-1,0,i-1) sp['xT'][i-1] = plt.plot(xT[0],xT[i],'k*',markersize=10,linewidth=1.5) sp.['xT_l'][i-1] = plt.plot(xT[0],xT[i],'k--',linewidth=1.5) for j in range(0, nbSPoint - 1): plt.plot(x[0,0,j],x[i,0,j],markersize=2,linewidth=7.5); sp['x'][i-1,j]= plt.plot(x[0,0,j],x[i,0,j]) plt.ylabel(r'$\xi_' + str(i) + '$',interpreter=latex,fontsize=12) if i==d : plt.xlabel(r'$\xi_1$',interpreter=latex,fontsize=12); plt.show() if mode=='u': #updating the figure if plt.gcf() != sp['fig']: plt.figure(sp['fig']) if d==2: ax=sp['axis']; for j in range(0, nbSPoint - 1): sp['x'][j].set_xdata(x[1,:,j]) sp['x'][j].set_ydata(x[1,:,j]) if np.maximum(x[0,end,:])>ax.get_xlim(1) or np.minimum(x[0,end,:])<ax.get_xlim(0) or np.maximmum(x[1,end,:])>ax.get_ylim(1) or np.minimum(x[1,end,:])<ax.get_ylim(0): plt.autoscale(enable=True, axis=sp['axis'], tight=True) ax=sp['axis']; sp['fig'].add_subplot(ax, [ax.get_xlim(0)-(ax.get_xlim(1)-ax.get_xlim(0))/10, ax.get_xlim(1)+(ax.get_xlim(1)-ax.get_xlim(0))/10, ax.get_ylim(0)-(ax.get_ylim(1)-ax.get_ylim(0))/10 ax.get_ylim(1)+(ax.get_ylim(1)-ax.get_ylim(0))/10]) elif d==3: ax=sp['axis']; for j in range(0, nbSPoint - 1): sp.['x'][j].set_xdata(x[0,:,j]) sp.['x'][j].set_ydata(x[1,:,j]) sp.['x'][j].set_zdata(x[2,:,j]) if np.maximum(x[0,end,:])>ax.get_xlim(1) or np.minimum(x[0,end,:])<ax.get_xlim(0) or np.maximum(x[1,end,:])>ax.get_ylim(1) or np.minimum(x[1,end,:])<ax.get_ylim(1) or np.maximum(x[2,end,:])>ax.get_zlim(1) or np.minimum(x[2,end,:])<ax.get_zlim(0): plt.autoscale(enable=True, axis=sp['axis'], tight=True) ax=sp['axis'] sp['fig'].add_subplot(ax, get_xlim(0)-(ax.get_xlim(1)-ax.get_xlim(0))/10, ax.get_xlim(1)+(ax.get_xlim(1)-ax.get_xlim(0))/10, ax.get_ylim(0)-(ax.get_ylim(1)-ax.get_ylim(0))/10 ax.get_ylim(1)+(ax.get_ylim(1)-ax.get_ylim(0))/10, ax.get_zlim(0)-(ax.get_zlim(1)-ax.get_zlim(0))/10 ax.get_zlim(1)+(ax.get_zlim(1)-ax.get_zlim(0))/10])
## plt.show() ## savefig('Pressure_at_left.png') # ---- VELOCITY ---- # y = 0.0 fig = plt.figure() ax = fig.gca(projection='3d') for j in range(40,78) u = [] for k in range(1,nRows): u.append(a[k][j]) ax.plot(time, u, y) y = y+0.021875 plt.xlabel('time [sec]') plt.ylabel('velocity [m/s]') plt.zlabel('height [m]') plt.suptitle('Velocity') plt.grid(True) plt.show() savefig('Velocities_at_left.png') ##################################################################################### ### Print an output file to validate the results ## maxPressureCal = max(pressure2) ## maxPressureRef = 999.53 ## err = 100*abs(maxPressureRef-maxPressureCal)/maxPressureRef ## val = open('validation_pressure.txt', 'w') ## val.write('Only for gauges taken at (x,y)=(0.5,0.5)'+'\n') ## val.write('Maximum pressure:'+'\n') ## val.write('Reference'+'\t'+'Simulation'+'\t'+'\t'+'Error'+'\n')
import matplotlib.pyplot as plt import pyexcel as p graph = p.get_excel('/home/cl311/Rathi/xyzgraph.csv') plt.plot(x, y, z) plt.xlabel("X AXIS") plt.ylabel("Y AXIS") plt.zlabel("Z AXIS") plt.title("PLOTTING A GRAPH FROM EXCEL") plt.show()
from sklearn.preprocessing import MinMaxScaler import warnings warnings.filterwarnings("ignore") import matplotlib.pyplot as plt for i in range(1,2): filename = "./data_skin/skin_benchmark_"+'{0:04}'.format(i)+".csv" df = pd.read_csv(filename) print(df.describe()) show = False if show: plt.figure(figsize=(10,10)) plt.scatter(df['R'],df['G'],df['B']) plt.xlabel("R") plt.ylabel("G") plt.zlabel("B") plt.show() scaler = MinMaxScaler(feature_range=(0,1)) df[['R','G','B']] = scaler.fit_transform(df[['R','G','B']]) print(df[['R','G','B']].head()) t1=df['ground.truth'].value_counts(normalize=True) t2=df['ground.truth'].value_counts(normalize=False) x1 = df['R'].values.reshape(-1,1) x2 = df['G'].values.reshape(-1,1) x3 = df['B'].values.reshape(-1,1) x = np.concatenate((x1,x2,x3),axis=1) # 设置离群点数据 random_state = np.random.RandomState(42) outliers_fraction = t1["anomaly"]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 18 16:40:48 2018 @author: mmvillangca tri-surface from point cloud """ from mpl_toolkits.mplot3d import Axes3D import matplotlib.pyplot as plt import numpy as np coor = np.loadtxt('insertPointCloudFileHere.txt') x = coor[:, 0] y = coor[:, 1] z = coor[:, 2] fig = plt.figure() ax = fig.gca(projection='3d') ax.set_aspect('equal') ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True, shade=True) plt.xlabel('x', fontsize=14) plt.ylabel('y', fontsize=14) plt.zlabel('y', fontsize=14) plt.show()
def plot_trajectory(self): font1 = { 'family': 'Times New Roman', 'weight': 'normal', 'size': 20, } font2 = { 'family': 'Times New Roman', 'weight': 'normal', 'size': 18, } fig = plt.figure(figsize=(10, 10)) if self.plot_3d: ax1 = fig.add_subplot(111, projection='3d') else: ax1 = fig.add_subplot(111) Gt_traj = self.GtPose[:, :3, 3] if self.rotate: rotate_theta = -np.pi / 4 Gt_traj = np.dot( Gt_traj, np.array([[np.cos(rotate_theta), -np.sin(rotate_theta)], [np.sin(rotate_theta), np.cos(rotate_theta)]])) if self.plot_3d: ax1.plot(Gt_traj[:, 0], Gt_traj[:, 1], Gt_traj[:, 2], '--', linewidth=4, color='k') else: ax1.plot(Gt_traj[:, 0], Gt_traj[:, 2], '--', linewidth=4, color='k') Lo_traj = self.LoPose[:, :3, 3] if self.rotate: rotate_theta = np.pi Lo_traj = np.dot( Lo_traj, np.array([[np.cos(rotate_theta), -np.sin(rotate_theta)], [np.sin(rotate_theta), np.cos(rotate_theta)]])) if self.plot_3d: ax1.plot(Lo_traj[:, 0], Lo_traj[:, 1], Lo_traj[:, 2], linewidth=4, color='r') else: ax1.plot(Lo_traj[:, 0], Lo_traj[:, 2], linewidth=4, color='r') if self.plot_loop_closure: Ls_traj = self.LsPose[:, :3, 3] if self.rotate: rotate_theta = np.pi Ls_traj = np.dot( Ls_traj, np.array([[np.cos(rotate_theta), -np.sin(rotate_theta)], [np.sin(rotate_theta), np.cos(rotate_theta)]])) if self.plot_3d: ax1.plot(Ls_traj[:, 0], Ls_traj[:, 1], Ls_traj[:, 2], linewidth=4, color='b') else: ax1.plot(Ls_traj[:, 0], Ls_traj[:, 2], linewidth=4, color='b') plt.tick_params(labelsize=14) labels = ax1.get_xticklabels() + ax1.get_yticklabels() [label.set_fontname('Times New Roman') for label in labels] #plt.title('Comparison of trajectory') if self.plot_3d: plt.xlabel('x(m)', font2) plt.ylabel('y(m)', font2) plt.zlabel('z(m)', font2) else: plt.xlabel('x(m)', font2) plt.ylabel('z(m)', font2) plt.axis("equal") if self.plot_loop_closure: plt.legend(('Ground truth', 'Lidar odometry', 'Lidar SLAM'), prop=font1) else: plt.legend(('Ground truth', 'Lidar odometry'), prop=font1) plt.savefig(self.saving_path + "_trajectory.jpg", dpi=500) plt.show()
clusterNum = 3 k_means = KMeans(init="k-means++", n_clusters=clusterNum, n_init=12) k_means.fit(X) labels = k_means.labels_ df["Clus_km"] = labels df.head(5) df.groupby('Clus_km').mean() area = np.pi * (X[:, 1])**2 plt.scatter(X[:, 0], X[:, 3], s=area, c=labels.astype(np.float), alpha=0.5) plt.xlabel('Age', fontsize=18) plt.ylabel('Income', fontsize=16) plt.show() fig = plt.figure(1, figsize=(8, 6)) plt.clf() ax = Axes3D(fig, rect=[0, 0, .95, 1], elev=48, azim=134) plt.cla() plt.ylabel('Age', fontsize=18) plt.xlabel('Income', fontsize=16) plt.zlabel('Education', fontsize=16) ax.set_xlabel('Education') ax.set_ylabel('Age') ax.set_zlabel('Income') ax.scatter(X[:, 1], X[:, 0], X[:, 3], c=labels.astype(np.float))
# calculate the function value: z = x^2 + sin(y^2) Z = (X**2) + np.sin(Y**2) # initialize the 3D figure fig = plt.figure(figsize=(10, 6)) ax = fig.gca(projection='3d') # plot the surface ax.plot_surface(X, Y, Z, cmap='Reds') # add labels plt.xlabel('x') plt.ylabel('y') plt.title('f(x, y)') plt.zlabel('z') plt.show() # Let's take a step further and plot the 3D surface side-by-side with the slices. Run this code **as-is** and play around with the interactive sliders. # # **NOTE:** The code may be slow to refresh, so be patient. # In[74]: def plot_surface_problem3(x0, y0): # resolution delta = 0.1
def nsga_2(input_v, activate_parallel, num_cores, crossover_perc, mutation_perc, obj_func_plot): ##import sys import numpy as np from objective_description_function import objective_description_function from initialize_variables import initialize_variables from non_domination_sort_mod import non_domination_sort_mod from tournament_selection import tournament_selection import genetic_operator_adv from replace_chromosome import replace_chromosome import matplotlib.pyplot as plt from ga_mono_binary_conv_info import ga_mono_binary_conv_info print('Running Optimization...') input_v['objAll'] = [] input_v['xAll'] = [] import os import timing import time ##Making sure thet population and generations are integers input_v['population'] = round(input_v['population']) input_v['generations'] = round(input_v['generations']) bin_info_variable_list = ga_mono_binary_conv_info( input_v['range_of_decision_variables']) total_binary_len = sum(bin_info_variable_list['Bits'][:]) ##Forming the objective function ##input_v['M'] --- number of objective functions ##input_v['V'] --- number of decision variables ##input_v['min_range'] --- list of corresponding lowerbound of the decision variables ##input_v['max_range'] --- list of corresponding upperbound of the decision variables input_v['M'], input_v['V'], input_v['min_range'], input_v[ 'max_range'] = objective_description_function(input_v) ##Initialize the population ##Population is initialzied with random values which are within the specified range. Each chromosome consist of the ##decision variables. Also the value fo the objective functions, rank and crowding distance information are also added ##to the chromosome vector but only the elements of the vector which has the decision variables are operatedupon to ##perform the genetic operations like crossover and mutation chromosome, input_v = initialize_variables(input_v, activate_parallel, num_cores, bin_info_variable_list) ##Sort the initialized population ##Sort the population using non-domination-sort. This returns two columns for each individual which are the rank and the ##crowding distance corresponding to their position in the front they belong. At this stage the rank and the crowding distance ##for each chromosome is added to the chromosome vector for easy of computation. chromosome = non_domination_sort_mod(chromosome, input_v['M'], input_v['V']) ## Start the evolution process # The following are performed in each generation # * Select the parents which are fit for reproduction # * Perfrom crossover and Mutation operator on the selected parents # * Perform Selection from the parents and the offsprings # * Replace the unfit individuals with the fit individuals to maintain a # constant population size. ##Generating probability reference for the mutation process mutation_prob = mutation_probab(bin_info_variable_list, total_binary_len) axes = plt.gca() print('Starting search process...') for i in range(0, input_v['generations']): ## Select the parents ## Parents are selected for reproduction to generate offspring. The ## original NSGA-II uses a binary tournament selection based on the ## crowded-comparision operator. The arguments are ## pool - size of the mating pool. It is common to have this to be half the ## population size. ## tour - Tournament size. Original NSGA-II uses a binary tournament ## selection, but to see the effect of tournament size this is kept ## arbitary, to be choosen by the user. pool = int(round(input_v['population'] / 2)) tour = 2 ## Selection process ## A binary tournament selection is employed in NSGA-II. In a binary ## tournament selection process two individuals are selected at random ## and their fitness is compared. The individual with better fitness is ## selcted as a parent. Tournament selection is carried out until the ## pool size is filled. Basically a pool size is the number of parents ## to be selected. The input arguments to the function ## tournament_selection are chromosome, pool, tour. The function uses ## only the information from last two elements in the chromosome vector. ## The last element has the crowding distance information while the ## penultimate element has the rank information. Selection is based on ## rank and if individuals with same rank are encountered, crowding ## distance is compared. A lower rank and higher crowding distance is ## the selection criteria. parent_chromosome = tournament_selection(chromosome, pool, tour) ## Perfrom crossover and Mutation operator ## The original NSGA-II algorithm uses Simulated Binary Crossover (SBX) and ## Polynomial mutation. Crossover probability pc = 0.9 and mutation ## probability is pm = 1/n, where n is the number of decision variables. ## Both real-coded GA and binary-coded GA are implemented in the original ## algorithm, while in this program only the real-coded GA is considered. ## The distribution indeices for crossover and mutation operators as mu = 20 ## and mum = 20 respectively. mu = 20 mum = 20 parent_chrom_bin = conv_dec_to_bin(bin_info_variable_list, parent_chromosome, input_v['M']) offspring_chromosome, input_v = genetic_operator_adv.genetic_operator_adv( parent_chrom_bin, mutation_prob, input_v, bin_info_variable_list, activate_parallel, num_cores) ##Intermediate population ##Intermediate population is the combined population of parents and offsprings of the current generation. The population ##size is two times the initial population. dim_chromosome = chromosome.shape main_pop = dim_chromosome[0] dim_offspring_chromosome = offspring_chromosome.shape offspring_pop = dim_offspring_chromosome[0] ##Intermediate_chromosome is a concatenation of current population and the offspring population. intermediate_chromosome = np.zeros( (main_pop + offspring_pop, input_v['M'] + input_v['V'])) for j in range(0, main_pop): for k in range(0, input_v['M'] + input_v['V']): intermediate_chromosome[j, k] = chromosome[j, k] for j in range(main_pop, main_pop + offspring_pop): for k in range(0, input_v['M'] + input_v['V']): intermediate_chromosome[j, k] = offspring_chromosome[j - main_pop, k] ##Non-domination-sort of intermediate population ##The intermediate population is sorted again based on non-domination sort before the replacement operator is performed ##on the intermediate population. intermediate_chromosome = non_domination_sort_mod( intermediate_chromosome, input_v['M'], input_v['V']) ##np.savetxt('C:\\Optimization_zlc\\solution.csv', intermediate_chromosome, delimiter=',') ##sys.exit() ##Perform Selection ##Once the intermediate population is sorted only the best solution is selected based on it rank and crowding distance. ##Each front is filled in ascending order until the addition of population size is reached. The last front is included ##in the population based on the individuals with least crowding distance chromosome = replace_chromosome(intermediate_chromosome, input_v['M'], input_v['V'], input_v['population']) if obj_func_plot == 'yes': plt.plot(chromosome[:, input_v['V']], chromosome[:, input_v['V'] + 1], '*') plt.title('Objective function last population') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.draw() plt.pause(1e-17) axes.clear() print('Search ' + 'iteration ' + str(i)) # if not(i%100) and (i !=0): # disp_msg = str(i) + ' generations completed \n' # print(disp_msg) ##Result ##Save the result in csv format xAll = input_v['xAll'] objAll = input_v['objAll'] np.savetxt(os.path.dirname(__file__) + '\\solution\\solution.csv', chromosome, delimiter=',') np.savetxt(os.path.dirname(__file__) + '\\solution\\solutionX.csv', xAll, delimiter=',') np.savetxt(os.path.dirname(__file__) + '\\solution\\solutionObj.csv', objAll, delimiter=',') ##Visualize ##The following is used to visualize the result if objective space dimension can be displayed i.e. 2D, 3D timing.log("NOW") if input_v['M'] == 2: ##Objective functions plt.plot(chromosome[:, input_v['V']], chromosome[:, input_v['V'] + 1], '*') plt.title('Objective function last population') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.show() ##All populations plt.plot(objAll[:, 0], objAll[:, 1], '*') plt.title('Objective function all populations') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.show() elif input_v['M'] == 3: ##Objective functions plt.plot(chromosome[:, input_v['V']], chromosome[:, input_v['V'] + 1], chromosome[:, input_v['V'] + 2], '*') plt.title('Objective function last population') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.zlabel('Objective 3') plt.show() ##All populations plt.plot(objAll[:, 0], objAll[:, 1], objAll[:, 2], '*') plt.title('Objective function all populations') plt.xlabel('Objective 1') plt.ylabel('Objective 2') plt.zlabel('Objective 3') plt.show()
# numbers of limes of different species sold each month key_limes_per_month = [92.0, 109.0, 124.0, 70.0, 101.0, 79.0, 106.0, 101.0, 103.0, 90.0, 102.0, 106.0] persian_limes_per_month = [67.0, 51.0, 57.0, 54.0, 83.0, 90.0, 52.0, 63.0, 51.0, 44.0, 64.0, 78.0] blood_limes_per_month = [75.0, 75.0, 76.0, 71.0, 74.0, 77.0, 69.0, 80.0, 63.0, 69.0, 73.0, 82.0] plt.figure(figsize=12,8) ax1=plt.subplot(1,2,1) x_values=range(len(12)) plt.plot(x_values,visits_per_month,marker='*') plt.title('Amount of visits per months') plt.xlabel('Months') plt.ylabel('Visits') ax.set_xticks(x_values) ax.set_xticklabels(months) #ax.set_yticks([0.10, 0.25, 0.5, 0.75]) #ax.set_yticklabels(["10%", "25%", "50%", "75%"]) ax2=plt.subplot(1,2,2) plt.plot(persian_limes_per_month,months,marker='s') plt.plot([x_values, key_limes_per_month,color='orange'],[x_values,persian_limes_per_month,color='blue'],[x_values,blood_limes_per_month,color='purple'])#nose si es asi plt.xlabel('key limes') plt.ylabel('persian limes') plt.zlabel('blood limes') ax.set_xticks(x_values) ax.set_xticklabels(months) plt.title('LIMES') plt.savefig('plot.png') plt.show()
import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm fig = plt.figure() fig.clf() ax = fig.gca(projection='3d') plt.xlabel('MAX') plt.ylabel('NUM') plt.zlabel('AVG') ax.scatter(x, y, z) ax.set_zlim(0.2, 0.5) ax.set_xlabel('Max features') ax.set_ylabel('Num estimator') ax.set_zlabel('Avg accuracy') plt.show()
x_coord = np.empty(core.size) y_coord = np.empty(core.size) z_coord = np.empty(core.size) p_size = np.empty(core.size) for i in range(core.shape[0]): for j in range(core.shape[1]): for k in range(core.shape[2]): x_coord[i*core.shape[1]*core.shape[2] + j*core.shape[2] + k] = i y_coord[i*core.shape[1]*core.shape[2] + j*core.shape[2] + k] = j z_coord[i*core.shape[1]*core.shape[2] + j*core.shape[2] + k] = k p_size[i*core.shape[1]*core.shape[2] + j*core.shape[2] + k] = core[i,j,k]* 5 fig = plt.figure() ax = Axes3D(fig) plt.xlabel('neurons') plt.ylabel('stimulus category') plt.zlabel('time slot') ax.scatter(x_coord, y_coord, z_coord, s=np.abs(p_size)) plt.show() time_good = np.zeros(8) for i in range(8): time_good[i] = np.sum(core[:,:,:(i+1)]) / np.sum(core) plt.title('Representation power on Time') plt.xlabel('# of PCs') plt.ylabel('Accum % of total variance') plt.plot(time_good) plt.show() stimulus_good = np.zeros(8) for i in range(8):