def extract_metric(self, trip, metric): """ method to extract 'metric' from dict 'trip' returned by QPX API must support all metrics defined in self.supported_metrics """ if metric == 'Sale Total, USD': return np.float(trip['saleTotal'][3:]) elif metric == 'Number of Layovers': return len(trip['slice'][0]['segment']) - 1 elif metric == 'Total Flight Duration, Hours': return trip['slice'][0]['duration'] / 60 elif metric == 'Hours In Air': set_trace() elif metric == 'Hours In Layover': set_trace()
def init_results(self): """ method to intialize the results tab from currrent selection, runs: -- when flight-results tab is pressed -- when flight origin combo is changed -- when flight metric combo box is changed """ # set local hooks for data and selected flight configurations # (flight data is guaranteed to exist at this point) data = self.flight_data config = self.getContents(checked=True) # update the origin combo box if necessary, unwire the combo action # temporarily to avoid a recursive call while the combo updates if len(config[0]) != self.origin_combo.count(): self.origin_combo.currentIndexChanged.disconnect() self.origin_combo.clear() self.origin_combo.addItems(config[0]) self.origin_combo.currentIndexChanged.connect(self.init_results) # get current selected origin, selected dests, selected dates, and # current selected flight metric origin = config[0][self.origin_combo.currentIndex()] dests = config[1] dates = [time.strftime('%Y-%m-%d', time.strptime(x, self.format)) for x in config[2]] metric = self.supported_metrics[self.metric_combo.currentIndex()] # get numpy 3-dimensional array, where each number is the 'metric' for: # dim-0 -> destination # dim-1 -> date # dim-2 -> flight number, from 0 to self.n_flights-1 plot_data = np.full((len(dests), len(dates), self.n_flights), np.nan) for i, dest in enumerate(dests): for j, date in enumerate(dates): trips = data[origin][dest][date]['trips']['tripOption'] for k, trip in enumerate(trips): plot_data[i, j, k] = self.extract_metric(trip, metric) # find the maximum number of trip options available for all flights # set the radio button with the appropriate text label n = [[len(data[origin][dest][date]['trips']['tripOption']) for dest \ in dests] for date in dates] n_min = min([min(x) for x in n]) if str(n_min)[-1:] == 1: n_min = str(n_min) + 'st' if str(n_min)[-1:] == 2: n_min = str(n_min) + 'nd' if str(n_min)[-1:] == 3: n_min = str(n_min) + 'rd' else: n_min = str(n_min) + 'th' self.radio_button_n.setText('Show 1st to {}\nLeast Expensive Flights'. format(n_min)) # clear the current figure, create a new axes self.figure.clf() self.figure.canvas.draw() ax = self.figure.add_subplot(111) # set the x-axis as the dates, set the width of the bars xdata = np.arange(len(dates)) frac_width = 0.8 width = frac_width / len(dests) # get a matplotlib color cycle colors = [plt.cm.gist_heat(x) for x in np.linspace(0, 0.9, len(dests))] # create a different plot type based on the 1 or 1 to n flight selection if self.radio_button_1.isChecked(): # initialize a numpy array for the bar plot objects, then create them bars = np.empty(len(dests), dtype='O') for i, dest in enumerate(dests): bars[i] = ax.bar(xdata+width*i, plot_data[i, :, 0], width, color=colors[i]) elif self.radio_button_1.isChecked(): set_trace() # clean up ax.set_xlim((xdata[0] - width/2, xdata[-1] + len(dests)*width + width/2)) ax.legend(bars, dests, loc='upper left', bbox_to_anchor=(0.985, 1.025), title='Flight\nDestination', fontsize=16, fancybox=True, shadow=True, frameon=True).get_title().set_fontsize(16) ax.set_title(metric, fontsize=20, fontweight='bold') ax.set_xticks(xdata + frac_width / 2) xticks = [time.strftime(r'%-d %b%n%Y', time.strptime(x, self.format)) for x in config[2]] ax.set_xticklabels(xticks) self.figure.tight_layout() ax.grid(False, axis='x') plt.subplots_adjust(right=0.79, bottom=0.10) # update the figure canvas self.figure.canvas.draw()