def apply_data_set_fields_all(plotgui): """ Apply the values in the data set window to all sets. This routine reads the values in the plotgui.data_set_window and applies these to all data sets on the list. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object Returns ------- None """ index = plotgui.set_list_area.current() for loop in range(plotgui.nsets): plotgui.set_list_area.current(newindex=loop) if loop == index: apply_data_set_fields(plotgui, use_label=True) else: apply_data_set_fields(plotgui, use_label=False) plotgui.set_list_area.current(newindex=index) make_plot.make_plot(plotgui)
def delete_set(plotgui): """ Carry out clearing a data set from the variables. This is a work routine that takes the input for deleting a set, checks with the user, and if requested removes a set from the list. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object Returns ------- None """ ind1 = plotgui.set_list_area2.current() if (ind1 >= 0) and (ind1 < plotgui.nsets): response = tkinter.messagebox.askyesno( 'Verify', 'Do you really want to remove set %d?' % (ind1 + 1)) if response: if plotgui.nsets > 0: plotgui.nsets = plotgui.nsets - 1 for loop in range(ind1, plotgui.nsets): plotgui.set_properties[loop] = deepcopy( plotgui.set_properties[loop + 1]) plotgui.xdata[loop] = deepcopy(plotgui.xdata[loop + 1]) plotgui.ydata[loop] = deepcopy(plotgui.ydata[loop + 1]) plotgui.xdata[plotgui.nsets + 1] = None plotgui.ydata[plotgui.nsets + 1] = None plotgui.set_properties[plotgui.nsets + 1]['symbol'] = None plotgui.set_properties[plotgui.nsets + 1]['symbolsize'] = 4.0 plotgui.set_properties[plotgui.nsets + 1]['linestyle'] = 'None' plotgui.set_properties[plotgui.nsets + 1]['linewidth'] = 1.0 plotgui.set_properties[plotgui.nsets + 1]['colour'] = 'black' plotgui.set_properties[plotgui.nsets + 1]['label'] = '' plotgui.set_properties[plotgui.nsets + 1]['xmin'] = 0.0 plotgui.set_properties[plotgui.nsets + 1]['xmax'] = 0.0 plotgui.set_properties[plotgui.nsets + 1]['ymin'] = 0.0 plotgui.set_properties[plotgui.nsets + 1]['ymax'] = 0.0 plotgui.set_properties[plotgui.nsets + 1]['display'] = True plotgui.set_properties[plotgui.nsets + 1]['errors'] = False plotgui.set_properties[plotgui.nsets + 1]['legend'] = True plotgui.set_properties[plotgui.nsets + 1]['plot'] = 1 make_plot.make_plot(plotgui) # revise the set list area setlist = [] for loop in range(plotgui.nsets): label = ( 'Set %3d: %5d points, x range %13.6g to %13.6g, ' % (loop + 1, len(plotgui.xdata[loop]['values']), plotgui.xdata[loop]['minimum'], plotgui.xdata[loop]['maximum']) + ' y range %13.6g to %13.6g' % (plotgui.ydata[loop]['minimum'], plotgui.ydata[loop]['maximum'])) setlist.append(label) plotgui.set_list_area2['values'] = setlist
def clear_labels(plotgui): """ Clear all the labels on the plot. This routine is called when the "Clear Labels" button is pressed. It asks whether the labels should be cleared, and if so all labels are removed. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ response = tkinter.messagebox.askyesno("Verify", "Delete all labels.") if response: plotgui.label_flag = False plotgui.plot_labels = [] plotgui.max_labels = 100 for loop in range(plotgui.max_labels): plotgui.plot_labels.append({'xposition': None, 'yposition': None, 'labelstring': '', 'plot': 1, 'colour': 'black', 'size': 12, # 'font': 'sans-serif', 'font': 'times new roman', 'fontweight': 'normal'}) plotgui.positions = [] make_plot.make_plot(plotgui)
def hide_selected_plot(plotgui): """ Set a plot to be hidden, if there are multiple plots. The routine here brings up a window wherein the user can select the current plot number in the case where several plots are displayed. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object Returns ------- None """ try: n1 = int(plotgui.hideplot_select.get()) if (n1 < 1) | (n1 > plotgui.number_of_plots): raise ValueError plotgui.hide_subplot[n1 - 1] = not plotgui.hide_subplot[n1 - 1] plotnumber = plotgui.current_plot plotgui.current_plot = n1 make_plot.make_plot(plotgui) plotgui.current_plot = plotnumber except ValueError: tkinter.messagebox.showinfo( "Error", "There was an error in the requested plot number.")
def apply_ellipse_values(plotgui): """ Create an ellipse for the plot. This code reads the values in the ellipse properties defintion window and applies them to the next available ellipse. The plot is then redone and the ellipse properties window is removed. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ matplotlib_line_name_list = [ 'solid', 'dashed', 'dashdot', 'dotted', 'None' ] try: x1 = float(plotgui.ellipsefields[0].get()) y1 = float(plotgui.ellipsefields[1].get()) x2 = float(plotgui.ellipsefields[2].get()) y2 = float(plotgui.ellipsefields[3].get()) angle = float(plotgui.ellipsefields[4].get()) angle = angle % 360. t1 = float(plotgui.ellipsefields[7].get()) plotgui.plot_ellipses[plotgui.number_of_ellipses]['xposition'] = x1 plotgui.plot_ellipses[plotgui.number_of_ellipses]['yposition'] = y1 plotgui.plot_ellipses[plotgui.number_of_ellipses]['major'] = x2 plotgui.plot_ellipses[plotgui.number_of_ellipses]['minor'] = y2 plotgui.plot_ellipses[plotgui.number_of_ellipses]['rotation'] = angle line_index = plotgui.ellipsefields[5].current() colour_index1 = plotgui.ellipsefields[6].current() colour_index2 = plotgui.ellipsefields[8].current() plotgui.plot_ellipses[ plotgui.number_of_ellipses]['line_thickness'] = t1 if plotgui.colourset[colour_index1] == 'select': values = askcolor() plotgui.plot_ellipses[plotgui.number_of_ellipses]['line_colour'] = \ values[1] else: plotgui.plot_ellipses[plotgui.number_of_ellipses]['line_colour'] = \ plotgui.colourset[colour_index1] plotgui.plot_ellipses[plotgui.number_of_ellipses]['line_type'] = \ matplotlib_line_name_list[line_index] plotgui.plot_ellipses[plotgui.number_of_ellipses]['plot'] = \ plotgui.current_plot plotgui.plot_ellipses[plotgui.number_of_ellipses]['fill_colour'] = \ plotgui.altcolourset[colour_index2] plotgui.number_of_ellipses = plotgui.number_of_ellipses + 1 make_plot.make_plot(plotgui) plotgui.close_window(plotgui.ellipse_window, 'ellipse_window') except Exception: return
def apply_line_values(plotgui): """ Create a line on the plot. This code reads the values in the line properties defintion window and applies them to the next available line. The plot is then redone and the line properties window is removed. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ matplotlib_line_name_list = [ 'solid', 'dashed', 'dashdot', 'dotted', 'None' ] try: x1 = float(plotgui.linefields[0].get()) y1 = float(plotgui.linefields[1].get()) x2 = float(plotgui.linefields[2].get()) y2 = float(plotgui.linefields[3].get()) t1 = float(plotgui.linefields[6].get()) plotgui.plot_lines[plotgui.number_of_lines]['xstart'] = x1 plotgui.plot_lines[plotgui.number_of_lines]['ystart'] = y1 plotgui.plot_lines[plotgui.number_of_lines]['xend'] = x2 plotgui.plot_lines[plotgui.number_of_lines]['yend'] = y2 line_index = plotgui.linefields[4].current() colour_index = plotgui.linefields[5].current() plotgui.plot_lines[plotgui.number_of_lines]['line_thickness'] = t1 if plotgui.colourset[colour_index] == 'select': values = askcolor() plotgui.plot_lines[plotgui.number_of_lines]['line_colour'] = \ values[1] else: plotgui.plot_lines[plotgui.number_of_lines]['line_colour'] = \ plotgui.colourset[colour_index] plotgui.plot_lines[plotgui.number_of_lines]['line_type'] = \ matplotlib_line_name_list[line_index] plotgui.plot_lines[ plotgui.number_of_lines]['plot'] = plotgui.current_plot plotgui.number_of_lines = plotgui.number_of_lines + 1 make_plot.make_plot(plotgui) plotgui.close_window(plotgui.line_window, 'line_window') except Exception: return
def plot_btn_clk(event=None): # build weekday_l weekday_l = [] for weekday_d in self.weekdays_dl: if weekday_d['sel'].get() == 1: weekday_l.append(weekday_d['cbtn']['text']) # build month_l month_l = [] for month_d in self.months_dl: if month_d['sel'].get() == 1: month_l.append(month_d['cbtn']['text']) make_plot.make_plot(weekday_l, month_l, self.plot_type_cbox.get())
def endProgram(): global done global dt global stopper for f in files: f.close() img_directory = os.path.abspath("images/" + channel + '\\' + dt) if create_graph: make_plot(channel, dt) print "Rate chart created under " + img_directory + "!" if create_wordcloud: make_cloud(channel, dt) print "Word clouds created under " + img_directory + "!" else: print create_graph raw_input('All images created! Press enter to close the program.') sys.exit()
def toggle_equal_aspect(plotgui): """ Toggle the equal aspect plot display flag. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object Returns ------- None """ plotgui.equal_aspect[plotgui.current_plot-1] = not \ plotgui.equal_aspect[plotgui.current_plot-1] make_plot.make_plot(plotgui)
def apply_data_edits(plotgui, nset, data_text): """ Read the data edit window and apply the values. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object nset: an integer variable for the set number that is being edited data_text: a tkinter text field variable which is read for the values Returns ------- None """ text = data_text.get("1.0", Tk.END) xvalues, dxvalues1, dxvalues2, yvalues, dyvalues1, dyvalues2,\ errorflag = general_utilities.parse_data_input_text(text) try: xvalues = numpy.asarray(xvalues) yvalues = numpy.asarray(yvalues) dxvalues1 = numpy.asarray(dxvalues1) dxvalues2 = numpy.asarray(dxvalues2) dyvalues1 = numpy.asarray(dyvalues1) dyvalues2 = numpy.asarray(dyvalues2) if len(xvalues) < 1: tkinter.messagebox.showinfo( 'error', 'Unable to parse text from edit widget (2)') return plotgui.xdata[nset - 1]['values'] = xvalues plotgui.xdata[nset - 1]['lowerror'] = dxvalues1 plotgui.xdata[nset - 1]['higherror'] = dxvalues2 plotgui.ydata[nset - 1]['values'] = yvalues plotgui.ydata[nset - 1]['lowerror'] = dyvalues1 plotgui.ydata[nset - 1]['higherror'] = dyvalues2 make_plot.make_plot(plotgui) except ValueError: tkinter.messagebox.showinfo('error', 'Unable to parse text from edit widget') return
def remove_box(plotgui): """ Remove the last box from the list of plot elements. This routine sets the box counter down by 1 so the last box is no longer plotted by the code. Any new box subsequently defined will then overwrite the last existing one. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ if plotgui.number_of_boxes > 0: plotgui.number_of_boxes = plotgui.number_of_boxes - 1 make_plot.make_plot(plotgui)
def remove_vector(plotgui): """ Remove the last vector from the list of plot elements. This routine sets the vector counter down by 1 so the last defined vector is no longer plotted by the code. The next new vector subsequently defined will then overwrite the last current one. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ if plotgui.number_of_vectors > 0: plotgui.number_of_vectors = plotgui.number_of_vectors - 1 make_plot.make_plot(plotgui)
def set_label_values(plotgui, ind1): """ Read parameters from the label input fields and apply them. Parameters ---------- plotgui : the matplotlib_user_interface object holding the plot ind1 : an integer value >= 0, the index of the label that is having the properties set Returns ------- Nothing """ try: font = plotgui.label_font_name_list.get() fontweight = plotgui.label_font_weight_list.get() fontsize = int(plotgui.label_font_size_list.get()) fontcolour = plotgui.label_font_colour_list.get() labelstring = plotgui.label_text_entry.get() xpos1 = float(plotgui.label_x_position.get()) if plotgui.xparameters[plotgui.plot_labels[ind1]['plot']-1]['hybridlog']: xpos1 = general_utilities.hybrid_transform(xpos1) ypos1 = float(plotgui.label_y_position.get()) if plotgui.yparameters[plotgui.plot_labels[ind1]['plot']-1]['hybridlog']: ypos1 = general_utilities.hybrid_transform(ypos1) plotgui.plot_labels[ind1]['xposition'] = xpos1 plotgui.plot_labels[ind1]['yposition'] = ypos1 plotgui.plot_labels[ind1]['labelstring'] = labelstring plotgui.plot_labels[ind1]['colour'] = fontcolour plotgui.plot_labels[ind1]['size'] = fontsize plotgui.plot_labels[ind1]['font'] = font plotgui.plot_labels[ind1]['fontweight'] = fontweight make_plot.make_plot(plotgui) except Exception: pass
def set_font_values(plotgui): """ Read the font fields and apply them to the plot. This routine reads the font fields and saves them to the internal variables. It then calls the routine to re-plot. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object Returns ------- None """ plotgui.fontname[plotgui.current_plot - 1] = plotgui.font_name_list.get() plotgui.fontsize[plotgui.current_plot - 1] = plotgui.font_size_list.get() plotgui.fontweight[plotgui.current_plot - 1] = plotgui.font_weight_list.get() make_plot.make_plot(plotgui)
def cancel_fitting_fields(plotgui, nsets): """ Clear the set fitting results. This routine will "clear" the fitting data sets. This is done by reverting the plotgui.nsets value to what it was before the fitting was started. Hence all the fitting data sets are still present but are not plotted, and if more data sets are read in the fitting sets will be overwritten. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object Returns ------- None """ plotgui.nsets = nsets make_plot.make_plot(plotgui)
def remove_ellipse(plotgui): """ Remove the last ellipse from the list of plot elements. This routine sets the ellipse counter down by 1 so the last defined ellipse is no longer plotted by the code. Any new ellipses subsquently defined will then overwrite the last current one. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ if plotgui.number_of_ellipses > 0: plotgui.number_of_ellipses = plotgui.number_of_ellipses - 1 make_plot.make_plot(plotgui)
def remove_all_boxes(plotgui): """ Remove all boxes from the plot elements. This routine sets the box counter variable to zero so that any defined boxes are not plotted, and subsequently defined boxes will overwrite any that are currently in the plotgui.plot_boxes variable. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ if plotgui.number_of_boxes > 0: plotgui.number_of_boxes = 0 plotgui.positions = [] make_plot.make_plot(plotgui)
def test_plot(self): top = Problem() top.root = Basic() top.setup(check=False) top["loads.P_constant"] = 10 top["des_vars.array_power"] = 300 top["des_vars.power_capacity"] = 420 top.run() fig = make_plot(top) fig.savefig("test_fig.png", format="png", bbox_inches="tight", pad_inches=0) assert os.path.exists("test_fig.png")
def test_plot(self): top = Problem() top.root = Basic() top.setup(check=False) top['loads.P_constant'] = 10 top['des_vars.array_power'] = 300 top['des_vars.power_capacity'] = 420 top.run() fig = make_plot(top) fig.savefig("test_fig.png", format="png", bbox_inches='tight', pad_inches=0) assert os.path.exists("test_fig.png")
def read_labels(plotgui, label_message_text, label_window): """ Read and parse the label text field. This routine reads the label text field and makes the new set of labels and label positions. It then applies these and closes the label window. Parameters ---------- plotgui: A matplotlib_user_interface object label_message_text: A tkinter text field variable label_window: A tkinter top level variable for the label entry Returns ------- Nothing The code does, however, change the plotgui.plot_labels values as needed to match what is in the label text field. """ labeltext = label_message_text.get(0.0, Tk.END) lines = labeltext.split('\n') newlabels = [] nlabels = 0 for line in lines: values = line.split('\t') if len(values) == 8: try: x1 = float(values[0]) y1 = float(values[1]) nplot = int(values[2]) label = values[3] colour = values[4] size = int(values[5]) font = values[6] fontweight = values[7] label = label.strip('\n') if plotgui.xparameters[nplot-1]['hybridlog']: x1 = general_utilities.hybrid_transform(x1) if plotgui.yparameters[nplot-1]['hybridlog']: y1 = general_utilities.hybrid_transform(y1) newlabels.append({'xposition': x1, 'yposition': y1, 'labelstring': label, 'plot': nplot, 'colour': colour, 'size': size, 'font': font, 'fontweight': fontweight}) nlabels = nlabels + 1 except ValueError: pass label_window.destroy() if nlabels > plotgui.max_labels: plotgui.max_labels = nlabels else: for loop in range(nlabels, plotgui.max_labels): newlabels.append({'xposition': None, 'yposition': None, 'labelstring': '', 'plot': 1, 'colour': 'black', 'size': 12, # 'font': 'sans-serif', 'font': 'times new roman', 'fontweight': 'normal'}) plotgui.plot_labels = newlabels plotgui.number_of_labels = nlabels make_plot.make_plot(plotgui)
def plot(pv=None, pv2=None, timevar=None, date1=None, date2=None, pvmin=None, pvmax=None, pv2min=None, pv2max=None, fdat=None): if pv2 in ('', None, 'None'): pv2 = None if timevar is None: timevar = 'time_ago' sdate1 = date1 tmin, tmax, date1, date2, time_ago = parse_times(timevar, date1, date2) timestr = 'time_ago/%s' % time_ago if timevar.startswith('date'): timestr = 'date_range/%s/%s' % (date1, date2) messages = [] pvcurrent, pv2current = None, None ts, dat, enums, ylabel, ylog = None, None, None, None, False try: related = arch.related_pvs(pv) if len(related) > 25: related = related[:25] pvinfo = arch.get_pvinfo(pv) desc = pvinfo['desc'] dtype = pvinfo['type'] if dtype == 'enum': thispv = PV(pv) thispv.get() enums = thispv.enum_strs ylog = pvinfo['graph_type'].startswith('log') ts, dat = arch.get_data(pv, tmin=tmin, tmax=tmax, with_current=True) ylabel = "%s\n[%s]" % (desc, pv) pvcurrent = "%g" % dat[-1] except: messages.append("data for '%s' not found" % pv) ts2, dat2, enums2, y2label, y2log = None, None, None, None, False if pv2 is not None: try: pvinfo2 = arch.get_pvinfo(pv2) desc2 = pvinfo2['desc'] dtype2 = pvinfo2['type'] if dtype2 == 'enum': thispv = PV(pv2) thispv.get() enums2 = thispv.enum_strs y2log = pvinfo2['graph_type'].startswith('log') ts2, dat2 = arch.get_data(pv2, tmin=tmin, tmax=tmax, with_current=True) y2label="%s\n[%s]" % (desc2, pv2) pv2current = "%g" % dat2[-1] except: messages.append("data for '%s' not found" % pv2) try: arch.set_pair_score(pv, pv2) except: messages.append(" could not increment pair score ") fig, pvdata, pv2data = None, None, None if ts is not None: if dat.dtype.type == np.string_: dat = convert_string_data(dat) pvdata = [] for _t, _d in zip(ts, dat): pvdata.append({'ts': strftime("%Y-%m-%d %H:%M:%S", localtime(_t)), 'val': _d}) last_pt = pvdata.pop() pvdata.append({'ts': "Now", 'val': last_pt['val']}) if dat2 is not None and dat2.dtype.type == np.string_: dat2 = convert_string_data(dat2) pv2data = [] for _t, _d in zip(ts2, dat2): pv2data.append({'ts': strftime("%Y-%m-%d %H:%M:%S", localtime(_t)), 'val': _d}) last_pt = pv2data.pop() pv2data.append({'ts': "Now", 'val': last_pt['val']}) if pvdata is None and pv2data is None: fig = make_plot(ts, dat, ylabel=ylabel, enums=enums, ylog=ylog, ts2=ts2, dat2=dat2, y2label=y2label, enums2=enums2, y2log=y2log, tmin=tmin, tmax=tmax, ymin=pvmin, ymax=pvmax, y2min=pv2min, y2max=pv2max) if len(messages) > 0: messages = ', '.join(messages) else: messages = None # if pv2 is None: pv2 = '' if date1 is None: date1 = '' if date2 is None: date2 = '' if pvmin is None: pvmin = '' if pvmax is None: pvmax = '' if pv2min is None: pv2min = '' if pv2max is None: pv2max = '' if fdat is None: fdat = {} opts = {'pv': pv, 'pv2': pv2, 'pvcurrent': pvcurrent, 'pv2current': pv2current, 'pvdata': pvdata, 'pv2data': pv2data, 'pvmin': pvmin, 'pvmax': pvmax, 'pv2min': pv2min, 'pv2max': pv2max, 'fdat': fdat, 'date1': date1, 'date2': date2, 'sdate1': date1, 'timestr': timestr, 'timevar': timevar, 'time_ago': time_ago, 'messages': messages, 'figure' : fig, 'related': related, 'ago_choices': ago_choices} return render_template('plot.html', **opts)
self.q_sampling.q_function[ s_f, s_s, action] = last_delta + self.q_parameters.alpha * delta state = next_state total_score += reward scores.append(total_score) self.env.close() return scores epoch_number = 10000 eps = 0.2 alpha = 0.5 gamma = 0.8 q_parameters = QParameters(eps, alpha, gamma) velocity = get_distribution(-0.701, 0.701, 0.001) position = get_distribution(0, 0.51, 0.01) actions = get_distribution(-1, 1.01, 0.01) q_two_dim_func_sampling = QTwoDimFunctionSampling(position, velocity, actions) env = gym.make('MountainCarContinuous-v0').env car = Car(q_parameters, q_two_dim_func_sampling, env) scores = car.learn(epoch_number, False) make_plot.make_plot(scores, epoch_number)
def recommendation(): errors = [] letters = [] admit_class = [] sector = [] edu_level = [] probs = [] htmltables = [] titles = [] plotscript = [] plotdiv = [] agent_used = [] trends = '' if request.method == "POST": #get url that the user has entered try: #get user input from home page form admit_class = request.form['admit_class'] edu_level = request.form['edu_level'] sector = request.form['sector'] agent_used = request.form['agent_used'] #work_state = request.form['work_state'] #citizen_country = request.form['citizen_country'] #business_size = request.form['business_size'] #calculate probabilities probs, top3probs, bot3probs = calc_probabilities(admit_class, edu_level, float(sector[:2]), agent_used) #, work_state[:2]) #, #citizen_country.upper())#, business_size) #put probability tables to html form #probstrans = probs.transpose() htmltables.append( probs.style .applymap(highlight_cols, subset=pd.IndexSlice[[0, 2, 4, 6, 8, 10], :]) .set_properties(**{'text-align':'center', 'width':'300px'}) .hide_index() .set_table_attributes('align="center"') .render() ) htmltables.append( top3probs.style .set_properties(**{'text-align':'center', 'width':'175px'})#, 'float':'left', 'overflow':'hidden'}) .set_table_attributes('align="left"') .render() ) htmltables.append( bot3probs.style .set_properties(**{'text-align':'center', 'width':'175px'})#, 'float':'right', 'overflow':'hidden'}) .set_table_attributes('align="left"') .render() ) #make plot plotscript, plotdiv = make_plot(probs) except: errors.append("Unable to get URL. Please make sure it's valid and try again." ) print("error") return render_template('recommendation.html', errors=errors, admit_class = admit_class, sector = sector, edu_level = edu_level, agent_used = agent_used, tables=htmltables, plotscript = plotscript, plotdiv=plotdiv)
def run_fitting(plotgui): function_string = plotgui.tkcontrol[-1].get() try: tolerance = float(plotgui.tkcontrol[-3].get()) if (tolerance <= 0.) or (tolerance > 0.0001): tolerance = 1.e-10 except: tolerance = 1.e-10 nset = int(plotgui.tkcontrol[-2].get()) if (nset < 0) or (nset > plotgui.nsets): nset = 1 params = [] start = [] lowbound = [] highbound = [] fixed = [] lowflag = [] highflag = [] for loop in range(10): if plotgui.tkcontrol[loop][0].get(): params.append(True) start.append(float(plotgui.tkcontrol[loop][2].get())) if plotgui.tkcontrol[loop][3].get(): lowbound.append(float(plotgui.tkcontrol[loop][5].get())) lowflag.append(True) else: lowbound.append(0.) lowflag.append(False) if plotgui.tkcontrol[loop][6].get(): highbound.append(float(plotgui.tkcontrol[loop][8].get())) highflag.append(True) else: highbound.append(0.) highflag.append(False) if plotgui.tkcontrol[loop][9].get(): fixed.append(True) else: fixed.append(False) else: params.append(False) start.append(0.) lowflag.append(False) lowbound.append(0.) highflag.append(False) highbound.append(0.) fixed.append(True) params = numpy.asarray(params, dtype=bool) inds = numpy.where(params) start = numpy.asarray(start) lowbound = numpy.asarray(lowbound) highbound = numpy.asarray(highbound) fixed = numpy.asarray(fixed, dtype=bool) lowflag = numpy.asarray(lowflag, dtype=bool) highflag = numpy.asarray(highflag, dtype=bool) parinfo = [] for loop in range(10): if lowflag[loop] and highflag[loop]: if (lowbound[loop] == highbound[loop]): str1 = '\nBad limits on parameter %d; check your inputs\n' % ( loop) plotgui.non_linear_set_fitting_text_field.insert(Tk.END, str1) return if params[loop]: parinfo1 = { 'value': start[loop], 'fixed': fixed[loop], 'limited': [lowflag[loop], highflag[loop]], 'limits': [lowbound[loop], highbound[loop]] } parinfo.append(parinfo1) plotgui.non_linear_set_fitting_text_field.insert(Tk.END, 'Function to fit:\n') plotgui.non_linear_set_fitting_text_field.insert(Tk.END, function_string + '\n') try: yerrors = (numpy.copy(plotgui.ydata[nset - 1]['lowerror']) + numpy.copy(plotgui.ydata[nset - 1]['higherror'])) / 2. except: plotgui.non_linear_set_fitting_text_field.insert( 'Constant uncertainties used.\n') yerrors = plotgui.ydata[nset - 1]['values'] * 0. + 0.01 emin = numpy.min(yerrors) emax = numpy.max(yerrors) if (emin == 0.) and (emax == 0.): yerrors = yerrors + 0.01 else: inds = numpy.where(yerrors <= 0.) altinds = numpy.where(yerrors > 0.) if len(altinds[0]) == 0: yerrors = yerrors * 0. + 0.01 else: meanerror = numpy.mean(yerrors[altinds]) yerrors[inds] = meanerror start_values = start[params] fitparams, yfit = mpfitexpr.mpfitexpr(function_string, plotgui.xdata[nset - 1]['values'], plotgui.ydata[nset - 1]['values'], yerrors, start_values, check=True, full_output=True, parinfo=parinfo, ftol=tolerance) str1 = '\nMPFIT status: %d\n' % (fitparams.status) if fitparams.status < 0: str1 = 'Error in the fitting: ' + str1 else: cov = fitparams.covar pcov = cov * 0. sh1 = cov.shape for i in range(sh1[0]): for j in range(sh1[1]): pcov[i, j] = cov[i, j] / math.sqrt(cov[i, i] * cov[j, j]) for loop in range(len(fitparams.params)): str1 = str1 + 'parameter %2d : value %15.8g +/- %15.8g\n' % ( loop + 1, fitparams.params[loop], fitparams.perror[loop]) plotgui.non_linear_set_fitting_text_field.insert(Tk.END, str1) xvalues = numpy.copy(plotgui.xdata[nset - 1]['values']) yvalues = numpy.copy(plotgui.ydata[nset - 1]['values']) plotgui.add_set(xvalues, yfit) oset = 1 * plotgui.nsets mpfit_values = { 'fit_parameters': fitparams, 'set_fit': nset, 'set_out': oset, 'xvalues': xvalues, 'yvalues': yvalues, 'yerrors': yerrors } plotgui.mpfit_values.append(mpfit_values) make_plot.make_plot(plotgui) for loop in range(10): if params[loop]: plotgui.tkcontrol[loop][2].delete(0, Tk.END) plotgui.tkcontrol[loop][2].insert(0, str(fitparams.params[loop]))
def get_set(plotgui, datavalues, labelstring): """ Extract data values to a new data set. This routine tries to make a data set (x, y) pair according to the specified values from the read sets window. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object datavalues : This is a numpy array from the "loadtxt" function. labelstring : This is a string variable, used to set the labels for the set(s) Returns ------- None """ if datavalues is None: tkinter.messagebox.showinfo( 'Error', 'You must specify a file before reading data.') return if len(datavalues.shape) == 1: datavalues = numpy.expand_dims(datavalues, 0) if True: # try: set_option_string = plotgui.set_options.get() if set_option_string is None: set_option_string = 'None' option1 = plotgui.set_option_list.index(set_option_string) autoscale_option_string = plotgui.autoscale_options.get() option2 = plotgui.autoscale_option_list.index(autoscale_option_string) option3 = plotgui.ally.get() option4 = plotgui.sortdata.get() shape1 = datavalues.shape xerrorinds = [2, 3, 5, 6] yerrorinds = [1, 3, 4, 6] if option3 == 0: try: inds = numpy.zeros((6), dtype=numpy.int8) - 1 str1 = plotgui.xdata_field.get() n1 = int(str1) - 1 inds[0] = n1 str1 = plotgui.ydata_field.get() n1 = int(str1) - 1 inds[1] = n1 if option1 in xerrorinds: str1 = plotgui.dxdata_field.get() values = str1.split(', ') n1 = int(values[0]) - 1 inds[2] = n1 if len(values) > 1: n1 = int(values[1]) - 1 inds[3] = n1 else: inds[3] = -1 if option1 in yerrorinds: str1 = plotgui.dydata_field.get() values = str1.split(', ') n1 = int(values[0]) - 1 inds[4] = n1 if len(values) > 1: n1 = int(values[1]) - 1 inds[5] = n1 else: inds[5] = -1 # exit here if there is an exception setting values except Exception: raise ValueError newinds = inds * 0 - 1 for loop in range(len(inds)): for n in range(len(plotgui.data_indexes)): if inds[loop] == plotgui.data_indexes[n]: newinds[loop] = n if max(newinds) > plotgui.ndatacolumns: tkinter.messagebox.showinfo( 'Error', 'The requested columns do not match the shape' + ' of the input data values.') return if newinds[0] >= 0: xvalues = numpy.squeeze(datavalues[:, newinds[0]]) else: xvalues = numpy.arange(1, shape1[0] + 1) xerrorflag = False yerrorflag = False if option1 in xerrorinds: xlowerror = numpy.squeeze(datavalues[:, newinds[2]]) if newinds[3] > 0: xhigherror = numpy.squeeze(datavalues[:, newinds[3]]) else: xhigherror = numpy.squeeze(datavalues[:, newinds[2]]) xerrorflag = True else: xlowerror = xvalues * 0. xhigherror = xvalues * 0. if newinds[1] >= 0: yvalues = numpy.squeeze(datavalues[:, newinds[1]]) else: yvalues = numpy.arange(1, shape1[0] + 1) if option1 in yerrorinds: ylowerror = numpy.squeeze(datavalues[:, newinds[4]]) if newinds[5] > 0: yhigherror = numpy.squeeze(datavalues[:, newinds[5]]) else: yhigherror = numpy.squeeze(datavalues[:, newinds[4]]) yerrorflag = True else: ylowerror = yvalues * 0. yhigherror = yvalues * 0. flags = numpy.logical_not(numpy.isnan(xvalues)) xvalues = xvalues[flags] xlowerror = xlowerror[flags] xhigherror = xhigherror[flags] yvalues = yvalues[flags] ylowerror = ylowerror[flags] yhigherror = yhigherror[flags] flags = numpy.logical_not(numpy.isnan(yvalues)) xvalues = xvalues[flags] xlowerror = xlowerror[flags] xhigherror = xhigherror[flags] yvalues = yvalues[flags] ylowerror = ylowerror[flags] yhigherror = yhigherror[flags] if option4 > 0: if option4 == 2: inds = numpy.argsort(xvalues) else: inds = numpy.argsort(yvalues) if newinds[0] >= 0: xvalues = xvalues[inds] xlowerror = xlowerror[inds] xhigherror = xhigherror[inds] else: xlowerror = xvalues * 0. xhigherror = xvalues * 0. if newinds[1] >= 0: yvalues = yvalues[inds] ylowerror = ylowerror[inds] xhigherror = yhigherror[inds] else: ylowerror = yvalues * 0. yhigherror = yvalues * 0. newlabelstring = 'columns %d/%d %s' % (newinds[0] + 1, newinds[1] + 1, labelstring) plotgui.add_set(xvalues, yvalues, xlowerror, xhigherror, ylowerror, yhigherror, xerrorflag, yerrorflag, option2, newlabelstring, plotgui.current_plot) else: str1 = plotgui.xdata_field.get() n1 = int(str1) - 1 for loop in range(len(plotgui.data_indexes)): if n1 == plotgui.data_indexes[loop]: xind = loop xvalues = numpy.squeeze(datavalues[:, xind]) xlowerror = xvalues * 0. xhigherror = xvalues * 0. xerrorflag = False yerrorflag = False for loop in range(len(plotgui.data_indexes)): if loop == n1: pass else: yvalues = numpy.squeeze(datavalues[:, loop]) ylowerror = yvalues * 0. yhigherror = yvalues * 0. newlabelstring = 'columns %d and %d from file %s' % ( n1 + 1, loop + 1, labelstring) plotgui.add_set(xvalues, yvalues, xlowerror, xhigherror, ylowerror, yhigherror, xerrorflag, yerrorflag, option2, labelstring, plotgui.current_plot) plotgui.filename = None make_plot.make_plot(plotgui) return
def apply_plot_parameters(plotgui): """ Apply the values from the plot parameters window. This routine is called when the values in the plot control window are to be applied to the plot. It reads the values and places them in the internal variables, and then replots the data. Parameters ---------- Returns ------- None """ matplotlib_line_list = ['-', '--', '-.', ':', None] matplotlib_line_name_list = ['solid', 'dashed', 'dashdot', 'dotted', 'None'] try: plotgui.title[plotgui.current_plot-1] = plotgui.title_field.get() instring = plotgui.xlabel_field.get() # To do: test the string is OK as a label here.... plotgui.xparameters[plotgui.current_plot-1]['label'] = instring instring = plotgui.ylabel_field.get() plotgui.yparameters[plotgui.current_plot-1]['label'] = instring plotgui.xparameters[plotgui.current_plot-1]['logarithmic'] = \ plotgui.logx_variable.get() plotgui.yparameters[plotgui.current_plot-1]['logarithmic'] = \ plotgui.logy_variable.get() plotgui.xparameters[plotgui.current_plot-1]['hybridlog'] = \ plotgui.hlogx_variable.get() plotgui.yparameters[plotgui.current_plot-1]['hybridlog'] = \ plotgui.hlogy_variable.get() plotgui.xparameters[plotgui.current_plot-1]['invert'] = \ plotgui.invertx_variable.get() plotgui.yparameters[plotgui.current_plot-1]['invert'] = \ plotgui.inverty_variable.get() plotgui.xparameters[plotgui.current_plot-1]['hide'] = \ plotgui.hidex_variable.get() plotgui.yparameters[plotgui.current_plot-1]['hide'] = \ plotgui.hidey_variable.get() plotgui.xparameters[plotgui.current_plot-1]['hideticks'] = \ plotgui.hidexticks_variable.get() plotgui.yparameters[plotgui.current_plot-1]['hideticks'] = \ plotgui.hideyticks_variable.get() plotgui.xparameters[plotgui.current_plot-1]['hidelabels'] = \ plotgui.hidexlabels_variable.get() plotgui.yparameters[plotgui.current_plot-1]['hidelabels'] = \ plotgui.hideylabels_variable.get() plotgui.xparameters[plotgui.current_plot-1]['inverseticks'] = \ plotgui.inversexticks_variable.get() plotgui.yparameters[plotgui.current_plot-1]['inverseticks'] = \ plotgui.inverseyticks_variable.get() plotgui.xparameters[plotgui.current_plot-1]['bothticks'] = \ plotgui.bothxticks_variable.get() plotgui.yparameters[plotgui.current_plot-1]['bothticks'] = \ plotgui.bothyticks_variable.get() plotgui.xparameters[plotgui.current_plot-1]['oppositeaxis'] = \ plotgui.oppositex_variable.get() plotgui.yparameters[plotgui.current_plot-1]['oppositeaxis'] = \ plotgui.oppositey_variable.get() plotgui.xparameters[plotgui.current_plot-1]['majorgridlines'] = \ plotgui.majorxgrid_variable.get() plotgui.xparameters[plotgui.current_plot-1]['minorgridlines'] = \ plotgui.minorxgrid_variable.get() plotgui.yparameters[plotgui.current_plot-1]['majorgridlines'] = \ plotgui.majorygrid_variable.get() plotgui.yparameters[plotgui.current_plot-1]['minorgridlines'] = \ plotgui.minorygrid_variable.get() try: plotgui.xparameters[plotgui.current_plot-1]['minorticks'] = \ float(plotgui.xminortickfield.get()) except ValueError: plotgui.xparameters[plotgui.current_plot-1]['minorticks'] = 0.0 if plotgui.xparameters[plotgui.current_plot-1]['minorticks'] < 0.0: plotgui.xparameters[plotgui.current_plot-1]['minorticks'] = 0.0 try: plotgui.yparameters[plotgui.current_plot-1]['minorticks'] = \ float(plotgui.yminortickfield.get()) except ValueError: plotgui.yparameters[plotgui.current_plot-1]['minorticks'] = 0.0 if plotgui.yparameters[plotgui.current_plot-1]['minorticks'] < 0.0: plotgui.yparameters[plotgui.current_plot-1]['minorticks'] = 0.0 try: ticklength = int(plotgui.ticklengthfield.get()) ticklength = max(ticklength, 1) except ValueError: ticklength = 6 plotgui.xparameters[plotgui.current_plot-1]['ticklength'] = ticklength plotgui.yparameters[plotgui.current_plot-1]['ticklength'] = ticklength try: frame = float(plotgui.plot_frame_field.get()) if (frame <= 0.) or (frame > 5.): plotgui.plot_frame[plotgui.current_plot-1] = 0. else: plotgui.plot_frame[plotgui.current_plot-1] = frame except ValueError: plotgui.plot_frame[plotgui.current_plot-1] = 0. try: margin = float(plotgui.plot_margin_field.get()) plotgui.plot_margin = margin if margin > 0.3: tkinter.messagebox.showinfo( 'Warning', 'Margins are limited to the range -0.1 to +0.3.') margin = 0.3 plotgui.plot_margin_field.delete(0, Tk.END) plotgui.plot_margin_field.insert(0, '0.3') if margin < -0.1: tkinter.messagebox.showinfo( 'Warning', 'Margins are limited to the range -0.1 to +0.3.') margin = -0.1 plotgui.plot_margin_field.delete(0, Tk.END) plotgui.plot_margin_field.insert(0, '-0.1') plotgui.plot_margin = margin except Exception: tkinter.messagebox.showinfo( 'Warning', 'Margin value could not be read, setting to zero.') plotgui.plot_margin_field.delete(0, Tk.END) plotgui.plot_margin_field.insert(0, '0.0') try: xmin = float(plotgui.xmin_field.get()) xmax = float(plotgui.xmax_field.get()) ymin = float(plotgui.ymin_field.get()) ymax = float(plotgui.ymax_field.get()) if (xmin >= xmax) | (ymin >= ymax): raise ValueError plotgui.plot_range[plotgui.current_plot-1][0] = xmin plotgui.plot_range[plotgui.current_plot-1][1] = xmax plotgui.plot_range[plotgui.current_plot-1][2] = ymin plotgui.plot_range[plotgui.current_plot-1][3] = ymax except Exception: tkinter.messagebox.showinfo( 'Error', 'There was some error in the axis range values.' + ' Please check your inputs.') plotgui.legend_position[plotgui.current_plot-1] = \ plotgui.legend_options[plotgui.current_plot-1].get() str1 = plotgui.grid_linetype_variable.get() for loop in range(len(matplotlib_line_list)): if matplotlib_line_name_list[loop] == str1: plotgui.grid_linetype[plotgui.current_plot-1] = \ matplotlib_line_list[loop] for loop in range(len(plotgui.share_axis)): if plotgui.current_plot == abs(plotgui.share_axis[loop]): if plotgui.share_axis[loop] < 0: for key in plotgui.yparameters[-1].keys(): plotgui.yparameters[loop][key] = plotgui.yparameters[ plotgui.current_plot-1][key] else: for key in plotgui.xparameters[-1].keys(): plotgui.xparameters[loop][key] = plotgui.xparameters[ plotgui.current_plot-1][key] make_plot.make_plot(plotgui) except Exception: tkinter.messagebox.showinfo( 'Error', 'There was some error in the input values. ' + 'Please check your inputs.')
if i % 10000 == 0: print('10000 iterations') if done or i > 100000: print(done) print('Iteration: {}'.format(i)) break i += 1 next_state = torch.FloatTensor(next_state) next_value = critic(next_state) returns = compute_returns(next_value, my_rewards) log_probs = torch.cat(log_probs) probs = torch.cat(probs) entropy = entropyLoss(probs) returns = torch.cat(returns).detach() values = torch.cat(values) advantage = advantage_norm(returns - values) actor_loss = -(log_probs * advantage.detach()).mean() actor_loss += entropy * 0.001 critic_loss = advantage.pow(2).mean() optimizerA.zero_grad() optimizerC.zero_grad() actor_loss.backward() critic_loss.backward() torch.nn.utils.clip_grad_norm_(actor.parameters(), 0.5) torch.nn.utils.clip_grad_norm_(critic.parameters(), 0.5) optimizerA.step() optimizerC.step() scores.append(torch.tensor(rewards).sum().item()) make_plot.make_plot(scores, n_iters)
def apply_vector_values(plotgui): """ Create a vector for the plot. This code reads the values in the vector properties defintion window and applies them to the next available vector. The plot is then redone and the vector properties window is removed. Parameters ---------- plotgui: the matplotlib_user_interface object holding the plot Returns ------- None """ matplotlib_line_name_list = [ 'solid', 'dashed', 'dashdot', 'dotted', 'None' ] try: x1 = float(plotgui.vectorfields[0].get()) y1 = float(plotgui.vectorfields[1].get()) x2 = float(plotgui.vectorfields[2].get()) y2 = float(plotgui.vectorfields[3].get()) delx = float(plotgui.vectorfields[4].get()) dely = float(plotgui.vectorfields[5].get()) t1 = float(plotgui.vectorfields[8].get()) plotgui.plot_vectors[plotgui.number_of_vectors]['xstart'] = x1 plotgui.plot_vectors[plotgui.number_of_vectors]['ystart'] = y1 plotgui.plot_vectors[plotgui.number_of_vectors]['xend'] = x2 plotgui.plot_vectors[plotgui.number_of_vectors]['yend'] = y2 plotgui.plot_vectors[plotgui.number_of_vectors]['delx'] = delx plotgui.plot_vectors[plotgui.number_of_vectors]['dely'] = dely plotgui.plot_vectors[plotgui.number_of_vectors]['line_thickness'] = t1 line_index = plotgui.vectorfields[6].current() colour_index = plotgui.vectorfields[7].current() if plotgui.colourset[colour_index] == 'select': values = askcolor() plotgui.plot_vectors[plotgui.number_of_vectors]['line_colour'] = \ values[1] else: plotgui.plot_vectors[plotgui.number_of_vectors]['line_colour'] = \ plotgui.colourset[colour_index] plotgui.plot_vectors[plotgui.number_of_vectors]['line_type'] = \ matplotlib_line_name_list[line_index] plotgui.plot_vectors[plotgui.number_of_vectors]['plot'] = \ plotgui.current_plot flag = plotgui.vectorfields[9].get() if flag == 1: plotgui.plot_vectors[plotgui.number_of_vectors]['fill'] = True else: plotgui.plot_vectors[plotgui.number_of_vectors]['fill'] = False colour_index = plotgui.vectorfields[10].current() if plotgui.colourset[colour_index] == 'select': values = askcolor() plotgui.plot_vectors[plotgui.number_of_vectors]['fill_colour'] = \ values[1] else: plotgui.plot_vectors[plotgui.number_of_vectors]['fill_colour'] = \ plotgui.colourset[colour_index] plotgui.number_of_vectors = plotgui.number_of_vectors + 1 make_plot.make_plot(plotgui) plotgui.close_window(plotgui.vector_window, 'vector_window') except Exception: return
def make_controls(plotgui, parent): """ Make the control area within the main window. This routine makes a control area within the main window, under frame "parent". The overall root value is also passed here, but not currently used. It may be neeed for orderly closing of the window depending on what is done in the main window, hence it is included here. Parameters ---------- plotgui: by assumption a matplotlib_user_interface object parent : A Tk.Frame variable for the holder of the controla Returns ------- None """ holder = Tk.Frame(parent) holder.pack(side=Tk.TOP) label1 = Tk.Label(holder, text=' ') label1.pack(side=Tk.TOP, fill=Tk.X) button1 = Tk.Button(holder, text='Plot', command=lambda: make_plot.make_plot(plotgui)) button1.pack(side=Tk.TOP, fill=Tk.X) button2 = Tk.Button(holder, text='Auto scale', command=plotgui.autoscale_plot) button2.pack(side=Tk.TOP, fill=Tk.X) sl = general_utilities.separator_line(holder, 300, 25, 5, True) button3 = Tk.Button( holder, text='2-D Histogram', command=lambda: histogram_utilities.make_hess_plot(plotgui)) button3.pack(side=Tk.TOP, fill=Tk.X) field = Tk.Frame(holder) field.pack(side=Tk.TOP) label1 = Tk.Label(field, text='Number of pixels: ') label1.pack(side=Tk.LEFT) plotgui.npixelfield = Tk.Entry(field, width=5) plotgui.npixelfield.pack(side=Tk.TOP) plotgui.npixelfield.insert(0, '500') plotgui.overplotflag = Tk.IntVar() h1 = Tk.Frame(holder) h1.pack(side=Tk.TOP) plotgui.hessindividualhistogramflag = Tk.IntVar() b1 = Tk.Frame(h1) general_utilities.put_yes_no(b1, plotgui.hessindividualhistogramflag, ['all sets', 'one set'], True) b1.pack(side=Tk.LEFT) b1 = Tk.Frame(h1) plotgui.hess_set_field = Tk.Entry(b1, width=5) plotgui.hess_set_field.insert(0, '1') plotgui.hess_set_field.pack(side=Tk.LEFT) b1.pack(side=Tk.LEFT) h1 = Tk.Frame(holder) h1.pack(side=Tk.TOP) label1 = Tk.Label(h1, text='Overplot Sets: ') label1.pack(side=Tk.LEFT) b1 = Tk.Frame(h1) general_utilities.put_yes_no( b1, plotgui.overplotflag, ['Yes', 'No'], True, ) b1.pack(side=Tk.LEFT) sl = general_utilities.separator_line(holder, 300, 25, 5, True) button4 = Tk.Button( holder, text='1-D Histogram', command=lambda: histogram_utilities.make_histogram(plotgui)) button4.pack(side=Tk.TOP, fill=Tk.X) field = Tk.Frame(holder) field.pack(side=Tk.TOP) label1 = Tk.Label(field, text='Number of bins or bin size: ') label1.pack(side=Tk.LEFT) plotgui.nbinfield = Tk.Entry(field, width=10) plotgui.nbinfield.pack(side=Tk.TOP) plotgui.nbinfield.insert(0, '500') plotgui.histogramflag = Tk.IntVar() b1 = Tk.Frame(holder) general_utilities.put_yes_no(b1, plotgui.histogramflag, ['x values', 'y values'], True) b1.pack(side=Tk.TOP) plotgui.histogramflag = Tk.IntVar() b1 = Tk.Frame(holder) plotgui.individualhistogramflag = Tk.IntVar() general_utilities.put_yes_no(b1, plotgui.individualhistogramflag, ['all sets', 'individual sets'], True) b1.pack(side=Tk.TOP) sl = general_utilities.separator_line(holder, 300, 25, 5, True) plotgui.matplotlib_rounding = Tk.IntVar() b1 = Tk.Frame(holder) label1 = Tk.Label(b1, text='Axis limits rounding algorithm: ') label1.pack(side=Tk.TOP) b1.pack(side=Tk.TOP) b1 = Tk.Frame(holder) general_utilities.put_yes_no(b1, plotgui.matplotlib_rounding, ['Matplotlib', 'Alternate'], True) b1.pack(side=Tk.TOP) sl = general_utilities.separator_line(holder, 300, 25, 5, True) button5 = Tk.Button( holder, text='Save as PNG', command=lambda: general_utilities.save_png_figure(plotgui.figure)) button5.pack(side=Tk.TOP, fill=Tk.X) button6 = Tk.Button( holder, text='Save as PS', command=lambda: general_utilities.save_ps_figure(plotgui.figure)) button6.pack(side=Tk.TOP, fill=Tk.X) button7 = Tk.Button( holder, text='Clear Current Plot', command=lambda: plot_flag_utilities.clear_current_plot(plotgui)) button7.pack(side=Tk.TOP, fill=Tk.X) button8 = Tk.Button( holder, text='Tile Plots', command=lambda: plot_flag_utilities.tile_plots(plotgui)) button8.pack(side=Tk.TOP, fill=Tk.X) button9 = Tk.Button( holder, text='Set Plot', command=lambda: plot_flag_utilities.set_plot_number(plotgui)) button9.pack(side=Tk.TOP, fill=Tk.X) button10 = Tk.Button(holder, text='Close Window', command=plotgui.root.destroy) button10.pack(side=Tk.TOP, fill=Tk.X)
""" TESTING MAKEPLOT() Function """ import numpy as np import matplotlib.pyplot as plt from make_plot import make_plot x = np.arange(0, 2 * np.pi, 0.5) y1 = np.sin(x) y2 = np.sin(2 * x) y3 = np.cos(x) y4 = np.random.random(len(x)) plt.style.use('default') for pt in ['scatter']: make_plot( data={ 'y1': [x, y1], 'y2': [x, y2] }, color='bw', plottype=pt, xaxis_grid=False, yaxis_grid=True, title='Graph title', hline=(0, 0.2), ).savefig('single.png')
params_plot = { 'colors': colors, 'palette_name': "viridis", 'params': params, 'tools': TOOLS, 'source_polys': source_polys, 'source_pts': source_pts, # 'buildings':buildings, # 'network':network, 'tile_provider': STAMEN_TONER, 'x_range': [243978, 276951], 'y_range': [6234235, 6265465] } l_viridis = make_plot(params_plot) x_range = l_viridis[0].x_range y_range = l_viridis[0].y_range params_plot['palette_name'] = "plasma" params_plot['x_range'] = x_range params_plot['y_range'] = y_range l_plasma = make_plot(params_plot) params_plot['palette_name'] = "spectral" l_spectral = make_plot(params_plot) def run(): date_value = date_.value
self.connect("data.wind", "loads.wind") self.connect("data.irradiance", "loads.irradiance") self.connect("data.hour", "loads.hour") self.connect("data.day", "loads.day") self.connect("data.weekday", "loads.weekday") self.connect("data.month", "loads.month") self.connect("panels.P_generated", ["batteries.P_generated", "loads.P_generated"]) self.connect("loads.P_consumption", "batteries.P_consumption") if __name__ == "__main__": import pylab top = Problem() top.root = Greenhouse() top.root.fd_options['force_fd'] = True top.root.fd_options['step_size'] = 1.0 top.setup(check=False) top['des_vars.panels_array_power'] = 350.0 top['des_vars.power_capacity'] = 12*100 top.run() fig = make_plot(top) pylab.show()
self.connect("data.P_generated", ["batteries.P_generated", "loads.P_generated"]) self.connect("loads.P_consumption", "batteries.P_consumption") if __name__ == "__main__": import pylab top = Problem() top.root = Greenhouse() top.root.fd_options['force_fd'] = True top.root.fd_options['step_size'] = 1.0 top.setup(check=False) top.root.data.nrel_api_key = "DEMO_KEY" top.root.data.location = "cleveland, ohio" # cutt-off times for PV power due to shading: top.root.data.start_time = 10 top.root.data.end_time = 16 top['des_vars.panels_array_power'] = 350.0 top['des_vars.power_capacity'] = 12 * 100 top.run() fig = make_plot(top) pylab.show()